LiveDebugVariables.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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/ArrayRef.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/IntervalMap.h"
  25. #include "llvm/ADT/STLExtras.h"
  26. #include "llvm/ADT/SmallSet.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/CodeGen/LexicalScopes.h"
  31. #include "llvm/CodeGen/LiveInterval.h"
  32. #include "llvm/CodeGen/LiveIntervals.h"
  33. #include "llvm/CodeGen/MachineBasicBlock.h"
  34. #include "llvm/CodeGen/MachineDominators.h"
  35. #include "llvm/CodeGen/MachineFunction.h"
  36. #include "llvm/CodeGen/MachineInstr.h"
  37. #include "llvm/CodeGen/MachineInstrBuilder.h"
  38. #include "llvm/CodeGen/MachineOperand.h"
  39. #include "llvm/CodeGen/MachineRegisterInfo.h"
  40. #include "llvm/CodeGen/SlotIndexes.h"
  41. #include "llvm/CodeGen/TargetInstrInfo.h"
  42. #include "llvm/CodeGen/TargetOpcodes.h"
  43. #include "llvm/CodeGen/TargetRegisterInfo.h"
  44. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  45. #include "llvm/CodeGen/VirtRegMap.h"
  46. #include "llvm/Config/llvm-config.h"
  47. #include "llvm/IR/DebugInfoMetadata.h"
  48. #include "llvm/IR/DebugLoc.h"
  49. #include "llvm/IR/Function.h"
  50. #include "llvm/IR/Metadata.h"
  51. #include "llvm/MC/MCRegisterInfo.h"
  52. #include "llvm/Pass.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/CommandLine.h"
  55. #include "llvm/Support/Compiler.h"
  56. #include "llvm/Support/Debug.h"
  57. #include "llvm/Support/raw_ostream.h"
  58. #include <algorithm>
  59. #include <cassert>
  60. #include <iterator>
  61. #include <memory>
  62. #include <utility>
  63. using namespace llvm;
  64. #define DEBUG_TYPE "livedebugvars"
  65. static cl::opt<bool>
  66. EnableLDV("live-debug-variables", cl::init(true),
  67. cl::desc("Enable the live debug variables pass"), cl::Hidden);
  68. STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
  69. char LiveDebugVariables::ID = 0;
  70. INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
  71. "Debug Variable Analysis", false, false)
  72. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  73. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  74. INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
  75. "Debug Variable Analysis", false, false)
  76. void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
  77. AU.addRequired<MachineDominatorTree>();
  78. AU.addRequiredTransitive<LiveIntervals>();
  79. AU.setPreservesAll();
  80. MachineFunctionPass::getAnalysisUsage(AU);
  81. }
  82. LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
  83. initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
  84. }
  85. enum : unsigned { UndefLocNo = ~0U };
  86. /// Describes a location by number along with some flags about the original
  87. /// usage of the location.
  88. class DbgValueLocation {
  89. public:
  90. DbgValueLocation(unsigned LocNo, bool WasIndirect)
  91. : LocNo(LocNo), WasIndirect(WasIndirect) {
  92. static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
  93. assert(locNo() == LocNo && "location truncation");
  94. }
  95. DbgValueLocation() : LocNo(0), WasIndirect(0) {}
  96. unsigned locNo() const {
  97. // Fix up the undef location number, which gets truncated.
  98. return LocNo == INT_MAX ? UndefLocNo : LocNo;
  99. }
  100. bool wasIndirect() const { return WasIndirect; }
  101. bool isUndef() const { return locNo() == UndefLocNo; }
  102. DbgValueLocation changeLocNo(unsigned NewLocNo) const {
  103. return DbgValueLocation(NewLocNo, WasIndirect);
  104. }
  105. friend inline bool operator==(const DbgValueLocation &LHS,
  106. const DbgValueLocation &RHS) {
  107. return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect;
  108. }
  109. friend inline bool operator!=(const DbgValueLocation &LHS,
  110. const DbgValueLocation &RHS) {
  111. return !(LHS == RHS);
  112. }
  113. private:
  114. unsigned LocNo : 31;
  115. unsigned WasIndirect : 1;
  116. };
  117. /// LocMap - Map of where a user value is live, and its location.
  118. using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
  119. namespace {
  120. class LDVImpl;
  121. /// UserValue - A user value is a part of a debug info user variable.
  122. ///
  123. /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
  124. /// holds part of a user variable. The part is identified by a byte offset.
  125. ///
  126. /// UserValues are grouped into equivalence classes for easier searching. Two
  127. /// user values are related if they refer to the same variable, or if they are
  128. /// held by the same virtual register. The equivalence class is the transitive
  129. /// closure of that relation.
  130. class UserValue {
  131. const DILocalVariable *Variable; ///< The debug info variable we are part of.
  132. const DIExpression *Expression; ///< Any complex address expression.
  133. DebugLoc dl; ///< The debug location for the variable. This is
  134. ///< used by dwarf writer to find lexical scope.
  135. UserValue *leader; ///< Equivalence class leader.
  136. UserValue *next = nullptr; ///< Next value in equivalence class, or null.
  137. /// Numbered locations referenced by locmap.
  138. SmallVector<MachineOperand, 4> locations;
  139. /// Map of slot indices where this value is live.
  140. LocMap locInts;
  141. /// Set of interval start indexes that have been trimmed to the
  142. /// lexical scope.
  143. SmallSet<SlotIndex, 2> trimmedDefs;
  144. /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
  145. void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  146. SlotIndex StopIdx,
  147. DbgValueLocation Loc, bool Spilled, LiveIntervals &LIS,
  148. const TargetInstrInfo &TII,
  149. const TargetRegisterInfo &TRI);
  150. /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
  151. /// is live. Returns true if any changes were made.
  152. bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  153. LiveIntervals &LIS);
  154. public:
  155. /// UserValue - Create a new UserValue.
  156. UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
  157. LocMap::Allocator &alloc)
  158. : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
  159. locInts(alloc) {}
  160. /// getLeader - Get the leader of this value's equivalence class.
  161. UserValue *getLeader() {
  162. UserValue *l = leader;
  163. while (l != l->leader)
  164. l = l->leader;
  165. return leader = l;
  166. }
  167. /// getNext - Return the next UserValue in the equivalence class.
  168. UserValue *getNext() const { return next; }
  169. /// match - Does this UserValue match the parameters?
  170. bool match(const DILocalVariable *Var, const DIExpression *Expr,
  171. const DILocation *IA) const {
  172. // FIXME: The fragment should be part of the equivalence class, but not
  173. // other things in the expression like stack values.
  174. return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
  175. }
  176. /// merge - Merge equivalence classes.
  177. static UserValue *merge(UserValue *L1, UserValue *L2) {
  178. L2 = L2->getLeader();
  179. if (!L1)
  180. return L2;
  181. L1 = L1->getLeader();
  182. if (L1 == L2)
  183. return L1;
  184. // Splice L2 before L1's members.
  185. UserValue *End = L2;
  186. while (End->next) {
  187. End->leader = L1;
  188. End = End->next;
  189. }
  190. End->leader = L1;
  191. End->next = L1->next;
  192. L1->next = L2;
  193. return L1;
  194. }
  195. /// getLocationNo - Return the location number that matches Loc.
  196. unsigned getLocationNo(const MachineOperand &LocMO) {
  197. if (LocMO.isReg()) {
  198. if (LocMO.getReg() == 0)
  199. return UndefLocNo;
  200. // For register locations we dont care about use/def and other flags.
  201. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  202. if (locations[i].isReg() &&
  203. locations[i].getReg() == LocMO.getReg() &&
  204. locations[i].getSubReg() == LocMO.getSubReg())
  205. return i;
  206. } else
  207. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  208. if (LocMO.isIdenticalTo(locations[i]))
  209. return i;
  210. locations.push_back(LocMO);
  211. // We are storing a MachineOperand outside a MachineInstr.
  212. locations.back().clearParent();
  213. // Don't store def operands.
  214. if (locations.back().isReg()) {
  215. if (locations.back().isDef())
  216. locations.back().setIsDead(false);
  217. locations.back().setIsUse();
  218. }
  219. return locations.size() - 1;
  220. }
  221. /// mapVirtRegs - Ensure that all virtual register locations are mapped.
  222. void mapVirtRegs(LDVImpl *LDV);
  223. /// addDef - Add a definition point to this value.
  224. void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
  225. DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
  226. // Add a singular (Idx,Idx) -> Loc mapping.
  227. LocMap::iterator I = locInts.find(Idx);
  228. if (!I.valid() || I.start() != Idx)
  229. I.insert(Idx, Idx.getNextSlot(), Loc);
  230. else
  231. // A later DBG_VALUE at the same SlotIndex overrides the old location.
  232. I.setValue(Loc);
  233. }
  234. /// extendDef - Extend the current definition as far as possible down.
  235. /// Stop when meeting an existing def or when leaving the live
  236. /// range of VNI.
  237. /// End points where VNI is no longer live are added to Kills.
  238. /// @param Idx Starting point for the definition.
  239. /// @param Loc Location number to propagate.
  240. /// @param LR Restrict liveness to where LR has the value VNI. May be null.
  241. /// @param VNI When LR is not null, this is the value to restrict to.
  242. /// @param Kills Append end points of VNI's live range to Kills.
  243. /// @param LIS Live intervals analysis.
  244. void extendDef(SlotIndex Idx, DbgValueLocation Loc,
  245. LiveRange *LR, const VNInfo *VNI,
  246. SmallVectorImpl<SlotIndex> *Kills,
  247. LiveIntervals &LIS);
  248. /// addDefsFromCopies - The value in LI/LocNo may be copies to other
  249. /// registers. Determine if any of the copies are available at the kill
  250. /// points, and add defs if possible.
  251. /// @param LI Scan for copies of the value in LI->reg.
  252. /// @param LocNo Location number of LI->reg.
  253. /// @param WasIndirect Indicates if the original use of LI->reg was indirect
  254. /// @param Kills Points where the range of LocNo could be extended.
  255. /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
  256. void addDefsFromCopies(
  257. LiveInterval *LI, unsigned LocNo, bool WasIndirect,
  258. const SmallVectorImpl<SlotIndex> &Kills,
  259. SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
  260. MachineRegisterInfo &MRI, LiveIntervals &LIS);
  261. /// computeIntervals - Compute the live intervals of all locations after
  262. /// collecting all their def points.
  263. void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  264. LiveIntervals &LIS, LexicalScopes &LS);
  265. /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
  266. /// live. Returns true if any changes were made.
  267. bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  268. LiveIntervals &LIS);
  269. /// rewriteLocations - Rewrite virtual register locations according to the
  270. /// provided virtual register map. Record which locations were spilled.
  271. void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
  272. BitVector &SpilledLocations);
  273. /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
  274. void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  275. const TargetInstrInfo &TII,
  276. const TargetRegisterInfo &TRI,
  277. const BitVector &SpilledLocations);
  278. /// getDebugLoc - Return DebugLoc of this UserValue.
  279. DebugLoc getDebugLoc() { return dl;}
  280. void print(raw_ostream &, const TargetRegisterInfo *);
  281. };
  282. /// LDVImpl - Implementation of the LiveDebugVariables pass.
  283. class LDVImpl {
  284. LiveDebugVariables &pass;
  285. LocMap::Allocator allocator;
  286. MachineFunction *MF = nullptr;
  287. LiveIntervals *LIS;
  288. const TargetRegisterInfo *TRI;
  289. /// Whether emitDebugValues is called.
  290. bool EmitDone = false;
  291. /// Whether the machine function is modified during the pass.
  292. bool ModifiedMF = false;
  293. /// userValues - All allocated UserValue instances.
  294. SmallVector<std::unique_ptr<UserValue>, 8> userValues;
  295. /// Map virtual register to eq class leader.
  296. using VRMap = DenseMap<unsigned, UserValue *>;
  297. VRMap virtRegToEqClass;
  298. /// Map user variable to eq class leader.
  299. using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
  300. UVMap userVarMap;
  301. /// getUserValue - Find or create a UserValue.
  302. UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
  303. const DebugLoc &DL);
  304. /// lookupVirtReg - Find the EC leader for VirtReg or null.
  305. UserValue *lookupVirtReg(unsigned VirtReg);
  306. /// handleDebugValue - Add DBG_VALUE instruction to our maps.
  307. /// @param MI DBG_VALUE instruction
  308. /// @param Idx Last valid SLotIndex before instruction.
  309. /// @return True if the DBG_VALUE instruction should be deleted.
  310. bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
  311. /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
  312. /// a UserValue def for each instruction.
  313. /// @param mf MachineFunction to be scanned.
  314. /// @return True if any debug values were found.
  315. bool collectDebugValues(MachineFunction &mf);
  316. /// computeIntervals - Compute the live intervals of all user values after
  317. /// collecting all their def points.
  318. void computeIntervals();
  319. public:
  320. LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
  321. bool runOnMachineFunction(MachineFunction &mf);
  322. /// clear - Release all memory.
  323. void clear() {
  324. MF = nullptr;
  325. userValues.clear();
  326. virtRegToEqClass.clear();
  327. userVarMap.clear();
  328. // Make sure we call emitDebugValues if the machine function was modified.
  329. assert((!ModifiedMF || EmitDone) &&
  330. "Dbg values are not emitted in LDV");
  331. EmitDone = false;
  332. ModifiedMF = false;
  333. }
  334. /// mapVirtReg - Map virtual register to an equivalence class.
  335. void mapVirtReg(unsigned VirtReg, UserValue *EC);
  336. /// splitRegister - Replace all references to OldReg with NewRegs.
  337. void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
  338. /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
  339. void emitDebugValues(VirtRegMap *VRM);
  340. void print(raw_ostream&);
  341. };
  342. } // end anonymous namespace
  343. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  344. static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
  345. const LLVMContext &Ctx) {
  346. if (!DL)
  347. return;
  348. auto *Scope = cast<DIScope>(DL.getScope());
  349. // Omit the directory, because it's likely to be long and uninteresting.
  350. CommentOS << Scope->getFilename();
  351. CommentOS << ':' << DL.getLine();
  352. if (DL.getCol() != 0)
  353. CommentOS << ':' << DL.getCol();
  354. DebugLoc InlinedAtDL = DL.getInlinedAt();
  355. if (!InlinedAtDL)
  356. return;
  357. CommentOS << " @[ ";
  358. printDebugLoc(InlinedAtDL, CommentOS, Ctx);
  359. CommentOS << " ]";
  360. }
  361. static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
  362. const DILocation *DL) {
  363. const LLVMContext &Ctx = V->getContext();
  364. StringRef Res = V->getName();
  365. if (!Res.empty())
  366. OS << Res << "," << V->getLine();
  367. if (auto *InlinedAt = DL->getInlinedAt()) {
  368. if (DebugLoc InlinedAtDL = InlinedAt) {
  369. OS << " @[";
  370. printDebugLoc(InlinedAtDL, OS, Ctx);
  371. OS << "]";
  372. }
  373. }
  374. }
  375. void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  376. auto *DV = cast<DILocalVariable>(Variable);
  377. OS << "!\"";
  378. printExtendedName(OS, DV, dl);
  379. OS << "\"\t";
  380. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  381. OS << " [" << I.start() << ';' << I.stop() << "):";
  382. if (I.value().isUndef())
  383. OS << "undef";
  384. else {
  385. OS << I.value().locNo();
  386. if (I.value().wasIndirect())
  387. OS << " ind";
  388. }
  389. }
  390. for (unsigned i = 0, e = locations.size(); i != e; ++i) {
  391. OS << " Loc" << i << '=';
  392. locations[i].print(OS, TRI);
  393. }
  394. OS << '\n';
  395. }
  396. void LDVImpl::print(raw_ostream &OS) {
  397. OS << "********** DEBUG VARIABLES **********\n";
  398. for (unsigned i = 0, e = userValues.size(); i != e; ++i)
  399. userValues[i]->print(OS, TRI);
  400. }
  401. #endif
  402. void UserValue::mapVirtRegs(LDVImpl *LDV) {
  403. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  404. if (locations[i].isReg() &&
  405. TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
  406. LDV->mapVirtReg(locations[i].getReg(), this);
  407. }
  408. UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
  409. const DIExpression *Expr, const DebugLoc &DL) {
  410. UserValue *&Leader = userVarMap[Var];
  411. if (Leader) {
  412. UserValue *UV = Leader->getLeader();
  413. Leader = UV;
  414. for (; UV; UV = UV->getNext())
  415. if (UV->match(Var, Expr, DL->getInlinedAt()))
  416. return UV;
  417. }
  418. userValues.push_back(
  419. llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
  420. UserValue *UV = userValues.back().get();
  421. Leader = UserValue::merge(Leader, UV);
  422. return UV;
  423. }
  424. void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
  425. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
  426. UserValue *&Leader = virtRegToEqClass[VirtReg];
  427. Leader = UserValue::merge(Leader, EC);
  428. }
  429. UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
  430. if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
  431. return UV->getLeader();
  432. return nullptr;
  433. }
  434. bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
  435. // DBG_VALUE loc, offset, variable
  436. if (MI.getNumOperands() != 4 ||
  437. !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
  438. !MI.getOperand(2).isMetadata()) {
  439. DEBUG(dbgs() << "Can't handle " << MI);
  440. return false;
  441. }
  442. // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
  443. // register that hasn't been defined yet. If we do not remove those here, then
  444. // the re-insertion of the DBG_VALUE instruction after register allocation
  445. // will be incorrect.
  446. // TODO: If earlier passes are corrected to generate sane debug information
  447. // (and if the machine verifier is improved to catch this), then these checks
  448. // could be removed or replaced by asserts.
  449. bool Discard = false;
  450. if (MI.getOperand(0).isReg() &&
  451. TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
  452. const unsigned Reg = MI.getOperand(0).getReg();
  453. if (!LIS->hasInterval(Reg)) {
  454. // The DBG_VALUE is described by a virtual register that does not have a
  455. // live interval. Discard the DBG_VALUE.
  456. Discard = true;
  457. DEBUG(dbgs() << "Discarding debug info (no LIS interval): "
  458. << Idx << " " << MI);
  459. } else {
  460. // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
  461. // is defined dead at Idx (where Idx is the slot index for the instruction
  462. // preceeding the DBG_VALUE).
  463. const LiveInterval &LI = LIS->getInterval(Reg);
  464. LiveQueryResult LRQ = LI.Query(Idx);
  465. if (!LRQ.valueOutOrDead()) {
  466. // We have found a DBG_VALUE with the value in a virtual register that
  467. // is not live. Discard the DBG_VALUE.
  468. Discard = true;
  469. DEBUG(dbgs() << "Discarding debug info (reg not live): "
  470. << Idx << " " << MI);
  471. }
  472. }
  473. }
  474. // Get or create the UserValue for (variable,offset) here.
  475. bool IsIndirect = MI.getOperand(1).isImm();
  476. if (IsIndirect)
  477. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  478. const DILocalVariable *Var = MI.getDebugVariable();
  479. const DIExpression *Expr = MI.getDebugExpression();
  480. UserValue *UV =
  481. getUserValue(Var, Expr, MI.getDebugLoc());
  482. if (!Discard)
  483. UV->addDef(Idx, MI.getOperand(0), IsIndirect);
  484. else {
  485. MachineOperand MO = MachineOperand::CreateReg(0U, false);
  486. MO.setIsDebug();
  487. UV->addDef(Idx, MO, false);
  488. }
  489. return true;
  490. }
  491. bool LDVImpl::collectDebugValues(MachineFunction &mf) {
  492. bool Changed = false;
  493. for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
  494. ++MFI) {
  495. MachineBasicBlock *MBB = &*MFI;
  496. for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
  497. MBBI != MBBE;) {
  498. if (!MBBI->isDebugValue()) {
  499. ++MBBI;
  500. continue;
  501. }
  502. // DBG_VALUE has no slot index, use the previous instruction instead.
  503. SlotIndex Idx =
  504. MBBI == MBB->begin()
  505. ? LIS->getMBBStartIdx(MBB)
  506. : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
  507. // Handle consecutive DBG_VALUE instructions with the same slot index.
  508. do {
  509. if (handleDebugValue(*MBBI, Idx)) {
  510. MBBI = MBB->erase(MBBI);
  511. Changed = true;
  512. } else
  513. ++MBBI;
  514. } while (MBBI != MBBE && MBBI->isDebugValue());
  515. }
  516. }
  517. return Changed;
  518. }
  519. /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
  520. /// data-flow analysis to propagate them beyond basic block boundaries.
  521. void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
  522. const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
  523. LiveIntervals &LIS) {
  524. SlotIndex Start = Idx;
  525. MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
  526. SlotIndex Stop = LIS.getMBBEndIdx(MBB);
  527. LocMap::iterator I = locInts.find(Start);
  528. // Limit to VNI's live range.
  529. bool ToEnd = true;
  530. if (LR && VNI) {
  531. LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
  532. if (!Segment || Segment->valno != VNI) {
  533. if (Kills)
  534. Kills->push_back(Start);
  535. return;
  536. }
  537. if (Segment->end < Stop) {
  538. Stop = Segment->end;
  539. ToEnd = false;
  540. }
  541. }
  542. // There could already be a short def at Start.
  543. if (I.valid() && I.start() <= Start) {
  544. // Stop when meeting a different location or an already extended interval.
  545. Start = Start.getNextSlot();
  546. if (I.value() != Loc || I.stop() != Start)
  547. return;
  548. // This is a one-slot placeholder. Just skip it.
  549. ++I;
  550. }
  551. // Limited by the next def.
  552. if (I.valid() && I.start() < Stop) {
  553. Stop = I.start();
  554. ToEnd = false;
  555. }
  556. // Limited by VNI's live range.
  557. else if (!ToEnd && Kills)
  558. Kills->push_back(Stop);
  559. if (Start < Stop)
  560. I.insert(Start, Stop, Loc);
  561. }
  562. void UserValue::addDefsFromCopies(
  563. LiveInterval *LI, unsigned LocNo, bool WasIndirect,
  564. const SmallVectorImpl<SlotIndex> &Kills,
  565. SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
  566. MachineRegisterInfo &MRI, LiveIntervals &LIS) {
  567. if (Kills.empty())
  568. return;
  569. // Don't track copies from physregs, there are too many uses.
  570. if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
  571. return;
  572. // Collect all the (vreg, valno) pairs that are copies of LI.
  573. SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
  574. for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
  575. MachineInstr *MI = MO.getParent();
  576. // Copies of the full value.
  577. if (MO.getSubReg() || !MI->isCopy())
  578. continue;
  579. unsigned DstReg = MI->getOperand(0).getReg();
  580. // Don't follow copies to physregs. These are usually setting up call
  581. // arguments, and the argument registers are always call clobbered. We are
  582. // better off in the source register which could be a callee-saved register,
  583. // or it could be spilled.
  584. if (!TargetRegisterInfo::isVirtualRegister(DstReg))
  585. continue;
  586. // Is LocNo extended to reach this copy? If not, another def may be blocking
  587. // it, or we are looking at a wrong value of LI.
  588. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  589. LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
  590. if (!I.valid() || I.value().locNo() != LocNo)
  591. continue;
  592. if (!LIS.hasInterval(DstReg))
  593. continue;
  594. LiveInterval *DstLI = &LIS.getInterval(DstReg);
  595. const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
  596. assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
  597. CopyValues.push_back(std::make_pair(DstLI, DstVNI));
  598. }
  599. if (CopyValues.empty())
  600. return;
  601. DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
  602. // Try to add defs of the copied values for each kill point.
  603. for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
  604. SlotIndex Idx = Kills[i];
  605. for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
  606. LiveInterval *DstLI = CopyValues[j].first;
  607. const VNInfo *DstVNI = CopyValues[j].second;
  608. if (DstLI->getVNInfoAt(Idx) != DstVNI)
  609. continue;
  610. // Check that there isn't already a def at Idx
  611. LocMap::iterator I = locInts.find(Idx);
  612. if (I.valid() && I.start() <= Idx)
  613. continue;
  614. DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
  615. << DstVNI->id << " in " << *DstLI << '\n');
  616. MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
  617. assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
  618. unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
  619. DbgValueLocation NewLoc(LocNo, WasIndirect);
  620. I.insert(Idx, Idx.getNextSlot(), NewLoc);
  621. NewDefs.push_back(std::make_pair(Idx, NewLoc));
  622. break;
  623. }
  624. }
  625. }
  626. void UserValue::computeIntervals(MachineRegisterInfo &MRI,
  627. const TargetRegisterInfo &TRI,
  628. LiveIntervals &LIS, LexicalScopes &LS) {
  629. SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
  630. // Collect all defs to be extended (Skipping undefs).
  631. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
  632. if (!I.value().isUndef())
  633. Defs.push_back(std::make_pair(I.start(), I.value()));
  634. // Extend all defs, and possibly add new ones along the way.
  635. for (unsigned i = 0; i != Defs.size(); ++i) {
  636. SlotIndex Idx = Defs[i].first;
  637. DbgValueLocation Loc = Defs[i].second;
  638. const MachineOperand &LocMO = locations[Loc.locNo()];
  639. if (!LocMO.isReg()) {
  640. extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
  641. continue;
  642. }
  643. // Register locations are constrained to where the register value is live.
  644. if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
  645. LiveInterval *LI = nullptr;
  646. const VNInfo *VNI = nullptr;
  647. if (LIS.hasInterval(LocMO.getReg())) {
  648. LI = &LIS.getInterval(LocMO.getReg());
  649. VNI = LI->getVNInfoAt(Idx);
  650. }
  651. SmallVector<SlotIndex, 16> Kills;
  652. extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
  653. if (LI)
  654. addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
  655. LIS);
  656. continue;
  657. }
  658. // For physregs, we only mark the start slot idx. DwarfDebug will see it
  659. // as if the DBG_VALUE is valid up until the end of the basic block, or
  660. // the next def of the physical register. So we do not need to extend the
  661. // range. It might actually happen that the DBG_VALUE is the last use of
  662. // the physical register (e.g. if this is an unused input argument to a
  663. // function).
  664. }
  665. // Erase all the undefs.
  666. for (LocMap::iterator I = locInts.begin(); I.valid();)
  667. if (I.value().isUndef())
  668. I.erase();
  669. else
  670. ++I;
  671. // The computed intervals may extend beyond the range of the debug
  672. // location's lexical scope. In this case, splitting of an interval
  673. // can result in an interval outside of the scope being created,
  674. // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
  675. // this, trim the intervals to the lexical scope.
  676. LexicalScope *Scope = LS.findLexicalScope(dl);
  677. if (!Scope)
  678. return;
  679. SlotIndex PrevEnd;
  680. LocMap::iterator I = locInts.begin();
  681. // Iterate over the lexical scope ranges. Each time round the loop
  682. // we check the intervals for overlap with the end of the previous
  683. // range and the start of the next. The first range is handled as
  684. // a special case where there is no PrevEnd.
  685. for (const InsnRange &Range : Scope->getRanges()) {
  686. SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
  687. SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
  688. // At the start of each iteration I has been advanced so that
  689. // I.stop() >= PrevEnd. Check for overlap.
  690. if (PrevEnd && I.start() < PrevEnd) {
  691. SlotIndex IStop = I.stop();
  692. DbgValueLocation Loc = I.value();
  693. // Stop overlaps previous end - trim the end of the interval to
  694. // the scope range.
  695. I.setStopUnchecked(PrevEnd);
  696. ++I;
  697. // If the interval also overlaps the start of the "next" (i.e.
  698. // current) range create a new interval for the remainder (which
  699. // may be further trimmed).
  700. if (RStart < IStop)
  701. I.insert(RStart, IStop, Loc);
  702. }
  703. // Advance I so that I.stop() >= RStart, and check for overlap.
  704. I.advanceTo(RStart);
  705. if (!I.valid())
  706. return;
  707. if (I.start() < RStart) {
  708. // Interval start overlaps range - trim to the scope range.
  709. I.setStartUnchecked(RStart);
  710. // Remember that this interval was trimmed.
  711. trimmedDefs.insert(RStart);
  712. }
  713. // The end of a lexical scope range is the last instruction in the
  714. // range. To convert to an interval we need the index of the
  715. // instruction after it.
  716. REnd = REnd.getNextIndex();
  717. // Advance I to first interval outside current range.
  718. I.advanceTo(REnd);
  719. if (!I.valid())
  720. return;
  721. PrevEnd = REnd;
  722. }
  723. // Check for overlap with end of final range.
  724. if (PrevEnd && I.start() < PrevEnd)
  725. I.setStopUnchecked(PrevEnd);
  726. }
  727. void LDVImpl::computeIntervals() {
  728. LexicalScopes LS;
  729. LS.initialize(*MF);
  730. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  731. userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
  732. userValues[i]->mapVirtRegs(this);
  733. }
  734. }
  735. bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
  736. clear();
  737. MF = &mf;
  738. LIS = &pass.getAnalysis<LiveIntervals>();
  739. TRI = mf.getSubtarget().getRegisterInfo();
  740. DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
  741. << mf.getName() << " **********\n");
  742. bool Changed = collectDebugValues(mf);
  743. computeIntervals();
  744. DEBUG(print(dbgs()));
  745. ModifiedMF = Changed;
  746. return Changed;
  747. }
  748. static void removeDebugValues(MachineFunction &mf) {
  749. for (MachineBasicBlock &MBB : mf) {
  750. for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
  751. if (!MBBI->isDebugValue()) {
  752. ++MBBI;
  753. continue;
  754. }
  755. MBBI = MBB.erase(MBBI);
  756. }
  757. }
  758. }
  759. bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
  760. if (!EnableLDV)
  761. return false;
  762. if (!mf.getFunction().getSubprogram()) {
  763. removeDebugValues(mf);
  764. return false;
  765. }
  766. if (!pImpl)
  767. pImpl = new LDVImpl(this);
  768. return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
  769. }
  770. void LiveDebugVariables::releaseMemory() {
  771. if (pImpl)
  772. static_cast<LDVImpl*>(pImpl)->clear();
  773. }
  774. LiveDebugVariables::~LiveDebugVariables() {
  775. if (pImpl)
  776. delete static_cast<LDVImpl*>(pImpl);
  777. }
  778. //===----------------------------------------------------------------------===//
  779. // Live Range Splitting
  780. //===----------------------------------------------------------------------===//
  781. bool
  782. UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  783. LiveIntervals& LIS) {
  784. DEBUG({
  785. dbgs() << "Splitting Loc" << OldLocNo << '\t';
  786. print(dbgs(), nullptr);
  787. });
  788. bool DidChange = false;
  789. LocMap::iterator LocMapI;
  790. LocMapI.setMap(locInts);
  791. for (unsigned i = 0; i != NewRegs.size(); ++i) {
  792. LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
  793. if (LI->empty())
  794. continue;
  795. // Don't allocate the new LocNo until it is needed.
  796. unsigned NewLocNo = UndefLocNo;
  797. // Iterate over the overlaps between locInts and LI.
  798. LocMapI.find(LI->beginIndex());
  799. if (!LocMapI.valid())
  800. continue;
  801. LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
  802. LiveInterval::iterator LIE = LI->end();
  803. while (LocMapI.valid() && LII != LIE) {
  804. // At this point, we know that LocMapI.stop() > LII->start.
  805. LII = LI->advanceTo(LII, LocMapI.start());
  806. if (LII == LIE)
  807. break;
  808. // Now LII->end > LocMapI.start(). Do we have an overlap?
  809. if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
  810. // Overlapping correct location. Allocate NewLocNo now.
  811. if (NewLocNo == UndefLocNo) {
  812. MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
  813. MO.setSubReg(locations[OldLocNo].getSubReg());
  814. NewLocNo = getLocationNo(MO);
  815. DidChange = true;
  816. }
  817. SlotIndex LStart = LocMapI.start();
  818. SlotIndex LStop = LocMapI.stop();
  819. DbgValueLocation OldLoc = LocMapI.value();
  820. // Trim LocMapI down to the LII overlap.
  821. if (LStart < LII->start)
  822. LocMapI.setStartUnchecked(LII->start);
  823. if (LStop > LII->end)
  824. LocMapI.setStopUnchecked(LII->end);
  825. // Change the value in the overlap. This may trigger coalescing.
  826. LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
  827. // Re-insert any removed OldLocNo ranges.
  828. if (LStart < LocMapI.start()) {
  829. LocMapI.insert(LStart, LocMapI.start(), OldLoc);
  830. ++LocMapI;
  831. assert(LocMapI.valid() && "Unexpected coalescing");
  832. }
  833. if (LStop > LocMapI.stop()) {
  834. ++LocMapI;
  835. LocMapI.insert(LII->end, LStop, OldLoc);
  836. --LocMapI;
  837. }
  838. }
  839. // Advance to the next overlap.
  840. if (LII->end < LocMapI.stop()) {
  841. if (++LII == LIE)
  842. break;
  843. LocMapI.advanceTo(LII->start);
  844. } else {
  845. ++LocMapI;
  846. if (!LocMapI.valid())
  847. break;
  848. LII = LI->advanceTo(LII, LocMapI.start());
  849. }
  850. }
  851. }
  852. // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
  853. locations.erase(locations.begin() + OldLocNo);
  854. LocMapI.goToBegin();
  855. while (LocMapI.valid()) {
  856. DbgValueLocation v = LocMapI.value();
  857. if (v.locNo() == OldLocNo) {
  858. DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
  859. << LocMapI.stop() << ")\n");
  860. LocMapI.erase();
  861. } else {
  862. if (v.locNo() > OldLocNo)
  863. LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
  864. ++LocMapI;
  865. }
  866. }
  867. DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
  868. return DidChange;
  869. }
  870. bool
  871. UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
  872. LiveIntervals &LIS) {
  873. bool DidChange = false;
  874. // Split locations referring to OldReg. Iterate backwards so splitLocation can
  875. // safely erase unused locations.
  876. for (unsigned i = locations.size(); i ; --i) {
  877. unsigned LocNo = i-1;
  878. const MachineOperand *Loc = &locations[LocNo];
  879. if (!Loc->isReg() || Loc->getReg() != OldReg)
  880. continue;
  881. DidChange |= splitLocation(LocNo, NewRegs, LIS);
  882. }
  883. return DidChange;
  884. }
  885. void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
  886. bool DidChange = false;
  887. for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
  888. DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
  889. if (!DidChange)
  890. return;
  891. // Map all of the new virtual registers.
  892. UserValue *UV = lookupVirtReg(OldReg);
  893. for (unsigned i = 0; i != NewRegs.size(); ++i)
  894. mapVirtReg(NewRegs[i], UV);
  895. }
  896. void LiveDebugVariables::
  897. splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
  898. if (pImpl)
  899. static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
  900. }
  901. void UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
  902. BitVector &SpilledLocations) {
  903. // Build a set of new locations with new numbers so we can coalesce our
  904. // IntervalMap if two vreg intervals collapse to the same physical location.
  905. // Use MapVector instead of SetVector because MapVector::insert returns the
  906. // position of the previously or newly inserted element. The boolean value
  907. // tracks if the location was produced by a spill.
  908. // FIXME: This will be problematic if we ever support direct and indirect
  909. // frame index locations, i.e. expressing both variables in memory and
  910. // 'int x, *px = &x'. The "spilled" bit must become part of the location.
  911. MapVector<MachineOperand, bool> NewLocations;
  912. SmallVector<unsigned, 4> LocNoMap(locations.size());
  913. for (unsigned I = 0, E = locations.size(); I != E; ++I) {
  914. bool Spilled = false;
  915. MachineOperand Loc = locations[I];
  916. // Only virtual registers are rewritten.
  917. if (Loc.isReg() && Loc.getReg() &&
  918. TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
  919. unsigned VirtReg = Loc.getReg();
  920. if (VRM.isAssignedReg(VirtReg) &&
  921. TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
  922. // This can create a %noreg operand in rare cases when the sub-register
  923. // index is no longer available. That means the user value is in a
  924. // non-existent sub-register, and %noreg is exactly what we want.
  925. Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
  926. } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
  927. // FIXME: Translate SubIdx to a stackslot offset.
  928. Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
  929. Spilled = true;
  930. } else {
  931. Loc.setReg(0);
  932. Loc.setSubReg(0);
  933. }
  934. }
  935. // Insert this location if it doesn't already exist and record a mapping
  936. // from the old number to the new number.
  937. auto InsertResult = NewLocations.insert({Loc, Spilled});
  938. unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
  939. LocNoMap[I] = NewLocNo;
  940. }
  941. // Rewrite the locations and record which ones were spill slots.
  942. locations.clear();
  943. SpilledLocations.clear();
  944. SpilledLocations.resize(NewLocations.size());
  945. for (auto &Pair : NewLocations) {
  946. locations.push_back(Pair.first);
  947. if (Pair.second) {
  948. unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
  949. SpilledLocations.set(NewLocNo);
  950. }
  951. }
  952. // Update the interval map, but only coalesce left, since intervals to the
  953. // right use the old location numbers. This should merge two contiguous
  954. // DBG_VALUE intervals with different vregs that were allocated to the same
  955. // physical register.
  956. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  957. DbgValueLocation Loc = I.value();
  958. unsigned NewLocNo = LocNoMap[Loc.locNo()];
  959. I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
  960. I.setStart(I.start());
  961. }
  962. }
  963. /// Find an iterator for inserting a DBG_VALUE instruction.
  964. static MachineBasicBlock::iterator
  965. findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
  966. LiveIntervals &LIS) {
  967. SlotIndex Start = LIS.getMBBStartIdx(MBB);
  968. Idx = Idx.getBaseIndex();
  969. // Try to find an insert location by going backwards from Idx.
  970. MachineInstr *MI;
  971. while (!(MI = LIS.getInstructionFromIndex(Idx))) {
  972. // We've reached the beginning of MBB.
  973. if (Idx == Start) {
  974. MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
  975. return I;
  976. }
  977. Idx = Idx.getPrevIndex();
  978. }
  979. // Don't insert anything after the first terminator, though.
  980. return MI->isTerminator() ? MBB->getFirstTerminator() :
  981. std::next(MachineBasicBlock::iterator(MI));
  982. }
  983. /// Find an iterator for inserting the next DBG_VALUE instruction
  984. /// (or end if no more insert locations found).
  985. static MachineBasicBlock::iterator
  986. findNextInsertLocation(MachineBasicBlock *MBB,
  987. MachineBasicBlock::iterator I,
  988. SlotIndex StopIdx, MachineOperand &LocMO,
  989. LiveIntervals &LIS,
  990. const TargetRegisterInfo &TRI) {
  991. if (!LocMO.isReg())
  992. return MBB->instr_end();
  993. unsigned Reg = LocMO.getReg();
  994. // Find the next instruction in the MBB that define the register Reg.
  995. while (I != MBB->end() && !I->isTerminator()) {
  996. if (!LIS.isNotInMIMap(*I) &&
  997. SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
  998. break;
  999. if (I->definesRegister(Reg, &TRI))
  1000. // The insert location is directly after the instruction/bundle.
  1001. return std::next(I);
  1002. ++I;
  1003. }
  1004. return MBB->end();
  1005. }
  1006. void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  1007. SlotIndex StopIdx,
  1008. DbgValueLocation Loc, bool Spilled,
  1009. LiveIntervals &LIS,
  1010. const TargetInstrInfo &TII,
  1011. const TargetRegisterInfo &TRI) {
  1012. SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
  1013. // Only search within the current MBB.
  1014. StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
  1015. MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
  1016. MachineOperand &MO = locations[Loc.locNo()];
  1017. ++NumInsertedDebugValues;
  1018. assert(cast<DILocalVariable>(Variable)
  1019. ->isValidLocationForIntrinsic(getDebugLoc()) &&
  1020. "Expected inlined-at fields to agree");
  1021. // If the location was spilled, the new DBG_VALUE will be indirect. If the
  1022. // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
  1023. // that the original virtual register was a pointer.
  1024. const DIExpression *Expr = Expression;
  1025. bool IsIndirect = Loc.wasIndirect();
  1026. if (Spilled) {
  1027. if (IsIndirect)
  1028. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  1029. IsIndirect = true;
  1030. }
  1031. assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
  1032. do {
  1033. MachineInstrBuilder MIB =
  1034. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
  1035. .add(MO);
  1036. if (IsIndirect)
  1037. MIB.addImm(0U);
  1038. else
  1039. MIB.addReg(0U, RegState::Debug);
  1040. MIB.addMetadata(Variable).addMetadata(Expr);
  1041. // Continue and insert DBG_VALUES after every redefinition of register
  1042. // associated with the debug value within the range
  1043. I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
  1044. } while (I != MBB->end());
  1045. }
  1046. void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  1047. const TargetInstrInfo &TII,
  1048. const TargetRegisterInfo &TRI,
  1049. const BitVector &SpilledLocations) {
  1050. MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
  1051. for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
  1052. SlotIndex Start = I.start();
  1053. SlotIndex Stop = I.stop();
  1054. DbgValueLocation Loc = I.value();
  1055. bool Spilled = !Loc.isUndef() ? SpilledLocations.test(Loc.locNo()) : false;
  1056. // If the interval start was trimmed to the lexical scope insert the
  1057. // DBG_VALUE at the previous index (otherwise it appears after the
  1058. // first instruction in the range).
  1059. if (trimmedDefs.count(Start))
  1060. Start = Start.getPrevIndex();
  1061. DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
  1062. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
  1063. SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1064. DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1065. insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
  1066. // This interval may span multiple basic blocks.
  1067. // Insert a DBG_VALUE into each one.
  1068. while (Stop > MBBEnd) {
  1069. // Move to the next block.
  1070. Start = MBBEnd;
  1071. if (++MBB == MFEnd)
  1072. break;
  1073. MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1074. DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1075. insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
  1076. }
  1077. DEBUG(dbgs() << '\n');
  1078. if (MBB == MFEnd)
  1079. break;
  1080. ++I;
  1081. }
  1082. }
  1083. void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
  1084. DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
  1085. if (!MF)
  1086. return;
  1087. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1088. BitVector SpilledLocations;
  1089. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  1090. DEBUG(userValues[i]->print(dbgs(), TRI));
  1091. userValues[i]->rewriteLocations(*VRM, *TRI, SpilledLocations);
  1092. userValues[i]->emitDebugValues(VRM, *LIS, *TII, *TRI, SpilledLocations);
  1093. }
  1094. EmitDone = true;
  1095. }
  1096. void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
  1097. if (pImpl)
  1098. static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
  1099. }
  1100. bool LiveDebugVariables::doInitialization(Module &M) {
  1101. return Pass::doInitialization(M);
  1102. }
  1103. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1104. LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
  1105. if (pImpl)
  1106. static_cast<LDVImpl*>(pImpl)->print(dbgs());
  1107. }
  1108. #endif