1 //===------ CFIInstrInserter.cpp - Insert additional CFI instructions -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This pass verifies incoming and outgoing CFA information of basic
10 /// blocks. CFA information is information about offset and register set by CFI
11 /// directives, valid at the start and end of a basic block. This pass checks
12 /// that outgoing information of predecessors matches incoming information of
13 /// their successors. Then it checks if blocks have correct CFA calculation rule
14 /// set and inserts additional CFI instruction at their beginnings if they
15 /// don't. CFI instructions are inserted if basic blocks have incorrect offset
16 /// or register set by previous blocks, as a result of a non-linear layout of
17 /// blocks in a function.
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/TargetFrameLowering.h"
25 #include "llvm/CodeGen/TargetInstrInfo.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/MC/MCDwarf.h"
29 using namespace llvm;
30
31 static cl::opt<bool> VerifyCFI("verify-cfiinstrs",
32 cl::desc("Verify Call Frame Information instructions"),
33 cl::init(false),
34 cl::Hidden);
35
36 namespace {
37 class CFIInstrInserter : public MachineFunctionPass {
38 public:
39 static char ID;
40
CFIInstrInserter()41 CFIInstrInserter() : MachineFunctionPass(ID) {
42 initializeCFIInstrInserterPass(*PassRegistry::getPassRegistry());
43 }
44
getAnalysisUsage(AnalysisUsage & AU) const45 void getAnalysisUsage(AnalysisUsage &AU) const override {
46 AU.setPreservesAll();
47 MachineFunctionPass::getAnalysisUsage(AU);
48 }
49
runOnMachineFunction(MachineFunction & MF)50 bool runOnMachineFunction(MachineFunction &MF) override {
51 if (!MF.needsFrameMoves())
52 return false;
53
54 MBBVector.resize(MF.getNumBlockIDs());
55 calculateCFAInfo(MF);
56
57 if (VerifyCFI) {
58 if (unsigned ErrorNum = verify(MF))
59 report_fatal_error("Found " + Twine(ErrorNum) +
60 " in/out CFI information errors.");
61 }
62 bool insertedCFI = insertCFIInstrs(MF);
63 MBBVector.clear();
64 return insertedCFI;
65 }
66
67 private:
68 struct MBBCFAInfo {
69 MachineBasicBlock *MBB;
70 /// Value of cfa offset valid at basic block entry.
71 int IncomingCFAOffset = -1;
72 /// Value of cfa offset valid at basic block exit.
73 int OutgoingCFAOffset = -1;
74 /// Value of cfa register valid at basic block entry.
75 unsigned IncomingCFARegister = 0;
76 /// Value of cfa register valid at basic block exit.
77 unsigned OutgoingCFARegister = 0;
78 /// Set of callee saved registers saved at basic block entry.
79 BitVector IncomingCSRSaved;
80 /// Set of callee saved registers saved at basic block exit.
81 BitVector OutgoingCSRSaved;
82 /// If in/out cfa offset and register values for this block have already
83 /// been set or not.
84 bool Processed = false;
85 };
86
87 #define INVALID_REG UINT_MAX
88 #define INVALID_OFFSET INT_MAX
89 /// contains the location where CSR register is saved.
90 struct CSRSavedLocation {
CSRSavedLocation__anon4de7dd820111::CFIInstrInserter::CSRSavedLocation91 CSRSavedLocation(std::optional<unsigned> R, std::optional<int> O)
92 : Reg(R), Offset(O) {}
93 std::optional<unsigned> Reg;
94 std::optional<int> Offset;
95 };
96
97 /// Contains cfa offset and register values valid at entry and exit of basic
98 /// blocks.
99 std::vector<MBBCFAInfo> MBBVector;
100
101 /// Map the callee save registers to the locations where they are saved.
102 SmallDenseMap<unsigned, CSRSavedLocation, 16> CSRLocMap;
103
104 /// Calculate cfa offset and register values valid at entry and exit for all
105 /// basic blocks in a function.
106 void calculateCFAInfo(MachineFunction &MF);
107 /// Calculate cfa offset and register values valid at basic block exit by
108 /// checking the block for CFI instructions. Block's incoming CFA info remains
109 /// the same.
110 void calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo);
111 /// Update in/out cfa offset and register values for successors of the basic
112 /// block.
113 void updateSuccCFAInfo(MBBCFAInfo &MBBInfo);
114
115 /// Check if incoming CFA information of a basic block matches outgoing CFA
116 /// information of the previous block. If it doesn't, insert CFI instruction
117 /// at the beginning of the block that corrects the CFA calculation rule for
118 /// that block.
119 bool insertCFIInstrs(MachineFunction &MF);
120 /// Return the cfa offset value that should be set at the beginning of a MBB
121 /// if needed. The negated value is needed when creating CFI instructions that
122 /// set absolute offset.
getCorrectCFAOffset(MachineBasicBlock * MBB)123 int getCorrectCFAOffset(MachineBasicBlock *MBB) {
124 return MBBVector[MBB->getNumber()].IncomingCFAOffset;
125 }
126
127 void reportCFAError(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
128 void reportCSRError(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
129 /// Go through each MBB in a function and check that outgoing offset and
130 /// register of its predecessors match incoming offset and register of that
131 /// MBB, as well as that incoming offset and register of its successors match
132 /// outgoing offset and register of the MBB.
133 unsigned verify(MachineFunction &MF);
134 };
135 } // namespace
136
137 char CFIInstrInserter::ID = 0;
138 INITIALIZE_PASS(CFIInstrInserter, "cfi-instr-inserter",
139 "Check CFA info and insert CFI instructions if needed", false,
140 false)
createCFIInstrInserter()141 FunctionPass *llvm::createCFIInstrInserter() { return new CFIInstrInserter(); }
142
calculateCFAInfo(MachineFunction & MF)143 void CFIInstrInserter::calculateCFAInfo(MachineFunction &MF) {
144 // Initial CFA offset value i.e. the one valid at the beginning of the
145 // function.
146 int InitialOffset =
147 MF.getSubtarget().getFrameLowering()->getInitialCFAOffset(MF);
148 // Initial CFA register value i.e. the one valid at the beginning of the
149 // function.
150 Register InitialRegister =
151 MF.getSubtarget().getFrameLowering()->getInitialCFARegister(MF);
152 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
153 unsigned NumRegs = TRI.getNumRegs();
154
155 // Initialize MBBMap.
156 for (MachineBasicBlock &MBB : MF) {
157 MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
158 MBBInfo.MBB = &MBB;
159 MBBInfo.IncomingCFAOffset = InitialOffset;
160 MBBInfo.OutgoingCFAOffset = InitialOffset;
161 MBBInfo.IncomingCFARegister = InitialRegister;
162 MBBInfo.OutgoingCFARegister = InitialRegister;
163 MBBInfo.IncomingCSRSaved.resize(NumRegs);
164 MBBInfo.OutgoingCSRSaved.resize(NumRegs);
165 }
166 CSRLocMap.clear();
167
168 // Set in/out cfa info for all blocks in the function. This traversal is based
169 // on the assumption that the first block in the function is the entry block
170 // i.e. that it has initial cfa offset and register values as incoming CFA
171 // information.
172 updateSuccCFAInfo(MBBVector[MF.front().getNumber()]);
173 }
174
calculateOutgoingCFAInfo(MBBCFAInfo & MBBInfo)175 void CFIInstrInserter::calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo) {
176 // Outgoing cfa offset set by the block.
177 int SetOffset = MBBInfo.IncomingCFAOffset;
178 // Outgoing cfa register set by the block.
179 unsigned SetRegister = MBBInfo.IncomingCFARegister;
180 MachineFunction *MF = MBBInfo.MBB->getParent();
181 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
182 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
183 unsigned NumRegs = TRI.getNumRegs();
184 BitVector CSRSaved(NumRegs), CSRRestored(NumRegs);
185
186 // Determine cfa offset and register set by the block.
187 for (MachineInstr &MI : *MBBInfo.MBB) {
188 if (MI.isCFIInstruction()) {
189 std::optional<unsigned> CSRReg;
190 std::optional<int> CSROffset;
191 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
192 const MCCFIInstruction &CFI = Instrs[CFIIndex];
193 switch (CFI.getOperation()) {
194 case MCCFIInstruction::OpDefCfaRegister:
195 SetRegister = CFI.getRegister();
196 break;
197 case MCCFIInstruction::OpDefCfaOffset:
198 SetOffset = CFI.getOffset();
199 break;
200 case MCCFIInstruction::OpAdjustCfaOffset:
201 SetOffset += CFI.getOffset();
202 break;
203 case MCCFIInstruction::OpDefCfa:
204 SetRegister = CFI.getRegister();
205 SetOffset = CFI.getOffset();
206 break;
207 case MCCFIInstruction::OpOffset:
208 CSROffset = CFI.getOffset();
209 break;
210 case MCCFIInstruction::OpRegister:
211 CSRReg = CFI.getRegister2();
212 break;
213 case MCCFIInstruction::OpRelOffset:
214 CSROffset = CFI.getOffset() - SetOffset;
215 break;
216 case MCCFIInstruction::OpRestore:
217 CSRRestored.set(CFI.getRegister());
218 break;
219 case MCCFIInstruction::OpLLVMDefAspaceCfa:
220 // TODO: Add support for handling cfi_def_aspace_cfa.
221 #ifndef NDEBUG
222 report_fatal_error(
223 "Support for cfi_llvm_def_aspace_cfa not implemented! Value of CFA "
224 "may be incorrect!\n");
225 #endif
226 break;
227 case MCCFIInstruction::OpRememberState:
228 // TODO: Add support for handling cfi_remember_state.
229 #ifndef NDEBUG
230 report_fatal_error(
231 "Support for cfi_remember_state not implemented! Value of CFA "
232 "may be incorrect!\n");
233 #endif
234 break;
235 case MCCFIInstruction::OpRestoreState:
236 // TODO: Add support for handling cfi_restore_state.
237 #ifndef NDEBUG
238 report_fatal_error(
239 "Support for cfi_restore_state not implemented! Value of CFA may "
240 "be incorrect!\n");
241 #endif
242 break;
243 // Other CFI directives do not affect CFA value.
244 case MCCFIInstruction::OpUndefined:
245 case MCCFIInstruction::OpSameValue:
246 case MCCFIInstruction::OpEscape:
247 case MCCFIInstruction::OpWindowSave:
248 case MCCFIInstruction::OpNegateRAState:
249 case MCCFIInstruction::OpGnuArgsSize:
250 break;
251 }
252 if (CSRReg || CSROffset) {
253 auto It = CSRLocMap.find(CFI.getRegister());
254 if (It == CSRLocMap.end()) {
255 CSRLocMap.insert(
256 {CFI.getRegister(), CSRSavedLocation(CSRReg, CSROffset)});
257 } else if (It->second.Reg != CSRReg || It->second.Offset != CSROffset) {
258 llvm_unreachable("Different saved locations for the same CSR");
259 }
260 CSRSaved.set(CFI.getRegister());
261 }
262 }
263 }
264
265 MBBInfo.Processed = true;
266
267 // Update outgoing CFA info.
268 MBBInfo.OutgoingCFAOffset = SetOffset;
269 MBBInfo.OutgoingCFARegister = SetRegister;
270
271 // Update outgoing CSR info.
272 BitVector::apply([](auto x, auto y, auto z) { return (x | y) & ~z; },
273 MBBInfo.OutgoingCSRSaved, MBBInfo.IncomingCSRSaved, CSRSaved,
274 CSRRestored);
275 }
276
updateSuccCFAInfo(MBBCFAInfo & MBBInfo)277 void CFIInstrInserter::updateSuccCFAInfo(MBBCFAInfo &MBBInfo) {
278 SmallVector<MachineBasicBlock *, 4> Stack;
279 Stack.push_back(MBBInfo.MBB);
280
281 do {
282 MachineBasicBlock *Current = Stack.pop_back_val();
283 MBBCFAInfo &CurrentInfo = MBBVector[Current->getNumber()];
284 calculateOutgoingCFAInfo(CurrentInfo);
285 for (auto *Succ : CurrentInfo.MBB->successors()) {
286 MBBCFAInfo &SuccInfo = MBBVector[Succ->getNumber()];
287 if (!SuccInfo.Processed) {
288 SuccInfo.IncomingCFAOffset = CurrentInfo.OutgoingCFAOffset;
289 SuccInfo.IncomingCFARegister = CurrentInfo.OutgoingCFARegister;
290 SuccInfo.IncomingCSRSaved = CurrentInfo.OutgoingCSRSaved;
291 Stack.push_back(Succ);
292 }
293 }
294 } while (!Stack.empty());
295 }
296
insertCFIInstrs(MachineFunction & MF)297 bool CFIInstrInserter::insertCFIInstrs(MachineFunction &MF) {
298 const MBBCFAInfo *PrevMBBInfo = &MBBVector[MF.front().getNumber()];
299 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
300 bool InsertedCFIInstr = false;
301
302 BitVector SetDifference;
303 for (MachineBasicBlock &MBB : MF) {
304 // Skip the first MBB in a function
305 if (MBB.getNumber() == MF.front().getNumber()) continue;
306
307 const MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
308 auto MBBI = MBBInfo.MBB->begin();
309 DebugLoc DL = MBBInfo.MBB->findDebugLoc(MBBI);
310
311 // If the current MBB will be placed in a unique section, a full DefCfa
312 // must be emitted.
313 const bool ForceFullCFA = MBB.isBeginSection();
314
315 if ((PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset &&
316 PrevMBBInfo->OutgoingCFARegister != MBBInfo.IncomingCFARegister) ||
317 ForceFullCFA) {
318 // If both outgoing offset and register of a previous block don't match
319 // incoming offset and register of this block, or if this block begins a
320 // section, add a def_cfa instruction with the correct offset and
321 // register for this block.
322 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
323 nullptr, MBBInfo.IncomingCFARegister, getCorrectCFAOffset(&MBB)));
324 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
325 .addCFIIndex(CFIIndex);
326 InsertedCFIInstr = true;
327 } else if (PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset) {
328 // If outgoing offset of a previous block doesn't match incoming offset
329 // of this block, add a def_cfa_offset instruction with the correct
330 // offset for this block.
331 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
332 nullptr, getCorrectCFAOffset(&MBB)));
333 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
334 .addCFIIndex(CFIIndex);
335 InsertedCFIInstr = true;
336 } else if (PrevMBBInfo->OutgoingCFARegister !=
337 MBBInfo.IncomingCFARegister) {
338 unsigned CFIIndex =
339 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
340 nullptr, MBBInfo.IncomingCFARegister));
341 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
342 .addCFIIndex(CFIIndex);
343 InsertedCFIInstr = true;
344 }
345
346 if (ForceFullCFA) {
347 MF.getSubtarget().getFrameLowering()->emitCalleeSavedFrameMovesFullCFA(
348 *MBBInfo.MBB, MBBI);
349 InsertedCFIInstr = true;
350 PrevMBBInfo = &MBBInfo;
351 continue;
352 }
353
354 BitVector::apply([](auto x, auto y) { return x & ~y; }, SetDifference,
355 PrevMBBInfo->OutgoingCSRSaved, MBBInfo.IncomingCSRSaved);
356 for (int Reg : SetDifference.set_bits()) {
357 unsigned CFIIndex =
358 MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
359 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
360 .addCFIIndex(CFIIndex);
361 InsertedCFIInstr = true;
362 }
363
364 BitVector::apply([](auto x, auto y) { return x & ~y; }, SetDifference,
365 MBBInfo.IncomingCSRSaved, PrevMBBInfo->OutgoingCSRSaved);
366 for (int Reg : SetDifference.set_bits()) {
367 auto it = CSRLocMap.find(Reg);
368 assert(it != CSRLocMap.end() && "Reg should have an entry in CSRLocMap");
369 unsigned CFIIndex;
370 CSRSavedLocation RO = it->second;
371 if (!RO.Reg && RO.Offset) {
372 CFIIndex = MF.addFrameInst(
373 MCCFIInstruction::createOffset(nullptr, Reg, *RO.Offset));
374 } else if (RO.Reg && !RO.Offset) {
375 CFIIndex = MF.addFrameInst(
376 MCCFIInstruction::createRegister(nullptr, Reg, *RO.Reg));
377 } else {
378 llvm_unreachable("RO.Reg and RO.Offset cannot both be valid/invalid");
379 }
380 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
381 .addCFIIndex(CFIIndex);
382 InsertedCFIInstr = true;
383 }
384
385 PrevMBBInfo = &MBBInfo;
386 }
387 return InsertedCFIInstr;
388 }
389
reportCFAError(const MBBCFAInfo & Pred,const MBBCFAInfo & Succ)390 void CFIInstrInserter::reportCFAError(const MBBCFAInfo &Pred,
391 const MBBCFAInfo &Succ) {
392 errs() << "*** Inconsistent CFA register and/or offset between pred and succ "
393 "***\n";
394 errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
395 << " in " << Pred.MBB->getParent()->getName()
396 << " outgoing CFA Reg:" << Pred.OutgoingCFARegister << "\n";
397 errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
398 << " in " << Pred.MBB->getParent()->getName()
399 << " outgoing CFA Offset:" << Pred.OutgoingCFAOffset << "\n";
400 errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
401 << " incoming CFA Reg:" << Succ.IncomingCFARegister << "\n";
402 errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
403 << " incoming CFA Offset:" << Succ.IncomingCFAOffset << "\n";
404 }
405
reportCSRError(const MBBCFAInfo & Pred,const MBBCFAInfo & Succ)406 void CFIInstrInserter::reportCSRError(const MBBCFAInfo &Pred,
407 const MBBCFAInfo &Succ) {
408 errs() << "*** Inconsistent CSR Saved between pred and succ in function "
409 << Pred.MBB->getParent()->getName() << " ***\n";
410 errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
411 << " outgoing CSR Saved: ";
412 for (int Reg : Pred.OutgoingCSRSaved.set_bits())
413 errs() << Reg << " ";
414 errs() << "\n";
415 errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
416 << " incoming CSR Saved: ";
417 for (int Reg : Succ.IncomingCSRSaved.set_bits())
418 errs() << Reg << " ";
419 errs() << "\n";
420 }
421
verify(MachineFunction & MF)422 unsigned CFIInstrInserter::verify(MachineFunction &MF) {
423 unsigned ErrorNum = 0;
424 for (auto *CurrMBB : depth_first(&MF)) {
425 const MBBCFAInfo &CurrMBBInfo = MBBVector[CurrMBB->getNumber()];
426 for (MachineBasicBlock *Succ : CurrMBB->successors()) {
427 const MBBCFAInfo &SuccMBBInfo = MBBVector[Succ->getNumber()];
428 // Check that incoming offset and register values of successors match the
429 // outgoing offset and register values of CurrMBB
430 if (SuccMBBInfo.IncomingCFAOffset != CurrMBBInfo.OutgoingCFAOffset ||
431 SuccMBBInfo.IncomingCFARegister != CurrMBBInfo.OutgoingCFARegister) {
432 // Inconsistent offsets/registers are ok for 'noreturn' blocks because
433 // we don't generate epilogues inside such blocks.
434 if (SuccMBBInfo.MBB->succ_empty() && !SuccMBBInfo.MBB->isReturnBlock())
435 continue;
436 reportCFAError(CurrMBBInfo, SuccMBBInfo);
437 ErrorNum++;
438 }
439 // Check that IncomingCSRSaved of every successor matches the
440 // OutgoingCSRSaved of CurrMBB
441 if (SuccMBBInfo.IncomingCSRSaved != CurrMBBInfo.OutgoingCSRSaved) {
442 reportCSRError(CurrMBBInfo, SuccMBBInfo);
443 ErrorNum++;
444 }
445 }
446 }
447 return ErrorNum;
448 }
449