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