LLVM  7.0.0svn
LiveDebugVariables.cpp
Go to the documentation of this file.
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"
47 #include "llvm/Config/llvm-config.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/MC/MCRegisterInfo.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/Debug.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <iterator>
62 #include <memory>
63 #include <utility>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "livedebugvars"
68 
69 static cl::opt<bool>
70 EnableLDV("live-debug-variables", cl::init(true),
71  cl::desc("Enable the live debug variables pass"), cl::Hidden);
72 
73 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
74 
75 char LiveDebugVariables::ID = 0;
76 
78  "Debug Variable Analysis", false, false)
82  "Debug Variable Analysis", false, false)
83 
84 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
85  AU.addRequired<MachineDominatorTree>();
86  AU.addRequiredTransitive<LiveIntervals>();
87  AU.setPreservesAll();
89 }
90 
93 }
94 
95 enum : unsigned { UndefLocNo = ~0U };
96 
97 /// Describes a location by number along with some flags about the original
98 /// usage of the location.
100 public:
101  DbgValueLocation(unsigned LocNo, bool WasIndirect)
102  : LocNo(LocNo), WasIndirect(WasIndirect) {
103  static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
104  assert(locNo() == LocNo && "location truncation");
105  }
106 
107  DbgValueLocation() : LocNo(0), WasIndirect(0) {}
108 
109  unsigned locNo() const {
110  // Fix up the undef location number, which gets truncated.
111  return LocNo == INT_MAX ? UndefLocNo : LocNo;
112  }
113  bool wasIndirect() const { return WasIndirect; }
114  bool isUndef() const { return locNo() == UndefLocNo; }
115 
116  DbgValueLocation changeLocNo(unsigned NewLocNo) const {
117  return DbgValueLocation(NewLocNo, WasIndirect);
118  }
119 
120  friend inline bool operator==(const DbgValueLocation &LHS,
121  const DbgValueLocation &RHS) {
122  return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect;
123  }
124 
125  friend inline bool operator!=(const DbgValueLocation &LHS,
126  const DbgValueLocation &RHS) {
127  return !(LHS == RHS);
128  }
129 
130 private:
131  unsigned LocNo : 31;
132  unsigned WasIndirect : 1;
133 };
134 
135 /// LocMap - Map of where a user value is live, and its location.
137 
138 namespace {
139 
140 class LDVImpl;
141 
142 /// UserValue - A user value is a part of a debug info user variable.
143 ///
144 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
145 /// holds part of a user variable. The part is identified by a byte offset.
146 ///
147 /// UserValues are grouped into equivalence classes for easier searching. Two
148 /// user values are related if they refer to the same variable, or if they are
149 /// held by the same virtual register. The equivalence class is the transitive
150 /// closure of that relation.
151 class UserValue {
152  const DILocalVariable *Variable; ///< The debug info variable we are part of.
153  const DIExpression *Expression; ///< Any complex address expression.
154  DebugLoc dl; ///< The debug location for the variable. This is
155  ///< used by dwarf writer to find lexical scope.
156  UserValue *leader; ///< Equivalence class leader.
157  UserValue *next = nullptr; ///< Next value in equivalence class, or null.
158 
159  /// Numbered locations referenced by locmap.
161 
162  /// Map of slot indices where this value is live.
163  LocMap locInts;
164 
165  /// Set of interval start indexes that have been trimmed to the
166  /// lexical scope.
167  SmallSet<SlotIndex, 2> trimmedDefs;
168 
169  /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
170  void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
171  SlotIndex StopIdx,
172  DbgValueLocation Loc, bool Spilled, LiveIntervals &LIS,
173  const TargetInstrInfo &TII,
174  const TargetRegisterInfo &TRI);
175 
176  /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
177  /// is live. Returns true if any changes were made.
178  bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
179  LiveIntervals &LIS);
180 
181 public:
182  /// UserValue - Create a new UserValue.
183  UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
184  LocMap::Allocator &alloc)
185  : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
186  locInts(alloc) {}
187 
188  /// getLeader - Get the leader of this value's equivalence class.
189  UserValue *getLeader() {
190  UserValue *l = leader;
191  while (l != l->leader)
192  l = l->leader;
193  return leader = l;
194  }
195 
196  /// getNext - Return the next UserValue in the equivalence class.
197  UserValue *getNext() const { return next; }
198 
199  /// match - Does this UserValue match the parameters?
200  bool match(const DILocalVariable *Var, const DIExpression *Expr,
201  const DILocation *IA) const {
202  // FIXME: The fragment should be part of the equivalence class, but not
203  // other things in the expression like stack values.
204  return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
205  }
206 
207  /// merge - Merge equivalence classes.
208  static UserValue *merge(UserValue *L1, UserValue *L2) {
209  L2 = L2->getLeader();
210  if (!L1)
211  return L2;
212  L1 = L1->getLeader();
213  if (L1 == L2)
214  return L1;
215  // Splice L2 before L1's members.
216  UserValue *End = L2;
217  while (End->next) {
218  End->leader = L1;
219  End = End->next;
220  }
221  End->leader = L1;
222  End->next = L1->next;
223  L1->next = L2;
224  return L1;
225  }
226 
227  /// Return the location number that matches Loc.
228  ///
229  /// For undef values we always return location number UndefLocNo without
230  /// inserting anything in locations. Since locations is a vector and the
231  /// location number is the position in the vector and UndefLocNo is ~0,
232  /// we would need a very big vector to put the value at the right position.
233  unsigned getLocationNo(const MachineOperand &LocMO) {
234  if (LocMO.isReg()) {
235  if (LocMO.getReg() == 0)
236  return UndefLocNo;
237  // For register locations we dont care about use/def and other flags.
238  for (unsigned i = 0, e = locations.size(); i != e; ++i)
239  if (locations[i].isReg() &&
240  locations[i].getReg() == LocMO.getReg() &&
241  locations[i].getSubReg() == LocMO.getSubReg())
242  return i;
243  } else
244  for (unsigned i = 0, e = locations.size(); i != e; ++i)
245  if (LocMO.isIdenticalTo(locations[i]))
246  return i;
247  locations.push_back(LocMO);
248  // We are storing a MachineOperand outside a MachineInstr.
249  locations.back().clearParent();
250  // Don't store def operands.
251  if (locations.back().isReg()) {
252  if (locations.back().isDef())
253  locations.back().setIsDead(false);
254  locations.back().setIsUse();
255  }
256  return locations.size() - 1;
257  }
258 
259  /// mapVirtRegs - Ensure that all virtual register locations are mapped.
260  void mapVirtRegs(LDVImpl *LDV);
261 
262  /// addDef - Add a definition point to this value.
263  void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
264  DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
265  // Add a singular (Idx,Idx) -> Loc mapping.
266  LocMap::iterator I = locInts.find(Idx);
267  if (!I.valid() || I.start() != Idx)
268  I.insert(Idx, Idx.getNextSlot(), Loc);
269  else
270  // A later DBG_VALUE at the same SlotIndex overrides the old location.
271  I.setValue(Loc);
272  }
273 
274  /// extendDef - Extend the current definition as far as possible down.
275  /// Stop when meeting an existing def or when leaving the live
276  /// range of VNI.
277  /// End points where VNI is no longer live are added to Kills.
278  /// @param Idx Starting point for the definition.
279  /// @param Loc Location number to propagate.
280  /// @param LR Restrict liveness to where LR has the value VNI. May be null.
281  /// @param VNI When LR is not null, this is the value to restrict to.
282  /// @param Kills Append end points of VNI's live range to Kills.
283  /// @param LIS Live intervals analysis.
284  void extendDef(SlotIndex Idx, DbgValueLocation Loc,
285  LiveRange *LR, const VNInfo *VNI,
287  LiveIntervals &LIS);
288 
289  /// addDefsFromCopies - The value in LI/LocNo may be copies to other
290  /// registers. Determine if any of the copies are available at the kill
291  /// points, and add defs if possible.
292  /// @param LI Scan for copies of the value in LI->reg.
293  /// @param LocNo Location number of LI->reg.
294  /// @param WasIndirect Indicates if the original use of LI->reg was indirect
295  /// @param Kills Points where the range of LocNo could be extended.
296  /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
297  void addDefsFromCopies(
298  LiveInterval *LI, unsigned LocNo, bool WasIndirect,
299  const SmallVectorImpl<SlotIndex> &Kills,
300  SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
302 
303  /// computeIntervals - Compute the live intervals of all locations after
304  /// collecting all their def points.
305  void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
307 
308  /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
309  /// live. Returns true if any changes were made.
310  bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
311  LiveIntervals &LIS);
312 
313  /// rewriteLocations - Rewrite virtual register locations according to the
314  /// provided virtual register map. Record which locations were spilled.
315  void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
316  BitVector &SpilledLocations);
317 
318  /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
319  void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
320  const TargetInstrInfo &TII,
321  const TargetRegisterInfo &TRI,
322  const BitVector &SpilledLocations);
323 
324  /// getDebugLoc - Return DebugLoc of this UserValue.
325  DebugLoc getDebugLoc() { return dl;}
326 
327  void print(raw_ostream &, const TargetRegisterInfo *);
328 };
329 
330 /// LDVImpl - Implementation of the LiveDebugVariables pass.
331 class LDVImpl {
333  LocMap::Allocator allocator;
334  MachineFunction *MF = nullptr;
335  LiveIntervals *LIS;
336  const TargetRegisterInfo *TRI;
337 
338  /// Whether emitDebugValues is called.
339  bool EmitDone = false;
340 
341  /// Whether the machine function is modified during the pass.
342  bool ModifiedMF = false;
343 
344  /// userValues - All allocated UserValue instances.
346 
347  /// Map virtual register to eq class leader.
348  using VRMap = DenseMap<unsigned, UserValue *>;
349  VRMap virtRegToEqClass;
350 
351  /// Map user variable to eq class leader.
353  UVMap userVarMap;
354 
355  /// getUserValue - Find or create a UserValue.
356  UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
357  const DebugLoc &DL);
358 
359  /// lookupVirtReg - Find the EC leader for VirtReg or null.
360  UserValue *lookupVirtReg(unsigned VirtReg);
361 
362  /// handleDebugValue - Add DBG_VALUE instruction to our maps.
363  /// @param MI DBG_VALUE instruction
364  /// @param Idx Last valid SLotIndex before instruction.
365  /// @return True if the DBG_VALUE instruction should be deleted.
366  bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
367 
368  /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
369  /// a UserValue def for each instruction.
370  /// @param mf MachineFunction to be scanned.
371  /// @return True if any debug values were found.
373 
374  /// computeIntervals - Compute the live intervals of all user values after
375  /// collecting all their def points.
376  void computeIntervals();
377 
378 public:
379  LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
380 
381  bool runOnMachineFunction(MachineFunction &mf);
382 
383  /// clear - Release all memory.
384  void clear() {
385  MF = nullptr;
386  userValues.clear();
387  virtRegToEqClass.clear();
388  userVarMap.clear();
389  // Make sure we call emitDebugValues if the machine function was modified.
390  assert((!ModifiedMF || EmitDone) &&
391  "Dbg values are not emitted in LDV");
392  EmitDone = false;
393  ModifiedMF = false;
394  }
395 
396  /// mapVirtReg - Map virtual register to an equivalence class.
397  void mapVirtReg(unsigned VirtReg, UserValue *EC);
398 
399  /// splitRegister - Replace all references to OldReg with NewRegs.
400  void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
401 
402  /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
403  void emitDebugValues(VirtRegMap *VRM);
404 
405  void print(raw_ostream&);
406 };
407 
408 } // end anonymous namespace
409 
410 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
411 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
412  const LLVMContext &Ctx) {
413  if (!DL)
414  return;
415 
416  auto *Scope = cast<DIScope>(DL.getScope());
417  // Omit the directory, because it's likely to be long and uninteresting.
418  CommentOS << Scope->getFilename();
419  CommentOS << ':' << DL.getLine();
420  if (DL.getCol() != 0)
421  CommentOS << ':' << DL.getCol();
422 
423  DebugLoc InlinedAtDL = DL.getInlinedAt();
424  if (!InlinedAtDL)
425  return;
426 
427  CommentOS << " @[ ";
428  printDebugLoc(InlinedAtDL, CommentOS, Ctx);
429  CommentOS << " ]";
430 }
431 
433  const DILocation *DL) {
434  const LLVMContext &Ctx = V->getContext();
435  StringRef Res = V->getName();
436  if (!Res.empty())
437  OS << Res << "," << V->getLine();
438  if (auto *InlinedAt = DL->getInlinedAt()) {
439  if (DebugLoc InlinedAtDL = InlinedAt) {
440  OS << " @[";
441  printDebugLoc(InlinedAtDL, OS, Ctx);
442  OS << "]";
443  }
444  }
445 }
446 
448  auto *DV = cast<DILocalVariable>(Variable);
449  OS << "!\"";
450  printExtendedName(OS, DV, dl);
451 
452  OS << "\"\t";
453  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
454  OS << " [" << I.start() << ';' << I.stop() << "):";
455  if (I.value().isUndef())
456  OS << "undef";
457  else {
458  OS << I.value().locNo();
459  if (I.value().wasIndirect())
460  OS << " ind";
461  }
462  }
463  for (unsigned i = 0, e = locations.size(); i != e; ++i) {
464  OS << " Loc" << i << '=';
465  locations[i].print(OS, TRI);
466  }
467  OS << '\n';
468 }
469 
470 void LDVImpl::print(raw_ostream &OS) {
471  OS << "********** DEBUG VARIABLES **********\n";
472  for (unsigned i = 0, e = userValues.size(); i != e; ++i)
473  userValues[i]->print(OS, TRI);
474 }
475 #endif
476 
477 void UserValue::mapVirtRegs(LDVImpl *LDV) {
478  for (unsigned i = 0, e = locations.size(); i != e; ++i)
479  if (locations[i].isReg() &&
481  LDV->mapVirtReg(locations[i].getReg(), this);
482 }
483 
484 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
485  const DIExpression *Expr, const DebugLoc &DL) {
486  UserValue *&Leader = userVarMap[Var];
487  if (Leader) {
488  UserValue *UV = Leader->getLeader();
489  Leader = UV;
490  for (; UV; UV = UV->getNext())
491  if (UV->match(Var, Expr, DL->getInlinedAt()))
492  return UV;
493  }
494 
495  userValues.push_back(
496  llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
497  UserValue *UV = userValues.back().get();
498  Leader = UserValue::merge(Leader, UV);
499  return UV;
500 }
501 
502 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
503  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
504  UserValue *&Leader = virtRegToEqClass[VirtReg];
505  Leader = UserValue::merge(Leader, EC);
506 }
507 
508 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
509  if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
510  return UV->getLeader();
511  return nullptr;
512 }
513 
514 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
515  // DBG_VALUE loc, offset, variable
516  if (MI.getNumOperands() != 4 ||
517  !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
518  !MI.getOperand(2).isMetadata()) {
519  LLVM_DEBUG(dbgs() << "Can't handle " << MI);
520  return false;
521  }
522 
523  // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
524  // register that hasn't been defined yet. If we do not remove those here, then
525  // the re-insertion of the DBG_VALUE instruction after register allocation
526  // will be incorrect.
527  // TODO: If earlier passes are corrected to generate sane debug information
528  // (and if the machine verifier is improved to catch this), then these checks
529  // could be removed or replaced by asserts.
530  bool Discard = false;
531  if (MI.getOperand(0).isReg() &&
533  const unsigned Reg = MI.getOperand(0).getReg();
534  if (!LIS->hasInterval(Reg)) {
535  // The DBG_VALUE is described by a virtual register that does not have a
536  // live interval. Discard the DBG_VALUE.
537  Discard = true;
538  LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
539  << " " << MI);
540  } else {
541  // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
542  // is defined dead at Idx (where Idx is the slot index for the instruction
543  // preceeding the DBG_VALUE).
544  const LiveInterval &LI = LIS->getInterval(Reg);
545  LiveQueryResult LRQ = LI.Query(Idx);
546  if (!LRQ.valueOutOrDead()) {
547  // We have found a DBG_VALUE with the value in a virtual register that
548  // is not live. Discard the DBG_VALUE.
549  Discard = true;
550  LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
551  << " " << MI);
552  }
553  }
554  }
555 
556  // Get or create the UserValue for (variable,offset) here.
557  bool IsIndirect = MI.getOperand(1).isImm();
558  if (IsIndirect)
559  assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
560  const DILocalVariable *Var = MI.getDebugVariable();
561  const DIExpression *Expr = MI.getDebugExpression();
562  UserValue *UV =
563  getUserValue(Var, Expr, MI.getDebugLoc());
564  if (!Discard)
565  UV->addDef(Idx, MI.getOperand(0), IsIndirect);
566  else {
568  MO.setIsDebug();
569  UV->addDef(Idx, MO, false);
570  }
571  return true;
572 }
573 
575  bool Changed = false;
576  for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
577  ++MFI) {
578  MachineBasicBlock *MBB = &*MFI;
579  for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
580  MBBI != MBBE;) {
581  if (!MBBI->isDebugValue()) {
582  ++MBBI;
583  continue;
584  }
585  // DBG_VALUE has no slot index, use the previous instruction instead.
586  SlotIndex Idx =
587  MBBI == MBB->begin()
588  ? LIS->getMBBStartIdx(MBB)
589  : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
590  // Handle consecutive DBG_VALUE instructions with the same slot index.
591  do {
592  if (handleDebugValue(*MBBI, Idx)) {
593  MBBI = MBB->erase(MBBI);
594  Changed = true;
595  } else
596  ++MBBI;
597  } while (MBBI != MBBE && MBBI->isDebugValue());
598  }
599  }
600  return Changed;
601 }
602 
603 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
604 /// data-flow analysis to propagate them beyond basic block boundaries.
605 void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
606  const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
607  LiveIntervals &LIS) {
608  SlotIndex Start = Idx;
609  MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
610  SlotIndex Stop = LIS.getMBBEndIdx(MBB);
611  LocMap::iterator I = locInts.find(Start);
612 
613  // Limit to VNI's live range.
614  bool ToEnd = true;
615  if (LR && VNI) {
616  LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
617  if (!Segment || Segment->valno != VNI) {
618  if (Kills)
619  Kills->push_back(Start);
620  return;
621  }
622  if (Segment->end < Stop) {
623  Stop = Segment->end;
624  ToEnd = false;
625  }
626  }
627 
628  // There could already be a short def at Start.
629  if (I.valid() && I.start() <= Start) {
630  // Stop when meeting a different location or an already extended interval.
631  Start = Start.getNextSlot();
632  if (I.value() != Loc || I.stop() != Start)
633  return;
634  // This is a one-slot placeholder. Just skip it.
635  ++I;
636  }
637 
638  // Limited by the next def.
639  if (I.valid() && I.start() < Stop) {
640  Stop = I.start();
641  ToEnd = false;
642  }
643  // Limited by VNI's live range.
644  else if (!ToEnd && Kills)
645  Kills->push_back(Stop);
646 
647  if (Start < Stop)
648  I.insert(Start, Stop, Loc);
649 }
650 
651 void UserValue::addDefsFromCopies(
652  LiveInterval *LI, unsigned LocNo, bool WasIndirect,
653  const SmallVectorImpl<SlotIndex> &Kills,
654  SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
656  if (Kills.empty())
657  return;
658  // Don't track copies from physregs, there are too many uses.
660  return;
661 
662  // Collect all the (vreg, valno) pairs that are copies of LI.
664  for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
665  MachineInstr *MI = MO.getParent();
666  // Copies of the full value.
667  if (MO.getSubReg() || !MI->isCopy())
668  continue;
669  unsigned DstReg = MI->getOperand(0).getReg();
670 
671  // Don't follow copies to physregs. These are usually setting up call
672  // arguments, and the argument registers are always call clobbered. We are
673  // better off in the source register which could be a callee-saved register,
674  // or it could be spilled.
676  continue;
677 
678  // Is LocNo extended to reach this copy? If not, another def may be blocking
679  // it, or we are looking at a wrong value of LI.
680  SlotIndex Idx = LIS.getInstructionIndex(*MI);
681  LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
682  if (!I.valid() || I.value().locNo() != LocNo)
683  continue;
684 
685  if (!LIS.hasInterval(DstReg))
686  continue;
687  LiveInterval *DstLI = &LIS.getInterval(DstReg);
688  const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
689  assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
690  CopyValues.push_back(std::make_pair(DstLI, DstVNI));
691  }
692 
693  if (CopyValues.empty())
694  return;
695 
696  LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
697  << '\n');
698 
699  // Try to add defs of the copied values for each kill point.
700  for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
701  SlotIndex Idx = Kills[i];
702  for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
703  LiveInterval *DstLI = CopyValues[j].first;
704  const VNInfo *DstVNI = CopyValues[j].second;
705  if (DstLI->getVNInfoAt(Idx) != DstVNI)
706  continue;
707  // Check that there isn't already a def at Idx
708  LocMap::iterator I = locInts.find(Idx);
709  if (I.valid() && I.start() <= Idx)
710  continue;
711  LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
712  << DstVNI->id << " in " << *DstLI << '\n');
713  MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
714  assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
715  unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
716  DbgValueLocation NewLoc(LocNo, WasIndirect);
717  I.insert(Idx, Idx.getNextSlot(), NewLoc);
718  NewDefs.push_back(std::make_pair(Idx, NewLoc));
719  break;
720  }
721  }
722 }
723 
724 void UserValue::computeIntervals(MachineRegisterInfo &MRI,
725  const TargetRegisterInfo &TRI,
726  LiveIntervals &LIS, LexicalScopes &LS) {
728 
729  // Collect all defs to be extended (Skipping undefs).
730  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
731  if (!I.value().isUndef())
732  Defs.push_back(std::make_pair(I.start(), I.value()));
733 
734  // Extend all defs, and possibly add new ones along the way.
735  for (unsigned i = 0; i != Defs.size(); ++i) {
736  SlotIndex Idx = Defs[i].first;
737  DbgValueLocation Loc = Defs[i].second;
738  const MachineOperand &LocMO = locations[Loc.locNo()];
739 
740  if (!LocMO.isReg()) {
741  extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
742  continue;
743  }
744 
745  // Register locations are constrained to where the register value is live.
747  LiveInterval *LI = nullptr;
748  const VNInfo *VNI = nullptr;
749  if (LIS.hasInterval(LocMO.getReg())) {
750  LI = &LIS.getInterval(LocMO.getReg());
751  VNI = LI->getVNInfoAt(Idx);
752  }
754  extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
755  if (LI)
756  addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
757  LIS);
758  continue;
759  }
760 
761  // For physregs, we only mark the start slot idx. DwarfDebug will see it
762  // as if the DBG_VALUE is valid up until the end of the basic block, or
763  // the next def of the physical register. So we do not need to extend the
764  // range. It might actually happen that the DBG_VALUE is the last use of
765  // the physical register (e.g. if this is an unused input argument to a
766  // function).
767  }
768 
769  // The computed intervals may extend beyond the range of the debug
770  // location's lexical scope. In this case, splitting of an interval
771  // can result in an interval outside of the scope being created,
772  // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
773  // this, trim the intervals to the lexical scope.
774 
775  LexicalScope *Scope = LS.findLexicalScope(dl);
776  if (!Scope)
777  return;
778 
779  SlotIndex PrevEnd;
780  LocMap::iterator I = locInts.begin();
781 
782  // Iterate over the lexical scope ranges. Each time round the loop
783  // we check the intervals for overlap with the end of the previous
784  // range and the start of the next. The first range is handled as
785  // a special case where there is no PrevEnd.
786  for (const InsnRange &Range : Scope->getRanges()) {
787  SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
788  SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
789 
790  // At the start of each iteration I has been advanced so that
791  // I.stop() >= PrevEnd. Check for overlap.
792  if (PrevEnd && I.start() < PrevEnd) {
793  SlotIndex IStop = I.stop();
794  DbgValueLocation Loc = I.value();
795 
796  // Stop overlaps previous end - trim the end of the interval to
797  // the scope range.
798  I.setStopUnchecked(PrevEnd);
799  ++I;
800 
801  // If the interval also overlaps the start of the "next" (i.e.
802  // current) range create a new interval for the remainder (which
803  // may be further trimmed).
804  if (RStart < IStop)
805  I.insert(RStart, IStop, Loc);
806  }
807 
808  // Advance I so that I.stop() >= RStart, and check for overlap.
809  I.advanceTo(RStart);
810  if (!I.valid())
811  return;
812 
813  if (I.start() < RStart) {
814  // Interval start overlaps range - trim to the scope range.
815  I.setStartUnchecked(RStart);
816  // Remember that this interval was trimmed.
817  trimmedDefs.insert(RStart);
818  }
819 
820  // The end of a lexical scope range is the last instruction in the
821  // range. To convert to an interval we need the index of the
822  // instruction after it.
823  REnd = REnd.getNextIndex();
824 
825  // Advance I to first interval outside current range.
826  I.advanceTo(REnd);
827  if (!I.valid())
828  return;
829 
830  PrevEnd = REnd;
831  }
832 
833  // Check for overlap with end of final range.
834  if (PrevEnd && I.start() < PrevEnd)
835  I.setStopUnchecked(PrevEnd);
836 }
837 
838 void LDVImpl::computeIntervals() {
840  LS.initialize(*MF);
841 
842  for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
843  userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
844  userValues[i]->mapVirtRegs(this);
845  }
846 }
847 
848 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
849  clear();
850  MF = &mf;
851  LIS = &pass.getAnalysis<LiveIntervals>();
852  TRI = mf.getSubtarget().getRegisterInfo();
853  LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
854  << mf.getName() << " **********\n");
855 
856  bool Changed = collectDebugValues(mf);
857  computeIntervals();
858  LLVM_DEBUG(print(dbgs()));
859  ModifiedMF = Changed;
860  return Changed;
861 }
862 
864  for (MachineBasicBlock &MBB : mf) {
865  for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
866  if (!MBBI->isDebugValue()) {
867  ++MBBI;
868  continue;
869  }
870  MBBI = MBB.erase(MBBI);
871  }
872  }
873 }
874 
875 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
876  if (!EnableLDV)
877  return false;
878  if (!mf.getFunction().getSubprogram()) {
879  removeDebugValues(mf);
880  return false;
881  }
882  if (!pImpl)
883  pImpl = new LDVImpl(this);
884  return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
885 }
886 
887 void LiveDebugVariables::releaseMemory() {
888  if (pImpl)
889  static_cast<LDVImpl*>(pImpl)->clear();
890 }
891 
893  if (pImpl)
894  delete static_cast<LDVImpl*>(pImpl);
895 }
896 
897 //===----------------------------------------------------------------------===//
898 // Live Range Splitting
899 //===----------------------------------------------------------------------===//
900 
901 bool
902 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
903  LiveIntervals& LIS) {
904  LLVM_DEBUG({
905  dbgs() << "Splitting Loc" << OldLocNo << '\t';
906  print(dbgs(), nullptr);
907  });
908  bool DidChange = false;
909  LocMap::iterator LocMapI;
910  LocMapI.setMap(locInts);
911  for (unsigned i = 0; i != NewRegs.size(); ++i) {
912  LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
913  if (LI->empty())
914  continue;
915 
916  // Don't allocate the new LocNo until it is needed.
917  unsigned NewLocNo = UndefLocNo;
918 
919  // Iterate over the overlaps between locInts and LI.
920  LocMapI.find(LI->beginIndex());
921  if (!LocMapI.valid())
922  continue;
923  LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
924  LiveInterval::iterator LIE = LI->end();
925  while (LocMapI.valid() && LII != LIE) {
926  // At this point, we know that LocMapI.stop() > LII->start.
927  LII = LI->advanceTo(LII, LocMapI.start());
928  if (LII == LIE)
929  break;
930 
931  // Now LII->end > LocMapI.start(). Do we have an overlap?
932  if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
933  // Overlapping correct location. Allocate NewLocNo now.
934  if (NewLocNo == UndefLocNo) {
936  MO.setSubReg(locations[OldLocNo].getSubReg());
937  NewLocNo = getLocationNo(MO);
938  DidChange = true;
939  }
940 
941  SlotIndex LStart = LocMapI.start();
942  SlotIndex LStop = LocMapI.stop();
943  DbgValueLocation OldLoc = LocMapI.value();
944 
945  // Trim LocMapI down to the LII overlap.
946  if (LStart < LII->start)
947  LocMapI.setStartUnchecked(LII->start);
948  if (LStop > LII->end)
949  LocMapI.setStopUnchecked(LII->end);
950 
951  // Change the value in the overlap. This may trigger coalescing.
952  LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
953 
954  // Re-insert any removed OldLocNo ranges.
955  if (LStart < LocMapI.start()) {
956  LocMapI.insert(LStart, LocMapI.start(), OldLoc);
957  ++LocMapI;
958  assert(LocMapI.valid() && "Unexpected coalescing");
959  }
960  if (LStop > LocMapI.stop()) {
961  ++LocMapI;
962  LocMapI.insert(LII->end, LStop, OldLoc);
963  --LocMapI;
964  }
965  }
966 
967  // Advance to the next overlap.
968  if (LII->end < LocMapI.stop()) {
969  if (++LII == LIE)
970  break;
971  LocMapI.advanceTo(LII->start);
972  } else {
973  ++LocMapI;
974  if (!LocMapI.valid())
975  break;
976  LII = LI->advanceTo(LII, LocMapI.start());
977  }
978  }
979  }
980 
981  // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
982  locations.erase(locations.begin() + OldLocNo);
983  LocMapI.goToBegin();
984  while (LocMapI.valid()) {
985  DbgValueLocation v = LocMapI.value();
986  if (v.locNo() == OldLocNo) {
987  LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
988  << LocMapI.stop() << ")\n");
989  LocMapI.erase();
990  } else {
991  // Undef values always have location number UndefLocNo, so don't change
992  // locNo in that case. See getLocationNo().
993  if (!v.isUndef() && v.locNo() > OldLocNo)
994  LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
995  ++LocMapI;
996  }
997  }
998 
999  LLVM_DEBUG({
1000  dbgs() << "Split result: \t";
1001  print(dbgs(), nullptr);
1002  });
1003  return DidChange;
1004 }
1005 
1006 bool
1007 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
1008  LiveIntervals &LIS) {
1009  bool DidChange = false;
1010  // Split locations referring to OldReg. Iterate backwards so splitLocation can
1011  // safely erase unused locations.
1012  for (unsigned i = locations.size(); i ; --i) {
1013  unsigned LocNo = i-1;
1014  const MachineOperand *Loc = &locations[LocNo];
1015  if (!Loc->isReg() || Loc->getReg() != OldReg)
1016  continue;
1017  DidChange |= splitLocation(LocNo, NewRegs, LIS);
1018  }
1019  return DidChange;
1020 }
1021 
1022 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
1023  bool DidChange = false;
1024  for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1025  DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1026 
1027  if (!DidChange)
1028  return;
1029 
1030  // Map all of the new virtual registers.
1031  UserValue *UV = lookupVirtReg(OldReg);
1032  for (unsigned i = 0; i != NewRegs.size(); ++i)
1033  mapVirtReg(NewRegs[i], UV);
1034 }
1035 
1037 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
1038  if (pImpl)
1039  static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1040 }
1041 
1042 void UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
1043  BitVector &SpilledLocations) {
1044  // Build a set of new locations with new numbers so we can coalesce our
1045  // IntervalMap if two vreg intervals collapse to the same physical location.
1046  // Use MapVector instead of SetVector because MapVector::insert returns the
1047  // position of the previously or newly inserted element. The boolean value
1048  // tracks if the location was produced by a spill.
1049  // FIXME: This will be problematic if we ever support direct and indirect
1050  // frame index locations, i.e. expressing both variables in memory and
1051  // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1052  MapVector<MachineOperand, bool> NewLocations;
1053  SmallVector<unsigned, 4> LocNoMap(locations.size());
1054  for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1055  bool Spilled = false;
1056  MachineOperand Loc = locations[I];
1057  // Only virtual registers are rewritten.
1058  if (Loc.isReg() && Loc.getReg() &&
1060  unsigned VirtReg = Loc.getReg();
1061  if (VRM.isAssignedReg(VirtReg) &&
1063  // This can create a %noreg operand in rare cases when the sub-register
1064  // index is no longer available. That means the user value is in a
1065  // non-existent sub-register, and %noreg is exactly what we want.
1066  Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1067  } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1068  // FIXME: Translate SubIdx to a stackslot offset.
1069  Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1070  Spilled = true;
1071  } else {
1072  Loc.setReg(0);
1073  Loc.setSubReg(0);
1074  }
1075  }
1076 
1077  // Insert this location if it doesn't already exist and record a mapping
1078  // from the old number to the new number.
1079  auto InsertResult = NewLocations.insert({Loc, Spilled});
1080  unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1081  LocNoMap[I] = NewLocNo;
1082  }
1083 
1084  // Rewrite the locations and record which ones were spill slots.
1085  locations.clear();
1086  SpilledLocations.clear();
1087  SpilledLocations.resize(NewLocations.size());
1088  for (auto &Pair : NewLocations) {
1089  locations.push_back(Pair.first);
1090  if (Pair.second) {
1091  unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1092  SpilledLocations.set(NewLocNo);
1093  }
1094  }
1095 
1096  // Update the interval map, but only coalesce left, since intervals to the
1097  // right use the old location numbers. This should merge two contiguous
1098  // DBG_VALUE intervals with different vregs that were allocated to the same
1099  // physical register.
1100  for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1101  DbgValueLocation Loc = I.value();
1102  // Undef values don't exist in locations (and thus not in LocNoMap either)
1103  // so skip over them. See getLocationNo().
1104  if (Loc.isUndef())
1105  continue;
1106  unsigned NewLocNo = LocNoMap[Loc.locNo()];
1107  I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
1108  I.setStart(I.start());
1109  }
1110 }
1111 
1112 /// Find an iterator for inserting a DBG_VALUE instruction.
1115  LiveIntervals &LIS) {
1116  SlotIndex Start = LIS.getMBBStartIdx(MBB);
1117  Idx = Idx.getBaseIndex();
1118 
1119  // Try to find an insert location by going backwards from Idx.
1120  MachineInstr *MI;
1121  while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1122  // We've reached the beginning of MBB.
1123  if (Idx == Start) {
1125  return I;
1126  }
1127  Idx = Idx.getPrevIndex();
1128  }
1129 
1130  // Don't insert anything after the first terminator, though.
1131  return MI->isTerminator() ? MBB->getFirstTerminator() :
1132  std::next(MachineBasicBlock::iterator(MI));
1133 }
1134 
1135 /// Find an iterator for inserting the next DBG_VALUE instruction
1136 /// (or end if no more insert locations found).
1140  SlotIndex StopIdx, MachineOperand &LocMO,
1141  LiveIntervals &LIS,
1142  const TargetRegisterInfo &TRI) {
1143  if (!LocMO.isReg())
1144  return MBB->instr_end();
1145  unsigned Reg = LocMO.getReg();
1146 
1147  // Find the next instruction in the MBB that define the register Reg.
1148  while (I != MBB->end() && !I->isTerminator()) {
1149  if (!LIS.isNotInMIMap(*I) &&
1151  break;
1152  if (I->definesRegister(Reg, &TRI))
1153  // The insert location is directly after the instruction/bundle.
1154  return std::next(I);
1155  ++I;
1156  }
1157  return MBB->end();
1158 }
1159 
1160 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1161  SlotIndex StopIdx,
1162  DbgValueLocation Loc, bool Spilled,
1163  LiveIntervals &LIS,
1164  const TargetInstrInfo &TII,
1165  const TargetRegisterInfo &TRI) {
1166  SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1167  // Only search within the current MBB.
1168  StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1169  MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
1170  // Undef values don't exist in locations so create new "noreg" register MOs
1171  // for them. See getLocationNo().
1172  MachineOperand MO = !Loc.isUndef() ?
1173  locations[Loc.locNo()] :
1174  MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1175  /* isKill */ false, /* isDead */ false,
1176  /* isUndef */ false, /* isEarlyClobber */ false,
1177  /* SubReg */ 0, /* isDebug */ true);
1178 
1179  ++NumInsertedDebugValues;
1180 
1181  assert(cast<DILocalVariable>(Variable)
1182  ->isValidLocationForIntrinsic(getDebugLoc()) &&
1183  "Expected inlined-at fields to agree");
1184 
1185  // If the location was spilled, the new DBG_VALUE will be indirect. If the
1186  // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1187  // that the original virtual register was a pointer.
1188  const DIExpression *Expr = Expression;
1189  bool IsIndirect = Loc.wasIndirect();
1190  if (Spilled) {
1191  if (IsIndirect)
1193  IsIndirect = true;
1194  }
1195 
1196  assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
1197 
1198  do {
1199  BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1200  IsIndirect, MO, Variable, Expr);
1201 
1202  // Continue and insert DBG_VALUES after every redefinition of register
1203  // associated with the debug value within the range
1204  I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1205  } while (I != MBB->end());
1206 }
1207 
1208 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1209  const TargetInstrInfo &TII,
1210  const TargetRegisterInfo &TRI,
1211  const BitVector &SpilledLocations) {
1213 
1214  for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1215  SlotIndex Start = I.start();
1216  SlotIndex Stop = I.stop();
1217  DbgValueLocation Loc = I.value();
1218  bool Spilled = !Loc.isUndef() ? SpilledLocations.test(Loc.locNo()) : false;
1219 
1220  // If the interval start was trimmed to the lexical scope insert the
1221  // DBG_VALUE at the previous index (otherwise it appears after the
1222  // first instruction in the range).
1223  if (trimmedDefs.count(Start))
1224  Start = Start.getPrevIndex();
1225 
1226  LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
1228  SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1229 
1230  LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1231  insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
1232  // This interval may span multiple basic blocks.
1233  // Insert a DBG_VALUE into each one.
1234  while (Stop > MBBEnd) {
1235  // Move to the next block.
1236  Start = MBBEnd;
1237  if (++MBB == MFEnd)
1238  break;
1239  MBBEnd = LIS.getMBBEndIdx(&*MBB);
1240  LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1241  insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
1242  }
1243  LLVM_DEBUG(dbgs() << '\n');
1244  if (MBB == MFEnd)
1245  break;
1246 
1247  ++I;
1248  }
1249 }
1250 
1251 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1252  LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1253  if (!MF)
1254  return;
1255  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1256  BitVector SpilledLocations;
1257  for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1258  LLVM_DEBUG(userValues[i]->print(dbgs(), TRI));
1259  userValues[i]->rewriteLocations(*VRM, *TRI, SpilledLocations);
1260  userValues[i]->emitDebugValues(VRM, *LIS, *TII, *TRI, SpilledLocations);
1261  }
1262  EmitDone = true;
1263 }
1264 
1266  if (pImpl)
1267  static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1268 }
1269 
1270 bool LiveDebugVariables::doInitialization(Module &M) {
1271  return Pass::doInitialization(M);
1272 }
1273 
1274 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1276  if (pImpl)
1277  static_cast<LDVImpl*>(pImpl)->print(dbgs());
1278 }
1279 #endif
static bool isReg(const MCInst &MI, unsigned OpNo)
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:372
void setValueUnchecked(ValT x)
setValueUnchecked - Change the mapped value of the current interval without checking for coalescing...
Definition: IntervalMap.h:1566
bool empty() const
Definition: LiveInterval.h:370
void setValue(ValT x)
setValue - Change the mapped value of the current interval.
Definition: IntervalMap.h:1704
BitVector & set()
Definition: BitVector.h:398
Safe Stack instrumentation pass
Definition: SafeStack.cpp:900
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
size_type size() const
Definition: MapVector.h:61
const unsigned reg
Definition: LiveInterval.h:667
instr_iterator instr_end()
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
Definition: SlotIndexes.h:242
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:61
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
SlotIndex getPrevIndex() const
Returns the previous index.
Definition: SlotIndexes.h:300
static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, const LLVMContext &Ctx)
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Segments::iterator iterator
Definition: LiveInterval.h:208
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:285
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:638
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
void initializeLiveDebugVariablesPass(PassRegistry &)
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position...
Definition: LiveInterval.h:259
unsigned Reg
This file contains the declarations for metadata subclasses.
unsigned getSubReg() const
bool test(unsigned Idx) const
Definition: BitVector.h:502
SmallVectorImpl< InsnRange > & getRanges()
Definition: LexicalScopes.h:67
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:38
bool isMetadata() const
isMetadata - Tests if this is a MO_Metadata operand.
unsigned getLine() const
Definition: DebugLoc.cpp:26
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:34
bool valid() const
valid - Return true if the current position is valid, false for end().
Definition: IntervalMap.h:1349
void setIsDead(bool Val=true)
void setMap(const IntervalMap &m)
setMap - Change the map iterated over.
Definition: IntervalMap.h:1346
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:452
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
LexicalScope - This class is used to track scope information.
Definition: LexicalScopes.h:45
void dump() const
dump - Print data structures to dbgs().
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
static DIExpression * prepend(const DIExpression *Expr, bool DerefBefore, int64_t Offset=0, bool DerefAfter=false, bool StackValue=false)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value...
static MachineOperand CreateReg(unsigned Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
This class represents the liveness of a register, stack slot, etc.
Definition: LiveInterval.h:157
bool isNotInMIMap(const MachineInstr &Instr) const
Returns true if the specified machine instr has been removed or was never entered in the map...
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
SlotIndex getNextIndex() const
Returns the next index.
Definition: SlotIndexes.h:280
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Definition: BitVector.h:367
MachineFunction & getMachineFunction() const
Definition: VirtRegMap.h:83
StringRef getName() const
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:314
iterator end()
Definition: LiveInterval.h:212
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Result of a LiveRange query.
Definition: LiveInterval.h:90
void advanceTo(KeyT x)
advanceTo - Move to the first interval with stop >= x, or end().
Definition: IntervalMap.h:1433
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:501
DbgValueLocation(unsigned LocNo, bool WasIndirect)
friend bool operator==(const DbgValueLocation &LHS, const DbgValueLocation &RHS)
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
Definition: SlotIndexes.h:255
void initialize(const MachineFunction &)
initialize - Scan machine function and constuct lexical scope nest, resets the instance if necessary...
void erase()
erase - Erase the current interval.
Definition: IntervalMap.h:1861
LLVMContext & getContext() const
Definition: Metadata.h:922
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
bool isAssignedReg(unsigned virtReg) const
returns true if the specified virtual register is not mapped to a stack slot or rematerialized.
Definition: VirtRegMap.h:154
SlotIndex getNextSlot() const
Returns the next slot in the index list.
Definition: SlotIndexes.h:270
void clearParent()
clearParent - Reset the parent pointer.
LexicalScope * findLexicalScope(const DILocation *DL)
findLexicalScope - Find lexical scope, either regular or inlined, for the given DebugLoc.
Debug location.
const_iterator find(KeyT x) const
find - Return an iterator pointing to the first interval ending at or after x, or end()...
Definition: IntervalMap.h:1129
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition: Pass.h:106
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void setStartUnchecked(KeyT a)
setStartUnchecked - Move the start of the current interval without checking for coalescing or overlap...
Definition: IntervalMap.h:1550
DbgValueLocation changeLocNo(unsigned NewLocNo) const
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
Definition: LiveInterval.h:529
TargetInstrInfo - Interface to description of machine instruction set.
bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:409
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
unsigned const MachineRegisterInfo * MRI
bool hasInterval(unsigned Reg) const
static void removeDebugValues(MachineFunction &mf)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
typename Sizer::Allocator Allocator
Definition: IntervalMap.h:959
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE, "Debug Variable Analysis", false, false) INITIALIZE_PASS_END(LiveDebugVariables
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
void find(KeyT x)
find - Move to the first interval with stop >= x, or end().
Definition: IntervalMap.h:1423
const KeyT & start() const
start - Return the beginning of the current interval.
Definition: IntervalMap.h:1355
void goToBegin()
goToBegin - Move to the first interval in map.
Definition: IntervalMap.h:1379
Represent the analysis usage information of a pass.
void substPhysReg(unsigned Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
self_iterator getIterator()
Definition: ilist_node.h:82
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
MDNode * getScope() const
Definition: DebugLoc.cpp:36
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
bool isCopy() const
Definition: MachineInstr.h:892
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
size_t size() const
Definition: SmallVector.h:53
DILocation * getInlinedAt() const
Definition: DebugLoc.cpp:41
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
unsigned id
The ID number of this value.
Definition: LiveInterval.h:58
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:118
#define DEBUG_TYPE
Iterator for intrusive lists based on ilist_node.
void splitRegister(unsigned OldReg, ArrayRef< unsigned > NewRegs, LiveIntervals &LIS)
splitRegister - Move any user variables in OldReg to the live ranges in NewRegs where they are live...
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
friend bool operator!=(const DbgValueLocation &LHS, const DbgValueLocation &RHS)
Debug Variable Analysis
LiveInterval & getInterval(unsigned Reg)
int64_t getImm() const
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
const ValT & value() const
value - Return the mapped value at the current interval.
Definition: IntervalMap.h:1361
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
Definition: LiveInterval.h:129
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:211
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
const KeyT & stop() const
stop - Return the end of the current interval.
Definition: IntervalMap.h:1358
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:156
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
void insert(KeyT a, KeyT b, ValT y)
insert - Insert mapping [a;b] -> y before the current position.
Definition: IntervalMap.h:1772
Representation of each machine instruction.
Definition: MachineInstr.h:60
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
static void printExtendedName(raw_ostream &OS, const DILocalVariable *V, const DILocation *DL)
static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B)
Return true if A refers to the same instruction as B or an earlier one.
Definition: SlotIndexes.h:210
LexicalScopes - This class provides interface to collect and use lexical scoping information from mac...
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
static MachineBasicBlock::iterator findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, SlotIndex StopIdx, MachineOperand &LocMO, LiveIntervals &LIS, const TargetRegisterInfo &TRI)
Find an iterator for inserting the next DBG_VALUE instruction (or end if no more insert locations fou...
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
static cl::opt< bool > EnableLDV("live-debug-variables", cl::init(true), cl::desc("Enable the live debug variables pass"), cl::Hidden)
void setIsUse(bool Val=true)
void setSubReg(unsigned subReg)
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:124
Describes a location by number along with some flags about the original usage of the location...
static void collectDebugValues(MachineInstr &MI, SmallVectorImpl< MachineInstr *> &DbgValues)
collectDebgValues - Scan instructions following MI and collect any matching DBG_VALUEs.
unsigned getPhys(unsigned virtReg) const
returns the physical register mapped to the specified virtual register
Definition: VirtRegMap.h:101
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
Definition: LiveInterval.h:396
iterator begin()
Definition: MapVector.h:70
unsigned getCol() const
Definition: DebugLoc.cpp:31
iterator begin()
Definition: LiveInterval.h:211
unsigned locNo() const
void setStopUnchecked(KeyT b)
setStopUnchecked - Move the end of the current interval without checking for coalescing or overlaps...
Definition: IntervalMap.h:1556
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:373
int getStackSlot(unsigned virtReg) const
returns the stack slot mapped to the specified virtual register
Definition: VirtRegMap.h:164
static cl::opt< bool, true > Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag))
const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
iterator SkipPHIsLabelsAndDebug(iterator I)
Return the first instruction in MBB after I that is not a PHI, label or debug.
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
unsigned getLine() const
static MachineBasicBlock::iterator findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS)
Find an iterator for inserting a DBG_VALUE instruction.
void setIsDebug(bool Val=true)
#define LLVM_DEBUG(X)
Definition: Debug.h:119
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:316
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:84
static MachineOperand CreateFI(int Idx)
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
InsnRange - This is used to track range of instructions with identical lexical scope.
Definition: LexicalScopes.h:40