LLVM 23.0.0git
MachineDebugify.cpp
Go to the documentation of this file.
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
17#include "llvm/ADT/DenseMap.h"
21#include "llvm/CodeGen/Passes.h"
27
28#define DEBUG_TYPE "mir-debugify"
29
30using namespace llvm;
31
33 DIBuilder &DIB, Function &F,
35 MachineFunction *MaybeMF = GetMF(F);
36 if (!MaybeMF)
37 return false;
38 MachineFunction &MF = *MaybeMF;
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(Ctx, NextLine++, 1, 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 DbgVariableRecord *EarliestDVR = nullptr;
68 DIExpression *Expr = nullptr;
69 for (BasicBlock &BB : F) {
70 for (Instruction &I : BB) {
71 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
72 if (!DVR.isDbgValue())
73 continue;
74 unsigned Line = DVR.getDebugLoc().getLine();
75 assert(Line != 0 && "debugify should not insert line 0 locations");
76 Line2Var[Line] = DVR.getVariable();
77 if (!EarliestDVR || Line < EarliestDVR->getDebugLoc().getLine())
78 EarliestDVR = &DVR;
79 Expr = DVR.getExpression();
80 }
81 }
82 }
83 if (Line2Var.empty())
84 return true;
85
86 // Now, try to insert a DBG_VALUE instruction after each real instruction.
87 // Do this by introducing debug uses of each register definition. If that is
88 // not possible (e.g. we have a phi or a meta instruction), emit a constant.
89 uint64_t NextImm = 0;
91 const MCInstrDesc &DbgValDesc = TII.get(TargetOpcode::DBG_VALUE);
92 for (MachineBasicBlock &MBB : MF) {
93 MachineBasicBlock::iterator FirstNonPHIIt = MBB.getFirstNonPHI();
94 for (auto I = MBB.begin(), E = MBB.end(); I != E;) {
95 MachineInstr &MI = *I;
96 ++I;
97
98 // `I` may point to a DBG_VALUE created in the previous loop iteration.
99 if (MI.isDebugInstr())
100 continue;
101
102 // It's not allowed to insert DBG_VALUEs after a terminator.
103 if (MI.isTerminator())
104 continue;
105
106 // Find a suitable insertion point for the DBG_VALUE.
107 auto InsertBeforeIt = MI.isPHI() ? FirstNonPHIIt : I;
108
109 // Find a suitable local variable for the DBG_VALUE.
110 unsigned Line = MI.getDebugLoc().getLine();
111 auto It = Line2Var.find(Line);
112 if (It == Line2Var.end()) {
113 Line = EarliestDVR->getDebugLoc().getLine();
114 It = Line2Var.find(Line);
115 assert(It != Line2Var.end());
116 }
117 DILocalVariable *LocalVar = It->second;
118 assert(LocalVar && "No variable for current line?");
119 VarSet.insert(LocalVar);
120
121 // Emit DBG_VALUEs for register definitions.
123 for (MachineOperand &MO : MI.all_defs())
124 if (MO.getReg())
125 RegDefs.push_back(&MO);
126 for (MachineOperand *MO : RegDefs)
127 BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
128 /*IsIndirect=*/false, *MO, LocalVar, Expr);
129
130 // OK, failing that, emit a constant DBG_VALUE.
131 if (RegDefs.empty()) {
132 auto ImmOp = MachineOperand::CreateImm(NextImm++);
133 BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
134 /*IsIndirect=*/false, ImmOp, LocalVar, Expr);
135 }
136 }
137 }
138
139 // Here we save the number of lines and variables into "llvm.mir.debugify".
140 // It is useful for mir-check-debugify.
141 NamedMDNode *NMD = M.getNamedMetadata("llvm.mir.debugify");
143 if (!NMD) {
144 NMD = M.getOrInsertNamedMetadata("llvm.mir.debugify");
145 auto addDebugifyOperand = [&](unsigned N) {
147 Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
148 };
149 // Add number of lines.
150 addDebugifyOperand(NextLine - 1);
151 // Add number of variables.
152 addDebugifyOperand(VarSet.size());
153 } else {
154 assert(NMD->getNumOperands() == 2 &&
155 "llvm.mir.debugify should have exactly 2 operands!");
156 auto setDebugifyOperand = [&](unsigned Idx, unsigned N) {
158 ConstantInt::get(Int32Ty, N))));
159 };
160 auto getDebugifyOperand = [&](unsigned Idx) {
162 ->getZExtValue();
163 };
164 // Set number of lines.
165 setDebugifyOperand(0, NextLine - 1);
166 // Set number of variables.
167 auto OldNumVars = getDebugifyOperand(1);
168 setDebugifyOperand(1, OldNumVars + VarSet.size());
169 }
170
171 return true;
172}
173
174namespace {
175
176/// ModulePass for attaching synthetic debug info to everything, used with the
177/// legacy module pass manager.
178struct DebugifyMachineModule : public ModulePass {
179 bool runOnModule(Module &M) override {
180 // We will insert new debugify metadata, so erasing the old one.
181 assert(!M.getNamedMetadata("llvm.mir.debugify") &&
182 "llvm.mir.debugify metadata already exists! Strip it first");
183 MachineModuleInfo &MMI =
184 getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
186 M, M.functions(),
187 "ModuleDebugify: ", [&](DIBuilder &DIB, Function &F) -> bool {
188 return applyDebugifyMetadataToMachineFunction(
189 DIB, F, [&MMI](Function &F) -> MachineFunction * {
190 return MMI.getMachineFunction(F);
191 });
192 });
193 }
194
195 DebugifyMachineModule() : ModulePass(ID) {}
196
197 void getAnalysisUsage(AnalysisUsage &AU) const override {
200 AU.setPreservesCFG();
201 }
202
203 static char ID; // Pass identification.
204};
205char DebugifyMachineModule::ID = 0;
206
207} // end anonymous namespace
208
209INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE,
210 "Machine Debugify Module", false, false)
211INITIALIZE_PASS_END(DebugifyMachineModule, DEBUG_TYPE,
212 "Machine Debugify Module", false, false)
213
215 return new DebugifyMachineModule();
216}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
LLVM Basic Block Representation.
Definition BasicBlock.h:62
DWARF expression.
Subprogram description. Uses SubclassData1.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI unsigned getLine() const
Definition DebugLoc.cpp:52
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool empty() const
Definition DenseMap.h:109
iterator end()
Definition DenseMap.h:81
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Describe properties that are true of each instruction in the target description file.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
MachineInstrBundleIterator< MachineInstr > iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateImm(int64_t Val)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1760
LLVM_ABI void setOperand(unsigned I, MDNode *New)
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
LLVM_ABI void addOperand(MDNode *M)
size_type size() const
Definition SmallPtrSet.h:99
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
virtual const TargetInstrInfo * getInstrInfo() const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:313
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:481
An efficient, type-erasing, non-owning reference to a callable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:328
LLVM_ABI bool applyDebugifyMetadata(Module &M, iterator_range< Module::iterator > Functions, StringRef Banner, std::function< bool(DIBuilder &, Function &)> ApplyToMF)
Add synthesized debug information to a module.
LLVM_ABI bool applyDebugifyMetadataToMachineFunction(DIBuilder &DIB, Function &F, llvm::function_ref< MachineFunction *(Function &)> GetMF)
LLVM_ABI ModulePass * createDebugifyMachineModulePass()
Creates MIR Debugify pass.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
#define N