LiveDebugValues.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. //===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// This pass implements a data flow analysis that propagates debug location
  11. /// information by inserting additional DBG_VALUE instructions into the machine
  12. /// instruction stream. The pass internally builds debug location liveness
  13. /// ranges to determine the points where additional DBG_VALUEs need to be
  14. /// inserted.
  15. ///
  16. /// This is a separate pass from DbgValueHistoryCalculator to facilitate
  17. /// testing and improve modularity.
  18. ///
  19. //===----------------------------------------------------------------------===//
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/PostOrderIterator.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/SparseBitVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/ADT/UniqueVector.h"
  27. #include "llvm/CodeGen/LexicalScopes.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineFrameInfo.h"
  30. #include "llvm/CodeGen/MachineFunction.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineMemOperand.h"
  35. #include "llvm/CodeGen/MachineOperand.h"
  36. #include "llvm/CodeGen/PseudoSourceValue.h"
  37. #include "llvm/CodeGen/TargetFrameLowering.h"
  38. #include "llvm/CodeGen/TargetInstrInfo.h"
  39. #include "llvm/CodeGen/TargetLowering.h"
  40. #include "llvm/CodeGen/TargetRegisterInfo.h"
  41. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  42. #include "llvm/IR/DebugInfoMetadata.h"
  43. #include "llvm/IR/DebugLoc.h"
  44. #include "llvm/IR/Function.h"
  45. #include "llvm/IR/Module.h"
  46. #include "llvm/MC/MCRegisterInfo.h"
  47. #include "llvm/Pass.h"
  48. #include "llvm/Support/Casting.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/Debug.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. #include <algorithm>
  53. #include <cassert>
  54. #include <cstdint>
  55. #include <functional>
  56. #include <queue>
  57. #include <utility>
  58. #include <vector>
  59. using namespace llvm;
  60. #define DEBUG_TYPE "livedebugvalues"
  61. STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
  62. // \brief If @MI is a DBG_VALUE with debug value described by a defined
  63. // register, returns the number of this register. In the other case, returns 0.
  64. static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
  65. assert(MI.isDebugValue() && "expected a DBG_VALUE");
  66. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  67. // If location of variable is described using a register (directly
  68. // or indirectly), this register is always a first operand.
  69. return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
  70. }
  71. namespace {
  72. class LiveDebugValues : public MachineFunctionPass {
  73. private:
  74. const TargetRegisterInfo *TRI;
  75. const TargetInstrInfo *TII;
  76. const TargetFrameLowering *TFI;
  77. LexicalScopes LS;
  78. /// Keeps track of lexical scopes associated with a user value's source
  79. /// location.
  80. class UserValueScopes {
  81. DebugLoc DL;
  82. LexicalScopes &LS;
  83. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  84. public:
  85. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
  86. /// Return true if current scope dominates at least one machine
  87. /// instruction in a given machine basic block.
  88. bool dominates(MachineBasicBlock *MBB) {
  89. if (LBlocks.empty())
  90. LS.getMachineBasicBlocks(DL, LBlocks);
  91. return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
  92. }
  93. };
  94. /// Based on std::pair so it can be used as an index into a DenseMap.
  95. using DebugVariableBase =
  96. std::pair<const DILocalVariable *, const DILocation *>;
  97. /// A potentially inlined instance of a variable.
  98. struct DebugVariable : public DebugVariableBase {
  99. DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
  100. : DebugVariableBase(Var, InlinedAt) {}
  101. const DILocalVariable *getVar() const { return this->first; }
  102. const DILocation *getInlinedAt() const { return this->second; }
  103. bool operator<(const DebugVariable &DV) const {
  104. if (getVar() == DV.getVar())
  105. return getInlinedAt() < DV.getInlinedAt();
  106. return getVar() < DV.getVar();
  107. }
  108. };
  109. /// A pair of debug variable and value location.
  110. struct VarLoc {
  111. const DebugVariable Var;
  112. const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
  113. mutable UserValueScopes UVS;
  114. enum { InvalidKind = 0, RegisterKind } Kind = InvalidKind;
  115. /// The value location. Stored separately to avoid repeatedly
  116. /// extracting it from MI.
  117. union {
  118. uint64_t RegNo;
  119. uint64_t Hash;
  120. } Loc;
  121. VarLoc(const MachineInstr &MI, LexicalScopes &LS)
  122. : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
  123. UVS(MI.getDebugLoc(), LS) {
  124. static_assert((sizeof(Loc) == sizeof(uint64_t)),
  125. "hash does not cover all members of Loc");
  126. assert(MI.isDebugValue() && "not a DBG_VALUE");
  127. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  128. if (int RegNo = isDbgValueDescribedByReg(MI)) {
  129. Kind = RegisterKind;
  130. Loc.RegNo = RegNo;
  131. }
  132. }
  133. /// If this variable is described by a register, return it,
  134. /// otherwise return 0.
  135. unsigned isDescribedByReg() const {
  136. if (Kind == RegisterKind)
  137. return Loc.RegNo;
  138. return 0;
  139. }
  140. /// Determine whether the lexical scope of this value's debug location
  141. /// dominates MBB.
  142. bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
  143. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  144. LLVM_DUMP_METHOD void dump() const { MI.dump(); }
  145. #endif
  146. bool operator==(const VarLoc &Other) const {
  147. return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
  148. }
  149. /// This operator guarantees that VarLocs are sorted by Variable first.
  150. bool operator<(const VarLoc &Other) const {
  151. if (Var == Other.Var)
  152. return Loc.Hash < Other.Loc.Hash;
  153. return Var < Other.Var;
  154. }
  155. };
  156. using VarLocMap = UniqueVector<VarLoc>;
  157. using VarLocSet = SparseBitVector<>;
  158. using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
  159. struct SpillDebugPair {
  160. MachineInstr *SpillInst;
  161. MachineInstr *DebugInst;
  162. };
  163. using SpillMap = SmallVector<SpillDebugPair, 4>;
  164. /// This holds the working set of currently open ranges. For fast
  165. /// access, this is done both as a set of VarLocIDs, and a map of
  166. /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
  167. /// previous open ranges for the same variable.
  168. class OpenRangesSet {
  169. VarLocSet VarLocs;
  170. SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
  171. public:
  172. const VarLocSet &getVarLocs() const { return VarLocs; }
  173. /// Terminate all open ranges for Var by removing it from the set.
  174. void erase(DebugVariable Var) {
  175. auto It = Vars.find(Var);
  176. if (It != Vars.end()) {
  177. unsigned ID = It->second;
  178. VarLocs.reset(ID);
  179. Vars.erase(It);
  180. }
  181. }
  182. /// Terminate all open ranges listed in \c KillSet by removing
  183. /// them from the set.
  184. void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
  185. VarLocs.intersectWithComplement(KillSet);
  186. for (unsigned ID : KillSet)
  187. Vars.erase(VarLocIDs[ID].Var);
  188. }
  189. /// Insert a new range into the set.
  190. void insert(unsigned VarLocID, DebugVariableBase Var) {
  191. VarLocs.set(VarLocID);
  192. Vars.insert({Var, VarLocID});
  193. }
  194. /// Empty the set.
  195. void clear() {
  196. VarLocs.clear();
  197. Vars.clear();
  198. }
  199. /// Return whether the set is empty or not.
  200. bool empty() const {
  201. assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
  202. return VarLocs.empty();
  203. }
  204. };
  205. bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
  206. unsigned &Reg);
  207. int extractSpillBaseRegAndOffset(const MachineInstr &MI, unsigned &Reg);
  208. void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
  209. VarLocMap &VarLocIDs);
  210. void transferSpillInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  211. VarLocMap &VarLocIDs, SpillMap &Spills);
  212. void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
  213. const VarLocMap &VarLocIDs);
  214. bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  215. VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
  216. bool transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
  217. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs, SpillMap &Spills,
  218. bool transferSpills);
  219. bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  220. const VarLocMap &VarLocIDs,
  221. SmallPtrSet<const MachineBasicBlock *, 16> &Visited);
  222. bool ExtendRanges(MachineFunction &MF);
  223. public:
  224. static char ID;
  225. /// Default construct and initialize the pass.
  226. LiveDebugValues();
  227. /// Tell the pass manager which passes we depend on and what
  228. /// information we preserve.
  229. void getAnalysisUsage(AnalysisUsage &AU) const override;
  230. MachineFunctionProperties getRequiredProperties() const override {
  231. return MachineFunctionProperties().set(
  232. MachineFunctionProperties::Property::NoVRegs);
  233. }
  234. /// Print to ostream with a message.
  235. void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
  236. const VarLocMap &VarLocIDs, const char *msg,
  237. raw_ostream &Out) const;
  238. /// Calculate the liveness information for the given machine function.
  239. bool runOnMachineFunction(MachineFunction &MF) override;
  240. };
  241. } // end anonymous namespace
  242. //===----------------------------------------------------------------------===//
  243. // Implementation
  244. //===----------------------------------------------------------------------===//
  245. char LiveDebugValues::ID = 0;
  246. char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
  247. INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
  248. false, false)
  249. /// Default construct and initialize the pass.
  250. LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
  251. initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
  252. }
  253. /// Tell the pass manager which passes we depend on and what information we
  254. /// preserve.
  255. void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
  256. AU.setPreservesCFG();
  257. MachineFunctionPass::getAnalysisUsage(AU);
  258. }
  259. //===----------------------------------------------------------------------===//
  260. // Debug Range Extension Implementation
  261. //===----------------------------------------------------------------------===//
  262. #ifndef NDEBUG
  263. void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
  264. const VarLocInMBB &V,
  265. const VarLocMap &VarLocIDs,
  266. const char *msg,
  267. raw_ostream &Out) const {
  268. Out << '\n' << msg << '\n';
  269. for (const MachineBasicBlock &BB : MF) {
  270. const auto &L = V.lookup(&BB);
  271. Out << "MBB: " << BB.getName() << ":\n";
  272. for (unsigned VLL : L) {
  273. const VarLoc &VL = VarLocIDs[VLL];
  274. Out << " Var: " << VL.Var.getVar()->getName();
  275. Out << " MI: ";
  276. VL.dump();
  277. }
  278. }
  279. Out << "\n";
  280. }
  281. #endif
  282. /// Given a spill instruction, extract the register and offset used to
  283. /// address the spill location in a target independent way.
  284. int LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI,
  285. unsigned &Reg) {
  286. assert(MI.hasOneMemOperand() &&
  287. "Spill instruction does not have exactly one memory operand?");
  288. auto MMOI = MI.memoperands_begin();
  289. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  290. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  291. "Inconsistent memory operand in spill instruction");
  292. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  293. const MachineBasicBlock *MBB = MI.getParent();
  294. return TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  295. }
  296. /// End all previous ranges related to @MI and start a new range from @MI
  297. /// if it is a DBG_VALUE instr.
  298. void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
  299. OpenRangesSet &OpenRanges,
  300. VarLocMap &VarLocIDs) {
  301. if (!MI.isDebugValue())
  302. return;
  303. const DILocalVariable *Var = MI.getDebugVariable();
  304. const DILocation *DebugLoc = MI.getDebugLoc();
  305. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  306. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  307. "Expected inlined-at fields to agree");
  308. // End all previous ranges of Var.
  309. DebugVariable V(Var, InlinedAt);
  310. OpenRanges.erase(V);
  311. // Add the VarLoc to OpenRanges from this DBG_VALUE.
  312. // TODO: Currently handles DBG_VALUE which has only reg as location.
  313. if (isDbgValueDescribedByReg(MI)) {
  314. VarLoc VL(MI, LS);
  315. unsigned ID = VarLocIDs.insert(VL);
  316. OpenRanges.insert(ID, VL.Var);
  317. }
  318. }
  319. /// A definition of a register may mark the end of a range.
  320. void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
  321. OpenRangesSet &OpenRanges,
  322. const VarLocMap &VarLocIDs) {
  323. MachineFunction *MF = MI.getMF();
  324. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  325. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  326. SparseBitVector<> KillSet;
  327. for (const MachineOperand &MO : MI.operands()) {
  328. // Determine whether the operand is a register def. Assume that call
  329. // instructions never clobber SP, because some backends (e.g., AArch64)
  330. // never list SP in the regmask.
  331. if (MO.isReg() && MO.isDef() && MO.getReg() &&
  332. TRI->isPhysicalRegister(MO.getReg()) &&
  333. !(MI.isCall() && MO.getReg() == SP)) {
  334. // Remove ranges of all aliased registers.
  335. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  336. for (unsigned ID : OpenRanges.getVarLocs())
  337. if (VarLocIDs[ID].isDescribedByReg() == *RAI)
  338. KillSet.set(ID);
  339. } else if (MO.isRegMask()) {
  340. // Remove ranges of all clobbered registers. Register masks don't usually
  341. // list SP as preserved. While the debug info may be off for an
  342. // instruction or two around callee-cleanup calls, transferring the
  343. // DEBUG_VALUE across the call is still a better user experience.
  344. for (unsigned ID : OpenRanges.getVarLocs()) {
  345. unsigned Reg = VarLocIDs[ID].isDescribedByReg();
  346. if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
  347. KillSet.set(ID);
  348. }
  349. }
  350. }
  351. OpenRanges.erase(KillSet, VarLocIDs);
  352. }
  353. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  354. /// criteria to make this decision:
  355. /// - Is this instruction a store to a spill slot?
  356. /// - Is there a register operand that is both used and killed?
  357. /// TODO: Store optimization can fold spills into other stores (including
  358. /// other spills). We do not handle this yet (more than one memory operand).
  359. bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
  360. MachineFunction *MF, unsigned &Reg) {
  361. const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
  362. int FI;
  363. const MachineMemOperand *MMO;
  364. // TODO: Handle multiple stores folded into one.
  365. if (!MI.hasOneMemOperand())
  366. return false;
  367. // To identify a spill instruction, use the same criteria as in AsmPrinter.
  368. if (!((TII->isStoreToStackSlotPostFE(MI, FI) ||
  369. TII->hasStoreToStackSlot(MI, MMO, FI)) &&
  370. FrameInfo.isSpillSlotObjectIndex(FI)))
  371. return false;
  372. // In a spill instruction generated by the InlineSpiller the spilled register
  373. // has its kill flag set. Return false if we don't find such a register.
  374. Reg = 0;
  375. for (const MachineOperand &MO : MI.operands()) {
  376. if (MO.isReg() && MO.isUse() && MO.isKill()) {
  377. Reg = MO.getReg();
  378. break;
  379. }
  380. }
  381. return Reg != 0;
  382. }
  383. /// A spilled register may indicate that we have to end the current range of
  384. /// a variable and create a new one for the spill location.
  385. /// We don't want to insert any instructions in transfer(), so we just create
  386. /// the DBG_VALUE witout inserting it and keep track of it in @Spills.
  387. /// It will be inserted into the BB when we're done iterating over the
  388. /// instructions.
  389. void LiveDebugValues::transferSpillInst(MachineInstr &MI,
  390. OpenRangesSet &OpenRanges,
  391. VarLocMap &VarLocIDs,
  392. SpillMap &Spills) {
  393. unsigned Reg;
  394. MachineFunction *MF = MI.getMF();
  395. if (!isSpillInstruction(MI, MF, Reg))
  396. return;
  397. // Check if the register is the location of a debug value.
  398. for (unsigned ID : OpenRanges.getVarLocs()) {
  399. if (VarLocIDs[ID].isDescribedByReg() == Reg) {
  400. DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
  401. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  402. // Create a DBG_VALUE instruction to describe the Var in its spilled
  403. // location, but don't insert it yet to avoid invalidating the
  404. // iterator in our caller.
  405. unsigned SpillBase;
  406. int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
  407. const MachineInstr *DMI = &VarLocIDs[ID].MI;
  408. auto *SpillExpr = DIExpression::prepend(
  409. DMI->getDebugExpression(), DIExpression::NoDeref, SpillOffset);
  410. MachineInstr *SpDMI =
  411. BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase,
  412. DMI->getDebugVariable(), SpillExpr);
  413. DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
  414. SpDMI->print(dbgs(), false, TII));
  415. // The newly created DBG_VALUE instruction SpDMI must be inserted after
  416. // MI. Keep track of the pairing.
  417. SpillDebugPair MIP = {&MI, SpDMI};
  418. Spills.push_back(MIP);
  419. // End all previous ranges of Var.
  420. OpenRanges.erase(VarLocIDs[ID].Var);
  421. // Add the VarLoc to OpenRanges.
  422. VarLoc VL(*SpDMI, LS);
  423. unsigned SpillLocID = VarLocIDs.insert(VL);
  424. OpenRanges.insert(SpillLocID, VL.Var);
  425. return;
  426. }
  427. }
  428. }
  429. /// Terminate all open ranges at the end of the current basic block.
  430. bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
  431. OpenRangesSet &OpenRanges,
  432. VarLocInMBB &OutLocs,
  433. const VarLocMap &VarLocIDs) {
  434. bool Changed = false;
  435. const MachineBasicBlock *CurMBB = MI.getParent();
  436. if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
  437. return false;
  438. if (OpenRanges.empty())
  439. return false;
  440. DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) {
  441. // Copy OpenRanges to OutLocs, if not already present.
  442. dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump();
  443. });
  444. VarLocSet &VLS = OutLocs[CurMBB];
  445. Changed = VLS |= OpenRanges.getVarLocs();
  446. OpenRanges.clear();
  447. return Changed;
  448. }
  449. /// This routine creates OpenRanges and OutLocs.
  450. bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
  451. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  452. SpillMap &Spills, bool transferSpills) {
  453. bool Changed = false;
  454. transferDebugValue(MI, OpenRanges, VarLocIDs);
  455. transferRegisterDef(MI, OpenRanges, VarLocIDs);
  456. if (transferSpills)
  457. transferSpillInst(MI, OpenRanges, VarLocIDs, Spills);
  458. Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
  459. return Changed;
  460. }
  461. /// This routine joins the analysis results of all incoming edges in @MBB by
  462. /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
  463. /// source variable in all the predecessors of @MBB reside in the same location.
  464. bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs,
  465. VarLocInMBB &InLocs, const VarLocMap &VarLocIDs,
  466. SmallPtrSet<const MachineBasicBlock *, 16> &Visited) {
  467. DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n");
  468. bool Changed = false;
  469. VarLocSet InLocsT; // Temporary incoming locations.
  470. // For all predecessors of this MBB, find the set of VarLocs that
  471. // can be joined.
  472. int NumVisited = 0;
  473. for (auto p : MBB.predecessors()) {
  474. // Ignore unvisited predecessor blocks. As we are processing
  475. // the blocks in reverse post-order any unvisited block can
  476. // be considered to not remove any incoming values.
  477. if (!Visited.count(p))
  478. continue;
  479. auto OL = OutLocs.find(p);
  480. // Join is null in case of empty OutLocs from any of the pred.
  481. if (OL == OutLocs.end())
  482. return false;
  483. // Just copy over the Out locs to incoming locs for the first visited
  484. // predecessor, and for all other predecessors join the Out locs.
  485. if (!NumVisited)
  486. InLocsT = OL->second;
  487. else
  488. InLocsT &= OL->second;
  489. NumVisited++;
  490. }
  491. // Filter out DBG_VALUES that are out of scope.
  492. VarLocSet KillSet;
  493. for (auto ID : InLocsT)
  494. if (!VarLocIDs[ID].dominates(MBB))
  495. KillSet.set(ID);
  496. InLocsT.intersectWithComplement(KillSet);
  497. // As we are processing blocks in reverse post-order we
  498. // should have processed at least one predecessor, unless it
  499. // is the entry block which has no predecessor.
  500. assert((NumVisited || MBB.pred_empty()) &&
  501. "Should have processed at least one predecessor");
  502. if (InLocsT.empty())
  503. return false;
  504. VarLocSet &ILS = InLocs[&MBB];
  505. // Insert DBG_VALUE instructions, if not already inserted.
  506. VarLocSet Diff = InLocsT;
  507. Diff.intersectWithComplement(ILS);
  508. for (auto ID : Diff) {
  509. // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
  510. // new range is started for the var from the mbb's beginning by inserting
  511. // a new DBG_VALUE. transfer() will end this range however appropriate.
  512. const VarLoc &DiffIt = VarLocIDs[ID];
  513. const MachineInstr *DMI = &DiffIt.MI;
  514. MachineInstr *MI =
  515. BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
  516. DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(),
  517. DMI->getDebugVariable(), DMI->getDebugExpression());
  518. if (DMI->isIndirectDebugValue())
  519. MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
  520. DEBUG(dbgs() << "Inserted: "; MI->dump(););
  521. ILS.set(ID);
  522. ++NumInserted;
  523. Changed = true;
  524. }
  525. return Changed;
  526. }
  527. /// Calculate the liveness information for the given machine function and
  528. /// extend ranges across basic blocks.
  529. bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
  530. DEBUG(dbgs() << "\nDebug Range Extension\n");
  531. bool Changed = false;
  532. bool OLChanged = false;
  533. bool MBBJoined = false;
  534. VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
  535. OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
  536. VarLocInMBB OutLocs; // Ranges that exist beyond bb.
  537. VarLocInMBB InLocs; // Ranges that are incoming after joining.
  538. SpillMap Spills; // DBG_VALUEs associated with spills.
  539. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  540. DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
  541. std::priority_queue<unsigned int, std::vector<unsigned int>,
  542. std::greater<unsigned int>>
  543. Worklist;
  544. std::priority_queue<unsigned int, std::vector<unsigned int>,
  545. std::greater<unsigned int>>
  546. Pending;
  547. // Initialize every mbb with OutLocs.
  548. // We are not looking at any spill instructions during the initial pass
  549. // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
  550. // instructions for spills of registers that are known to be user variables
  551. // within the BB in which the spill occurs.
  552. for (auto &MBB : MF)
  553. for (auto &MI : MBB)
  554. transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
  555. /*transferSpills=*/false);
  556. DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization",
  557. dbgs()));
  558. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  559. unsigned int RPONumber = 0;
  560. for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
  561. OrderToBB[RPONumber] = *RI;
  562. BBToOrder[*RI] = RPONumber;
  563. Worklist.push(RPONumber);
  564. ++RPONumber;
  565. }
  566. // This is a standard "union of predecessor outs" dataflow problem.
  567. // To solve it, we perform join() and transfer() using the two worklist method
  568. // until the ranges converge.
  569. // Ranges have converged when both worklists are empty.
  570. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  571. while (!Worklist.empty() || !Pending.empty()) {
  572. // We track what is on the pending worklist to avoid inserting the same
  573. // thing twice. We could avoid this with a custom priority queue, but this
  574. // is probably not worth it.
  575. SmallPtrSet<MachineBasicBlock *, 16> OnPending;
  576. DEBUG(dbgs() << "Processing Worklist\n");
  577. while (!Worklist.empty()) {
  578. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  579. Worklist.pop();
  580. MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited);
  581. Visited.insert(MBB);
  582. if (MBBJoined) {
  583. MBBJoined = false;
  584. Changed = true;
  585. // Now that we have started to extend ranges across BBs we need to
  586. // examine spill instructions to see whether they spill registers that
  587. // correspond to user variables.
  588. for (auto &MI : *MBB)
  589. OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
  590. /*transferSpills=*/true);
  591. // Add any DBG_VALUE instructions necessitated by spills.
  592. for (auto &SP : Spills)
  593. MBB->insertAfter(MachineBasicBlock::iterator(*SP.SpillInst),
  594. SP.DebugInst);
  595. Spills.clear();
  596. DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  597. "OutLocs after propagating", dbgs()));
  598. DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
  599. "InLocs after propagating", dbgs()));
  600. if (OLChanged) {
  601. OLChanged = false;
  602. for (auto s : MBB->successors())
  603. if (OnPending.insert(s).second) {
  604. Pending.push(BBToOrder[s]);
  605. }
  606. }
  607. }
  608. }
  609. Worklist.swap(Pending);
  610. // At this point, pending must be empty, since it was just the empty
  611. // worklist
  612. assert(Pending.empty() && "Pending should be empty");
  613. }
  614. DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
  615. DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
  616. return Changed;
  617. }
  618. bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
  619. if (!MF.getFunction().getSubprogram())
  620. // LiveDebugValues will already have removed all DBG_VALUEs.
  621. return false;
  622. // Skip functions from NoDebug compilation units.
  623. if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  624. DICompileUnit::NoDebug)
  625. return false;
  626. TRI = MF.getSubtarget().getRegisterInfo();
  627. TII = MF.getSubtarget().getInstrInfo();
  628. TFI = MF.getSubtarget().getFrameLowering();
  629. LS.initialize(MF);
  630. bool Changed = ExtendRanges(MF);
  631. return Changed;
  632. }