xref: /llvm-project/llvm/lib/CodeGen/LiveDebugVariables.cpp (revision 86c74dd7912900bd2c2bbdb42d8dcac154bc3c0e)
1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveDebugVariables analysis.
11 //
12 // Remove all DBG_VALUE instructions referencing virtual registers and replace
13 // them with a data structure tracking where live user variables are kept - in a
14 // virtual register or in a stack slot.
15 //
16 // Allow the data structure to be updated during register allocation when values
17 // are moved between registers and stack slots. Finally emit new DBG_VALUE
18 // instructions after register allocation is complete.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "LiveDebugVariables.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/IntervalMap.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/LiveIntervalAnalysis.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/VirtRegMap.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44 #include "llvm/IR/DebugLoc.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/Metadata.h"
47 #include "llvm/MC/MCRegisterInfo.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetOpcodes.h"
56 #include "llvm/Target/TargetRegisterInfo.h"
57 #include "llvm/Target/TargetSubtargetInfo.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <iterator>
61 #include <memory>
62 #include <utility>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "livedebugvars"
67 
68 static cl::opt<bool>
69 EnableLDV("live-debug-variables", cl::init(true),
70           cl::desc("Enable the live debug variables pass"), cl::Hidden);
71 
72 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
73 
74 char LiveDebugVariables::ID = 0;
75 
76 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
77                 "Debug Variable Analysis", false, false)
78 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
79 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
80 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
81                 "Debug Variable Analysis", false, false)
82 
83 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
84   AU.addRequired<MachineDominatorTree>();
85   AU.addRequiredTransitive<LiveIntervals>();
86   AU.setPreservesAll();
87   MachineFunctionPass::getAnalysisUsage(AU);
88 }
89 
90 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
91   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
92 }
93 
94 /// LocMap - Map of where a user value is live, and its location.
95 using LocMap = IntervalMap<SlotIndex, unsigned, 4>;
96 
97 namespace {
98 
99 class LDVImpl;
100 
101 /// UserValue - A user value is a part of a debug info user variable.
102 ///
103 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
104 /// holds part of a user variable. The part is identified by a byte offset.
105 ///
106 /// UserValues are grouped into equivalence classes for easier searching. Two
107 /// user values are related if they refer to the same variable, or if they are
108 /// held by the same virtual register. The equivalence class is the transitive
109 /// closure of that relation.
110 class UserValue {
111   const DILocalVariable *Variable; ///< The debug info variable we are part of.
112   const DIExpression *Expression; ///< Any complex address expression.
113   bool IsIndirect;        ///< true if this is a register-indirect+offset value.
114   DebugLoc dl;            ///< The debug location for the variable. This is
115                           ///< used by dwarf writer to find lexical scope.
116   UserValue *leader;      ///< Equivalence class leader.
117   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
118 
119   /// Numbered locations referenced by locmap.
120   SmallVector<MachineOperand, 4> locations;
121 
122   /// Map of slot indices where this value is live.
123   LocMap locInts;
124 
125   /// Set of interval start indexes that have been trimmed to the
126   /// lexical scope.
127   SmallSet<SlotIndex, 2> trimmedDefs;
128 
129   /// coalesceLocation - After LocNo was changed, check if it has become
130   /// identical to another location, and coalesce them. This may cause LocNo or
131   /// a later location to be erased, but no earlier location will be erased.
132   void coalesceLocation(unsigned LocNo);
133 
134   /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
135   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
136                         unsigned LocNo, bool Spilled, LiveIntervals &LIS,
137                         const TargetInstrInfo &TII);
138 
139   /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
140   /// is live. Returns true if any changes were made.
141   bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
142                      LiveIntervals &LIS);
143 
144 public:
145   /// UserValue - Create a new UserValue.
146   UserValue(const DILocalVariable *var, const DIExpression *expr, bool i,
147             DebugLoc L, LocMap::Allocator &alloc)
148       : Variable(var), Expression(expr), IsIndirect(i), dl(std::move(L)),
149         leader(this), locInts(alloc) {}
150 
151   /// getLeader - Get the leader of this value's equivalence class.
152   UserValue *getLeader() {
153     UserValue *l = leader;
154     while (l != l->leader)
155       l = l->leader;
156     return leader = l;
157   }
158 
159   /// getNext - Return the next UserValue in the equivalence class.
160   UserValue *getNext() const { return next; }
161 
162   /// match - Does this UserValue match the parameters?
163   bool match(const DILocalVariable *Var, const DIExpression *Expr,
164              const DILocation *IA, bool indirect) const {
165     return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
166            indirect == IsIndirect;
167   }
168 
169   enum : unsigned { UndefLocNo = ~0U };
170 
171   /// merge - Merge equivalence classes.
172   static UserValue *merge(UserValue *L1, UserValue *L2) {
173     L2 = L2->getLeader();
174     if (!L1)
175       return L2;
176     L1 = L1->getLeader();
177     if (L1 == L2)
178       return L1;
179     // Splice L2 before L1's members.
180     UserValue *End = L2;
181     while (End->next) {
182       End->leader = L1;
183       End = End->next;
184     }
185     End->leader = L1;
186     End->next = L1->next;
187     L1->next = L2;
188     return L1;
189   }
190 
191   /// getLocationNo - Return the location number that matches Loc.
192   unsigned getLocationNo(const MachineOperand &LocMO) {
193     if (LocMO.isReg()) {
194       if (LocMO.getReg() == 0)
195         return UndefLocNo;
196       // For register locations we dont care about use/def and other flags.
197       for (unsigned i = 0, e = locations.size(); i != e; ++i)
198         if (locations[i].isReg() &&
199             locations[i].getReg() == LocMO.getReg() &&
200             locations[i].getSubReg() == LocMO.getSubReg())
201           return i;
202     } else
203       for (unsigned i = 0, e = locations.size(); i != e; ++i)
204         if (LocMO.isIdenticalTo(locations[i]))
205           return i;
206     locations.push_back(LocMO);
207     // We are storing a MachineOperand outside a MachineInstr.
208     locations.back().clearParent();
209     // Don't store def operands.
210     if (locations.back().isReg())
211       locations.back().setIsUse();
212     return locations.size() - 1;
213   }
214 
215   /// mapVirtRegs - Ensure that all virtual register locations are mapped.
216   void mapVirtRegs(LDVImpl *LDV);
217 
218   /// addDef - Add a definition point to this value.
219   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
220     // Add a singular (Idx,Idx) -> Loc mapping.
221     LocMap::iterator I = locInts.find(Idx);
222     if (!I.valid() || I.start() != Idx)
223       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
224     else
225       // A later DBG_VALUE at the same SlotIndex overrides the old location.
226       I.setValue(getLocationNo(LocMO));
227   }
228 
229   /// extendDef - Extend the current definition as far as possible down.
230   /// Stop when meeting an existing def or when leaving the live
231   /// range of VNI.
232   /// End points where VNI is no longer live are added to Kills.
233   /// @param Idx   Starting point for the definition.
234   /// @param LocNo Location number to propagate.
235   /// @param LR    Restrict liveness to where LR has the value VNI. May be null.
236   /// @param VNI   When LR is not null, this is the value to restrict to.
237   /// @param Kills Append end points of VNI's live range to Kills.
238   /// @param LIS   Live intervals analysis.
239   void extendDef(SlotIndex Idx, unsigned LocNo,
240                  LiveRange *LR, const VNInfo *VNI,
241                  SmallVectorImpl<SlotIndex> *Kills,
242                  LiveIntervals &LIS);
243 
244   /// addDefsFromCopies - The value in LI/LocNo may be copies to other
245   /// registers. Determine if any of the copies are available at the kill
246   /// points, and add defs if possible.
247   /// @param LI      Scan for copies of the value in LI->reg.
248   /// @param LocNo   Location number of LI->reg.
249   /// @param Kills   Points where the range of LocNo could be extended.
250   /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
251   void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
252                        const SmallVectorImpl<SlotIndex> &Kills,
253                        SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs,
254                        MachineRegisterInfo &MRI,
255                        LiveIntervals &LIS);
256 
257   /// computeIntervals - Compute the live intervals of all locations after
258   /// collecting all their def points.
259   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
260                         LiveIntervals &LIS, LexicalScopes &LS);
261 
262   /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
263   /// live. Returns true if any changes were made.
264   bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
265                      LiveIntervals &LIS);
266 
267   /// rewriteLocations - Rewrite virtual register locations according to the
268   /// provided virtual register map. Record which locations were spilled.
269   void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
270                         BitVector &SpilledLocations);
271 
272   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
273   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
274                        const TargetInstrInfo &TRI,
275                        const BitVector &SpilledLocations);
276 
277   /// getDebugLoc - Return DebugLoc of this UserValue.
278   DebugLoc getDebugLoc() { return dl;}
279 
280   void print(raw_ostream &, const TargetRegisterInfo *);
281 };
282 
283 /// LDVImpl - Implementation of the LiveDebugVariables pass.
284 class LDVImpl {
285   LiveDebugVariables &pass;
286   LocMap::Allocator allocator;
287   MachineFunction *MF = nullptr;
288   LiveIntervals *LIS;
289   const TargetRegisterInfo *TRI;
290 
291   /// Whether emitDebugValues is called.
292   bool EmitDone = false;
293 
294   /// Whether the machine function is modified during the pass.
295   bool ModifiedMF = false;
296 
297   /// userValues - All allocated UserValue instances.
298   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
299 
300   /// Map virtual register to eq class leader.
301   using VRMap = DenseMap<unsigned, UserValue *>;
302   VRMap virtRegToEqClass;
303 
304   /// Map user variable to eq class leader.
305   using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
306   UVMap userVarMap;
307 
308   /// getUserValue - Find or create a UserValue.
309   UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
310                           bool IsIndirect, const DebugLoc &DL);
311 
312   /// lookupVirtReg - Find the EC leader for VirtReg or null.
313   UserValue *lookupVirtReg(unsigned VirtReg);
314 
315   /// handleDebugValue - Add DBG_VALUE instruction to our maps.
316   /// @param MI  DBG_VALUE instruction
317   /// @param Idx Last valid SLotIndex before instruction.
318   /// @return    True if the DBG_VALUE instruction should be deleted.
319   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
320 
321   /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
322   /// a UserValue def for each instruction.
323   /// @param mf MachineFunction to be scanned.
324   /// @return True if any debug values were found.
325   bool collectDebugValues(MachineFunction &mf);
326 
327   /// computeIntervals - Compute the live intervals of all user values after
328   /// collecting all their def points.
329   void computeIntervals();
330 
331 public:
332   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
333 
334   bool runOnMachineFunction(MachineFunction &mf);
335 
336   /// clear - Release all memory.
337   void clear() {
338     MF = nullptr;
339     userValues.clear();
340     virtRegToEqClass.clear();
341     userVarMap.clear();
342     // Make sure we call emitDebugValues if the machine function was modified.
343     assert((!ModifiedMF || EmitDone) &&
344            "Dbg values are not emitted in LDV");
345     EmitDone = false;
346     ModifiedMF = false;
347   }
348 
349   /// mapVirtReg - Map virtual register to an equivalence class.
350   void mapVirtReg(unsigned VirtReg, UserValue *EC);
351 
352   /// splitRegister -  Replace all references to OldReg with NewRegs.
353   void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
354 
355   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
356   void emitDebugValues(VirtRegMap *VRM);
357 
358   void print(raw_ostream&);
359 };
360 
361 } // end anonymous namespace
362 
363 #ifndef NDEBUG
364 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
365                           const LLVMContext &Ctx) {
366   if (!DL)
367     return;
368 
369   auto *Scope = cast<DIScope>(DL.getScope());
370   // Omit the directory, because it's likely to be long and uninteresting.
371   CommentOS << Scope->getFilename();
372   CommentOS << ':' << DL.getLine();
373   if (DL.getCol() != 0)
374     CommentOS << ':' << DL.getCol();
375 
376   DebugLoc InlinedAtDL = DL.getInlinedAt();
377   if (!InlinedAtDL)
378     return;
379 
380   CommentOS << " @[ ";
381   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
382   CommentOS << " ]";
383 }
384 
385 static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
386                               const DILocation *DL) {
387   const LLVMContext &Ctx = V->getContext();
388   StringRef Res = V->getName();
389   if (!Res.empty())
390     OS << Res << "," << V->getLine();
391   if (auto *InlinedAt = DL->getInlinedAt()) {
392     if (DebugLoc InlinedAtDL = InlinedAt) {
393       OS << " @[";
394       printDebugLoc(InlinedAtDL, OS, Ctx);
395       OS << "]";
396     }
397   }
398 }
399 
400 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
401   auto *DV = cast<DILocalVariable>(Variable);
402   OS << "!\"";
403   printExtendedName(OS, DV, dl);
404 
405   OS << "\"\t";
406   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
407     OS << " [" << I.start() << ';' << I.stop() << "):";
408     if (I.value() == UndefLocNo)
409       OS << "undef";
410     else
411       OS << I.value();
412   }
413   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
414     OS << " Loc" << i << '=';
415     locations[i].print(OS, TRI);
416   }
417   OS << '\n';
418 }
419 
420 void LDVImpl::print(raw_ostream &OS) {
421   OS << "********** DEBUG VARIABLES **********\n";
422   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
423     userValues[i]->print(OS, TRI);
424 }
425 #endif
426 
427 void UserValue::coalesceLocation(unsigned LocNo) {
428   unsigned KeepLoc = 0;
429   for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
430     if (KeepLoc == LocNo)
431       continue;
432     if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
433       break;
434   }
435   // No matches.
436   if (KeepLoc == locations.size())
437     return;
438 
439   // Keep the smaller location, erase the larger one.
440   unsigned EraseLoc = LocNo;
441   if (KeepLoc > EraseLoc)
442     std::swap(KeepLoc, EraseLoc);
443   locations.erase(locations.begin() + EraseLoc);
444 
445   // Rewrite values.
446   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
447     unsigned v = I.value();
448     if (v == EraseLoc)
449       I.setValue(KeepLoc);      // Coalesce when possible.
450     else if (v > EraseLoc)
451       I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
452   }
453 }
454 
455 void UserValue::mapVirtRegs(LDVImpl *LDV) {
456   for (unsigned i = 0, e = locations.size(); i != e; ++i)
457     if (locations[i].isReg() &&
458         TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
459       LDV->mapVirtReg(locations[i].getReg(), this);
460 }
461 
462 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
463                                  const DIExpression *Expr, bool IsIndirect,
464                                  const DebugLoc &DL) {
465   UserValue *&Leader = userVarMap[Var];
466   if (Leader) {
467     UserValue *UV = Leader->getLeader();
468     Leader = UV;
469     for (; UV; UV = UV->getNext())
470       if (UV->match(Var, Expr, DL->getInlinedAt(), IsIndirect))
471         return UV;
472   }
473 
474   userValues.push_back(
475       llvm::make_unique<UserValue>(Var, Expr, IsIndirect, DL, allocator));
476   UserValue *UV = userValues.back().get();
477   Leader = UserValue::merge(Leader, UV);
478   return UV;
479 }
480 
481 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
482   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
483   UserValue *&Leader = virtRegToEqClass[VirtReg];
484   Leader = UserValue::merge(Leader, EC);
485 }
486 
487 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
488   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
489     return UV->getLeader();
490   return nullptr;
491 }
492 
493 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
494   // DBG_VALUE loc, offset, variable
495   if (MI.getNumOperands() != 4 ||
496       !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
497       !MI.getOperand(2).isMetadata()) {
498     DEBUG(dbgs() << "Can't handle " << MI);
499     return false;
500   }
501 
502   // Get or create the UserValue for (variable,offset).
503   bool IsIndirect = MI.getOperand(1).isImm();
504   if (IsIndirect)
505     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
506   const DILocalVariable *Var = MI.getDebugVariable();
507   const DIExpression *Expr = MI.getDebugExpression();
508   //here.
509   UserValue *UV = getUserValue(Var, Expr, IsIndirect, MI.getDebugLoc());
510   UV->addDef(Idx, MI.getOperand(0));
511   return true;
512 }
513 
514 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
515   bool Changed = false;
516   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
517        ++MFI) {
518     MachineBasicBlock *MBB = &*MFI;
519     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
520          MBBI != MBBE;) {
521       if (!MBBI->isDebugValue()) {
522         ++MBBI;
523         continue;
524       }
525       // DBG_VALUE has no slot index, use the previous instruction instead.
526       SlotIndex Idx =
527           MBBI == MBB->begin()
528               ? LIS->getMBBStartIdx(MBB)
529               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
530       // Handle consecutive DBG_VALUE instructions with the same slot index.
531       do {
532         if (handleDebugValue(*MBBI, Idx)) {
533           MBBI = MBB->erase(MBBI);
534           Changed = true;
535         } else
536           ++MBBI;
537       } while (MBBI != MBBE && MBBI->isDebugValue());
538     }
539   }
540   return Changed;
541 }
542 
543 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
544 /// data-flow analysis to propagate them beyond basic block boundaries.
545 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
546                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
547                           LiveIntervals &LIS) {
548   SlotIndex Start = Idx;
549   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
550   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
551   LocMap::iterator I = locInts.find(Start);
552 
553   // Limit to VNI's live range.
554   bool ToEnd = true;
555   if (LR && VNI) {
556     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
557     if (!Segment || Segment->valno != VNI) {
558       if (Kills)
559         Kills->push_back(Start);
560       return;
561     }
562     if (Segment->end < Stop) {
563       Stop = Segment->end;
564       ToEnd = false;
565     }
566   }
567 
568   // There could already be a short def at Start.
569   if (I.valid() && I.start() <= Start) {
570     // Stop when meeting a different location or an already extended interval.
571     Start = Start.getNextSlot();
572     if (I.value() != LocNo || I.stop() != Start)
573       return;
574     // This is a one-slot placeholder. Just skip it.
575     ++I;
576   }
577 
578   // Limited by the next def.
579   if (I.valid() && I.start() < Stop) {
580     Stop = I.start();
581     ToEnd = false;
582   }
583   // Limited by VNI's live range.
584   else if (!ToEnd && Kills)
585     Kills->push_back(Stop);
586 
587   if (Start < Stop)
588     I.insert(Start, Stop, LocNo);
589 }
590 
591 void
592 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
593                        const SmallVectorImpl<SlotIndex> &Kills,
594                        SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs,
595                        MachineRegisterInfo &MRI, LiveIntervals &LIS) {
596   if (Kills.empty())
597     return;
598   // Don't track copies from physregs, there are too many uses.
599   if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
600     return;
601 
602   // Collect all the (vreg, valno) pairs that are copies of LI.
603   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
604   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
605     MachineInstr *MI = MO.getParent();
606     // Copies of the full value.
607     if (MO.getSubReg() || !MI->isCopy())
608       continue;
609     unsigned DstReg = MI->getOperand(0).getReg();
610 
611     // Don't follow copies to physregs. These are usually setting up call
612     // arguments, and the argument registers are always call clobbered. We are
613     // better off in the source register which could be a callee-saved register,
614     // or it could be spilled.
615     if (!TargetRegisterInfo::isVirtualRegister(DstReg))
616       continue;
617 
618     // Is LocNo extended to reach this copy? If not, another def may be blocking
619     // it, or we are looking at a wrong value of LI.
620     SlotIndex Idx = LIS.getInstructionIndex(*MI);
621     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
622     if (!I.valid() || I.value() != LocNo)
623       continue;
624 
625     if (!LIS.hasInterval(DstReg))
626       continue;
627     LiveInterval *DstLI = &LIS.getInterval(DstReg);
628     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
629     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
630     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
631   }
632 
633   if (CopyValues.empty())
634     return;
635 
636   DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
637 
638   // Try to add defs of the copied values for each kill point.
639   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
640     SlotIndex Idx = Kills[i];
641     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
642       LiveInterval *DstLI = CopyValues[j].first;
643       const VNInfo *DstVNI = CopyValues[j].second;
644       if (DstLI->getVNInfoAt(Idx) != DstVNI)
645         continue;
646       // Check that there isn't already a def at Idx
647       LocMap::iterator I = locInts.find(Idx);
648       if (I.valid() && I.start() <= Idx)
649         continue;
650       DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
651                    << DstVNI->id << " in " << *DstLI << '\n');
652       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
653       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
654       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
655       I.insert(Idx, Idx.getNextSlot(), LocNo);
656       NewDefs.push_back(std::make_pair(Idx, LocNo));
657       break;
658     }
659   }
660 }
661 
662 void UserValue::computeIntervals(MachineRegisterInfo &MRI,
663                                  const TargetRegisterInfo &TRI,
664                                  LiveIntervals &LIS, LexicalScopes &LS) {
665   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
666 
667   // Collect all defs to be extended (Skipping undefs).
668   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
669     if (I.value() != UndefLocNo)
670       Defs.push_back(std::make_pair(I.start(), I.value()));
671 
672   // Extend all defs, and possibly add new ones along the way.
673   for (unsigned i = 0; i != Defs.size(); ++i) {
674     SlotIndex Idx = Defs[i].first;
675     unsigned LocNo = Defs[i].second;
676     const MachineOperand &Loc = locations[LocNo];
677 
678     if (!Loc.isReg()) {
679       extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS);
680       continue;
681     }
682 
683     // Register locations are constrained to where the register value is live.
684     if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
685       LiveInterval *LI = nullptr;
686       const VNInfo *VNI = nullptr;
687       if (LIS.hasInterval(Loc.getReg())) {
688         LI = &LIS.getInterval(Loc.getReg());
689         VNI = LI->getVNInfoAt(Idx);
690       }
691       SmallVector<SlotIndex, 16> Kills;
692       extendDef(Idx, LocNo, LI, VNI, &Kills, LIS);
693       if (LI)
694         addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
695       continue;
696     }
697 
698     // For physregs, use the live range of the first regunit as a guide.
699     unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
700     LiveRange *LR = &LIS.getRegUnit(Unit);
701     const VNInfo *VNI = LR->getVNInfoAt(Idx);
702     // Don't track copies from physregs, it is too expensive.
703     extendDef(Idx, LocNo, LR, VNI, nullptr, LIS);
704   }
705 
706   // Erase all the undefs.
707   for (LocMap::iterator I = locInts.begin(); I.valid();)
708     if (I.value() == UndefLocNo)
709       I.erase();
710     else
711       ++I;
712 
713   // The computed intervals may extend beyond the range of the debug
714   // location's lexical scope. In this case, splitting of an interval
715   // can result in an interval outside of the scope being created,
716   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
717   // this, trim the intervals to the lexical scope.
718 
719   LexicalScope *Scope = LS.findLexicalScope(dl);
720   if (!Scope)
721     return;
722 
723   SlotIndex PrevEnd;
724   LocMap::iterator I = locInts.begin();
725 
726   // Iterate over the lexical scope ranges. Each time round the loop
727   // we check the intervals for overlap with the end of the previous
728   // range and the start of the next. The first range is handled as
729   // a special case where there is no PrevEnd.
730   for (const InsnRange &Range : Scope->getRanges()) {
731     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
732     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
733 
734     // At the start of each iteration I has been advanced so that
735     // I.stop() >= PrevEnd. Check for overlap.
736     if (PrevEnd && I.start() < PrevEnd) {
737       SlotIndex IStop = I.stop();
738       unsigned LocNo = I.value();
739 
740       // Stop overlaps previous end - trim the end of the interval to
741       // the scope range.
742       I.setStopUnchecked(PrevEnd);
743       ++I;
744 
745       // If the interval also overlaps the start of the "next" (i.e.
746       // current) range create a new interval for the remainder (which
747       // may be further trimmed).
748       if (RStart < IStop)
749         I.insert(RStart, IStop, LocNo);
750     }
751 
752     // Advance I so that I.stop() >= RStart, and check for overlap.
753     I.advanceTo(RStart);
754     if (!I.valid())
755       return;
756 
757     if (I.start() < RStart) {
758       // Interval start overlaps range - trim to the scope range.
759       I.setStartUnchecked(RStart);
760       // Remember that this interval was trimmed.
761       trimmedDefs.insert(RStart);
762     }
763 
764     // The end of a lexical scope range is the last instruction in the
765     // range. To convert to an interval we need the index of the
766     // instruction after it.
767     REnd = REnd.getNextIndex();
768 
769     // Advance I to first interval outside current range.
770     I.advanceTo(REnd);
771     if (!I.valid())
772       return;
773 
774     PrevEnd = REnd;
775   }
776 
777   // Check for overlap with end of final range.
778   if (PrevEnd && I.start() < PrevEnd)
779     I.setStopUnchecked(PrevEnd);
780 }
781 
782 void LDVImpl::computeIntervals() {
783   LexicalScopes LS;
784   LS.initialize(*MF);
785 
786   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
787     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
788     userValues[i]->mapVirtRegs(this);
789   }
790 }
791 
792 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
793   clear();
794   MF = &mf;
795   LIS = &pass.getAnalysis<LiveIntervals>();
796   TRI = mf.getSubtarget().getRegisterInfo();
797   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
798                << mf.getName() << " **********\n");
799 
800   bool Changed = collectDebugValues(mf);
801   computeIntervals();
802   DEBUG(print(dbgs()));
803   ModifiedMF = Changed;
804   return Changed;
805 }
806 
807 static void removeDebugValues(MachineFunction &mf) {
808   for (MachineBasicBlock &MBB : mf) {
809     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
810       if (!MBBI->isDebugValue()) {
811         ++MBBI;
812         continue;
813       }
814       MBBI = MBB.erase(MBBI);
815     }
816   }
817 }
818 
819 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
820   if (!EnableLDV)
821     return false;
822   if (!mf.getFunction()->getSubprogram()) {
823     removeDebugValues(mf);
824     return false;
825   }
826   if (!pImpl)
827     pImpl = new LDVImpl(this);
828   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
829 }
830 
831 void LiveDebugVariables::releaseMemory() {
832   if (pImpl)
833     static_cast<LDVImpl*>(pImpl)->clear();
834 }
835 
836 LiveDebugVariables::~LiveDebugVariables() {
837   if (pImpl)
838     delete static_cast<LDVImpl*>(pImpl);
839 }
840 
841 //===----------------------------------------------------------------------===//
842 //                           Live Range Splitting
843 //===----------------------------------------------------------------------===//
844 
845 bool
846 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
847                          LiveIntervals& LIS) {
848   DEBUG({
849     dbgs() << "Splitting Loc" << OldLocNo << '\t';
850     print(dbgs(), nullptr);
851   });
852   bool DidChange = false;
853   LocMap::iterator LocMapI;
854   LocMapI.setMap(locInts);
855   for (unsigned i = 0; i != NewRegs.size(); ++i) {
856     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
857     if (LI->empty())
858       continue;
859 
860     // Don't allocate the new LocNo until it is needed.
861     unsigned NewLocNo = UndefLocNo;
862 
863     // Iterate over the overlaps between locInts and LI.
864     LocMapI.find(LI->beginIndex());
865     if (!LocMapI.valid())
866       continue;
867     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
868     LiveInterval::iterator LIE = LI->end();
869     while (LocMapI.valid() && LII != LIE) {
870       // At this point, we know that LocMapI.stop() > LII->start.
871       LII = LI->advanceTo(LII, LocMapI.start());
872       if (LII == LIE)
873         break;
874 
875       // Now LII->end > LocMapI.start(). Do we have an overlap?
876       if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
877         // Overlapping correct location. Allocate NewLocNo now.
878         if (NewLocNo == UndefLocNo) {
879           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
880           MO.setSubReg(locations[OldLocNo].getSubReg());
881           NewLocNo = getLocationNo(MO);
882           DidChange = true;
883         }
884 
885         SlotIndex LStart = LocMapI.start();
886         SlotIndex LStop  = LocMapI.stop();
887 
888         // Trim LocMapI down to the LII overlap.
889         if (LStart < LII->start)
890           LocMapI.setStartUnchecked(LII->start);
891         if (LStop > LII->end)
892           LocMapI.setStopUnchecked(LII->end);
893 
894         // Change the value in the overlap. This may trigger coalescing.
895         LocMapI.setValue(NewLocNo);
896 
897         // Re-insert any removed OldLocNo ranges.
898         if (LStart < LocMapI.start()) {
899           LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
900           ++LocMapI;
901           assert(LocMapI.valid() && "Unexpected coalescing");
902         }
903         if (LStop > LocMapI.stop()) {
904           ++LocMapI;
905           LocMapI.insert(LII->end, LStop, OldLocNo);
906           --LocMapI;
907         }
908       }
909 
910       // Advance to the next overlap.
911       if (LII->end < LocMapI.stop()) {
912         if (++LII == LIE)
913           break;
914         LocMapI.advanceTo(LII->start);
915       } else {
916         ++LocMapI;
917         if (!LocMapI.valid())
918           break;
919         LII = LI->advanceTo(LII, LocMapI.start());
920       }
921     }
922   }
923 
924   // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
925   locations.erase(locations.begin() + OldLocNo);
926   LocMapI.goToBegin();
927   while (LocMapI.valid()) {
928     unsigned v = LocMapI.value();
929     if (v == OldLocNo) {
930       DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
931                    << LocMapI.stop() << ")\n");
932       LocMapI.erase();
933     } else {
934       if (v > OldLocNo)
935         LocMapI.setValueUnchecked(v-1);
936       ++LocMapI;
937     }
938   }
939 
940   DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
941   return DidChange;
942 }
943 
944 bool
945 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
946                          LiveIntervals &LIS) {
947   bool DidChange = false;
948   // Split locations referring to OldReg. Iterate backwards so splitLocation can
949   // safely erase unused locations.
950   for (unsigned i = locations.size(); i ; --i) {
951     unsigned LocNo = i-1;
952     const MachineOperand *Loc = &locations[LocNo];
953     if (!Loc->isReg() || Loc->getReg() != OldReg)
954       continue;
955     DidChange |= splitLocation(LocNo, NewRegs, LIS);
956   }
957   return DidChange;
958 }
959 
960 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
961   bool DidChange = false;
962   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
963     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
964 
965   if (!DidChange)
966     return;
967 
968   // Map all of the new virtual registers.
969   UserValue *UV = lookupVirtReg(OldReg);
970   for (unsigned i = 0; i != NewRegs.size(); ++i)
971     mapVirtReg(NewRegs[i], UV);
972 }
973 
974 void LiveDebugVariables::
975 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
976   if (pImpl)
977     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
978 }
979 
980 void UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
981                                  BitVector &SpilledLocations) {
982   SpilledLocations.clear();
983   SpilledLocations.resize(locations.size());
984 
985   // Iterate over locations in reverse makes it easier to handle coalescing.
986   for (unsigned i = locations.size(); i ; --i) {
987     unsigned LocNo = i-1;
988     MachineOperand &Loc = locations[LocNo];
989     // Only virtual registers are rewritten.
990     if (!Loc.isReg() || !Loc.getReg() ||
991         !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
992       continue;
993     unsigned VirtReg = Loc.getReg();
994     if (VRM.isAssignedReg(VirtReg) &&
995         TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
996       // This can create a %noreg operand in rare cases when the sub-register
997       // index is no longer available. That means the user value is in a
998       // non-existent sub-register, and %noreg is exactly what we want.
999       Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1000     } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1001       // FIXME: Translate SubIdx to a stackslot offset.
1002       Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1003       SpilledLocations.set(LocNo);
1004     } else {
1005       Loc.setReg(0);
1006       Loc.setSubReg(0);
1007     }
1008     coalesceLocation(LocNo);
1009   }
1010 }
1011 
1012 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
1013 /// instruction.
1014 static MachineBasicBlock::iterator
1015 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
1016                    LiveIntervals &LIS) {
1017   SlotIndex Start = LIS.getMBBStartIdx(MBB);
1018   Idx = Idx.getBaseIndex();
1019 
1020   // Try to find an insert location by going backwards from Idx.
1021   MachineInstr *MI;
1022   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1023     // We've reached the beginning of MBB.
1024     if (Idx == Start) {
1025       MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
1026       return I;
1027     }
1028     Idx = Idx.getPrevIndex();
1029   }
1030 
1031   // Don't insert anything after the first terminator, though.
1032   return MI->isTerminator() ? MBB->getFirstTerminator() :
1033                               std::next(MachineBasicBlock::iterator(MI));
1034 }
1035 
1036 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
1037                                  unsigned LocNo, bool Spilled,
1038                                  LiveIntervals &LIS,
1039                                  const TargetInstrInfo &TII) {
1040   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
1041   MachineOperand &Loc = locations[LocNo];
1042   ++NumInsertedDebugValues;
1043 
1044   assert(cast<DILocalVariable>(Variable)
1045              ->isValidLocationForIntrinsic(getDebugLoc()) &&
1046          "Expected inlined-at fields to agree");
1047 
1048   // If the location was spilled, the new DBG_VALUE will be indirect. If the
1049   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1050   // that the original virtual register was a pointer.
1051   bool NewIndirect = IsIndirect || Spilled;
1052   const DIExpression *Expr = Expression;
1053   if (Spilled && IsIndirect)
1054     Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
1055 
1056   MachineInstrBuilder MIB =
1057       BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
1058           .add(Loc);
1059   if (NewIndirect)
1060     MIB.addImm(0U);
1061   else
1062     MIB.addReg(0U, RegState::Debug);
1063   MIB.addMetadata(Variable).addMetadata(Expr);
1064 }
1065 
1066 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1067                                 const TargetInstrInfo &TII,
1068                                 const BitVector &SpilledLocations) {
1069   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1070 
1071   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1072     SlotIndex Start = I.start();
1073     SlotIndex Stop = I.stop();
1074     unsigned LocNo = I.value();
1075     bool Spilled = LocNo != UndefLocNo ? SpilledLocations.test(LocNo) : false;
1076 
1077     // If the interval start was trimmed to the lexical scope insert the
1078     // DBG_VALUE at the previous index (otherwise it appears after the
1079     // first instruction in the range).
1080     if (trimmedDefs.count(Start))
1081       Start = Start.getPrevIndex();
1082 
1083     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
1084     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1085     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1086 
1087     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1088     insertDebugValue(&*MBB, Start, LocNo, Spilled, LIS, TII);
1089     // This interval may span multiple basic blocks.
1090     // Insert a DBG_VALUE into each one.
1091     while(Stop > MBBEnd) {
1092       // Move to the next block.
1093       Start = MBBEnd;
1094       if (++MBB == MFEnd)
1095         break;
1096       MBBEnd = LIS.getMBBEndIdx(&*MBB);
1097       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1098       insertDebugValue(&*MBB, Start, LocNo, Spilled, LIS, TII);
1099     }
1100     DEBUG(dbgs() << '\n');
1101     if (MBB == MFEnd)
1102       break;
1103 
1104     ++I;
1105   }
1106 }
1107 
1108 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1109   DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1110   if (!MF)
1111     return;
1112   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1113   BitVector SpilledLocations;
1114   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1115     DEBUG(userValues[i]->print(dbgs(), TRI));
1116     userValues[i]->rewriteLocations(*VRM, *TRI, SpilledLocations);
1117     userValues[i]->emitDebugValues(VRM, *LIS, *TII, SpilledLocations);
1118   }
1119   EmitDone = true;
1120 }
1121 
1122 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1123   if (pImpl)
1124     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1125 }
1126 
1127 bool LiveDebugVariables::doInitialization(Module &M) {
1128   return Pass::doInitialization(M);
1129 }
1130 
1131 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1132 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1133   if (pImpl)
1134     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1135 }
1136 #endif
1137