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 (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
736        ++MFI) {
737     MachineBasicBlock *MBB = &*MFI;
738     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
739          MBBI != MBBE;) {
740       // Use the first debug instruction in the sequence to get a SlotIndex
741       // for following consecutive debug instructions.
742       if (!MBBI->isDebugInstr()) {
743         ++MBBI;
744         continue;
745       }
746       // Debug instructions has no slot index. Use the previous
747       // non-debug instruction's SlotIndex as its SlotIndex.
748       SlotIndex Idx =
749           MBBI == MBB->begin()
750               ? LIS->getMBBStartIdx(MBB)
751               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
752       // Handle consecutive debug instructions with the same slot index.
753       do {
754         // Only handle DBG_VALUE in handleDebugValue(). Skip all other
755         // kinds of debug instructions.
756         if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
757             (MBBI->isDebugRef() && handleDebugInstrRef(*MBBI, Idx)) ||
758             (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
759           MBBI = MBB->erase(MBBI);
760           Changed = true;
761         } else
762           ++MBBI;
763       } while (MBBI != MBBE && MBBI->isDebugInstr());
764     }
765   }
766   return Changed;
767 }
768 
769 void UserValue::extendDef(SlotIndex Idx, DbgVariableValue DbgValue, LiveRange *LR,
770                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
771                           LiveIntervals &LIS) {
772   SlotIndex Start = Idx;
773   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
774   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
775   LocMap::iterator I = locInts.find(Start);
776 
777   // Limit to VNI's live range.
778   bool ToEnd = true;
779   if (LR && VNI) {
780     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
781     if (!Segment || Segment->valno != VNI) {
782       if (Kills)
783         Kills->push_back(Start);
784       return;
785     }
786     if (Segment->end < Stop) {
787       Stop = Segment->end;
788       ToEnd = false;
789     }
790   }
791 
792   // There could already be a short def at Start.
793   if (I.valid() && I.start() <= Start) {
794     // Stop when meeting a different location or an already extended interval.
795     Start = Start.getNextSlot();
796     if (I.value() != DbgValue || I.stop() != Start)
797       return;
798     // This is a one-slot placeholder. Just skip it.
799     ++I;
800   }
801 
802   // Limited by the next def.
803   if (I.valid() && I.start() < Stop)
804     Stop = I.start();
805   // Limited by VNI's live range.
806   else if (!ToEnd && Kills)
807     Kills->push_back(Stop);
808 
809   if (Start < Stop)
810     I.insert(Start, Stop, DbgValue);
811 }
812 
813 void UserValue::addDefsFromCopies(
814     LiveInterval *LI, DbgVariableValue DbgValue,
815     const SmallVectorImpl<SlotIndex> &Kills,
816     SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
817     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
818   if (Kills.empty())
819     return;
820   // Don't track copies from physregs, there are too many uses.
821   if (!Register::isVirtualRegister(LI->reg()))
822     return;
823 
824   // Collect all the (vreg, valno) pairs that are copies of LI.
825   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
826   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
827     MachineInstr *MI = MO.getParent();
828     // Copies of the full value.
829     if (MO.getSubReg() || !MI->isCopy())
830       continue;
831     Register DstReg = MI->getOperand(0).getReg();
832 
833     // Don't follow copies to physregs. These are usually setting up call
834     // arguments, and the argument registers are always call clobbered. We are
835     // better off in the source register which could be a callee-saved register,
836     // or it could be spilled.
837     if (!Register::isVirtualRegister(DstReg))
838       continue;
839 
840     // Is the value extended to reach this copy? If not, another def may be
841     // blocking it, or we are looking at a wrong value of LI.
842     SlotIndex Idx = LIS.getInstructionIndex(*MI);
843     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
844     if (!I.valid() || I.value() != DbgValue)
845       continue;
846 
847     if (!LIS.hasInterval(DstReg))
848       continue;
849     LiveInterval *DstLI = &LIS.getInterval(DstReg);
850     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
851     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
852     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
853   }
854 
855   if (CopyValues.empty())
856     return;
857 
858   LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
859                     << '\n');
860 
861   // Try to add defs of the copied values for each kill point.
862   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
863     SlotIndex Idx = Kills[i];
864     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
865       LiveInterval *DstLI = CopyValues[j].first;
866       const VNInfo *DstVNI = CopyValues[j].second;
867       if (DstLI->getVNInfoAt(Idx) != DstVNI)
868         continue;
869       // Check that there isn't already a def at Idx
870       LocMap::iterator I = locInts.find(Idx);
871       if (I.valid() && I.start() <= Idx)
872         continue;
873       LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
874                         << DstVNI->id << " in " << *DstLI << '\n');
875       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
876       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
877       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
878       DbgVariableValue NewValue = DbgValue.changeLocNo(LocNo);
879       I.insert(Idx, Idx.getNextSlot(), NewValue);
880       NewDefs.push_back(std::make_pair(Idx, NewValue));
881       break;
882     }
883   }
884 }
885 
886 void UserValue::computeIntervals(MachineRegisterInfo &MRI,
887                                  const TargetRegisterInfo &TRI,
888                                  LiveIntervals &LIS, LexicalScopes &LS) {
889   SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
890 
891   // Collect all defs to be extended (Skipping undefs).
892   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
893     if (!I.value().isUndef())
894       Defs.push_back(std::make_pair(I.start(), I.value()));
895 
896   // Extend all defs, and possibly add new ones along the way.
897   for (unsigned i = 0; i != Defs.size(); ++i) {
898     SlotIndex Idx = Defs[i].first;
899     DbgVariableValue DbgValue = Defs[i].second;
900     const MachineOperand &LocMO = locations[DbgValue.getLocNo()];
901 
902     if (!LocMO.isReg()) {
903       extendDef(Idx, DbgValue, nullptr, nullptr, nullptr, LIS);
904       continue;
905     }
906 
907     // Register locations are constrained to where the register value is live.
908     if (Register::isVirtualRegister(LocMO.getReg())) {
909       LiveInterval *LI = nullptr;
910       const VNInfo *VNI = nullptr;
911       if (LIS.hasInterval(LocMO.getReg())) {
912         LI = &LIS.getInterval(LocMO.getReg());
913         VNI = LI->getVNInfoAt(Idx);
914       }
915       SmallVector<SlotIndex, 16> Kills;
916       extendDef(Idx, DbgValue, LI, VNI, &Kills, LIS);
917       // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
918       // if the original location for example is %vreg0:sub_hi, and we find a
919       // full register copy in addDefsFromCopies (at the moment it only handles
920       // full register copies), then we must add the sub1 sub-register index to
921       // the new location. However, that is only possible if the new virtual
922       // register is of the same regclass (or if there is an equivalent
923       // sub-register in that regclass). For now, simply skip handling copies if
924       // a sub-register is involved.
925       if (LI && !LocMO.getSubReg())
926         addDefsFromCopies(LI, DbgValue, Kills, Defs, MRI, LIS);
927       continue;
928     }
929 
930     // For physregs, we only mark the start slot idx. DwarfDebug will see it
931     // as if the DBG_VALUE is valid up until the end of the basic block, or
932     // the next def of the physical register. So we do not need to extend the
933     // range. It might actually happen that the DBG_VALUE is the last use of
934     // the physical register (e.g. if this is an unused input argument to a
935     // function).
936   }
937 
938   // The computed intervals may extend beyond the range of the debug
939   // location's lexical scope. In this case, splitting of an interval
940   // can result in an interval outside of the scope being created,
941   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
942   // this, trim the intervals to the lexical scope.
943 
944   LexicalScope *Scope = LS.findLexicalScope(dl);
945   if (!Scope)
946     return;
947 
948   SlotIndex PrevEnd;
949   LocMap::iterator I = locInts.begin();
950 
951   // Iterate over the lexical scope ranges. Each time round the loop
952   // we check the intervals for overlap with the end of the previous
953   // range and the start of the next. The first range is handled as
954   // a special case where there is no PrevEnd.
955   for (const InsnRange &Range : Scope->getRanges()) {
956     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
957     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
958 
959     // Variable locations at the first instruction of a block should be
960     // based on the block's SlotIndex, not the first instruction's index.
961     if (Range.first == Range.first->getParent()->begin())
962       RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
963 
964     // At the start of each iteration I has been advanced so that
965     // I.stop() >= PrevEnd. Check for overlap.
966     if (PrevEnd && I.start() < PrevEnd) {
967       SlotIndex IStop = I.stop();
968       DbgVariableValue DbgValue = I.value();
969 
970       // Stop overlaps previous end - trim the end of the interval to
971       // the scope range.
972       I.setStopUnchecked(PrevEnd);
973       ++I;
974 
975       // If the interval also overlaps the start of the "next" (i.e.
976       // current) range create a new interval for the remainder (which
977       // may be further trimmed).
978       if (RStart < IStop)
979         I.insert(RStart, IStop, DbgValue);
980     }
981 
982     // Advance I so that I.stop() >= RStart, and check for overlap.
983     I.advanceTo(RStart);
984     if (!I.valid())
985       return;
986 
987     if (I.start() < RStart) {
988       // Interval start overlaps range - trim to the scope range.
989       I.setStartUnchecked(RStart);
990       // Remember that this interval was trimmed.
991       trimmedDefs.insert(RStart);
992     }
993 
994     // The end of a lexical scope range is the last instruction in the
995     // range. To convert to an interval we need the index of the
996     // instruction after it.
997     REnd = REnd.getNextIndex();
998 
999     // Advance I to first interval outside current range.
1000     I.advanceTo(REnd);
1001     if (!I.valid())
1002       return;
1003 
1004     PrevEnd = REnd;
1005   }
1006 
1007   // Check for overlap with end of final range.
1008   if (PrevEnd && I.start() < PrevEnd)
1009     I.setStopUnchecked(PrevEnd);
1010 }
1011 
1012 void LDVImpl::computeIntervals() {
1013   LexicalScopes LS;
1014   LS.initialize(*MF);
1015 
1016   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1017     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
1018     userValues[i]->mapVirtRegs(this);
1019   }
1020 }
1021 
1022 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
1023   clear();
1024   MF = &mf;
1025   LIS = &pass.getAnalysis<LiveIntervals>();
1026   TRI = mf.getSubtarget().getRegisterInfo();
1027   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1028                     << mf.getName() << " **********\n");
1029 
1030   bool Changed = collectDebugValues(mf);
1031   computeIntervals();
1032   LLVM_DEBUG(print(dbgs()));
1033   ModifiedMF = Changed;
1034   return Changed;
1035 }
1036 
1037 static void removeDebugInstrs(MachineFunction &mf) {
1038   for (MachineBasicBlock &MBB : mf) {
1039     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
1040       if (!MBBI->isDebugInstr()) {
1041         ++MBBI;
1042         continue;
1043       }
1044       MBBI = MBB.erase(MBBI);
1045     }
1046   }
1047 }
1048 
1049 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
1050   if (!EnableLDV)
1051     return false;
1052   if (!mf.getFunction().getSubprogram()) {
1053     removeDebugInstrs(mf);
1054     return false;
1055   }
1056   if (!pImpl)
1057     pImpl = new LDVImpl(this);
1058   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
1059 }
1060 
1061 void LiveDebugVariables::releaseMemory() {
1062   if (pImpl)
1063     static_cast<LDVImpl*>(pImpl)->clear();
1064 }
1065 
1066 LiveDebugVariables::~LiveDebugVariables() {
1067   if (pImpl)
1068     delete static_cast<LDVImpl*>(pImpl);
1069 }
1070 
1071 //===----------------------------------------------------------------------===//
1072 //                           Live Range Splitting
1073 //===----------------------------------------------------------------------===//
1074 
1075 bool
1076 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1077                          LiveIntervals& LIS) {
1078   LLVM_DEBUG({
1079     dbgs() << "Splitting Loc" << OldLocNo << '\t';
1080     print(dbgs(), nullptr);
1081   });
1082   bool DidChange = false;
1083   LocMap::iterator LocMapI;
1084   LocMapI.setMap(locInts);
1085   for (unsigned i = 0; i != NewRegs.size(); ++i) {
1086     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
1087     if (LI->empty())
1088       continue;
1089 
1090     // Don't allocate the new LocNo until it is needed.
1091     unsigned NewLocNo = UndefLocNo;
1092 
1093     // Iterate over the overlaps between locInts and LI.
1094     LocMapI.find(LI->beginIndex());
1095     if (!LocMapI.valid())
1096       continue;
1097     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1098     LiveInterval::iterator LIE = LI->end();
1099     while (LocMapI.valid() && LII != LIE) {
1100       // At this point, we know that LocMapI.stop() > LII->start.
1101       LII = LI->advanceTo(LII, LocMapI.start());
1102       if (LII == LIE)
1103         break;
1104 
1105       // Now LII->end > LocMapI.start(). Do we have an overlap?
1106       if (LocMapI.value().getLocNo() == OldLocNo &&
1107           LII->start < LocMapI.stop()) {
1108         // Overlapping correct location. Allocate NewLocNo now.
1109         if (NewLocNo == UndefLocNo) {
1110           MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
1111           MO.setSubReg(locations[OldLocNo].getSubReg());
1112           NewLocNo = getLocationNo(MO);
1113           DidChange = true;
1114         }
1115 
1116         SlotIndex LStart = LocMapI.start();
1117         SlotIndex LStop = LocMapI.stop();
1118         DbgVariableValue OldDbgValue = LocMapI.value();
1119 
1120         // Trim LocMapI down to the LII overlap.
1121         if (LStart < LII->start)
1122           LocMapI.setStartUnchecked(LII->start);
1123         if (LStop > LII->end)
1124           LocMapI.setStopUnchecked(LII->end);
1125 
1126         // Change the value in the overlap. This may trigger coalescing.
1127         LocMapI.setValue(OldDbgValue.changeLocNo(NewLocNo));
1128 
1129         // Re-insert any removed OldDbgValue ranges.
1130         if (LStart < LocMapI.start()) {
1131           LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
1132           ++LocMapI;
1133           assert(LocMapI.valid() && "Unexpected coalescing");
1134         }
1135         if (LStop > LocMapI.stop()) {
1136           ++LocMapI;
1137           LocMapI.insert(LII->end, LStop, OldDbgValue);
1138           --LocMapI;
1139         }
1140       }
1141 
1142       // Advance to the next overlap.
1143       if (LII->end < LocMapI.stop()) {
1144         if (++LII == LIE)
1145           break;
1146         LocMapI.advanceTo(LII->start);
1147       } else {
1148         ++LocMapI;
1149         if (!LocMapI.valid())
1150           break;
1151         LII = LI->advanceTo(LII, LocMapI.start());
1152       }
1153     }
1154   }
1155 
1156   // Finally, remove OldLocNo unless it is still used by some interval in the
1157   // locInts map. One case when OldLocNo still is in use is when the register
1158   // has been spilled. In such situations the spilled register is kept as a
1159   // location until rewriteLocations is called (VirtRegMap is mapping the old
1160   // register to the spill slot). So for a while we can have locations that map
1161   // to virtual registers that have been removed from both the MachineFunction
1162   // and from LiveIntervals.
1163   //
1164   // We may also just be using the location for a value with a different
1165   // expression.
1166   removeLocationIfUnused(OldLocNo);
1167 
1168   LLVM_DEBUG({
1169     dbgs() << "Split result: \t";
1170     print(dbgs(), nullptr);
1171   });
1172   return DidChange;
1173 }
1174 
1175 bool
1176 UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1177                          LiveIntervals &LIS) {
1178   bool DidChange = false;
1179   // Split locations referring to OldReg. Iterate backwards so splitLocation can
1180   // safely erase unused locations.
1181   for (unsigned i = locations.size(); i ; --i) {
1182     unsigned LocNo = i-1;
1183     const MachineOperand *Loc = &locations[LocNo];
1184     if (!Loc->isReg() || Loc->getReg() != OldReg)
1185       continue;
1186     DidChange |= splitLocation(LocNo, NewRegs, LIS);
1187   }
1188   return DidChange;
1189 }
1190 
1191 void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1192   bool DidChange = false;
1193   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1194     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1195 
1196   if (!DidChange)
1197     return;
1198 
1199   // Map all of the new virtual registers.
1200   UserValue *UV = lookupVirtReg(OldReg);
1201   for (unsigned i = 0; i != NewRegs.size(); ++i)
1202     mapVirtReg(NewRegs[i], UV);
1203 }
1204 
1205 void LiveDebugVariables::
1206 splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
1207   if (pImpl)
1208     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1209 }
1210 
1211 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1212                                  const TargetInstrInfo &TII,
1213                                  const TargetRegisterInfo &TRI,
1214                                  SpillOffsetMap &SpillOffsets) {
1215   // Build a set of new locations with new numbers so we can coalesce our
1216   // IntervalMap if two vreg intervals collapse to the same physical location.
1217   // Use MapVector instead of SetVector because MapVector::insert returns the
1218   // position of the previously or newly inserted element. The boolean value
1219   // tracks if the location was produced by a spill.
1220   // FIXME: This will be problematic if we ever support direct and indirect
1221   // frame index locations, i.e. expressing both variables in memory and
1222   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1223   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1224   SmallVector<unsigned, 4> LocNoMap(locations.size());
1225   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1226     bool Spilled = false;
1227     unsigned SpillOffset = 0;
1228     MachineOperand Loc = locations[I];
1229     // Only virtual registers are rewritten.
1230     if (Loc.isReg() && Loc.getReg() &&
1231         Register::isVirtualRegister(Loc.getReg())) {
1232       Register VirtReg = Loc.getReg();
1233       if (VRM.isAssignedReg(VirtReg) &&
1234           Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1235         // This can create a %noreg operand in rare cases when the sub-register
1236         // index is no longer available. That means the user value is in a
1237         // non-existent sub-register, and %noreg is exactly what we want.
1238         Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1239       } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1240         // Retrieve the stack slot offset.
1241         unsigned SpillSize;
1242         const MachineRegisterInfo &MRI = MF.getRegInfo();
1243         const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1244         bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1245                                              SpillOffset, MF);
1246 
1247         // FIXME: Invalidate the location if the offset couldn't be calculated.
1248         (void)Success;
1249 
1250         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1251         Spilled = true;
1252       } else {
1253         Loc.setReg(0);
1254         Loc.setSubReg(0);
1255       }
1256     }
1257 
1258     // Insert this location if it doesn't already exist and record a mapping
1259     // from the old number to the new number.
1260     auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1261     unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1262     LocNoMap[I] = NewLocNo;
1263   }
1264 
1265   // Rewrite the locations and record the stack slot offsets for spills.
1266   locations.clear();
1267   SpillOffsets.clear();
1268   for (auto &Pair : NewLocations) {
1269     bool Spilled;
1270     unsigned SpillOffset;
1271     std::tie(Spilled, SpillOffset) = Pair.second;
1272     locations.push_back(Pair.first);
1273     if (Spilled) {
1274       unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1275       SpillOffsets[NewLocNo] = SpillOffset;
1276     }
1277   }
1278 
1279   // Update the interval map, but only coalesce left, since intervals to the
1280   // right use the old location numbers. This should merge two contiguous
1281   // DBG_VALUE intervals with different vregs that were allocated to the same
1282   // physical register.
1283   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1284     DbgVariableValue DbgValue = I.value();
1285     // Undef values don't exist in locations (and thus not in LocNoMap either)
1286     // so skip over them. See getLocationNo().
1287     if (DbgValue.isUndef())
1288       continue;
1289     unsigned NewLocNo = LocNoMap[DbgValue.getLocNo()];
1290     I.setValueUnchecked(DbgValue.changeLocNo(NewLocNo));
1291     I.setStart(I.start());
1292   }
1293 }
1294 
1295 /// Find an iterator for inserting a DBG_VALUE instruction.
1296 static MachineBasicBlock::iterator
1297 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1298                    BlockSkipInstsMap &BBSkipInstsMap) {
1299   SlotIndex Start = LIS.getMBBStartIdx(MBB);
1300   Idx = Idx.getBaseIndex();
1301 
1302   // Try to find an insert location by going backwards from Idx.
1303   MachineInstr *MI;
1304   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1305     // We've reached the beginning of MBB.
1306     if (Idx == Start) {
1307       // Retrieve the last PHI/Label/Debug location found when calling
1308       // SkipPHIsLabelsAndDebug last time. Start searching from there.
1309       //
1310       // Note the iterator kept in BBSkipInstsMap is one step back based
1311       // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1312       // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1313       // BBSkipInstsMap won't save it. This is to consider the case that
1314       // new instructions may be inserted at the beginning of MBB after
1315       // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1316       // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1317       // are inserted at the beginning of the MBB, the iterator in
1318       // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1319       // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1320       // newly added instructions and that is unwanted.
1321       MachineBasicBlock::iterator BeginIt;
1322       auto MapIt = BBSkipInstsMap.find(MBB);
1323       if (MapIt == BBSkipInstsMap.end())
1324         BeginIt = MBB->begin();
1325       else
1326         BeginIt = std::next(MapIt->second);
1327       auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1328       if (I != BeginIt)
1329         BBSkipInstsMap[MBB] = std::prev(I);
1330       return I;
1331     }
1332     Idx = Idx.getPrevIndex();
1333   }
1334 
1335   // Don't insert anything after the first terminator, though.
1336   return MI->isTerminator() ? MBB->getFirstTerminator() :
1337                               std::next(MachineBasicBlock::iterator(MI));
1338 }
1339 
1340 /// Find an iterator for inserting the next DBG_VALUE instruction
1341 /// (or end if no more insert locations found).
1342 static MachineBasicBlock::iterator
1343 findNextInsertLocation(MachineBasicBlock *MBB,
1344                        MachineBasicBlock::iterator I,
1345                        SlotIndex StopIdx, MachineOperand &LocMO,
1346                        LiveIntervals &LIS,
1347                        const TargetRegisterInfo &TRI) {
1348   if (!LocMO.isReg())
1349     return MBB->instr_end();
1350   Register Reg = LocMO.getReg();
1351 
1352   // Find the next instruction in the MBB that define the register Reg.
1353   while (I != MBB->end() && !I->isTerminator()) {
1354     if (!LIS.isNotInMIMap(*I) &&
1355         SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1356       break;
1357     if (I->definesRegister(Reg, &TRI))
1358       // The insert location is directly after the instruction/bundle.
1359       return std::next(I);
1360     ++I;
1361   }
1362   return MBB->end();
1363 }
1364 
1365 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1366                                  SlotIndex StopIdx, DbgVariableValue DbgValue,
1367                                  bool Spilled, unsigned SpillOffset,
1368                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1369                                  const TargetRegisterInfo &TRI,
1370                                  BlockSkipInstsMap &BBSkipInstsMap) {
1371   SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1372   // Only search within the current MBB.
1373   StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1374   MachineBasicBlock::iterator I =
1375       findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
1376   // Undef values don't exist in locations so create new "noreg" register MOs
1377   // for them. See getLocationNo().
1378   MachineOperand MO =
1379       !DbgValue.isUndef()
1380           ? locations[DbgValue.getLocNo()]
1381           : MachineOperand::CreateReg(
1382                 /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1383                 /* isKill */ false, /* isDead */ false,
1384                 /* isUndef */ false, /* isEarlyClobber */ false,
1385                 /* SubReg */ 0, /* isDebug */ true);
1386 
1387   ++NumInsertedDebugValues;
1388 
1389   assert(cast<DILocalVariable>(Variable)
1390              ->isValidLocationForIntrinsic(getDebugLoc()) &&
1391          "Expected inlined-at fields to agree");
1392 
1393   // If the location was spilled, the new DBG_VALUE will be indirect. If the
1394   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1395   // that the original virtual register was a pointer. Also, add the stack slot
1396   // offset for the spilled register to the expression.
1397   const DIExpression *Expr = DbgValue.getExpression();
1398   uint8_t DIExprFlags = DIExpression::ApplyOffset;
1399   bool IsIndirect = DbgValue.getWasIndirect();
1400   if (Spilled) {
1401     if (IsIndirect)
1402       DIExprFlags |= DIExpression::DerefAfter;
1403     Expr =
1404         DIExpression::prepend(Expr, DIExprFlags, SpillOffset);
1405     IsIndirect = true;
1406   }
1407 
1408   assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
1409 
1410   do {
1411     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1412             IsIndirect, MO, Variable, Expr);
1413 
1414     // Continue and insert DBG_VALUES after every redefinition of register
1415     // associated with the debug value within the range
1416     I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1417   } while (I != MBB->end());
1418 }
1419 
1420 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1421                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1422                                  BlockSkipInstsMap &BBSkipInstsMap) {
1423   MachineBasicBlock::iterator I =
1424       findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1425   ++NumInsertedDebugLabels;
1426   BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1427       .addMetadata(Label);
1428 }
1429 
1430 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1431                                 const TargetInstrInfo &TII,
1432                                 const TargetRegisterInfo &TRI,
1433                                 const SpillOffsetMap &SpillOffsets,
1434                                 BlockSkipInstsMap &BBSkipInstsMap) {
1435   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1436 
1437   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1438     SlotIndex Start = I.start();
1439     SlotIndex Stop = I.stop();
1440     DbgVariableValue DbgValue = I.value();
1441     auto SpillIt = !DbgValue.isUndef() ? SpillOffsets.find(DbgValue.getLocNo())
1442                                        : SpillOffsets.end();
1443     bool Spilled = SpillIt != SpillOffsets.end();
1444     unsigned SpillOffset = Spilled ? SpillIt->second : 0;
1445 
1446     // If the interval start was trimmed to the lexical scope insert the
1447     // DBG_VALUE at the previous index (otherwise it appears after the
1448     // first instruction in the range).
1449     if (trimmedDefs.count(Start))
1450       Start = Start.getPrevIndex();
1451 
1452     LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop
1453                       << "):" << DbgValue.getLocNo());
1454     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1455     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1456 
1457     LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1458     insertDebugValue(&*MBB, Start, Stop, DbgValue, Spilled, SpillOffset, LIS,
1459                      TII, TRI, BBSkipInstsMap);
1460     // This interval may span multiple basic blocks.
1461     // Insert a DBG_VALUE into each one.
1462     while (Stop > MBBEnd) {
1463       // Move to the next block.
1464       Start = MBBEnd;
1465       if (++MBB == MFEnd)
1466         break;
1467       MBBEnd = LIS.getMBBEndIdx(&*MBB);
1468       LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1469       insertDebugValue(&*MBB, Start, Stop, DbgValue, Spilled, SpillOffset, LIS,
1470                        TII, TRI, BBSkipInstsMap);
1471     }
1472     LLVM_DEBUG(dbgs() << '\n');
1473     if (MBB == MFEnd)
1474       break;
1475 
1476     ++I;
1477   }
1478 }
1479 
1480 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1481                                BlockSkipInstsMap &BBSkipInstsMap) {
1482   LLVM_DEBUG(dbgs() << "\t" << loc);
1483   MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
1484 
1485   LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1486   insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
1487 
1488   LLVM_DEBUG(dbgs() << '\n');
1489 }
1490 
1491 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1492   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1493   if (!MF)
1494     return;
1495 
1496   BlockSkipInstsMap BBSkipInstsMap;
1497   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1498   SpillOffsetMap SpillOffsets;
1499   for (auto &userValue : userValues) {
1500     LLVM_DEBUG(userValue->print(dbgs(), TRI));
1501     userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1502     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
1503                                BBSkipInstsMap);
1504   }
1505   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1506   for (auto &userLabel : userLabels) {
1507     LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1508     userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
1509   }
1510 
1511   LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1512 
1513   // Re-insert any DBG_INSTR_REFs back in the position they were. Ordering
1514   // is preserved by vector.
1515   auto Slots = LIS->getSlotIndexes();
1516   const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF);
1517   for (auto &P : StashedInstrReferences) {
1518     const SlotIndex &Idx = P.first;
1519     auto *MBB = Slots->getMBBFromIndex(Idx);
1520     MachineBasicBlock::iterator insertPos =
1521         findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
1522     for (auto &Stashed : P.second) {
1523       auto MIB = BuildMI(*MF, std::get<4>(Stashed), RefII);
1524       MIB.addImm(std::get<0>(Stashed));
1525       MIB.addImm(std::get<1>(Stashed));
1526       MIB.addMetadata(std::get<2>(Stashed));
1527       MIB.addMetadata(std::get<3>(Stashed));
1528       MachineInstr *New = MIB;
1529       MBB->insert(insertPos, New);
1530     }
1531   }
1532 
1533   EmitDone = true;
1534   BBSkipInstsMap.clear();
1535 }
1536 
1537 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1538   if (pImpl)
1539     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1540 }
1541 
1542 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1543 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1544   if (pImpl)
1545     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1546 }
1547 #endif
1548