blob: c4799855a2b30eed983974b647511ea9a692da4d [file] [log] [blame]
Petar Jovanovicb6bee652018-04-24 10:32:08 +00001//===------ CFIInstrInserter.cpp - Insert additional CFI instructions -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file This pass verifies incoming and outgoing CFA information of basic
11/// blocks. CFA information is information about offset and register set by CFI
12/// directives, valid at the start and end of a basic block. This pass checks
13/// that outgoing information of predecessors matches incoming information of
14/// their successors. Then it checks if blocks have correct CFA calculation rule
15/// set and inserts additional CFI instruction at their beginnings if they
16/// don't. CFI instructions are inserted if basic blocks have incorrect offset
17/// or register set by previous blocks, as a result of a non-linear layout of
18/// blocks in a function.
19//===----------------------------------------------------------------------===//
20
Petar Jovanovica7b63e72018-05-07 11:47:48 +000021#include "llvm/ADT/DepthFirstIterator.h"
Petar Jovanovicb6bee652018-04-24 10:32:08 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/TargetFrameLowering.h"
27#include "llvm/CodeGen/TargetInstrInfo.h"
28#include "llvm/CodeGen/TargetSubtargetInfo.h"
29#include "llvm/Target/TargetMachine.h"
30using namespace llvm;
31
Petar Jovanovic44b4b3a2018-05-07 14:09:33 +000032static cl::opt<bool> VerifyCFI("verify-cfiinstrs",
33 cl::desc("Verify Call Frame Information instructions"),
34 cl::init(false),
35 cl::Hidden);
36
Petar Jovanovicb6bee652018-04-24 10:32:08 +000037namespace {
38class CFIInstrInserter : public MachineFunctionPass {
39 public:
40 static char ID;
41
42 CFIInstrInserter() : MachineFunctionPass(ID) {
43 initializeCFIInstrInserterPass(*PassRegistry::getPassRegistry());
44 }
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
47 AU.setPreservesAll();
48 MachineFunctionPass::getAnalysisUsage(AU);
49 }
50
51 bool runOnMachineFunction(MachineFunction &MF) override {
52 if (!MF.getMMI().hasDebugInfo() &&
53 !MF.getFunction().needsUnwindTableEntry())
54 return false;
55
56 MBBVector.resize(MF.getNumBlockIDs());
57 calculateCFAInfo(MF);
Petar Jovanovic44b4b3a2018-05-07 14:09:33 +000058
59 if (VerifyCFI) {
60 if (unsigned ErrorNum = verify(MF))
61 report_fatal_error("Found " + Twine(ErrorNum) +
62 " in/out CFI information errors.");
63 }
Petar Jovanovicb6bee652018-04-24 10:32:08 +000064 bool insertedCFI = insertCFIInstrs(MF);
65 MBBVector.clear();
66 return insertedCFI;
67 }
68
69 private:
70 struct MBBCFAInfo {
71 MachineBasicBlock *MBB;
72 /// Value of cfa offset valid at basic block entry.
73 int IncomingCFAOffset = -1;
74 /// Value of cfa offset valid at basic block exit.
75 int OutgoingCFAOffset = -1;
76 /// Value of cfa register valid at basic block entry.
77 unsigned IncomingCFARegister = 0;
78 /// Value of cfa register valid at basic block exit.
79 unsigned OutgoingCFARegister = 0;
80 /// If in/out cfa offset and register values for this block have already
81 /// been set or not.
82 bool Processed = false;
83 };
84
85 /// Contains cfa offset and register values valid at entry and exit of basic
86 /// blocks.
87 std::vector<MBBCFAInfo> MBBVector;
88
89 /// Calculate cfa offset and register values valid at entry and exit for all
90 /// basic blocks in a function.
91 void calculateCFAInfo(MachineFunction &MF);
92 /// Calculate cfa offset and register values valid at basic block exit by
93 /// checking the block for CFI instructions. Block's incoming CFA info remains
94 /// the same.
95 void calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo);
96 /// Update in/out cfa offset and register values for successors of the basic
97 /// block.
98 void updateSuccCFAInfo(MBBCFAInfo &MBBInfo);
99
100 /// Check if incoming CFA information of a basic block matches outgoing CFA
101 /// information of the previous block. If it doesn't, insert CFI instruction
102 /// at the beginning of the block that corrects the CFA calculation rule for
103 /// that block.
104 bool insertCFIInstrs(MachineFunction &MF);
105 /// Return the cfa offset value that should be set at the beginning of a MBB
106 /// if needed. The negated value is needed when creating CFI instructions that
107 /// set absolute offset.
108 int getCorrectCFAOffset(MachineBasicBlock *MBB) {
109 return -MBBVector[MBB->getNumber()].IncomingCFAOffset;
110 }
111
112 void report(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
113 /// Go through each MBB in a function and check that outgoing offset and
114 /// register of its predecessors match incoming offset and register of that
115 /// MBB, as well as that incoming offset and register of its successors match
116 /// outgoing offset and register of the MBB.
117 unsigned verify(MachineFunction &MF);
118};
119} // namespace
120
121char CFIInstrInserter::ID = 0;
122INITIALIZE_PASS(CFIInstrInserter, "cfi-instr-inserter",
123 "Check CFA info and insert CFI instructions if needed", false,
124 false)
125FunctionPass *llvm::createCFIInstrInserter() { return new CFIInstrInserter(); }
126
127void CFIInstrInserter::calculateCFAInfo(MachineFunction &MF) {
128 // Initial CFA offset value i.e. the one valid at the beginning of the
129 // function.
130 int InitialOffset =
131 MF.getSubtarget().getFrameLowering()->getInitialCFAOffset(MF);
132 // Initial CFA register value i.e. the one valid at the beginning of the
133 // function.
134 unsigned InitialRegister =
135 MF.getSubtarget().getFrameLowering()->getInitialCFARegister(MF);
136
137 // Initialize MBBMap.
138 for (MachineBasicBlock &MBB : MF) {
139 MBBCFAInfo MBBInfo;
140 MBBInfo.MBB = &MBB;
141 MBBInfo.IncomingCFAOffset = InitialOffset;
142 MBBInfo.OutgoingCFAOffset = InitialOffset;
143 MBBInfo.IncomingCFARegister = InitialRegister;
144 MBBInfo.OutgoingCFARegister = InitialRegister;
145 MBBVector[MBB.getNumber()] = MBBInfo;
146 }
147
148 // Set in/out cfa info for all blocks in the function. This traversal is based
149 // on the assumption that the first block in the function is the entry block
150 // i.e. that it has initial cfa offset and register values as incoming CFA
151 // information.
152 for (MachineBasicBlock &MBB : MF) {
153 if (MBBVector[MBB.getNumber()].Processed) continue;
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000154 updateSuccCFAInfo(MBBVector[MBB.getNumber()]);
155 }
156}
157
158void CFIInstrInserter::calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo) {
159 // Outgoing cfa offset set by the block.
160 int SetOffset = MBBInfo.IncomingCFAOffset;
161 // Outgoing cfa register set by the block.
162 unsigned SetRegister = MBBInfo.IncomingCFARegister;
163 const std::vector<MCCFIInstruction> &Instrs =
164 MBBInfo.MBB->getParent()->getFrameInstructions();
165
166 // Determine cfa offset and register set by the block.
167 for (MachineInstr &MI : *MBBInfo.MBB) {
168 if (MI.isCFIInstruction()) {
169 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
170 const MCCFIInstruction &CFI = Instrs[CFIIndex];
171 switch (CFI.getOperation()) {
172 case MCCFIInstruction::OpDefCfaRegister:
173 SetRegister = CFI.getRegister();
174 break;
175 case MCCFIInstruction::OpDefCfaOffset:
176 SetOffset = CFI.getOffset();
177 break;
178 case MCCFIInstruction::OpAdjustCfaOffset:
179 SetOffset += CFI.getOffset();
180 break;
181 case MCCFIInstruction::OpDefCfa:
182 SetRegister = CFI.getRegister();
183 SetOffset = CFI.getOffset();
184 break;
185 case MCCFIInstruction::OpRememberState:
186 // TODO: Add support for handling cfi_remember_state.
187#ifndef NDEBUG
188 report_fatal_error(
189 "Support for cfi_remember_state not implemented! Value of CFA "
190 "may be incorrect!\n");
191#endif
192 break;
193 case MCCFIInstruction::OpRestoreState:
194 // TODO: Add support for handling cfi_restore_state.
195#ifndef NDEBUG
196 report_fatal_error(
197 "Support for cfi_restore_state not implemented! Value of CFA may "
198 "be incorrect!\n");
199#endif
200 break;
201 // Other CFI directives do not affect CFA value.
202 case MCCFIInstruction::OpSameValue:
203 case MCCFIInstruction::OpOffset:
204 case MCCFIInstruction::OpRelOffset:
205 case MCCFIInstruction::OpEscape:
206 case MCCFIInstruction::OpRestore:
207 case MCCFIInstruction::OpUndefined:
208 case MCCFIInstruction::OpRegister:
209 case MCCFIInstruction::OpWindowSave:
Luke Cheesemana0875a92018-12-18 10:37:42 +0000210 case MCCFIInstruction::OpNegateRAState:
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000211 case MCCFIInstruction::OpGnuArgsSize:
212 break;
213 }
214 }
215 }
216
217 MBBInfo.Processed = true;
218
219 // Update outgoing CFA info.
220 MBBInfo.OutgoingCFAOffset = SetOffset;
221 MBBInfo.OutgoingCFARegister = SetRegister;
222}
223
224void CFIInstrInserter::updateSuccCFAInfo(MBBCFAInfo &MBBInfo) {
Sanjoy Dasa345b842018-05-11 15:54:46 +0000225 SmallVector<MachineBasicBlock *, 4> Stack;
226 Stack.push_back(MBBInfo.MBB);
227
228 do {
229 MachineBasicBlock *Current = Stack.pop_back_val();
230 MBBCFAInfo &CurrentInfo = MBBVector[Current->getNumber()];
231 if (CurrentInfo.Processed)
232 continue;
233
234 calculateOutgoingCFAInfo(CurrentInfo);
235 for (auto *Succ : CurrentInfo.MBB->successors()) {
236 MBBCFAInfo &SuccInfo = MBBVector[Succ->getNumber()];
237 if (!SuccInfo.Processed) {
238 SuccInfo.IncomingCFAOffset = CurrentInfo.OutgoingCFAOffset;
239 SuccInfo.IncomingCFARegister = CurrentInfo.OutgoingCFARegister;
240 Stack.push_back(Succ);
241 }
242 }
243 } while (!Stack.empty());
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000244}
245
246bool CFIInstrInserter::insertCFIInstrs(MachineFunction &MF) {
247 const MBBCFAInfo *PrevMBBInfo = &MBBVector[MF.front().getNumber()];
248 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
249 bool InsertedCFIInstr = false;
250
251 for (MachineBasicBlock &MBB : MF) {
252 // Skip the first MBB in a function
253 if (MBB.getNumber() == MF.front().getNumber()) continue;
254
255 const MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
256 auto MBBI = MBBInfo.MBB->begin();
257 DebugLoc DL = MBBInfo.MBB->findDebugLoc(MBBI);
258
259 if (PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset) {
260 // If both outgoing offset and register of a previous block don't match
261 // incoming offset and register of this block, add a def_cfa instruction
262 // with the correct offset and register for this block.
263 if (PrevMBBInfo->OutgoingCFARegister != MBBInfo.IncomingCFARegister) {
264 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
265 nullptr, MBBInfo.IncomingCFARegister, getCorrectCFAOffset(&MBB)));
266 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
267 .addCFIIndex(CFIIndex);
268 // If outgoing offset of a previous block doesn't match incoming offset
269 // of this block, add a def_cfa_offset instruction with the correct
270 // offset for this block.
271 } else {
272 unsigned CFIIndex =
273 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(
274 nullptr, getCorrectCFAOffset(&MBB)));
275 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
276 .addCFIIndex(CFIIndex);
277 }
278 InsertedCFIInstr = true;
279 // If outgoing register of a previous block doesn't match incoming
280 // register of this block, add a def_cfa_register instruction with the
281 // correct register for this block.
282 } else if (PrevMBBInfo->OutgoingCFARegister !=
283 MBBInfo.IncomingCFARegister) {
284 unsigned CFIIndex =
285 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
286 nullptr, MBBInfo.IncomingCFARegister));
287 BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
288 .addCFIIndex(CFIIndex);
289 InsertedCFIInstr = true;
290 }
291 PrevMBBInfo = &MBBInfo;
292 }
293 return InsertedCFIInstr;
294}
295
Sanjoy Dasa345b842018-05-11 15:54:46 +0000296void CFIInstrInserter::report(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ) {
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000297 errs() << "*** Inconsistent CFA register and/or offset between pred and succ "
298 "***\n";
Sanjoy Dasa345b842018-05-11 15:54:46 +0000299 errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
300 << " in " << Pred.MBB->getParent()->getName()
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000301 << " outgoing CFA Reg:" << Pred.OutgoingCFARegister << "\n";
Sanjoy Dasa345b842018-05-11 15:54:46 +0000302 errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
303 << " in " << Pred.MBB->getParent()->getName()
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000304 << " outgoing CFA Offset:" << Pred.OutgoingCFAOffset << "\n";
Sanjoy Dasa345b842018-05-11 15:54:46 +0000305 errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000306 << " incoming CFA Reg:" << Succ.IncomingCFARegister << "\n";
Sanjoy Dasa345b842018-05-11 15:54:46 +0000307 errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000308 << " incoming CFA Offset:" << Succ.IncomingCFAOffset << "\n";
309}
310
311unsigned CFIInstrInserter::verify(MachineFunction &MF) {
312 unsigned ErrorNum = 0;
Petar Jovanovica7b63e72018-05-07 11:47:48 +0000313 for (auto *CurrMBB : depth_first(&MF)) {
314 const MBBCFAInfo &CurrMBBInfo = MBBVector[CurrMBB->getNumber()];
315 for (MachineBasicBlock *Succ : CurrMBB->successors()) {
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000316 const MBBCFAInfo &SuccMBBInfo = MBBVector[Succ->getNumber()];
317 // Check that incoming offset and register values of successors match the
318 // outgoing offset and register values of CurrMBB
319 if (SuccMBBInfo.IncomingCFAOffset != CurrMBBInfo.OutgoingCFAOffset ||
320 SuccMBBInfo.IncomingCFARegister != CurrMBBInfo.OutgoingCFARegister) {
Vladimir Stefanovica32d4032018-08-30 17:31:38 +0000321 // Inconsistent offsets/registers are ok for 'noreturn' blocks because
322 // we don't generate epilogues inside such blocks.
323 if (SuccMBBInfo.MBB->succ_empty() && !SuccMBBInfo.MBB->isReturnBlock())
324 continue;
Petar Jovanovicb6bee652018-04-24 10:32:08 +0000325 report(CurrMBBInfo, SuccMBBInfo);
326 ErrorNum++;
327 }
328 }
329 }
330 return ErrorNum;
331}