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