1 //===- MachineDebugify.cpp - Attach synthetic debug info to everything ----===//
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 attaches synthetic debug info to everything. It can be used
10 /// to create targeted tests for debug info preservation, or test for CodeGen
11 /// differences with vs. without debug info.
12 ///
13 /// This isn't intended to have feature parity with Debugify.
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/TargetInstrInfo.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Transforms/Utils/Debugify.h"
29
30 #define DEBUG_TYPE "mir-debugify"
31
32 using namespace llvm;
33
34 namespace {
applyDebugifyMetadataToMachineFunction(MachineModuleInfo & MMI,DIBuilder & DIB,Function & F)35 bool applyDebugifyMetadataToMachineFunction(MachineModuleInfo &MMI,
36 DIBuilder &DIB, Function &F) {
37 MachineFunction *MaybeMF = MMI.getMachineFunction(F);
38 if (!MaybeMF)
39 return false;
40 MachineFunction &MF = *MaybeMF;
41 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
42
43 DISubprogram *SP = F.getSubprogram();
44 assert(SP && "IR Debugify just created it?");
45
46 Module &M = *F.getParent();
47 LLVMContext &Ctx = M.getContext();
48
49 unsigned NextLine = SP->getLine();
50 for (MachineBasicBlock &MBB : MF) {
51 for (MachineInstr &MI : MBB) {
52 // This will likely emit line numbers beyond the end of the imagined
53 // source function and into subsequent ones. We don't do anything about
54 // that as it doesn't really matter to the compiler where the line is in
55 // the imaginary source code.
56 MI.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
57 }
58 }
59
60 // Find local variables defined by debugify. No attempt is made to match up
61 // MIR-level regs to the 'correct' IR-level variables: there isn't a simple
62 // way to do that, and it isn't necessary to find interesting CodeGen bugs.
63 // Instead, simply keep track of one variable per line. Later, we can insert
64 // DBG_VALUE insts that point to these local variables. Emitting DBG_VALUEs
65 // which cover a wide range of lines can help stress the debug info passes:
66 // if we can't do that, fall back to using the local variable which precedes
67 // all the others.
68 Function *DbgValF = M.getFunction("llvm.dbg.value");
69 DbgValueInst *EarliestDVI = nullptr;
70 DenseMap<unsigned, DILocalVariable *> Line2Var;
71 DIExpression *Expr = nullptr;
72 if (DbgValF) {
73 for (const Use &U : DbgValF->uses()) {
74 auto *DVI = dyn_cast<DbgValueInst>(U.getUser());
75 if (!DVI || DVI->getFunction() != &F)
76 continue;
77 unsigned Line = DVI->getDebugLoc().getLine();
78 assert(Line != 0 && "debugify should not insert line 0 locations");
79 Line2Var[Line] = DVI->getVariable();
80 if (!EarliestDVI || Line < EarliestDVI->getDebugLoc().getLine())
81 EarliestDVI = DVI;
82 Expr = DVI->getExpression();
83 }
84 }
85 if (Line2Var.empty())
86 return true;
87
88 // Now, try to insert a DBG_VALUE instruction after each real instruction.
89 // Do this by introducing debug uses of each register definition. If that is
90 // not possible (e.g. we have a phi or a meta instruction), emit a constant.
91 uint64_t NextImm = 0;
92 const MCInstrDesc &DbgValDesc = TII.get(TargetOpcode::DBG_VALUE);
93 for (MachineBasicBlock &MBB : MF) {
94 MachineBasicBlock::iterator FirstNonPHIIt = MBB.getFirstNonPHI();
95 for (auto I = MBB.begin(), E = MBB.end(); I != E; ) {
96 MachineInstr &MI = *I;
97 ++I;
98
99 // `I` may point to a DBG_VALUE created in the previous loop iteration.
100 if (MI.isDebugInstr())
101 continue;
102
103 // It's not allowed to insert DBG_VALUEs after a terminator.
104 if (MI.isTerminator())
105 continue;
106
107 // Find a suitable insertion point for the DBG_VALUE.
108 auto InsertBeforeIt = MI.isPHI() ? FirstNonPHIIt : I;
109
110 // Find a suitable local variable for the DBG_VALUE.
111 unsigned Line = MI.getDebugLoc().getLine();
112 if (!Line2Var.count(Line))
113 Line = EarliestDVI->getDebugLoc().getLine();
114 DILocalVariable *LocalVar = Line2Var[Line];
115 assert(LocalVar && "No variable for current line?");
116
117 // Emit DBG_VALUEs for register definitions.
118 SmallVector<MachineOperand *, 4> RegDefs;
119 for (MachineOperand &MO : MI.operands())
120 if (MO.isReg() && MO.isDef() && MO.getReg())
121 RegDefs.push_back(&MO);
122 for (MachineOperand *MO : RegDefs)
123 BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
124 /*IsIndirect=*/false, *MO, LocalVar, Expr);
125
126 // OK, failing that, emit a constant DBG_VALUE.
127 if (RegDefs.empty()) {
128 auto ImmOp = MachineOperand::CreateImm(NextImm++);
129 BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
130 /*IsIndirect=*/false, ImmOp, LocalVar, Expr);
131 }
132 }
133 }
134
135 return true;
136 }
137
138 /// ModulePass for attaching synthetic debug info to everything, used with the
139 /// legacy module pass manager.
140 struct DebugifyMachineModule : public ModulePass {
runOnModule__anon9385eecf0111::DebugifyMachineModule141 bool runOnModule(Module &M) override {
142 MachineModuleInfo &MMI =
143 getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
144 return applyDebugifyMetadata(
145 M, M.functions(),
146 "ModuleDebugify: ", [&](DIBuilder &DIB, Function &F) -> bool {
147 return applyDebugifyMetadataToMachineFunction(MMI, DIB, F);
148 });
149 }
150
DebugifyMachineModule__anon9385eecf0111::DebugifyMachineModule151 DebugifyMachineModule() : ModulePass(ID) {}
152
getAnalysisUsage__anon9385eecf0111::DebugifyMachineModule153 void getAnalysisUsage(AnalysisUsage &AU) const override {
154 AU.addRequired<MachineModuleInfoWrapperPass>();
155 AU.addPreserved<MachineModuleInfoWrapperPass>();
156 AU.setPreservesCFG();
157 }
158
159 static char ID; // Pass identification.
160 };
161 char DebugifyMachineModule::ID = 0;
162
163 } // end anonymous namespace
164
165 INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE,
166 "Machine Debugify Module", false, false)
167 INITIALIZE_PASS_END(DebugifyMachineModule, DEBUG_TYPE,
168 "Machine Debugify Module", false, false)
169
createDebugifyMachineModulePass()170 ModulePass *llvm::createDebugifyMachineModulePass() {
171 return new DebugifyMachineModule();
172 }
173