LiveDebugVariables.cpp 35 KB

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