LiveDebugValues.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. //===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
  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. /// This pass implements a data flow analysis that propagates debug location
  10. /// information by inserting additional DBG_VALUE instructions into the machine
  11. /// instruction stream. The pass internally builds debug location liveness
  12. /// ranges to determine the points where additional DBG_VALUEs need to be
  13. /// inserted.
  14. ///
  15. /// This is a separate pass from DbgValueHistoryCalculator to facilitate
  16. /// testing and improve modularity.
  17. ///
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/SparseBitVector.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/ADT/UniqueVector.h"
  26. #include "llvm/CodeGen/LexicalScopes.h"
  27. #include "llvm/CodeGen/MachineBasicBlock.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineFunction.h"
  30. #include "llvm/CodeGen/MachineFunctionPass.h"
  31. #include "llvm/CodeGen/MachineInstr.h"
  32. #include "llvm/CodeGen/MachineInstrBuilder.h"
  33. #include "llvm/CodeGen/MachineMemOperand.h"
  34. #include "llvm/CodeGen/MachineOperand.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/CodeGen/RegisterScavenging.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/DIBuilder.h"
  44. #include "llvm/IR/DebugInfoMetadata.h"
  45. #include "llvm/IR/DebugLoc.h"
  46. #include "llvm/IR/Function.h"
  47. #include "llvm/IR/Module.h"
  48. #include "llvm/MC/MCRegisterInfo.h"
  49. #include "llvm/Pass.h"
  50. #include "llvm/Support/Casting.h"
  51. #include "llvm/Support/Compiler.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <algorithm>
  55. #include <cassert>
  56. #include <cstdint>
  57. #include <functional>
  58. #include <queue>
  59. #include <utility>
  60. #include <vector>
  61. using namespace llvm;
  62. #define DEBUG_TYPE "livedebugvalues"
  63. STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
  64. // If @MI is a DBG_VALUE with debug value described by a defined
  65. // register, returns the number of this register. In the other case, returns 0.
  66. static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
  67. assert(MI.isDebugValue() && "expected a DBG_VALUE");
  68. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  69. // If location of variable is described using a register (directly
  70. // or indirectly), this register is always a first operand.
  71. return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
  72. }
  73. namespace {
  74. class LiveDebugValues : public MachineFunctionPass {
  75. private:
  76. const TargetRegisterInfo *TRI;
  77. const TargetInstrInfo *TII;
  78. const TargetFrameLowering *TFI;
  79. BitVector CalleeSavedRegs;
  80. LexicalScopes LS;
  81. enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
  82. /// Keeps track of lexical scopes associated with a user value's source
  83. /// location.
  84. class UserValueScopes {
  85. DebugLoc DL;
  86. LexicalScopes &LS;
  87. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  88. public:
  89. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
  90. /// Return true if current scope dominates at least one machine
  91. /// instruction in a given machine basic block.
  92. bool dominates(MachineBasicBlock *MBB) {
  93. if (LBlocks.empty())
  94. LS.getMachineBasicBlocks(DL, LBlocks);
  95. return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
  96. }
  97. };
  98. /// Based on std::pair so it can be used as an index into a DenseMap.
  99. using DebugVariableBase =
  100. std::pair<const DILocalVariable *, const DILocation *>;
  101. /// A potentially inlined instance of a variable.
  102. struct DebugVariable : public DebugVariableBase {
  103. DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
  104. : DebugVariableBase(Var, InlinedAt) {}
  105. const DILocalVariable *getVar() const { return this->first; }
  106. const DILocation *getInlinedAt() const { return this->second; }
  107. bool operator<(const DebugVariable &DV) const {
  108. if (getVar() == DV.getVar())
  109. return getInlinedAt() < DV.getInlinedAt();
  110. return getVar() < DV.getVar();
  111. }
  112. };
  113. /// A pair of debug variable and value location.
  114. struct VarLoc {
  115. // The location at which a spilled variable resides. It consists of a
  116. // register and an offset.
  117. struct SpillLoc {
  118. unsigned SpillBase;
  119. int SpillOffset;
  120. bool operator==(const SpillLoc &Other) const {
  121. return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
  122. }
  123. };
  124. const DebugVariable Var;
  125. const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
  126. mutable UserValueScopes UVS;
  127. enum VarLocKind {
  128. InvalidKind = 0,
  129. RegisterKind,
  130. SpillLocKind
  131. } Kind = InvalidKind;
  132. /// The value location. Stored separately to avoid repeatedly
  133. /// extracting it from MI.
  134. union {
  135. uint64_t RegNo;
  136. SpillLoc SpillLocation;
  137. uint64_t Hash;
  138. } Loc;
  139. VarLoc(const MachineInstr &MI, LexicalScopes &LS)
  140. : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
  141. UVS(MI.getDebugLoc(), LS) {
  142. static_assert((sizeof(Loc) == sizeof(uint64_t)),
  143. "hash does not cover all members of Loc");
  144. assert(MI.isDebugValue() && "not a DBG_VALUE");
  145. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  146. if (int RegNo = isDbgValueDescribedByReg(MI)) {
  147. Kind = RegisterKind;
  148. Loc.RegNo = RegNo;
  149. }
  150. }
  151. /// The constructor for spill locations.
  152. VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
  153. LexicalScopes &LS)
  154. : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
  155. UVS(MI.getDebugLoc(), LS) {
  156. assert(MI.isDebugValue() && "not a DBG_VALUE");
  157. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  158. Kind = SpillLocKind;
  159. Loc.SpillLocation = {SpillBase, SpillOffset};
  160. }
  161. /// If this variable is described by a register, return it,
  162. /// otherwise return 0.
  163. unsigned isDescribedByReg() const {
  164. if (Kind == RegisterKind)
  165. return Loc.RegNo;
  166. return 0;
  167. }
  168. /// Determine whether the lexical scope of this value's debug location
  169. /// dominates MBB.
  170. bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
  171. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  172. LLVM_DUMP_METHOD void dump() const { MI.dump(); }
  173. #endif
  174. bool operator==(const VarLoc &Other) const {
  175. return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
  176. }
  177. /// This operator guarantees that VarLocs are sorted by Variable first.
  178. bool operator<(const VarLoc &Other) const {
  179. if (Var == Other.Var)
  180. return Loc.Hash < Other.Loc.Hash;
  181. return Var < Other.Var;
  182. }
  183. };
  184. using VarLocMap = UniqueVector<VarLoc>;
  185. using VarLocSet = SparseBitVector<>;
  186. using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
  187. struct TransferDebugPair {
  188. MachineInstr *TransferInst;
  189. MachineInstr *DebugInst;
  190. };
  191. using TransferMap = SmallVector<TransferDebugPair, 4>;
  192. /// This holds the working set of currently open ranges. For fast
  193. /// access, this is done both as a set of VarLocIDs, and a map of
  194. /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
  195. /// previous open ranges for the same variable.
  196. class OpenRangesSet {
  197. VarLocSet VarLocs;
  198. SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
  199. public:
  200. const VarLocSet &getVarLocs() const { return VarLocs; }
  201. /// Terminate all open ranges for Var by removing it from the set.
  202. void erase(DebugVariable Var) {
  203. auto It = Vars.find(Var);
  204. if (It != Vars.end()) {
  205. unsigned ID = It->second;
  206. VarLocs.reset(ID);
  207. Vars.erase(It);
  208. }
  209. }
  210. /// Terminate all open ranges listed in \c KillSet by removing
  211. /// them from the set.
  212. void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
  213. VarLocs.intersectWithComplement(KillSet);
  214. for (unsigned ID : KillSet)
  215. Vars.erase(VarLocIDs[ID].Var);
  216. }
  217. /// Insert a new range into the set.
  218. void insert(unsigned VarLocID, DebugVariableBase Var) {
  219. VarLocs.set(VarLocID);
  220. Vars.insert({Var, VarLocID});
  221. }
  222. /// Empty the set.
  223. void clear() {
  224. VarLocs.clear();
  225. Vars.clear();
  226. }
  227. /// Return whether the set is empty or not.
  228. bool empty() const {
  229. assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
  230. return VarLocs.empty();
  231. }
  232. };
  233. bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
  234. unsigned &Reg);
  235. /// If a given instruction is identified as a spill, return the spill location
  236. /// and set \p Reg to the spilled register.
  237. Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
  238. MachineFunction *MF,
  239. unsigned &Reg);
  240. /// Given a spill instruction, extract the register and offset used to
  241. /// address the spill location in a target independent way.
  242. VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
  243. void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
  244. TransferMap &Transfers, VarLocMap &VarLocIDs,
  245. unsigned OldVarID, TransferKind Kind,
  246. unsigned NewReg = 0);
  247. void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
  248. VarLocMap &VarLocIDs);
  249. void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  250. VarLocMap &VarLocIDs, TransferMap &Transfers);
  251. void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
  252. VarLocMap &VarLocIDs, TransferMap &Transfers);
  253. void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
  254. const VarLocMap &VarLocIDs);
  255. bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  256. VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
  257. bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  258. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  259. TransferMap &Transfers, bool transferChanges);
  260. bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  261. const VarLocMap &VarLocIDs,
  262. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  263. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
  264. bool ExtendRanges(MachineFunction &MF);
  265. public:
  266. static char ID;
  267. /// Default construct and initialize the pass.
  268. LiveDebugValues();
  269. /// Tell the pass manager which passes we depend on and what
  270. /// information we preserve.
  271. void getAnalysisUsage(AnalysisUsage &AU) const override;
  272. MachineFunctionProperties getRequiredProperties() const override {
  273. return MachineFunctionProperties().set(
  274. MachineFunctionProperties::Property::NoVRegs);
  275. }
  276. /// Print to ostream with a message.
  277. void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
  278. const VarLocMap &VarLocIDs, const char *msg,
  279. raw_ostream &Out) const;
  280. /// Calculate the liveness information for the given machine function.
  281. bool runOnMachineFunction(MachineFunction &MF) override;
  282. };
  283. } // end anonymous namespace
  284. //===----------------------------------------------------------------------===//
  285. // Implementation
  286. //===----------------------------------------------------------------------===//
  287. char LiveDebugValues::ID = 0;
  288. char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
  289. INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
  290. false, false)
  291. /// Default construct and initialize the pass.
  292. LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
  293. initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
  294. }
  295. /// Tell the pass manager which passes we depend on and what information we
  296. /// preserve.
  297. void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
  298. AU.setPreservesCFG();
  299. MachineFunctionPass::getAnalysisUsage(AU);
  300. }
  301. //===----------------------------------------------------------------------===//
  302. // Debug Range Extension Implementation
  303. //===----------------------------------------------------------------------===//
  304. #ifndef NDEBUG
  305. void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
  306. const VarLocInMBB &V,
  307. const VarLocMap &VarLocIDs,
  308. const char *msg,
  309. raw_ostream &Out) const {
  310. Out << '\n' << msg << '\n';
  311. for (const MachineBasicBlock &BB : MF) {
  312. const VarLocSet &L = V.lookup(&BB);
  313. if (L.empty())
  314. continue;
  315. Out << "MBB: " << BB.getNumber() << ":\n";
  316. for (unsigned VLL : L) {
  317. const VarLoc &VL = VarLocIDs[VLL];
  318. Out << " Var: " << VL.Var.getVar()->getName();
  319. Out << " MI: ";
  320. VL.dump();
  321. }
  322. }
  323. Out << "\n";
  324. }
  325. #endif
  326. LiveDebugValues::VarLoc::SpillLoc
  327. LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
  328. assert(MI.hasOneMemOperand() &&
  329. "Spill instruction does not have exactly one memory operand?");
  330. auto MMOI = MI.memoperands_begin();
  331. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  332. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  333. "Inconsistent memory operand in spill instruction");
  334. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  335. const MachineBasicBlock *MBB = MI.getParent();
  336. unsigned Reg;
  337. int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  338. return {Reg, Offset};
  339. }
  340. /// End all previous ranges related to @MI and start a new range from @MI
  341. /// if it is a DBG_VALUE instr.
  342. void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
  343. OpenRangesSet &OpenRanges,
  344. VarLocMap &VarLocIDs) {
  345. if (!MI.isDebugValue())
  346. return;
  347. const DILocalVariable *Var = MI.getDebugVariable();
  348. const DILocation *DebugLoc = MI.getDebugLoc();
  349. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  350. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  351. "Expected inlined-at fields to agree");
  352. // End all previous ranges of Var.
  353. DebugVariable V(Var, InlinedAt);
  354. OpenRanges.erase(V);
  355. // Add the VarLoc to OpenRanges from this DBG_VALUE.
  356. // TODO: Currently handles DBG_VALUE which has only reg as location.
  357. if (isDbgValueDescribedByReg(MI)) {
  358. VarLoc VL(MI, LS);
  359. unsigned ID = VarLocIDs.insert(VL);
  360. OpenRanges.insert(ID, VL.Var);
  361. }
  362. }
  363. /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
  364. /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
  365. /// new VarLoc. If \p NewReg is different than default zero value then the
  366. /// new location will be register location created by the copy like instruction,
  367. /// otherwise it is variable's location on the stack.
  368. void LiveDebugValues::insertTransferDebugPair(
  369. MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
  370. VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
  371. unsigned NewReg) {
  372. const MachineInstr *DMI = &VarLocIDs[OldVarID].MI;
  373. MachineFunction *MF = MI.getParent()->getParent();
  374. MachineInstr *NewDMI;
  375. auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers,
  376. &VarLocIDs](VarLoc &VL, MachineInstr *NewDMI) {
  377. unsigned LocId = VarLocIDs.insert(VL);
  378. OpenRanges.insert(LocId, VL.Var);
  379. // The newly created DBG_VALUE instruction NewDMI must be inserted after
  380. // MI. Keep track of the pairing.
  381. TransferDebugPair MIP = {&MI, NewDMI};
  382. Transfers.push_back(MIP);
  383. };
  384. // End all previous ranges of Var.
  385. OpenRanges.erase(VarLocIDs[OldVarID].Var);
  386. switch (Kind) {
  387. case TransferKind::TransferCopy: {
  388. assert(NewReg &&
  389. "No register supplied when handling a copy of a debug value");
  390. // Create a DBG_VALUE instruction to describe the Var in its new
  391. // register location.
  392. NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(),
  393. DMI->isIndirectDebugValue(), NewReg,
  394. DMI->getDebugVariable(), DMI->getDebugExpression());
  395. if (DMI->isIndirectDebugValue())
  396. NewDMI->getOperand(1).setImm(DMI->getOperand(1).getImm());
  397. VarLoc VL(*NewDMI, LS);
  398. ProcessVarLoc(VL, NewDMI);
  399. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
  400. NewDMI->print(dbgs(), false, false, false, TII));
  401. return;
  402. }
  403. case TransferKind::TransferSpill: {
  404. // Create a DBG_VALUE instruction to describe the Var in its spilled
  405. // location.
  406. VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
  407. auto *SpillExpr =
  408. DIExpression::prepend(DMI->getDebugExpression(), DIExpression::NoDeref,
  409. SpillLocation.SpillOffset);
  410. NewDMI =
  411. BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true,
  412. SpillLocation.SpillBase, DMI->getDebugVariable(), SpillExpr);
  413. VarLoc VL(*NewDMI, SpillLocation.SpillBase, SpillLocation.SpillOffset, LS);
  414. ProcessVarLoc(VL, NewDMI);
  415. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
  416. NewDMI->print(dbgs(), false, false, false, TII));
  417. return;
  418. }
  419. case TransferKind::TransferRestore: {
  420. assert(NewReg &&
  421. "No register supplied when handling a restore of a debug value");
  422. MachineFunction *MF = MI.getMF();
  423. DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
  424. NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), false, NewReg,
  425. DMI->getDebugVariable(), DIB.createExpression());
  426. VarLoc VL(*NewDMI, LS);
  427. ProcessVarLoc(VL, NewDMI);
  428. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
  429. NewDMI->print(dbgs(), false, false, false, TII));
  430. return;
  431. }
  432. }
  433. llvm_unreachable("Invalid transfer kind");
  434. }
  435. /// A definition of a register may mark the end of a range.
  436. void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
  437. OpenRangesSet &OpenRanges,
  438. const VarLocMap &VarLocIDs) {
  439. MachineFunction *MF = MI.getMF();
  440. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  441. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  442. SparseBitVector<> KillSet;
  443. for (const MachineOperand &MO : MI.operands()) {
  444. // Determine whether the operand is a register def. Assume that call
  445. // instructions never clobber SP, because some backends (e.g., AArch64)
  446. // never list SP in the regmask.
  447. if (MO.isReg() && MO.isDef() && MO.getReg() &&
  448. TRI->isPhysicalRegister(MO.getReg()) &&
  449. !(MI.isCall() && MO.getReg() == SP)) {
  450. // Remove ranges of all aliased registers.
  451. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  452. for (unsigned ID : OpenRanges.getVarLocs())
  453. if (VarLocIDs[ID].isDescribedByReg() == *RAI)
  454. KillSet.set(ID);
  455. } else if (MO.isRegMask()) {
  456. // Remove ranges of all clobbered registers. Register masks don't usually
  457. // list SP as preserved. While the debug info may be off for an
  458. // instruction or two around callee-cleanup calls, transferring the
  459. // DEBUG_VALUE across the call is still a better user experience.
  460. for (unsigned ID : OpenRanges.getVarLocs()) {
  461. unsigned Reg = VarLocIDs[ID].isDescribedByReg();
  462. if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
  463. KillSet.set(ID);
  464. }
  465. }
  466. }
  467. OpenRanges.erase(KillSet, VarLocIDs);
  468. }
  469. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  470. /// criteria to make this decision:
  471. /// - Is this instruction a store to a spill slot?
  472. /// - Is there a register operand that is both used and killed?
  473. /// TODO: Store optimization can fold spills into other stores (including
  474. /// other spills). We do not handle this yet (more than one memory operand).
  475. bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
  476. MachineFunction *MF, unsigned &Reg) {
  477. SmallVector<const MachineMemOperand*, 1> Accesses;
  478. // TODO: Handle multiple stores folded into one.
  479. if (!MI.hasOneMemOperand())
  480. return false;
  481. if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
  482. return false; // This is not a spill instruction, since no valid size was
  483. // returned from either function.
  484. auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
  485. if (!MO.isReg() || !MO.isUse()) {
  486. Reg = 0;
  487. return false;
  488. }
  489. Reg = MO.getReg();
  490. return MO.isKill();
  491. };
  492. for (const MachineOperand &MO : MI.operands()) {
  493. // In a spill instruction generated by the InlineSpiller the spilled
  494. // register has its kill flag set.
  495. if (isKilledReg(MO, Reg))
  496. return true;
  497. if (Reg != 0) {
  498. // Check whether next instruction kills the spilled register.
  499. // FIXME: Current solution does not cover search for killed register in
  500. // bundles and instructions further down the chain.
  501. auto NextI = std::next(MI.getIterator());
  502. // Skip next instruction that points to basic block end iterator.
  503. if (MI.getParent()->end() == NextI)
  504. continue;
  505. unsigned RegNext;
  506. for (const MachineOperand &MONext : NextI->operands()) {
  507. // Return true if we came across the register from the
  508. // previous spill instruction that is killed in NextI.
  509. if (isKilledReg(MONext, RegNext) && RegNext == Reg)
  510. return true;
  511. }
  512. }
  513. }
  514. // Return false if we didn't find spilled register.
  515. return false;
  516. }
  517. Optional<LiveDebugValues::VarLoc::SpillLoc>
  518. LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
  519. MachineFunction *MF, unsigned &Reg) {
  520. if (!MI.hasOneMemOperand())
  521. return None;
  522. // FIXME: Handle folded restore instructions with more than one memory
  523. // operand.
  524. if (MI.getRestoreSize(TII)) {
  525. Reg = MI.getOperand(0).getReg();
  526. return extractSpillBaseRegAndOffset(MI);
  527. }
  528. return None;
  529. }
  530. /// A spilled register may indicate that we have to end the current range of
  531. /// a variable and create a new one for the spill location.
  532. /// A restored register may indicate the reverse situation.
  533. /// We don't want to insert any instructions in process(), so we just create
  534. /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
  535. /// It will be inserted into the BB when we're done iterating over the
  536. /// instructions.
  537. void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
  538. OpenRangesSet &OpenRanges,
  539. VarLocMap &VarLocIDs,
  540. TransferMap &Transfers) {
  541. MachineFunction *MF = MI.getMF();
  542. TransferKind TKind;
  543. unsigned Reg;
  544. Optional<VarLoc::SpillLoc> Loc;
  545. LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
  546. if (isSpillInstruction(MI, MF, Reg)) {
  547. TKind = TransferKind::TransferSpill;
  548. LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
  549. LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
  550. << "\n");
  551. } else {
  552. if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
  553. return;
  554. TKind = TransferKind::TransferRestore;
  555. LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
  556. LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
  557. << "\n");
  558. }
  559. // Check if the register or spill location is the location of a debug value.
  560. for (unsigned ID : OpenRanges.getVarLocs()) {
  561. if (TKind == TransferKind::TransferSpill &&
  562. VarLocIDs[ID].isDescribedByReg() == Reg) {
  563. LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
  564. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  565. } else if (TKind == TransferKind::TransferRestore &&
  566. VarLocIDs[ID].Loc.SpillLocation == *Loc) {
  567. LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
  568. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  569. } else
  570. continue;
  571. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
  572. Reg);
  573. return;
  574. }
  575. }
  576. /// If \p MI is a register copy instruction, that copies a previously tracked
  577. /// value from one register to another register that is callee saved, we
  578. /// create new DBG_VALUE instruction described with copy destination register.
  579. void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
  580. OpenRangesSet &OpenRanges,
  581. VarLocMap &VarLocIDs,
  582. TransferMap &Transfers) {
  583. const MachineOperand *SrcRegOp, *DestRegOp;
  584. if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
  585. !DestRegOp->isDef())
  586. return;
  587. auto isCalleSavedReg = [&](unsigned Reg) {
  588. for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
  589. if (CalleeSavedRegs.test(*RAI))
  590. return true;
  591. return false;
  592. };
  593. unsigned SrcReg = SrcRegOp->getReg();
  594. unsigned DestReg = DestRegOp->getReg();
  595. // We want to recognize instructions where destination register is callee
  596. // saved register. If register that could be clobbered by the call is
  597. // included, there would be a great chance that it is going to be clobbered
  598. // soon. It is more likely that previous register location, which is callee
  599. // saved, is going to stay unclobbered longer, even if it is killed.
  600. if (!isCalleSavedReg(DestReg))
  601. return;
  602. for (unsigned ID : OpenRanges.getVarLocs()) {
  603. if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
  604. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
  605. TransferKind::TransferCopy, DestReg);
  606. return;
  607. }
  608. }
  609. }
  610. /// Terminate all open ranges at the end of the current basic block.
  611. bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
  612. OpenRangesSet &OpenRanges,
  613. VarLocInMBB &OutLocs,
  614. const VarLocMap &VarLocIDs) {
  615. bool Changed = false;
  616. const MachineBasicBlock *CurMBB = MI.getParent();
  617. if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
  618. return false;
  619. if (OpenRanges.empty())
  620. return false;
  621. LLVM_DEBUG(for (unsigned ID
  622. : OpenRanges.getVarLocs()) {
  623. // Copy OpenRanges to OutLocs, if not already present.
  624. dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
  625. VarLocIDs[ID].dump();
  626. });
  627. VarLocSet &VLS = OutLocs[CurMBB];
  628. Changed = VLS |= OpenRanges.getVarLocs();
  629. OpenRanges.clear();
  630. return Changed;
  631. }
  632. /// This routine creates OpenRanges and OutLocs.
  633. bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  634. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  635. TransferMap &Transfers, bool transferChanges) {
  636. bool Changed = false;
  637. transferDebugValue(MI, OpenRanges, VarLocIDs);
  638. transferRegisterDef(MI, OpenRanges, VarLocIDs);
  639. if (transferChanges) {
  640. transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
  641. transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
  642. }
  643. Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
  644. return Changed;
  645. }
  646. /// This routine joins the analysis results of all incoming edges in @MBB by
  647. /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
  648. /// source variable in all the predecessors of @MBB reside in the same location.
  649. bool LiveDebugValues::join(
  650. MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  651. const VarLocMap &VarLocIDs,
  652. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  653. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
  654. LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
  655. bool Changed = false;
  656. VarLocSet InLocsT; // Temporary incoming locations.
  657. // For all predecessors of this MBB, find the set of VarLocs that
  658. // can be joined.
  659. int NumVisited = 0;
  660. for (auto p : MBB.predecessors()) {
  661. // Ignore unvisited predecessor blocks. As we are processing
  662. // the blocks in reverse post-order any unvisited block can
  663. // be considered to not remove any incoming values.
  664. if (!Visited.count(p)) {
  665. LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
  666. << "\n");
  667. continue;
  668. }
  669. auto OL = OutLocs.find(p);
  670. // Join is null in case of empty OutLocs from any of the pred.
  671. if (OL == OutLocs.end())
  672. return false;
  673. // Just copy over the Out locs to incoming locs for the first visited
  674. // predecessor, and for all other predecessors join the Out locs.
  675. if (!NumVisited)
  676. InLocsT = OL->second;
  677. else
  678. InLocsT &= OL->second;
  679. LLVM_DEBUG({
  680. if (!InLocsT.empty()) {
  681. for (auto ID : InLocsT)
  682. dbgs() << " gathered candidate incoming var: "
  683. << VarLocIDs[ID].Var.getVar()->getName() << "\n";
  684. }
  685. });
  686. NumVisited++;
  687. }
  688. // Filter out DBG_VALUES that are out of scope.
  689. VarLocSet KillSet;
  690. bool IsArtificial = ArtificialBlocks.count(&MBB);
  691. if (!IsArtificial) {
  692. for (auto ID : InLocsT) {
  693. if (!VarLocIDs[ID].dominates(MBB)) {
  694. KillSet.set(ID);
  695. LLVM_DEBUG({
  696. auto Name = VarLocIDs[ID].Var.getVar()->getName();
  697. dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
  698. });
  699. }
  700. }
  701. }
  702. InLocsT.intersectWithComplement(KillSet);
  703. // As we are processing blocks in reverse post-order we
  704. // should have processed at least one predecessor, unless it
  705. // is the entry block which has no predecessor.
  706. assert((NumVisited || MBB.pred_empty()) &&
  707. "Should have processed at least one predecessor");
  708. if (InLocsT.empty())
  709. return false;
  710. VarLocSet &ILS = InLocs[&MBB];
  711. // Insert DBG_VALUE instructions, if not already inserted.
  712. VarLocSet Diff = InLocsT;
  713. Diff.intersectWithComplement(ILS);
  714. for (auto ID : Diff) {
  715. // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
  716. // new range is started for the var from the mbb's beginning by inserting
  717. // a new DBG_VALUE. process() will end this range however appropriate.
  718. const VarLoc &DiffIt = VarLocIDs[ID];
  719. const MachineInstr *DMI = &DiffIt.MI;
  720. MachineInstr *MI =
  721. BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
  722. DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(),
  723. DMI->getDebugVariable(), DMI->getDebugExpression());
  724. if (DMI->isIndirectDebugValue())
  725. MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
  726. LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
  727. ILS.set(ID);
  728. ++NumInserted;
  729. Changed = true;
  730. }
  731. return Changed;
  732. }
  733. /// Calculate the liveness information for the given machine function and
  734. /// extend ranges across basic blocks.
  735. bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
  736. LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
  737. bool Changed = false;
  738. bool OLChanged = false;
  739. bool MBBJoined = false;
  740. VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
  741. OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
  742. VarLocInMBB OutLocs; // Ranges that exist beyond bb.
  743. VarLocInMBB InLocs; // Ranges that are incoming after joining.
  744. TransferMap Transfers; // DBG_VALUEs associated with spills.
  745. // Blocks which are artificial, i.e. blocks which exclusively contain
  746. // instructions without locations, or with line 0 locations.
  747. SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
  748. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  749. DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
  750. std::priority_queue<unsigned int, std::vector<unsigned int>,
  751. std::greater<unsigned int>>
  752. Worklist;
  753. std::priority_queue<unsigned int, std::vector<unsigned int>,
  754. std::greater<unsigned int>>
  755. Pending;
  756. enum : bool { dontTransferChanges = false, transferChanges = true };
  757. // Initialize every mbb with OutLocs.
  758. // We are not looking at any spill instructions during the initial pass
  759. // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
  760. // instructions for spills of registers that are known to be user variables
  761. // within the BB in which the spill occurs.
  762. for (auto &MBB : MF)
  763. for (auto &MI : MBB)
  764. process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  765. dontTransferChanges);
  766. auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
  767. if (const DebugLoc &DL = MI.getDebugLoc())
  768. return DL.getLine() != 0;
  769. return false;
  770. };
  771. for (auto &MBB : MF)
  772. if (none_of(MBB.instrs(), hasNonArtificialLocation))
  773. ArtificialBlocks.insert(&MBB);
  774. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  775. "OutLocs after initialization", dbgs()));
  776. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  777. unsigned int RPONumber = 0;
  778. for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
  779. OrderToBB[RPONumber] = *RI;
  780. BBToOrder[*RI] = RPONumber;
  781. Worklist.push(RPONumber);
  782. ++RPONumber;
  783. }
  784. // This is a standard "union of predecessor outs" dataflow problem.
  785. // To solve it, we perform join() and process() using the two worklist method
  786. // until the ranges converge.
  787. // Ranges have converged when both worklists are empty.
  788. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  789. while (!Worklist.empty() || !Pending.empty()) {
  790. // We track what is on the pending worklist to avoid inserting the same
  791. // thing twice. We could avoid this with a custom priority queue, but this
  792. // is probably not worth it.
  793. SmallPtrSet<MachineBasicBlock *, 16> OnPending;
  794. LLVM_DEBUG(dbgs() << "Processing Worklist\n");
  795. while (!Worklist.empty()) {
  796. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  797. Worklist.pop();
  798. MBBJoined =
  799. join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
  800. Visited.insert(MBB);
  801. if (MBBJoined) {
  802. MBBJoined = false;
  803. Changed = true;
  804. // Now that we have started to extend ranges across BBs we need to
  805. // examine spill instructions to see whether they spill registers that
  806. // correspond to user variables.
  807. for (auto &MI : *MBB)
  808. OLChanged |= process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  809. transferChanges);
  810. // Add any DBG_VALUE instructions necessitated by spills.
  811. for (auto &TR : Transfers)
  812. MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
  813. TR.DebugInst);
  814. Transfers.clear();
  815. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  816. "OutLocs after propagating", dbgs()));
  817. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
  818. "InLocs after propagating", dbgs()));
  819. if (OLChanged) {
  820. OLChanged = false;
  821. for (auto s : MBB->successors())
  822. if (OnPending.insert(s).second) {
  823. Pending.push(BBToOrder[s]);
  824. }
  825. }
  826. }
  827. }
  828. Worklist.swap(Pending);
  829. // At this point, pending must be empty, since it was just the empty
  830. // worklist
  831. assert(Pending.empty() && "Pending should be empty");
  832. }
  833. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
  834. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
  835. return Changed;
  836. }
  837. bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
  838. if (!MF.getFunction().getSubprogram())
  839. // LiveDebugValues will already have removed all DBG_VALUEs.
  840. return false;
  841. // Skip functions from NoDebug compilation units.
  842. if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  843. DICompileUnit::NoDebug)
  844. return false;
  845. TRI = MF.getSubtarget().getRegisterInfo();
  846. TII = MF.getSubtarget().getInstrInfo();
  847. TFI = MF.getSubtarget().getFrameLowering();
  848. TFI->determineCalleeSaves(MF, CalleeSavedRegs,
  849. make_unique<RegScavenger>().get());
  850. LS.initialize(MF);
  851. bool Changed = ExtendRanges(MF);
  852. return Changed;
  853. }