LiveDebugVariables.cpp 34 KB

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