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