@@ -45,10 +45,28 @@ char RISCVPushPopOpt::ID = 0;
45
45
INITIALIZE_PASS (RISCVPushPopOpt, " riscv-push-pop-opt" , RISCV_PUSH_POP_OPT_NAME,
46
46
false , false )
47
47
48
+ template <typename IterT>
49
+ static IterT nextNoDebugNoCFIInst(const IterT It, const IterT End) {
50
+ return std::find_if_not (std::next (It), End, [](const auto &Inst) {
51
+ return Inst.isDebugInstr () || Inst.isCFIInstruction () ||
52
+ Inst.isPseudoProbe ();
53
+ });
54
+ }
55
+
56
+ static void eraseCFIInst (const MachineBasicBlock::iterator Begin,
57
+ const MachineBasicBlock::iterator End) {
58
+ std::vector<std::reference_wrapper<llvm::MachineInstr>> CFIInstrs;
59
+ std::copy_if (std::next (Begin), End, std::back_inserter (CFIInstrs),
60
+ [](const auto &Inst) { return Inst.isCFIInstruction (); });
61
+
62
+ for (auto Inst : CFIInstrs)
63
+ Inst.get ().eraseFromParent ();
64
+ }
65
+
48
66
// Check if POP instruction was inserted into the MBB and return iterator to it.
49
67
static MachineBasicBlock::iterator containsPop (MachineBasicBlock &MBB) {
50
68
for (MachineBasicBlock::iterator MBBI = MBB.begin (); MBBI != MBB.end ();
51
- MBBI = next_nodbg (MBBI, MBB.end ()))
69
+ MBBI = nextNoDebugNoCFIInst (MBBI, MBB.end ()))
52
70
if (MBBI->getOpcode () == RISCV::CM_POP)
53
71
return MBBI;
54
72
@@ -76,6 +94,9 @@ bool RISCVPushPopOpt::usePopRet(MachineBasicBlock::iterator &MBBI,
76
94
for (unsigned i = FirstNonDeclaredOp; i < MBBI->getNumOperands (); ++i)
77
95
PopRetBuilder.add (MBBI->getOperand (i));
78
96
97
+ // Remove CFI instructions, they are not needed for cm.popret and cm.popretz
98
+ eraseCFIInst (MBBI, NextI);
99
+
79
100
MBBI->eraseFromParent ();
80
101
NextI->eraseFromParent ();
81
102
return true ;
@@ -92,8 +113,8 @@ bool RISCVPushPopOpt::adjustRetVal(MachineBasicBlock::iterator &MBBI) {
92
113
// Since POP instruction is in Epilogue no normal instructions will follow
93
114
// after it. Therefore search only previous ones to find the return value.
94
115
for (MachineBasicBlock::reverse_iterator I =
95
- next_nodbg (MBBI.getReverse (), RE);
96
- I != RE; I = next_nodbg (I, RE)) {
116
+ nextNoDebugNoCFIInst (MBBI.getReverse (), RE);
117
+ I != RE; I = nextNoDebugNoCFIInst (I, RE)) {
97
118
MachineInstr &MI = *I;
98
119
if (auto OperandPair = TII->isCopyInstrImpl (MI)) {
99
120
Register DestReg = OperandPair->Destination ->getReg ();
@@ -138,7 +159,7 @@ bool RISCVPushPopOpt::runOnMachineFunction(MachineFunction &Fn) {
138
159
bool Modified = false ;
139
160
for (auto &MBB : Fn) {
140
161
MachineBasicBlock::iterator MBBI = containsPop (MBB);
141
- MachineBasicBlock::iterator NextI = next_nodbg (MBBI, MBB.end ());
162
+ MachineBasicBlock::iterator NextI = nextNoDebugNoCFIInst (MBBI, MBB.end ());
142
163
if (MBBI != MBB.end () && NextI != MBB.end () &&
143
164
NextI->getOpcode () == RISCV::PseudoRET)
144
165
Modified |= usePopRet (MBBI, NextI, adjustRetVal (MBBI));
0 commit comments