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