MachineDebugify.cpp 7.6 KB

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