LiveDebugVariables.cpp 50 KB

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