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