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