2
0

LiveDebugVariables.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
  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 file implements the LiveDebugVariables analysis.
  11. //
  12. // Remove all DBG_VALUE instructions referencing virtual registers and replace
  13. // them with a data structure tracking where live user variables are kept - in a
  14. // virtual register or in a stack slot.
  15. //
  16. // Allow the data structure to be updated during register allocation when values
  17. // are moved between registers and stack slots. Finally emit new DBG_VALUE
  18. // instructions after register allocation is complete.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #include "LiveDebugVariables.h"
  22. #include "llvm/ADT/IntervalMap.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/CodeGen/LexicalScopes.h"
  25. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  26. #include "llvm/CodeGen/MachineDominators.h"
  27. #include "llvm/CodeGen/MachineFunction.h"
  28. #include "llvm/CodeGen/MachineInstrBuilder.h"
  29. #include "llvm/CodeGen/MachineRegisterInfo.h"
  30. #include "llvm/CodeGen/Passes.h"
  31. #include "llvm/CodeGen/VirtRegMap.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DebugInfo.h"
  34. #include "llvm/IR/Metadata.h"
  35. #include "llvm/IR/Value.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Target/TargetInstrInfo.h"
  40. #include "llvm/Target/TargetMachine.h"
  41. #include "llvm/Target/TargetRegisterInfo.h"
  42. #include "llvm/Target/TargetSubtargetInfo.h"
  43. #include <memory>
  44. using namespace llvm;
  45. #define DEBUG_TYPE "livedebug"
  46. static cl::opt<bool>
  47. EnableLDV("live-debug-variables", cl::init(true),
  48. cl::desc("Enable the live debug variables pass"), cl::Hidden);
  49. STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
  50. char LiveDebugVariables::ID = 0;
  51. INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
  52. "Debug Variable Analysis", false, false)
  53. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  54. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  55. INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
  56. "Debug Variable Analysis", false, false)
  57. void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
  58. AU.addRequired<MachineDominatorTree>();
  59. AU.addRequiredTransitive<LiveIntervals>();
  60. AU.setPreservesAll();
  61. MachineFunctionPass::getAnalysisUsage(AU);
  62. }
  63. LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
  64. initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
  65. }
  66. /// LocMap - Map of where a user value is live, and its location.
  67. typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
  68. namespace {
  69. /// UserValueScopes - Keeps track of lexical scopes associated with a
  70. /// user value's source location.
  71. class UserValueScopes {
  72. DebugLoc DL;
  73. LexicalScopes &LS;
  74. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  75. public:
  76. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {}
  77. /// dominates - Return true if current scope dominates at least one machine
  78. /// instruction in a given machine basic block.
  79. bool dominates(MachineBasicBlock *MBB) {
  80. if (LBlocks.empty())
  81. LS.getMachineBasicBlocks(DL, LBlocks);
  82. if (LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB))
  83. return true;
  84. return false;
  85. }
  86. };
  87. } // end anonymous namespace
  88. /// UserValue - A user value is a part of a debug info user variable.
  89. ///
  90. /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
  91. /// holds part of a user variable. The part is identified by a byte offset.
  92. ///
  93. /// UserValues are grouped into equivalence classes for easier searching. Two
  94. /// user values are related if they refer to the same variable, or if they are
  95. /// held by the same virtual register. The equivalence class is the transitive
  96. /// closure of that relation.
  97. namespace {
  98. class LDVImpl;
  99. class UserValue {
  100. const MDNode *Variable; ///< The debug info variable we are part of.
  101. const MDNode *Expression; ///< Any complex address expression.
  102. unsigned offset; ///< Byte offset into variable.
  103. bool IsIndirect; ///< true if this is a register-indirect+offset value.
  104. DebugLoc dl; ///< The debug location for the variable. This is
  105. ///< used by dwarf writer to find lexical scope.
  106. UserValue *leader; ///< Equivalence class leader.
  107. UserValue *next; ///< Next value in equivalence class, or null.
  108. /// Numbered locations referenced by locmap.
  109. SmallVector<MachineOperand, 4> locations;
  110. /// Map of slot indices where this value is live.
  111. LocMap locInts;
  112. /// coalesceLocation - After LocNo was changed, check if it has become
  113. /// identical to another location, and coalesce them. This may cause LocNo or
  114. /// a later location to be erased, but no earlier location will be erased.
  115. void coalesceLocation(unsigned LocNo);
  116. /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
  117. void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
  118. LiveIntervals &LIS, const TargetInstrInfo &TII);
  119. /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
  120. /// is live. Returns true if any changes were made.
  121. bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  122. LiveIntervals &LIS);
  123. public:
  124. /// UserValue - Create a new UserValue.
  125. UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
  126. DebugLoc L, LocMap::Allocator &alloc)
  127. : Variable(var), Expression(expr), offset(o), IsIndirect(i), dl(L),
  128. leader(this), next(nullptr), locInts(alloc) {}
  129. /// getLeader - Get the leader of this value's equivalence class.
  130. UserValue *getLeader() {
  131. UserValue *l = leader;
  132. while (l != l->leader)
  133. l = l->leader;
  134. return leader = l;
  135. }
  136. /// getNext - Return the next UserValue in the equivalence class.
  137. UserValue *getNext() const { return next; }
  138. /// match - Does this UserValue match the parameters?
  139. bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
  140. unsigned Offset, bool indirect) const {
  141. return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
  142. Offset == offset && indirect == IsIndirect;
  143. }
  144. /// merge - Merge equivalence classes.
  145. static UserValue *merge(UserValue *L1, UserValue *L2) {
  146. L2 = L2->getLeader();
  147. if (!L1)
  148. return L2;
  149. L1 = L1->getLeader();
  150. if (L1 == L2)
  151. return L1;
  152. // Splice L2 before L1's members.
  153. UserValue *End = L2;
  154. while (End->next)
  155. End->leader = L1, End = End->next;
  156. End->leader = L1;
  157. End->next = L1->next;
  158. L1->next = L2;
  159. return L1;
  160. }
  161. /// getLocationNo - Return the location number that matches Loc.
  162. unsigned getLocationNo(const MachineOperand &LocMO) {
  163. if (LocMO.isReg()) {
  164. if (LocMO.getReg() == 0)
  165. return ~0u;
  166. // For register locations we dont care about use/def and other flags.
  167. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  168. if (locations[i].isReg() &&
  169. locations[i].getReg() == LocMO.getReg() &&
  170. locations[i].getSubReg() == LocMO.getSubReg())
  171. return i;
  172. } else
  173. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  174. if (LocMO.isIdenticalTo(locations[i]))
  175. return i;
  176. locations.push_back(LocMO);
  177. // We are storing a MachineOperand outside a MachineInstr.
  178. locations.back().clearParent();
  179. // Don't store def operands.
  180. if (locations.back().isReg())
  181. locations.back().setIsUse();
  182. return locations.size() - 1;
  183. }
  184. /// mapVirtRegs - Ensure that all virtual register locations are mapped.
  185. void mapVirtRegs(LDVImpl *LDV);
  186. /// addDef - Add a definition point to this value.
  187. void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
  188. // Add a singular (Idx,Idx) -> Loc mapping.
  189. LocMap::iterator I = locInts.find(Idx);
  190. if (!I.valid() || I.start() != Idx)
  191. I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
  192. else
  193. // A later DBG_VALUE at the same SlotIndex overrides the old location.
  194. I.setValue(getLocationNo(LocMO));
  195. }
  196. /// extendDef - Extend the current definition as far as possible down the
  197. /// dominator tree. Stop when meeting an existing def or when leaving the live
  198. /// range of VNI.
  199. /// End points where VNI is no longer live are added to Kills.
  200. /// @param Idx Starting point for the definition.
  201. /// @param LocNo Location number to propagate.
  202. /// @param LR Restrict liveness to where LR has the value VNI. May be null.
  203. /// @param VNI When LR is not null, this is the value to restrict to.
  204. /// @param Kills Append end points of VNI's live range to Kills.
  205. /// @param LIS Live intervals analysis.
  206. /// @param MDT Dominator tree.
  207. void extendDef(SlotIndex Idx, unsigned LocNo,
  208. LiveRange *LR, const VNInfo *VNI,
  209. SmallVectorImpl<SlotIndex> *Kills,
  210. LiveIntervals &LIS, MachineDominatorTree &MDT,
  211. UserValueScopes &UVS);
  212. /// addDefsFromCopies - The value in LI/LocNo may be copies to other
  213. /// registers. Determine if any of the copies are available at the kill
  214. /// points, and add defs if possible.
  215. /// @param LI Scan for copies of the value in LI->reg.
  216. /// @param LocNo Location number of LI->reg.
  217. /// @param Kills Points where the range of LocNo could be extended.
  218. /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
  219. void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
  220. const SmallVectorImpl<SlotIndex> &Kills,
  221. SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
  222. MachineRegisterInfo &MRI,
  223. LiveIntervals &LIS);
  224. /// computeIntervals - Compute the live intervals of all locations after
  225. /// collecting all their def points.
  226. void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  227. LiveIntervals &LIS, MachineDominatorTree &MDT,
  228. UserValueScopes &UVS);
  229. /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
  230. /// live. Returns true if any changes were made.
  231. bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  232. LiveIntervals &LIS);
  233. /// rewriteLocations - Rewrite virtual register locations according to the
  234. /// provided virtual register map.
  235. void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
  236. /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
  237. void emitDebugValues(VirtRegMap *VRM,
  238. LiveIntervals &LIS, const TargetInstrInfo &TRI);
  239. /// getDebugLoc - Return DebugLoc of this UserValue.
  240. DebugLoc getDebugLoc() { return dl;}
  241. void print(raw_ostream &, const TargetRegisterInfo *);
  242. };
  243. } // namespace
  244. /// LDVImpl - Implementation of the LiveDebugVariables pass.
  245. namespace {
  246. class LDVImpl {
  247. LiveDebugVariables &pass;
  248. LocMap::Allocator allocator;
  249. MachineFunction *MF;
  250. LiveIntervals *LIS;
  251. LexicalScopes LS;
  252. MachineDominatorTree *MDT;
  253. const TargetRegisterInfo *TRI;
  254. /// Whether emitDebugValues is called.
  255. bool EmitDone;
  256. /// Whether the machine function is modified during the pass.
  257. bool ModifiedMF;
  258. /// userValues - All allocated UserValue instances.
  259. SmallVector<std::unique_ptr<UserValue>, 8> userValues;
  260. /// Map virtual register to eq class leader.
  261. typedef DenseMap<unsigned, UserValue*> VRMap;
  262. VRMap virtRegToEqClass;
  263. /// Map user variable to eq class leader.
  264. typedef DenseMap<const MDNode *, UserValue*> UVMap;
  265. UVMap userVarMap;
  266. /// getUserValue - Find or create a UserValue.
  267. UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
  268. unsigned Offset, bool IsIndirect, DebugLoc DL);
  269. /// lookupVirtReg - Find the EC leader for VirtReg or null.
  270. UserValue *lookupVirtReg(unsigned VirtReg);
  271. /// handleDebugValue - Add DBG_VALUE instruction to our maps.
  272. /// @param MI DBG_VALUE instruction
  273. /// @param Idx Last valid SLotIndex before instruction.
  274. /// @return True if the DBG_VALUE instruction should be deleted.
  275. bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
  276. /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
  277. /// a UserValue def for each instruction.
  278. /// @param mf MachineFunction to be scanned.
  279. /// @return True if any debug values were found.
  280. bool collectDebugValues(MachineFunction &mf);
  281. /// computeIntervals - Compute the live intervals of all user values after
  282. /// collecting all their def points.
  283. void computeIntervals();
  284. public:
  285. LDVImpl(LiveDebugVariables *ps)
  286. : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
  287. bool runOnMachineFunction(MachineFunction &mf);
  288. /// clear - Release all memory.
  289. void clear() {
  290. MF = nullptr;
  291. userValues.clear();
  292. virtRegToEqClass.clear();
  293. userVarMap.clear();
  294. // Make sure we call emitDebugValues if the machine function was modified.
  295. assert((!ModifiedMF || EmitDone) &&
  296. "Dbg values are not emitted in LDV");
  297. EmitDone = false;
  298. ModifiedMF = false;
  299. LS.reset();
  300. }
  301. /// mapVirtReg - Map virtual register to an equivalence class.
  302. void mapVirtReg(unsigned VirtReg, UserValue *EC);
  303. /// splitRegister - Replace all references to OldReg with NewRegs.
  304. void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
  305. /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
  306. void emitDebugValues(VirtRegMap *VRM);
  307. void print(raw_ostream&);
  308. };
  309. } // namespace
  310. static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
  311. const LLVMContext &Ctx) {
  312. if (!DL)
  313. return;
  314. auto *Scope = cast<DIScope>(DL.getScope());
  315. // Omit the directory, because it's likely to be long and uninteresting.
  316. CommentOS << Scope->getFilename();
  317. CommentOS << ':' << DL.getLine();
  318. if (DL.getCol() != 0)
  319. CommentOS << ':' << DL.getCol();
  320. DebugLoc InlinedAtDL = DL.getInlinedAt();
  321. if (!InlinedAtDL)
  322. return;
  323. CommentOS << " @[ ";
  324. printDebugLoc(InlinedAtDL, CommentOS, Ctx);
  325. CommentOS << " ]";
  326. }
  327. static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
  328. const DILocation *DL) {
  329. const LLVMContext &Ctx = V->getContext();
  330. StringRef Res = V->getName();
  331. if (!Res.empty())
  332. OS << Res << "," << V->getLine();
  333. if (auto *InlinedAt = DL->getInlinedAt()) {
  334. if (DebugLoc InlinedAtDL = InlinedAt) {
  335. OS << " @[";
  336. printDebugLoc(InlinedAtDL, OS, Ctx);
  337. OS << "]";
  338. }
  339. }
  340. }
  341. void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  342. auto *DV = cast<DILocalVariable>(Variable);
  343. OS << "!\"";
  344. printExtendedName(OS, DV, dl);
  345. OS << "\"\t";
  346. if (offset)
  347. OS << '+' << offset;
  348. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  349. OS << " [" << I.start() << ';' << I.stop() << "):";
  350. if (I.value() == ~0u)
  351. OS << "undef";
  352. else
  353. OS << I.value();
  354. }
  355. for (unsigned i = 0, e = locations.size(); i != e; ++i) {
  356. OS << " Loc" << i << '=';
  357. locations[i].print(OS, TRI);
  358. }
  359. OS << '\n';
  360. }
  361. void LDVImpl::print(raw_ostream &OS) {
  362. OS << "********** DEBUG VARIABLES **********\n";
  363. for (unsigned i = 0, e = userValues.size(); i != e; ++i)
  364. userValues[i]->print(OS, TRI);
  365. }
  366. void UserValue::coalesceLocation(unsigned LocNo) {
  367. unsigned KeepLoc = 0;
  368. for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
  369. if (KeepLoc == LocNo)
  370. continue;
  371. if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
  372. break;
  373. }
  374. // No matches.
  375. if (KeepLoc == locations.size())
  376. return;
  377. // Keep the smaller location, erase the larger one.
  378. unsigned EraseLoc = LocNo;
  379. if (KeepLoc > EraseLoc)
  380. std::swap(KeepLoc, EraseLoc);
  381. locations.erase(locations.begin() + EraseLoc);
  382. // Rewrite values.
  383. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  384. unsigned v = I.value();
  385. if (v == EraseLoc)
  386. I.setValue(KeepLoc); // Coalesce when possible.
  387. else if (v > EraseLoc)
  388. I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
  389. }
  390. }
  391. void UserValue::mapVirtRegs(LDVImpl *LDV) {
  392. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  393. if (locations[i].isReg() &&
  394. TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
  395. LDV->mapVirtReg(locations[i].getReg(), this);
  396. }
  397. UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
  398. unsigned Offset, bool IsIndirect,
  399. DebugLoc DL) {
  400. UserValue *&Leader = userVarMap[Var];
  401. if (Leader) {
  402. UserValue *UV = Leader->getLeader();
  403. Leader = UV;
  404. for (; UV; UV = UV->getNext())
  405. if (UV->match(Var, Expr, DL->getInlinedAt(), Offset, IsIndirect))
  406. return UV;
  407. }
  408. userValues.push_back(
  409. make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
  410. UserValue *UV = userValues.back().get();
  411. Leader = UserValue::merge(Leader, UV);
  412. return UV;
  413. }
  414. void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
  415. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
  416. UserValue *&Leader = virtRegToEqClass[VirtReg];
  417. Leader = UserValue::merge(Leader, EC);
  418. }
  419. UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
  420. if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
  421. return UV->getLeader();
  422. return nullptr;
  423. }
  424. bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
  425. // DBG_VALUE loc, offset, variable
  426. if (MI->getNumOperands() != 4 ||
  427. !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
  428. !MI->getOperand(2).isMetadata()) {
  429. DEBUG(dbgs() << "Can't handle " << *MI);
  430. return false;
  431. }
  432. // Get or create the UserValue for (variable,offset).
  433. bool IsIndirect = MI->isIndirectDebugValue();
  434. unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
  435. const MDNode *Var = MI->getDebugVariable();
  436. const MDNode *Expr = MI->getDebugExpression();
  437. //here.
  438. UserValue *UV =
  439. getUserValue(Var, Expr, Offset, IsIndirect, MI->getDebugLoc());
  440. UV->addDef(Idx, MI->getOperand(0));
  441. return true;
  442. }
  443. bool LDVImpl::collectDebugValues(MachineFunction &mf) {
  444. bool Changed = false;
  445. for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
  446. ++MFI) {
  447. MachineBasicBlock *MBB = MFI;
  448. for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
  449. MBBI != MBBE;) {
  450. if (!MBBI->isDebugValue()) {
  451. ++MBBI;
  452. continue;
  453. }
  454. // DBG_VALUE has no slot index, use the previous instruction instead.
  455. SlotIndex Idx = MBBI == MBB->begin() ?
  456. LIS->getMBBStartIdx(MBB) :
  457. LIS->getInstructionIndex(std::prev(MBBI)).getRegSlot();
  458. // Handle consecutive DBG_VALUE instructions with the same slot index.
  459. do {
  460. if (handleDebugValue(MBBI, Idx)) {
  461. MBBI = MBB->erase(MBBI);
  462. Changed = true;
  463. } else
  464. ++MBBI;
  465. } while (MBBI != MBBE && MBBI->isDebugValue());
  466. }
  467. }
  468. return Changed;
  469. }
  470. void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
  471. LiveRange *LR, const VNInfo *VNI,
  472. SmallVectorImpl<SlotIndex> *Kills,
  473. LiveIntervals &LIS, MachineDominatorTree &MDT,
  474. UserValueScopes &UVS) {
  475. SmallVector<SlotIndex, 16> Todo;
  476. Todo.push_back(Idx);
  477. do {
  478. SlotIndex Start = Todo.pop_back_val();
  479. MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
  480. SlotIndex Stop = LIS.getMBBEndIdx(MBB);
  481. LocMap::iterator I = locInts.find(Start);
  482. // Limit to VNI's live range.
  483. bool ToEnd = true;
  484. if (LR && VNI) {
  485. LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
  486. if (!Segment || Segment->valno != VNI) {
  487. if (Kills)
  488. Kills->push_back(Start);
  489. continue;
  490. }
  491. if (Segment->end < Stop)
  492. Stop = Segment->end, ToEnd = false;
  493. }
  494. // There could already be a short def at Start.
  495. if (I.valid() && I.start() <= Start) {
  496. // Stop when meeting a different location or an already extended interval.
  497. Start = Start.getNextSlot();
  498. if (I.value() != LocNo || I.stop() != Start)
  499. continue;
  500. // This is a one-slot placeholder. Just skip it.
  501. ++I;
  502. }
  503. // Limited by the next def.
  504. if (I.valid() && I.start() < Stop)
  505. Stop = I.start(), ToEnd = false;
  506. // Limited by VNI's live range.
  507. else if (!ToEnd && Kills)
  508. Kills->push_back(Stop);
  509. if (Start >= Stop)
  510. continue;
  511. I.insert(Start, Stop, LocNo);
  512. // If we extended to the MBB end, propagate down the dominator tree.
  513. if (!ToEnd)
  514. continue;
  515. const std::vector<MachineDomTreeNode*> &Children =
  516. MDT.getNode(MBB)->getChildren();
  517. for (unsigned i = 0, e = Children.size(); i != e; ++i) {
  518. MachineBasicBlock *MBB = Children[i]->getBlock();
  519. if (UVS.dominates(MBB))
  520. Todo.push_back(LIS.getMBBStartIdx(MBB));
  521. }
  522. } while (!Todo.empty());
  523. }
  524. void
  525. UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
  526. const SmallVectorImpl<SlotIndex> &Kills,
  527. SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
  528. MachineRegisterInfo &MRI, LiveIntervals &LIS) {
  529. if (Kills.empty())
  530. return;
  531. // Don't track copies from physregs, there are too many uses.
  532. if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
  533. return;
  534. // Collect all the (vreg, valno) pairs that are copies of LI.
  535. SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
  536. for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
  537. MachineInstr *MI = MO.getParent();
  538. // Copies of the full value.
  539. if (MO.getSubReg() || !MI->isCopy())
  540. continue;
  541. unsigned DstReg = MI->getOperand(0).getReg();
  542. // Don't follow copies to physregs. These are usually setting up call
  543. // arguments, and the argument registers are always call clobbered. We are
  544. // better off in the source register which could be a callee-saved register,
  545. // or it could be spilled.
  546. if (!TargetRegisterInfo::isVirtualRegister(DstReg))
  547. continue;
  548. // Is LocNo extended to reach this copy? If not, another def may be blocking
  549. // it, or we are looking at a wrong value of LI.
  550. SlotIndex Idx = LIS.getInstructionIndex(MI);
  551. LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
  552. if (!I.valid() || I.value() != LocNo)
  553. continue;
  554. if (!LIS.hasInterval(DstReg))
  555. continue;
  556. LiveInterval *DstLI = &LIS.getInterval(DstReg);
  557. const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
  558. assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
  559. CopyValues.push_back(std::make_pair(DstLI, DstVNI));
  560. }
  561. if (CopyValues.empty())
  562. return;
  563. DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
  564. // Try to add defs of the copied values for each kill point.
  565. for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
  566. SlotIndex Idx = Kills[i];
  567. for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
  568. LiveInterval *DstLI = CopyValues[j].first;
  569. const VNInfo *DstVNI = CopyValues[j].second;
  570. if (DstLI->getVNInfoAt(Idx) != DstVNI)
  571. continue;
  572. // Check that there isn't already a def at Idx
  573. LocMap::iterator I = locInts.find(Idx);
  574. if (I.valid() && I.start() <= Idx)
  575. continue;
  576. DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
  577. << DstVNI->id << " in " << *DstLI << '\n');
  578. MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
  579. assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
  580. unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
  581. I.insert(Idx, Idx.getNextSlot(), LocNo);
  582. NewDefs.push_back(std::make_pair(Idx, LocNo));
  583. break;
  584. }
  585. }
  586. }
  587. void
  588. UserValue::computeIntervals(MachineRegisterInfo &MRI,
  589. const TargetRegisterInfo &TRI,
  590. LiveIntervals &LIS,
  591. MachineDominatorTree &MDT,
  592. UserValueScopes &UVS) {
  593. SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
  594. // Collect all defs to be extended (Skipping undefs).
  595. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
  596. if (I.value() != ~0u)
  597. Defs.push_back(std::make_pair(I.start(), I.value()));
  598. // Extend all defs, and possibly add new ones along the way.
  599. for (unsigned i = 0; i != Defs.size(); ++i) {
  600. SlotIndex Idx = Defs[i].first;
  601. unsigned LocNo = Defs[i].second;
  602. const MachineOperand &Loc = locations[LocNo];
  603. if (!Loc.isReg()) {
  604. extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
  605. continue;
  606. }
  607. // Register locations are constrained to where the register value is live.
  608. if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
  609. LiveInterval *LI = nullptr;
  610. const VNInfo *VNI = nullptr;
  611. if (LIS.hasInterval(Loc.getReg())) {
  612. LI = &LIS.getInterval(Loc.getReg());
  613. VNI = LI->getVNInfoAt(Idx);
  614. }
  615. SmallVector<SlotIndex, 16> Kills;
  616. extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
  617. if (LI)
  618. addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
  619. continue;
  620. }
  621. // For physregs, use the live range of the first regunit as a guide.
  622. unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
  623. LiveRange *LR = &LIS.getRegUnit(Unit);
  624. const VNInfo *VNI = LR->getVNInfoAt(Idx);
  625. // Don't track copies from physregs, it is too expensive.
  626. extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
  627. }
  628. // Finally, erase all the undefs.
  629. for (LocMap::iterator I = locInts.begin(); I.valid();)
  630. if (I.value() == ~0u)
  631. I.erase();
  632. else
  633. ++I;
  634. }
  635. void LDVImpl::computeIntervals() {
  636. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  637. UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
  638. userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
  639. userValues[i]->mapVirtRegs(this);
  640. }
  641. }
  642. bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
  643. clear();
  644. MF = &mf;
  645. LIS = &pass.getAnalysis<LiveIntervals>();
  646. MDT = &pass.getAnalysis<MachineDominatorTree>();
  647. TRI = mf.getSubtarget().getRegisterInfo();
  648. LS.initialize(mf);
  649. DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
  650. << mf.getName() << " **********\n");
  651. bool Changed = collectDebugValues(mf);
  652. computeIntervals();
  653. DEBUG(print(dbgs()));
  654. ModifiedMF = Changed;
  655. return Changed;
  656. }
  657. static void removeDebugValues(MachineFunction &mf) {
  658. for (MachineBasicBlock &MBB : mf) {
  659. for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
  660. if (!MBBI->isDebugValue()) {
  661. ++MBBI;
  662. continue;
  663. }
  664. MBBI = MBB.erase(MBBI);
  665. }
  666. }
  667. }
  668. bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
  669. if (!EnableLDV)
  670. return false;
  671. if (!FunctionDIs.count(mf.getFunction())) {
  672. removeDebugValues(mf);
  673. return false;
  674. }
  675. if (!pImpl)
  676. pImpl = new LDVImpl(this);
  677. return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
  678. }
  679. void LiveDebugVariables::releaseMemory() {
  680. if (pImpl)
  681. static_cast<LDVImpl*>(pImpl)->clear();
  682. }
  683. LiveDebugVariables::~LiveDebugVariables() {
  684. if (pImpl)
  685. delete static_cast<LDVImpl*>(pImpl);
  686. }
  687. //===----------------------------------------------------------------------===//
  688. // Live Range Splitting
  689. //===----------------------------------------------------------------------===//
  690. bool
  691. UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  692. LiveIntervals& LIS) {
  693. DEBUG({
  694. dbgs() << "Splitting Loc" << OldLocNo << '\t';
  695. print(dbgs(), nullptr);
  696. });
  697. bool DidChange = false;
  698. LocMap::iterator LocMapI;
  699. LocMapI.setMap(locInts);
  700. for (unsigned i = 0; i != NewRegs.size(); ++i) {
  701. LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
  702. if (LI->empty())
  703. continue;
  704. // Don't allocate the new LocNo until it is needed.
  705. unsigned NewLocNo = ~0u;
  706. // Iterate over the overlaps between locInts and LI.
  707. LocMapI.find(LI->beginIndex());
  708. if (!LocMapI.valid())
  709. continue;
  710. LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
  711. LiveInterval::iterator LIE = LI->end();
  712. while (LocMapI.valid() && LII != LIE) {
  713. // At this point, we know that LocMapI.stop() > LII->start.
  714. LII = LI->advanceTo(LII, LocMapI.start());
  715. if (LII == LIE)
  716. break;
  717. // Now LII->end > LocMapI.start(). Do we have an overlap?
  718. if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
  719. // Overlapping correct location. Allocate NewLocNo now.
  720. if (NewLocNo == ~0u) {
  721. MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
  722. MO.setSubReg(locations[OldLocNo].getSubReg());
  723. NewLocNo = getLocationNo(MO);
  724. DidChange = true;
  725. }
  726. SlotIndex LStart = LocMapI.start();
  727. SlotIndex LStop = LocMapI.stop();
  728. // Trim LocMapI down to the LII overlap.
  729. if (LStart < LII->start)
  730. LocMapI.setStartUnchecked(LII->start);
  731. if (LStop > LII->end)
  732. LocMapI.setStopUnchecked(LII->end);
  733. // Change the value in the overlap. This may trigger coalescing.
  734. LocMapI.setValue(NewLocNo);
  735. // Re-insert any removed OldLocNo ranges.
  736. if (LStart < LocMapI.start()) {
  737. LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
  738. ++LocMapI;
  739. assert(LocMapI.valid() && "Unexpected coalescing");
  740. }
  741. if (LStop > LocMapI.stop()) {
  742. ++LocMapI;
  743. LocMapI.insert(LII->end, LStop, OldLocNo);
  744. --LocMapI;
  745. }
  746. }
  747. // Advance to the next overlap.
  748. if (LII->end < LocMapI.stop()) {
  749. if (++LII == LIE)
  750. break;
  751. LocMapI.advanceTo(LII->start);
  752. } else {
  753. ++LocMapI;
  754. if (!LocMapI.valid())
  755. break;
  756. LII = LI->advanceTo(LII, LocMapI.start());
  757. }
  758. }
  759. }
  760. // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
  761. locations.erase(locations.begin() + OldLocNo);
  762. LocMapI.goToBegin();
  763. while (LocMapI.valid()) {
  764. unsigned v = LocMapI.value();
  765. if (v == OldLocNo) {
  766. DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
  767. << LocMapI.stop() << ")\n");
  768. LocMapI.erase();
  769. } else {
  770. if (v > OldLocNo)
  771. LocMapI.setValueUnchecked(v-1);
  772. ++LocMapI;
  773. }
  774. }
  775. DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
  776. return DidChange;
  777. }
  778. bool
  779. UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
  780. LiveIntervals &LIS) {
  781. bool DidChange = false;
  782. // Split locations referring to OldReg. Iterate backwards so splitLocation can
  783. // safely erase unused locations.
  784. for (unsigned i = locations.size(); i ; --i) {
  785. unsigned LocNo = i-1;
  786. const MachineOperand *Loc = &locations[LocNo];
  787. if (!Loc->isReg() || Loc->getReg() != OldReg)
  788. continue;
  789. DidChange |= splitLocation(LocNo, NewRegs, LIS);
  790. }
  791. return DidChange;
  792. }
  793. void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
  794. bool DidChange = false;
  795. for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
  796. DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
  797. if (!DidChange)
  798. return;
  799. // Map all of the new virtual registers.
  800. UserValue *UV = lookupVirtReg(OldReg);
  801. for (unsigned i = 0; i != NewRegs.size(); ++i)
  802. mapVirtReg(NewRegs[i], UV);
  803. }
  804. void LiveDebugVariables::
  805. splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
  806. if (pImpl)
  807. static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
  808. }
  809. void
  810. UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
  811. // Iterate over locations in reverse makes it easier to handle coalescing.
  812. for (unsigned i = locations.size(); i ; --i) {
  813. unsigned LocNo = i-1;
  814. MachineOperand &Loc = locations[LocNo];
  815. // Only virtual registers are rewritten.
  816. if (!Loc.isReg() || !Loc.getReg() ||
  817. !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
  818. continue;
  819. unsigned VirtReg = Loc.getReg();
  820. if (VRM.isAssignedReg(VirtReg) &&
  821. TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
  822. // This can create a %noreg operand in rare cases when the sub-register
  823. // index is no longer available. That means the user value is in a
  824. // non-existent sub-register, and %noreg is exactly what we want.
  825. Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
  826. } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
  827. // FIXME: Translate SubIdx to a stackslot offset.
  828. Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
  829. } else {
  830. Loc.setReg(0);
  831. Loc.setSubReg(0);
  832. }
  833. coalesceLocation(LocNo);
  834. }
  835. }
  836. /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
  837. /// instruction.
  838. static MachineBasicBlock::iterator
  839. findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
  840. LiveIntervals &LIS) {
  841. SlotIndex Start = LIS.getMBBStartIdx(MBB);
  842. Idx = Idx.getBaseIndex();
  843. // Try to find an insert location by going backwards from Idx.
  844. MachineInstr *MI;
  845. while (!(MI = LIS.getInstructionFromIndex(Idx))) {
  846. // We've reached the beginning of MBB.
  847. if (Idx == Start) {
  848. MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
  849. return I;
  850. }
  851. Idx = Idx.getPrevIndex();
  852. }
  853. // Don't insert anything after the first terminator, though.
  854. return MI->isTerminator() ? MBB->getFirstTerminator() :
  855. std::next(MachineBasicBlock::iterator(MI));
  856. }
  857. void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
  858. unsigned LocNo,
  859. LiveIntervals &LIS,
  860. const TargetInstrInfo &TII) {
  861. MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
  862. MachineOperand &Loc = locations[LocNo];
  863. ++NumInsertedDebugValues;
  864. assert(cast<DILocalVariable>(Variable)
  865. ->isValidLocationForIntrinsic(getDebugLoc()) &&
  866. "Expected inlined-at fields to agree");
  867. if (Loc.isReg())
  868. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
  869. IsIndirect, Loc.getReg(), offset, Variable, Expression);
  870. else
  871. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
  872. .addOperand(Loc)
  873. .addImm(offset)
  874. .addMetadata(Variable)
  875. .addMetadata(Expression);
  876. }
  877. void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  878. const TargetInstrInfo &TII) {
  879. MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
  880. for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
  881. SlotIndex Start = I.start();
  882. SlotIndex Stop = I.stop();
  883. unsigned LocNo = I.value();
  884. DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
  885. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
  886. SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
  887. DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
  888. insertDebugValue(MBB, Start, LocNo, LIS, TII);
  889. // This interval may span multiple basic blocks.
  890. // Insert a DBG_VALUE into each one.
  891. while(Stop > MBBEnd) {
  892. // Move to the next block.
  893. Start = MBBEnd;
  894. if (++MBB == MFEnd)
  895. break;
  896. MBBEnd = LIS.getMBBEndIdx(MBB);
  897. DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
  898. insertDebugValue(MBB, Start, LocNo, LIS, TII);
  899. }
  900. DEBUG(dbgs() << '\n');
  901. if (MBB == MFEnd)
  902. break;
  903. ++I;
  904. }
  905. }
  906. void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
  907. DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
  908. if (!MF)
  909. return;
  910. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  911. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  912. DEBUG(userValues[i]->print(dbgs(), TRI));
  913. userValues[i]->rewriteLocations(*VRM, *TRI);
  914. userValues[i]->emitDebugValues(VRM, *LIS, *TII);
  915. }
  916. EmitDone = true;
  917. }
  918. void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
  919. if (pImpl)
  920. static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
  921. }
  922. bool LiveDebugVariables::doInitialization(Module &M) {
  923. FunctionDIs = makeSubprogramMap(M);
  924. return Pass::doInitialization(M);
  925. }
  926. #ifndef NDEBUG
  927. void LiveDebugVariables::dump() {
  928. if (pImpl)
  929. static_cast<LDVImpl*>(pImpl)->print(dbgs());
  930. }
  931. #endif