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