LiveDebugVariables.cpp 35 KB

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