LiveDebugVariables.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. /// Return the location number that matches Loc.
  196. ///
  197. /// For undef values we always return location number UndefLocNo without
  198. /// inserting anything in locations. Since locations is a vector and the
  199. /// location number is the position in the vector and UndefLocNo is ~0,
  200. /// we would need a very big vector to put the value at the right position.
  201. unsigned getLocationNo(const MachineOperand &LocMO) {
  202. if (LocMO.isReg()) {
  203. if (LocMO.getReg() == 0)
  204. return UndefLocNo;
  205. // For register locations we dont care about use/def and other flags.
  206. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  207. if (locations[i].isReg() &&
  208. locations[i].getReg() == LocMO.getReg() &&
  209. locations[i].getSubReg() == LocMO.getSubReg())
  210. return i;
  211. } else
  212. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  213. if (LocMO.isIdenticalTo(locations[i]))
  214. return i;
  215. locations.push_back(LocMO);
  216. // We are storing a MachineOperand outside a MachineInstr.
  217. locations.back().clearParent();
  218. // Don't store def operands.
  219. if (locations.back().isReg()) {
  220. if (locations.back().isDef())
  221. locations.back().setIsDead(false);
  222. locations.back().setIsUse();
  223. }
  224. return locations.size() - 1;
  225. }
  226. /// mapVirtRegs - Ensure that all virtual register locations are mapped.
  227. void mapVirtRegs(LDVImpl *LDV);
  228. /// addDef - Add a definition point to this value.
  229. void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
  230. DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
  231. // Add a singular (Idx,Idx) -> Loc mapping.
  232. LocMap::iterator I = locInts.find(Idx);
  233. if (!I.valid() || I.start() != Idx)
  234. I.insert(Idx, Idx.getNextSlot(), Loc);
  235. else
  236. // A later DBG_VALUE at the same SlotIndex overrides the old location.
  237. I.setValue(Loc);
  238. }
  239. /// extendDef - Extend the current definition as far as possible down.
  240. /// Stop when meeting an existing def or when leaving the live
  241. /// range of VNI.
  242. /// End points where VNI is no longer live are added to Kills.
  243. /// @param Idx Starting point for the definition.
  244. /// @param Loc Location number to propagate.
  245. /// @param LR Restrict liveness to where LR has the value VNI. May be null.
  246. /// @param VNI When LR is not null, this is the value to restrict to.
  247. /// @param Kills Append end points of VNI's live range to Kills.
  248. /// @param LIS Live intervals analysis.
  249. void extendDef(SlotIndex Idx, DbgValueLocation Loc,
  250. LiveRange *LR, const VNInfo *VNI,
  251. SmallVectorImpl<SlotIndex> *Kills,
  252. LiveIntervals &LIS);
  253. /// addDefsFromCopies - The value in LI/LocNo may be copies to other
  254. /// registers. Determine if any of the copies are available at the kill
  255. /// points, and add defs if possible.
  256. /// @param LI Scan for copies of the value in LI->reg.
  257. /// @param LocNo Location number of LI->reg.
  258. /// @param WasIndirect Indicates if the original use of LI->reg was indirect
  259. /// @param Kills Points where the range of LocNo could be extended.
  260. /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
  261. void addDefsFromCopies(
  262. LiveInterval *LI, unsigned LocNo, bool WasIndirect,
  263. const SmallVectorImpl<SlotIndex> &Kills,
  264. SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
  265. MachineRegisterInfo &MRI, LiveIntervals &LIS);
  266. /// computeIntervals - Compute the live intervals of all locations after
  267. /// collecting all their def points.
  268. void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  269. LiveIntervals &LIS, LexicalScopes &LS);
  270. /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
  271. /// live. Returns true if any changes were made.
  272. bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
  273. LiveIntervals &LIS);
  274. /// rewriteLocations - Rewrite virtual register locations according to the
  275. /// provided virtual register map. Record which locations were spilled.
  276. void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
  277. BitVector &SpilledLocations);
  278. /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
  279. void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  280. const TargetInstrInfo &TII,
  281. const TargetRegisterInfo &TRI,
  282. const BitVector &SpilledLocations);
  283. /// getDebugLoc - Return DebugLoc of this UserValue.
  284. DebugLoc getDebugLoc() { return dl;}
  285. void print(raw_ostream &, const TargetRegisterInfo *);
  286. };
  287. /// LDVImpl - Implementation of the LiveDebugVariables pass.
  288. class LDVImpl {
  289. LiveDebugVariables &pass;
  290. LocMap::Allocator allocator;
  291. MachineFunction *MF = nullptr;
  292. LiveIntervals *LIS;
  293. const TargetRegisterInfo *TRI;
  294. /// Whether emitDebugValues is called.
  295. bool EmitDone = false;
  296. /// Whether the machine function is modified during the pass.
  297. bool ModifiedMF = false;
  298. /// userValues - All allocated UserValue instances.
  299. SmallVector<std::unique_ptr<UserValue>, 8> userValues;
  300. /// Map virtual register to eq class leader.
  301. using VRMap = DenseMap<unsigned, UserValue *>;
  302. VRMap virtRegToEqClass;
  303. /// Map user variable to eq class leader.
  304. using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
  305. UVMap userVarMap;
  306. /// getUserValue - Find or create a UserValue.
  307. UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
  308. const DebugLoc &DL);
  309. /// lookupVirtReg - Find the EC leader for VirtReg or null.
  310. UserValue *lookupVirtReg(unsigned VirtReg);
  311. /// handleDebugValue - Add DBG_VALUE instruction to our maps.
  312. /// @param MI DBG_VALUE instruction
  313. /// @param Idx Last valid SLotIndex before instruction.
  314. /// @return True if the DBG_VALUE instruction should be deleted.
  315. bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
  316. /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
  317. /// a UserValue def for each instruction.
  318. /// @param mf MachineFunction to be scanned.
  319. /// @return True if any debug values were found.
  320. bool collectDebugValues(MachineFunction &mf);
  321. /// computeIntervals - Compute the live intervals of all user values after
  322. /// collecting all their def points.
  323. void computeIntervals();
  324. public:
  325. LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
  326. bool runOnMachineFunction(MachineFunction &mf);
  327. /// clear - Release all memory.
  328. void clear() {
  329. MF = nullptr;
  330. userValues.clear();
  331. virtRegToEqClass.clear();
  332. userVarMap.clear();
  333. // Make sure we call emitDebugValues if the machine function was modified.
  334. assert((!ModifiedMF || EmitDone) &&
  335. "Dbg values are not emitted in LDV");
  336. EmitDone = false;
  337. ModifiedMF = false;
  338. }
  339. /// mapVirtReg - Map virtual register to an equivalence class.
  340. void mapVirtReg(unsigned VirtReg, UserValue *EC);
  341. /// splitRegister - Replace all references to OldReg with NewRegs.
  342. void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
  343. /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
  344. void emitDebugValues(VirtRegMap *VRM);
  345. void print(raw_ostream&);
  346. };
  347. } // end anonymous namespace
  348. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  349. static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
  350. const LLVMContext &Ctx) {
  351. if (!DL)
  352. return;
  353. auto *Scope = cast<DIScope>(DL.getScope());
  354. // Omit the directory, because it's likely to be long and uninteresting.
  355. CommentOS << Scope->getFilename();
  356. CommentOS << ':' << DL.getLine();
  357. if (DL.getCol() != 0)
  358. CommentOS << ':' << DL.getCol();
  359. DebugLoc InlinedAtDL = DL.getInlinedAt();
  360. if (!InlinedAtDL)
  361. return;
  362. CommentOS << " @[ ";
  363. printDebugLoc(InlinedAtDL, CommentOS, Ctx);
  364. CommentOS << " ]";
  365. }
  366. static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
  367. const DILocation *DL) {
  368. const LLVMContext &Ctx = V->getContext();
  369. StringRef Res = V->getName();
  370. if (!Res.empty())
  371. OS << Res << "," << V->getLine();
  372. if (auto *InlinedAt = DL->getInlinedAt()) {
  373. if (DebugLoc InlinedAtDL = InlinedAt) {
  374. OS << " @[";
  375. printDebugLoc(InlinedAtDL, OS, Ctx);
  376. OS << "]";
  377. }
  378. }
  379. }
  380. void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  381. auto *DV = cast<DILocalVariable>(Variable);
  382. OS << "!\"";
  383. printExtendedName(OS, DV, dl);
  384. OS << "\"\t";
  385. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  386. OS << " [" << I.start() << ';' << I.stop() << "):";
  387. if (I.value().isUndef())
  388. OS << "undef";
  389. else {
  390. OS << I.value().locNo();
  391. if (I.value().wasIndirect())
  392. OS << " ind";
  393. }
  394. }
  395. for (unsigned i = 0, e = locations.size(); i != e; ++i) {
  396. OS << " Loc" << i << '=';
  397. locations[i].print(OS, TRI);
  398. }
  399. OS << '\n';
  400. }
  401. void LDVImpl::print(raw_ostream &OS) {
  402. OS << "********** DEBUG VARIABLES **********\n";
  403. for (unsigned i = 0, e = userValues.size(); i != e; ++i)
  404. userValues[i]->print(OS, TRI);
  405. }
  406. #endif
  407. void UserValue::mapVirtRegs(LDVImpl *LDV) {
  408. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  409. if (locations[i].isReg() &&
  410. TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
  411. LDV->mapVirtReg(locations[i].getReg(), this);
  412. }
  413. UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
  414. const DIExpression *Expr, const DebugLoc &DL) {
  415. UserValue *&Leader = userVarMap[Var];
  416. if (Leader) {
  417. UserValue *UV = Leader->getLeader();
  418. Leader = UV;
  419. for (; UV; UV = UV->getNext())
  420. if (UV->match(Var, Expr, DL->getInlinedAt()))
  421. return UV;
  422. }
  423. userValues.push_back(
  424. llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
  425. UserValue *UV = userValues.back().get();
  426. Leader = UserValue::merge(Leader, UV);
  427. return UV;
  428. }
  429. void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
  430. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
  431. UserValue *&Leader = virtRegToEqClass[VirtReg];
  432. Leader = UserValue::merge(Leader, EC);
  433. }
  434. UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
  435. if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
  436. return UV->getLeader();
  437. return nullptr;
  438. }
  439. bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
  440. // DBG_VALUE loc, offset, variable
  441. if (MI.getNumOperands() != 4 ||
  442. !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
  443. !MI.getOperand(2).isMetadata()) {
  444. LLVM_DEBUG(dbgs() << "Can't handle " << MI);
  445. return false;
  446. }
  447. // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
  448. // register that hasn't been defined yet. If we do not remove those here, then
  449. // the re-insertion of the DBG_VALUE instruction after register allocation
  450. // will be incorrect.
  451. // TODO: If earlier passes are corrected to generate sane debug information
  452. // (and if the machine verifier is improved to catch this), then these checks
  453. // could be removed or replaced by asserts.
  454. bool Discard = false;
  455. if (MI.getOperand(0).isReg() &&
  456. TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
  457. const unsigned Reg = MI.getOperand(0).getReg();
  458. if (!LIS->hasInterval(Reg)) {
  459. // The DBG_VALUE is described by a virtual register that does not have a
  460. // live interval. Discard the DBG_VALUE.
  461. Discard = true;
  462. LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
  463. << " " << MI);
  464. } else {
  465. // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
  466. // is defined dead at Idx (where Idx is the slot index for the instruction
  467. // preceeding the DBG_VALUE).
  468. const LiveInterval &LI = LIS->getInterval(Reg);
  469. LiveQueryResult LRQ = LI.Query(Idx);
  470. if (!LRQ.valueOutOrDead()) {
  471. // We have found a DBG_VALUE with the value in a virtual register that
  472. // is not live. Discard the DBG_VALUE.
  473. Discard = true;
  474. LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
  475. << " " << MI);
  476. }
  477. }
  478. }
  479. // Get or create the UserValue for (variable,offset) here.
  480. bool IsIndirect = MI.getOperand(1).isImm();
  481. if (IsIndirect)
  482. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  483. const DILocalVariable *Var = MI.getDebugVariable();
  484. const DIExpression *Expr = MI.getDebugExpression();
  485. UserValue *UV =
  486. getUserValue(Var, Expr, MI.getDebugLoc());
  487. if (!Discard)
  488. UV->addDef(Idx, MI.getOperand(0), IsIndirect);
  489. else {
  490. MachineOperand MO = MachineOperand::CreateReg(0U, false);
  491. MO.setIsDebug();
  492. UV->addDef(Idx, MO, false);
  493. }
  494. return true;
  495. }
  496. bool LDVImpl::collectDebugValues(MachineFunction &mf) {
  497. bool Changed = false;
  498. for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
  499. ++MFI) {
  500. MachineBasicBlock *MBB = &*MFI;
  501. for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
  502. MBBI != MBBE;) {
  503. if (!MBBI->isDebugValue()) {
  504. ++MBBI;
  505. continue;
  506. }
  507. // DBG_VALUE has no slot index, use the previous instruction instead.
  508. SlotIndex Idx =
  509. MBBI == MBB->begin()
  510. ? LIS->getMBBStartIdx(MBB)
  511. : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
  512. // Handle consecutive DBG_VALUE instructions with the same slot index.
  513. do {
  514. if (handleDebugValue(*MBBI, Idx)) {
  515. MBBI = MBB->erase(MBBI);
  516. Changed = true;
  517. } else
  518. ++MBBI;
  519. } while (MBBI != MBBE && MBBI->isDebugValue());
  520. }
  521. }
  522. return Changed;
  523. }
  524. /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
  525. /// data-flow analysis to propagate them beyond basic block boundaries.
  526. void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
  527. const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
  528. LiveIntervals &LIS) {
  529. SlotIndex Start = Idx;
  530. MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
  531. SlotIndex Stop = LIS.getMBBEndIdx(MBB);
  532. LocMap::iterator I = locInts.find(Start);
  533. // Limit to VNI's live range.
  534. bool ToEnd = true;
  535. if (LR && VNI) {
  536. LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
  537. if (!Segment || Segment->valno != VNI) {
  538. if (Kills)
  539. Kills->push_back(Start);
  540. return;
  541. }
  542. if (Segment->end < Stop) {
  543. Stop = Segment->end;
  544. ToEnd = false;
  545. }
  546. }
  547. // There could already be a short def at Start.
  548. if (I.valid() && I.start() <= Start) {
  549. // Stop when meeting a different location or an already extended interval.
  550. Start = Start.getNextSlot();
  551. if (I.value() != Loc || I.stop() != Start)
  552. return;
  553. // This is a one-slot placeholder. Just skip it.
  554. ++I;
  555. }
  556. // Limited by the next def.
  557. if (I.valid() && I.start() < Stop) {
  558. Stop = I.start();
  559. ToEnd = false;
  560. }
  561. // Limited by VNI's live range.
  562. else if (!ToEnd && Kills)
  563. Kills->push_back(Stop);
  564. if (Start < Stop)
  565. I.insert(Start, Stop, Loc);
  566. }
  567. void UserValue::addDefsFromCopies(
  568. LiveInterval *LI, unsigned LocNo, bool WasIndirect,
  569. const SmallVectorImpl<SlotIndex> &Kills,
  570. SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
  571. MachineRegisterInfo &MRI, LiveIntervals &LIS) {
  572. if (Kills.empty())
  573. return;
  574. // Don't track copies from physregs, there are too many uses.
  575. if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
  576. return;
  577. // Collect all the (vreg, valno) pairs that are copies of LI.
  578. SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
  579. for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
  580. MachineInstr *MI = MO.getParent();
  581. // Copies of the full value.
  582. if (MO.getSubReg() || !MI->isCopy())
  583. continue;
  584. unsigned DstReg = MI->getOperand(0).getReg();
  585. // Don't follow copies to physregs. These are usually setting up call
  586. // arguments, and the argument registers are always call clobbered. We are
  587. // better off in the source register which could be a callee-saved register,
  588. // or it could be spilled.
  589. if (!TargetRegisterInfo::isVirtualRegister(DstReg))
  590. continue;
  591. // Is LocNo extended to reach this copy? If not, another def may be blocking
  592. // it, or we are looking at a wrong value of LI.
  593. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  594. LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
  595. if (!I.valid() || I.value().locNo() != LocNo)
  596. continue;
  597. if (!LIS.hasInterval(DstReg))
  598. continue;
  599. LiveInterval *DstLI = &LIS.getInterval(DstReg);
  600. const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
  601. assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
  602. CopyValues.push_back(std::make_pair(DstLI, DstVNI));
  603. }
  604. if (CopyValues.empty())
  605. return;
  606. LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
  607. << '\n');
  608. // Try to add defs of the copied values for each kill point.
  609. for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
  610. SlotIndex Idx = Kills[i];
  611. for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
  612. LiveInterval *DstLI = CopyValues[j].first;
  613. const VNInfo *DstVNI = CopyValues[j].second;
  614. if (DstLI->getVNInfoAt(Idx) != DstVNI)
  615. continue;
  616. // Check that there isn't already a def at Idx
  617. LocMap::iterator I = locInts.find(Idx);
  618. if (I.valid() && I.start() <= Idx)
  619. continue;
  620. LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
  621. << DstVNI->id << " in " << *DstLI << '\n');
  622. MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
  623. assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
  624. unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
  625. DbgValueLocation NewLoc(LocNo, WasIndirect);
  626. I.insert(Idx, Idx.getNextSlot(), NewLoc);
  627. NewDefs.push_back(std::make_pair(Idx, NewLoc));
  628. break;
  629. }
  630. }
  631. }
  632. void UserValue::computeIntervals(MachineRegisterInfo &MRI,
  633. const TargetRegisterInfo &TRI,
  634. LiveIntervals &LIS, LexicalScopes &LS) {
  635. SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
  636. // Collect all defs to be extended (Skipping undefs).
  637. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
  638. if (!I.value().isUndef())
  639. Defs.push_back(std::make_pair(I.start(), I.value()));
  640. // Extend all defs, and possibly add new ones along the way.
  641. for (unsigned i = 0; i != Defs.size(); ++i) {
  642. SlotIndex Idx = Defs[i].first;
  643. DbgValueLocation Loc = Defs[i].second;
  644. const MachineOperand &LocMO = locations[Loc.locNo()];
  645. if (!LocMO.isReg()) {
  646. extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
  647. continue;
  648. }
  649. // Register locations are constrained to where the register value is live.
  650. if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
  651. LiveInterval *LI = nullptr;
  652. const VNInfo *VNI = nullptr;
  653. if (LIS.hasInterval(LocMO.getReg())) {
  654. LI = &LIS.getInterval(LocMO.getReg());
  655. VNI = LI->getVNInfoAt(Idx);
  656. }
  657. SmallVector<SlotIndex, 16> Kills;
  658. extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
  659. if (LI)
  660. addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
  661. LIS);
  662. continue;
  663. }
  664. // For physregs, we only mark the start slot idx. DwarfDebug will see it
  665. // as if the DBG_VALUE is valid up until the end of the basic block, or
  666. // the next def of the physical register. So we do not need to extend the
  667. // range. It might actually happen that the DBG_VALUE is the last use of
  668. // the physical register (e.g. if this is an unused input argument to a
  669. // function).
  670. }
  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. LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
  741. << mf.getName() << " **********\n");
  742. bool Changed = collectDebugValues(mf);
  743. computeIntervals();
  744. LLVM_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. LLVM_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. LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
  859. << LocMapI.stop() << ")\n");
  860. LocMapI.erase();
  861. } else {
  862. // Undef values always have location number UndefLocNo, so don't change
  863. // locNo in that case. See getLocationNo().
  864. if (!v.isUndef() && v.locNo() > OldLocNo)
  865. LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
  866. ++LocMapI;
  867. }
  868. }
  869. LLVM_DEBUG({
  870. dbgs() << "Split result: \t";
  871. print(dbgs(), nullptr);
  872. });
  873. return DidChange;
  874. }
  875. bool
  876. UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
  877. LiveIntervals &LIS) {
  878. bool DidChange = false;
  879. // Split locations referring to OldReg. Iterate backwards so splitLocation can
  880. // safely erase unused locations.
  881. for (unsigned i = locations.size(); i ; --i) {
  882. unsigned LocNo = i-1;
  883. const MachineOperand *Loc = &locations[LocNo];
  884. if (!Loc->isReg() || Loc->getReg() != OldReg)
  885. continue;
  886. DidChange |= splitLocation(LocNo, NewRegs, LIS);
  887. }
  888. return DidChange;
  889. }
  890. void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
  891. bool DidChange = false;
  892. for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
  893. DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
  894. if (!DidChange)
  895. return;
  896. // Map all of the new virtual registers.
  897. UserValue *UV = lookupVirtReg(OldReg);
  898. for (unsigned i = 0; i != NewRegs.size(); ++i)
  899. mapVirtReg(NewRegs[i], UV);
  900. }
  901. void LiveDebugVariables::
  902. splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
  903. if (pImpl)
  904. static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
  905. }
  906. void UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
  907. BitVector &SpilledLocations) {
  908. // Build a set of new locations with new numbers so we can coalesce our
  909. // IntervalMap if two vreg intervals collapse to the same physical location.
  910. // Use MapVector instead of SetVector because MapVector::insert returns the
  911. // position of the previously or newly inserted element. The boolean value
  912. // tracks if the location was produced by a spill.
  913. // FIXME: This will be problematic if we ever support direct and indirect
  914. // frame index locations, i.e. expressing both variables in memory and
  915. // 'int x, *px = &x'. The "spilled" bit must become part of the location.
  916. MapVector<MachineOperand, bool> NewLocations;
  917. SmallVector<unsigned, 4> LocNoMap(locations.size());
  918. for (unsigned I = 0, E = locations.size(); I != E; ++I) {
  919. bool Spilled = false;
  920. MachineOperand Loc = locations[I];
  921. // Only virtual registers are rewritten.
  922. if (Loc.isReg() && Loc.getReg() &&
  923. TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
  924. unsigned VirtReg = Loc.getReg();
  925. if (VRM.isAssignedReg(VirtReg) &&
  926. TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
  927. // This can create a %noreg operand in rare cases when the sub-register
  928. // index is no longer available. That means the user value is in a
  929. // non-existent sub-register, and %noreg is exactly what we want.
  930. Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
  931. } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
  932. // FIXME: Translate SubIdx to a stackslot offset.
  933. Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
  934. Spilled = true;
  935. } else {
  936. Loc.setReg(0);
  937. Loc.setSubReg(0);
  938. }
  939. }
  940. // Insert this location if it doesn't already exist and record a mapping
  941. // from the old number to the new number.
  942. auto InsertResult = NewLocations.insert({Loc, Spilled});
  943. unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
  944. LocNoMap[I] = NewLocNo;
  945. }
  946. // Rewrite the locations and record which ones were spill slots.
  947. locations.clear();
  948. SpilledLocations.clear();
  949. SpilledLocations.resize(NewLocations.size());
  950. for (auto &Pair : NewLocations) {
  951. locations.push_back(Pair.first);
  952. if (Pair.second) {
  953. unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
  954. SpilledLocations.set(NewLocNo);
  955. }
  956. }
  957. // Update the interval map, but only coalesce left, since intervals to the
  958. // right use the old location numbers. This should merge two contiguous
  959. // DBG_VALUE intervals with different vregs that were allocated to the same
  960. // physical register.
  961. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  962. DbgValueLocation Loc = I.value();
  963. // Undef values don't exist in locations (and thus not in LocNoMap either)
  964. // so skip over them. See getLocationNo().
  965. if (Loc.isUndef())
  966. continue;
  967. unsigned NewLocNo = LocNoMap[Loc.locNo()];
  968. I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
  969. I.setStart(I.start());
  970. }
  971. }
  972. /// Find an iterator for inserting a DBG_VALUE instruction.
  973. static MachineBasicBlock::iterator
  974. findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
  975. LiveIntervals &LIS) {
  976. SlotIndex Start = LIS.getMBBStartIdx(MBB);
  977. Idx = Idx.getBaseIndex();
  978. // Try to find an insert location by going backwards from Idx.
  979. MachineInstr *MI;
  980. while (!(MI = LIS.getInstructionFromIndex(Idx))) {
  981. // We've reached the beginning of MBB.
  982. if (Idx == Start) {
  983. MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
  984. return I;
  985. }
  986. Idx = Idx.getPrevIndex();
  987. }
  988. // Don't insert anything after the first terminator, though.
  989. return MI->isTerminator() ? MBB->getFirstTerminator() :
  990. std::next(MachineBasicBlock::iterator(MI));
  991. }
  992. /// Find an iterator for inserting the next DBG_VALUE instruction
  993. /// (or end if no more insert locations found).
  994. static MachineBasicBlock::iterator
  995. findNextInsertLocation(MachineBasicBlock *MBB,
  996. MachineBasicBlock::iterator I,
  997. SlotIndex StopIdx, MachineOperand &LocMO,
  998. LiveIntervals &LIS,
  999. const TargetRegisterInfo &TRI) {
  1000. if (!LocMO.isReg())
  1001. return MBB->instr_end();
  1002. unsigned Reg = LocMO.getReg();
  1003. // Find the next instruction in the MBB that define the register Reg.
  1004. while (I != MBB->end() && !I->isTerminator()) {
  1005. if (!LIS.isNotInMIMap(*I) &&
  1006. SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
  1007. break;
  1008. if (I->definesRegister(Reg, &TRI))
  1009. // The insert location is directly after the instruction/bundle.
  1010. return std::next(I);
  1011. ++I;
  1012. }
  1013. return MBB->end();
  1014. }
  1015. void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  1016. SlotIndex StopIdx,
  1017. DbgValueLocation Loc, bool Spilled,
  1018. LiveIntervals &LIS,
  1019. const TargetInstrInfo &TII,
  1020. const TargetRegisterInfo &TRI) {
  1021. SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
  1022. // Only search within the current MBB.
  1023. StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
  1024. MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
  1025. // Undef values don't exist in locations so create new "noreg" register MOs
  1026. // for them. See getLocationNo().
  1027. MachineOperand MO = !Loc.isUndef() ?
  1028. locations[Loc.locNo()] :
  1029. MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
  1030. /* isKill */ false, /* isDead */ false,
  1031. /* isUndef */ false, /* isEarlyClobber */ false,
  1032. /* SubReg */ 0, /* isDebug */ true);
  1033. ++NumInsertedDebugValues;
  1034. assert(cast<DILocalVariable>(Variable)
  1035. ->isValidLocationForIntrinsic(getDebugLoc()) &&
  1036. "Expected inlined-at fields to agree");
  1037. // If the location was spilled, the new DBG_VALUE will be indirect. If the
  1038. // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
  1039. // that the original virtual register was a pointer.
  1040. const DIExpression *Expr = Expression;
  1041. bool IsIndirect = Loc.wasIndirect();
  1042. if (Spilled) {
  1043. if (IsIndirect)
  1044. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  1045. IsIndirect = true;
  1046. }
  1047. assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
  1048. do {
  1049. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
  1050. IsIndirect, MO, Variable, Expr);
  1051. // Continue and insert DBG_VALUES after every redefinition of register
  1052. // associated with the debug value within the range
  1053. I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
  1054. } while (I != MBB->end());
  1055. }
  1056. void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  1057. const TargetInstrInfo &TII,
  1058. const TargetRegisterInfo &TRI,
  1059. const BitVector &SpilledLocations) {
  1060. MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
  1061. for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
  1062. SlotIndex Start = I.start();
  1063. SlotIndex Stop = I.stop();
  1064. DbgValueLocation Loc = I.value();
  1065. bool Spilled = !Loc.isUndef() ? SpilledLocations.test(Loc.locNo()) : false;
  1066. // If the interval start was trimmed to the lexical scope insert the
  1067. // DBG_VALUE at the previous index (otherwise it appears after the
  1068. // first instruction in the range).
  1069. if (trimmedDefs.count(Start))
  1070. Start = Start.getPrevIndex();
  1071. LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
  1072. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
  1073. SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1074. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1075. insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
  1076. // This interval may span multiple basic blocks.
  1077. // Insert a DBG_VALUE into each one.
  1078. while (Stop > MBBEnd) {
  1079. // Move to the next block.
  1080. Start = MBBEnd;
  1081. if (++MBB == MFEnd)
  1082. break;
  1083. MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1084. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1085. insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
  1086. }
  1087. LLVM_DEBUG(dbgs() << '\n');
  1088. if (MBB == MFEnd)
  1089. break;
  1090. ++I;
  1091. }
  1092. }
  1093. void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
  1094. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
  1095. if (!MF)
  1096. return;
  1097. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1098. BitVector SpilledLocations;
  1099. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  1100. LLVM_DEBUG(userValues[i]->print(dbgs(), TRI));
  1101. userValues[i]->rewriteLocations(*VRM, *TRI, SpilledLocations);
  1102. userValues[i]->emitDebugValues(VRM, *LIS, *TII, *TRI, SpilledLocations);
  1103. }
  1104. EmitDone = true;
  1105. }
  1106. void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
  1107. if (pImpl)
  1108. static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
  1109. }
  1110. bool LiveDebugVariables::doInitialization(Module &M) {
  1111. return Pass::doInitialization(M);
  1112. }
  1113. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1114. LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
  1115. if (pImpl)
  1116. static_cast<LDVImpl*>(pImpl)->print(dbgs());
  1117. }
  1118. #endif