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