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