LiveDebugValues.cpp 28 KB

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