LLVM  11.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 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/InitializePasses.h"
29 
30 #define DEBUG_TYPE "mir-debugify"
31 
32 using namespace llvm;
33 
34 namespace {
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;
42 
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;
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) {
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.
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 {
141  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 
151  DebugifyMachineModule() : ModulePass(ID) {}
152 
153  void getAnalysisUsage(AnalysisUsage &AU) const override {
156  AU.setPreservesCFG();
157  }
158 
159  static char ID; // Pass identification.
160 };
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 
171  return new DebugifyMachineModule();
172 }
iterator_range< use_iterator > uses()
Definition: Value.h:373
LLVM_NODISCARD std::enable_if_t< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > dyn_cast(const Y &Val)
Definition: Casting.h:334
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:67
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:409
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:187
unsigned getLine() const
Definition: DebugLoc.cpp:25
F(f)
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:559
bool isPHI() const
MachineBasicBlock & MBB
AnalysisUsage & addRequired()
const HexagonInstrInfo * TII
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:253
A Use represents the edge between a Value definition and its users.
Definition: Use.h:44
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:784
Subprogram description.
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:365
virtual const TargetInstrInfo * getInstrInfo() const
TargetInstrInfo - Interface to description of machine instruction set.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1172
iterator_range< iterator > functions()
Definition: Module.h:621
bool applyDebugifyMetadata(Module &M, iterator_range< Module::iterator > Functions, StringRef Banner, std::function< bool(DIBuilder &, Function &)> ApplyToMF)
Add synthesized debug information to a module.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1528
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Represent the analysis usage information of a pass.
ModulePass * createDebugifyMachineModulePass()
Creates MIR Debugify pass.
bool isDebugInstr() const
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr...
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:883
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
DWARF expression.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:174
Representation of each machine instruction.
Definition: MachineInstr.h:62
INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE, "Machine Debugify Module", false, false) INITIALIZE_PASS_END(DebugifyMachineModule
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:363
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
This represents the llvm.dbg.value instruction.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:62
static MachineOperand CreateImm(int64_t Val)
#define I(x, y, z)
Definition: MD5.cpp:59
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:145
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:572
IRTranslator LLVM IR MI
#define DEBUG_TYPE
This class contains meta information specific to a module.