LiveDebugVariables.cpp revision b08773749a42a8c68afca96360b6e361147779b4
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#define DEBUG_TYPE "livedebug"
23#include "LiveDebugVariables.h"
24#include "VirtRegMap.h"
25#include "llvm/Constants.h"
26#include "llvm/Metadata.h"
27#include "llvm/Value.h"
28#include "llvm/ADT/IntervalMap.h"
29#include "llvm/CodeGen/LiveIntervalAnalysis.h"
30#include "llvm/CodeGen/MachineDominators.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetRegisterInfo.h"
39
40using namespace llvm;
41
42static cl::opt<bool>
43EnableLDV("live-debug-variables",
44          cl::desc("Enable the live debug variables pass"), cl::Hidden);
45
46char LiveDebugVariables::ID = 0;
47
48INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
49                "Debug Variable Analysis", false, false)
50INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
51INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
52INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
53                "Debug Variable Analysis", false, false)
54
55void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
56  AU.addRequired<MachineDominatorTree>();
57  AU.addRequiredTransitive<LiveIntervals>();
58  AU.setPreservesAll();
59  MachineFunctionPass::getAnalysisUsage(AU);
60}
61
62LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
63  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
64}
65
66/// LocMap - Map of where a user value is live, and its location.
67typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
68
69/// UserValue - A user value is a part of a debug info user variable.
70///
71/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
72/// holds part of a user variable. The part is identified by a byte offset.
73///
74/// UserValues are grouped into equivalence classes for easier searching. Two
75/// user values are related if they refer to the same variable, or if they are
76/// held by the same virtual register. The equivalence class is the transitive
77/// closure of that relation.
78namespace {
79class UserValue {
80  const MDNode *variable; ///< The debug info variable we are part of.
81  unsigned offset;        ///< Byte offset into variable.
82
83  UserValue *leader;      ///< Equivalence class leader.
84  UserValue *next;        ///< Next value in equivalence class, or null.
85
86  /// Numbered locations referenced by locmap.
87  SmallVector<MachineOperand, 4> locations;
88
89  /// Map of slot indices where this value is live.
90  LocMap locInts;
91
92  /// coalesceLocation - After LocNo was changed, check if it has become
93  /// identical to another location, and coalesce them. This may cause LocNo or
94  /// a later location to be erased, but no earlier location will be erased.
95  void coalesceLocation(unsigned LocNo);
96
97  /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
98  void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
99                        LiveIntervals &LIS, const TargetInstrInfo &TII);
100
101  /// insertDebugKill - Insert an undef DBG_VALUE into MBB at Idx.
102  void insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
103                       LiveIntervals &LIS, const TargetInstrInfo &TII);
104
105public:
106  /// UserValue - Create a new UserValue.
107  UserValue(const MDNode *var, unsigned o, LocMap::Allocator &alloc)
108    : variable(var), offset(o), leader(this), next(0), locInts(alloc)
109  {}
110
111  /// getLeader - Get the leader of this value's equivalence class.
112  UserValue *getLeader() {
113    UserValue *l = leader;
114    while (l != l->leader)
115      l = l->leader;
116    return leader = l;
117  }
118
119  /// getNext - Return the next UserValue in the equivalence class.
120  UserValue *getNext() const { return next; }
121
122  /// match - Does this UserValue match the aprameters?
123  bool match(const MDNode *Var, unsigned Offset) const {
124    return Var == variable && Offset == offset;
125  }
126
127  /// merge - Merge equivalence classes.
128  static UserValue *merge(UserValue *L1, UserValue *L2) {
129    L2 = L2->getLeader();
130    if (!L1)
131      return L2;
132    L1 = L1->getLeader();
133    if (L1 == L2)
134      return L1;
135    // Splice L2 before L1's members.
136    UserValue *End = L2;
137    while (End->next)
138      End->leader = L1, End = End->next;
139    End->leader = L1;
140    End->next = L1->next;
141    L1->next = L2;
142    return L1;
143  }
144
145  /// getLocationNo - Return the location number that matches Loc.
146  unsigned getLocationNo(const MachineOperand &LocMO) {
147    if (LocMO.isReg() && LocMO.getReg() == 0)
148      return ~0u;
149    for (unsigned i = 0, e = locations.size(); i != e; ++i)
150      if (LocMO.isIdenticalTo(locations[i]))
151        return i;
152    locations.push_back(LocMO);
153    // We are storing a MachineOperand outside a MachineInstr.
154    locations.back().clearParent();
155    return locations.size() - 1;
156  }
157
158  /// addDef - Add a definition point to this value.
159  void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
160    // Add a singular (Idx,Idx) -> Loc mapping.
161    LocMap::iterator I = locInts.find(Idx);
162    if (!I.valid() || I.start() != Idx)
163      I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
164  }
165
166  /// extendDef - Extend the current definition as far as possible down the
167  /// dominator tree. Stop when meeting an existing def or when leaving the live
168  /// range of VNI.
169  /// @param Idx   Starting point for the definition.
170  /// @param LocNo Location number to propagate.
171  /// @param LI    Restrict liveness to where LI has the value VNI. May be null.
172  /// @param VNI   When LI is not null, this is the value to restrict to.
173  /// @param LIS   Live intervals analysis.
174  /// @param MDT   Dominator tree.
175  void extendDef(SlotIndex Idx, unsigned LocNo,
176                 LiveInterval *LI, const VNInfo *VNI,
177                 LiveIntervals &LIS, MachineDominatorTree &MDT);
178
179  /// computeIntervals - Compute the live intervals of all locations after
180  /// collecting all their def points.
181  void computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT);
182
183  /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
184  void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
185                      const TargetRegisterInfo *TRI);
186
187  /// rewriteLocations - Rewrite virtual register locations according to the
188  /// provided virtual register map.
189  void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
190
191  /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
192  void emitDebugValues(VirtRegMap *VRM,
193                       LiveIntervals &LIS, const TargetInstrInfo &TRI);
194
195  void print(raw_ostream&, const TargetRegisterInfo*);
196};
197} // namespace
198
199/// LDVImpl - Implementation of the LiveDebugVariables pass.
200namespace {
201class LDVImpl {
202  LiveDebugVariables &pass;
203  LocMap::Allocator allocator;
204  MachineFunction *MF;
205  LiveIntervals *LIS;
206  MachineDominatorTree *MDT;
207  const TargetRegisterInfo *TRI;
208
209  /// userValues - All allocated UserValue instances.
210  SmallVector<UserValue*, 8> userValues;
211
212  /// Map virtual register to eq class leader.
213  typedef DenseMap<unsigned, UserValue*> VRMap;
214  VRMap virtRegToEqClass;
215
216  /// Map user variable to eq class leader.
217  typedef DenseMap<const MDNode *, UserValue*> UVMap;
218  UVMap userVarMap;
219
220  /// getUserValue - Find or create a UserValue.
221  UserValue *getUserValue(const MDNode *Var, unsigned Offset);
222
223  /// lookupVirtReg - Find the EC leader for VirtReg or null.
224  UserValue *lookupVirtReg(unsigned VirtReg);
225
226  /// mapVirtReg - Map virtual register to an equivalence class.
227  void mapVirtReg(unsigned VirtReg, UserValue *EC);
228
229  /// handleDebugValue - Add DBG_VALUE instruction to our maps.
230  /// @param MI  DBG_VALUE instruction
231  /// @param Idx Last valid SLotIndex before instruction.
232  /// @return    True if the DBG_VALUE instruction should be deleted.
233  bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
234
235  /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
236  /// a UserValue def for each instruction.
237  /// @param mf MachineFunction to be scanned.
238  /// @return True if any debug values were found.
239  bool collectDebugValues(MachineFunction &mf);
240
241  /// computeIntervals - Compute the live intervals of all user values after
242  /// collecting all their def points.
243  void computeIntervals();
244
245public:
246  LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
247  bool runOnMachineFunction(MachineFunction &mf);
248
249  /// clear - Relase all memory.
250  void clear() {
251    DeleteContainerPointers(userValues);
252    userValues.clear();
253    virtRegToEqClass.clear();
254    userVarMap.clear();
255  }
256
257  /// renameRegister - Replace all references to OldReg wiht NewReg:SubIdx.
258  void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
259
260  /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
261  void emitDebugValues(VirtRegMap *VRM);
262
263  void print(raw_ostream&);
264};
265} // namespace
266
267void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
268  if (const MDString *MDS = dyn_cast<MDString>(variable->getOperand(2)))
269    OS << "!\"" << MDS->getString() << "\"\t";
270  if (offset)
271    OS << '+' << offset;
272  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
273    OS << " [" << I.start() << ';' << I.stop() << "):";
274    if (I.value() == ~0u)
275      OS << "undef";
276    else
277      OS << I.value();
278  }
279  for (unsigned i = 0, e = locations.size(); i != e; ++i)
280    OS << " Loc" << i << '=' << locations[i];
281  OS << '\n';
282}
283
284void LDVImpl::print(raw_ostream &OS) {
285  OS << "********** DEBUG VARIABLES **********\n";
286  for (unsigned i = 0, e = userValues.size(); i != e; ++i)
287    userValues[i]->print(OS, TRI);
288}
289
290void UserValue::coalesceLocation(unsigned LocNo) {
291  unsigned KeepLoc = 0;
292  for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
293    if (KeepLoc == LocNo)
294      continue;
295    if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
296      break;
297  }
298  // No matches.
299  if (KeepLoc == locations.size())
300    return;
301
302  // Keep the smaller location, erase the larger one.
303  unsigned EraseLoc = LocNo;
304  if (KeepLoc > EraseLoc)
305    std::swap(KeepLoc, EraseLoc);
306  locations.erase(locations.begin() + EraseLoc);
307
308  // Rewrite values.
309  for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
310    unsigned v = I.value();
311    if (v == EraseLoc)
312      I.setValue(KeepLoc);      // Coalesce when possible.
313    else if (v > EraseLoc)
314      I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
315  }
316}
317
318UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset) {
319  UserValue *&Leader = userVarMap[Var];
320  if (Leader) {
321    UserValue *UV = Leader->getLeader();
322    Leader = UV;
323    for (; UV; UV = UV->getNext())
324      if (UV->match(Var, Offset))
325        return UV;
326  }
327
328  UserValue *UV = new UserValue(Var, Offset, allocator);
329  userValues.push_back(UV);
330  Leader = UserValue::merge(Leader, UV);
331  return UV;
332}
333
334void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
335  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
336  UserValue *&Leader = virtRegToEqClass[VirtReg];
337  Leader = UserValue::merge(Leader, EC);
338}
339
340UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
341  if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
342    return UV->getLeader();
343  return 0;
344}
345
346bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
347  // DBG_VALUE loc, offset, variable
348  if (MI->getNumOperands() != 3 ||
349      !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
350    DEBUG(dbgs() << "Can't handle " << *MI);
351    return false;
352  }
353
354  // Get or create the UserValue for (variable,offset).
355  unsigned Offset = MI->getOperand(1).getImm();
356  const MDNode *Var = MI->getOperand(2).getMetadata();
357  UserValue *UV = getUserValue(Var, Offset);
358
359  // If the location is a virtual register, make sure it is mapped.
360  if (MI->getOperand(0).isReg()) {
361    unsigned Reg = MI->getOperand(0).getReg();
362    if (TargetRegisterInfo::isVirtualRegister(Reg))
363      mapVirtReg(Reg, UV);
364  }
365
366  UV->addDef(Idx, MI->getOperand(0));
367  return true;
368}
369
370bool LDVImpl::collectDebugValues(MachineFunction &mf) {
371  bool Changed = false;
372  for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
373       ++MFI) {
374    MachineBasicBlock *MBB = MFI;
375    for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
376         MBBI != MBBE;) {
377      if (!MBBI->isDebugValue()) {
378        ++MBBI;
379        continue;
380      }
381      // DBG_VALUE has no slot index, use the previous instruction instead.
382      SlotIndex Idx = MBBI == MBB->begin() ?
383        LIS->getMBBStartIdx(MBB) :
384        LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
385      // Handle consecutive DBG_VALUE instructions with the same slot index.
386      do {
387        if (handleDebugValue(MBBI, Idx)) {
388          MBBI = MBB->erase(MBBI);
389          Changed = true;
390        } else
391          ++MBBI;
392      } while (MBBI != MBBE && MBBI->isDebugValue());
393    }
394  }
395  return Changed;
396}
397
398void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
399                          LiveInterval *LI, const VNInfo *VNI,
400                          LiveIntervals &LIS, MachineDominatorTree &MDT) {
401  SmallVector<SlotIndex, 16> Todo;
402  Todo.push_back(Idx);
403
404  do {
405    SlotIndex Start = Todo.pop_back_val();
406    MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
407    SlotIndex Stop = LIS.getMBBEndIdx(MBB);
408    LocMap::iterator I = locInts.find(Idx);
409
410    // Limit to VNI's live range.
411    bool ToEnd = true;
412    if (LI && VNI) {
413      LiveRange *Range = LI->getLiveRangeContaining(Start);
414      if (!Range || Range->valno != VNI)
415        continue;
416      if (Range->end < Stop)
417        Stop = Range->end, ToEnd = false;
418    }
419
420    // There could already be a short def at Start.
421    if (I.valid() && I.start() <= Start) {
422      // Stop when meeting a different location or an already extended interval.
423      Start = Start.getNextSlot();
424      if (I.value() != LocNo || I.stop() != Start)
425        continue;
426      // This is a one-slot placeholder. Just skip it.
427      ++I;
428    }
429
430    // Limited by the next def.
431    if (I.valid() && I.start() < Stop)
432      Stop = I.start(), ToEnd = false;
433
434    if (Start >= Stop)
435      continue;
436
437    I.insert(Start, Stop, LocNo);
438
439    // If we extended to the MBB end, propagate down the dominator tree.
440    if (!ToEnd)
441      continue;
442    const std::vector<MachineDomTreeNode*> &Children =
443      MDT.getNode(MBB)->getChildren();
444    for (unsigned i = 0, e = Children.size(); i != e; ++i)
445      Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
446  } while (!Todo.empty());
447}
448
449void
450UserValue::computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT) {
451  SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
452
453  // Collect all defs to be extended (Skipping undefs).
454  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
455    if (I.value() != ~0u)
456      Defs.push_back(std::make_pair(I.start(), I.value()));
457
458  for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
459    SlotIndex Idx = Defs[i].first;
460    unsigned LocNo = Defs[i].second;
461    const MachineOperand &Loc = locations[LocNo];
462
463    // Register locations are constrained to where the register value is live.
464    if (Loc.isReg() && LIS.hasInterval(Loc.getReg())) {
465      LiveInterval *LI = &LIS.getInterval(Loc.getReg());
466      const VNInfo *VNI = LI->getVNInfoAt(Idx);
467      extendDef(Idx, LocNo, LI, VNI, LIS, MDT);
468    } else
469      extendDef(Idx, LocNo, 0, 0, LIS, MDT);
470  }
471
472  // Finally, erase all the undefs.
473  for (LocMap::iterator I = locInts.begin(); I.valid();)
474    if (I.value() == ~0u)
475      I.erase();
476    else
477      ++I;
478}
479
480void LDVImpl::computeIntervals() {
481  for (unsigned i = 0, e = userValues.size(); i != e; ++i)
482    userValues[i]->computeIntervals(*LIS, *MDT);
483}
484
485bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
486  MF = &mf;
487  LIS = &pass.getAnalysis<LiveIntervals>();
488  MDT = &pass.getAnalysis<MachineDominatorTree>();
489  TRI = mf.getTarget().getRegisterInfo();
490  clear();
491  DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
492               << ((Value*)mf.getFunction())->getName()
493               << " **********\n");
494
495  bool Changed = collectDebugValues(mf);
496  computeIntervals();
497  DEBUG(print(dbgs()));
498  return Changed;
499}
500
501bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
502  if (!EnableLDV)
503    return false;
504  if (!pImpl)
505    pImpl = new LDVImpl(this);
506  return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
507}
508
509void LiveDebugVariables::releaseMemory() {
510  if (pImpl)
511    static_cast<LDVImpl*>(pImpl)->clear();
512}
513
514LiveDebugVariables::~LiveDebugVariables() {
515  if (pImpl)
516    delete static_cast<LDVImpl*>(pImpl);
517}
518
519void UserValue::
520renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
521               const TargetRegisterInfo *TRI) {
522  for (unsigned i = locations.size(); i; --i) {
523    unsigned LocNo = i - 1;
524    MachineOperand &Loc = locations[LocNo];
525    if (!Loc.isReg() || Loc.getReg() != OldReg)
526      continue;
527    if (TargetRegisterInfo::isPhysicalRegister(NewReg))
528      Loc.substPhysReg(NewReg, *TRI);
529    else
530      Loc.substVirtReg(NewReg, SubIdx, *TRI);
531    coalesceLocation(LocNo);
532  }
533}
534
535void LDVImpl::
536renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
537  UserValue *UV = lookupVirtReg(OldReg);
538  if (!UV)
539    return;
540
541  if (TargetRegisterInfo::isVirtualRegister(NewReg))
542    mapVirtReg(NewReg, UV);
543  virtRegToEqClass.erase(OldReg);
544
545  do {
546    UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
547    UV = UV->getNext();
548  } while (UV);
549}
550
551void LiveDebugVariables::
552renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
553  if (pImpl)
554    static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
555}
556
557void
558UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
559  // Iterate over locations in reverse makes it easier to handle coalescing.
560  for (unsigned i = locations.size(); i ; --i) {
561    unsigned LocNo = i-1;
562    MachineOperand &Loc = locations[LocNo];
563    // Only virtual registers are rewritten.
564    if (!Loc.isReg() || !Loc.getReg() ||
565        !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
566      continue;
567    unsigned VirtReg = Loc.getReg();
568    if (VRM.isAssignedReg(VirtReg)) {
569      Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
570    } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
571      // FIXME: Translate SubIdx to a stackslot offset.
572      Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
573    } else {
574      Loc.setReg(0);
575      Loc.setSubReg(0);
576    }
577    coalesceLocation(LocNo);
578  }
579  DEBUG(print(dbgs(), &TRI));
580}
581
582/// findInsertLocation - Find an iterator and DebugLoc for inserting a DBG_VALUE
583/// instruction.
584static MachineBasicBlock::iterator
585findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, DebugLoc &DL,
586                   LiveIntervals &LIS) {
587  SlotIndex Start = LIS.getMBBStartIdx(MBB);
588  Idx = Idx.getBaseIndex();
589
590  // Don't insert anything after the first terminator.
591  MachineBasicBlock::iterator Term = MBB->getFirstTerminator();
592  if (Term != MBB->end() && Idx >= LIS.getInstructionIndex(Term)) {
593    DL = Term->getDebugLoc();
594    return Term;
595  }
596
597  // Try to find an insert location by going backwards from Idx.
598  MachineInstr *MI;
599  while (!(MI = LIS.getInstructionFromIndex(Idx))) {
600    // We've reached the beginning of MBB.
601    if (Idx == Start) {
602      MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
603      if (I != MBB->end())
604        DL = I->getDebugLoc();
605      return I;
606    }
607    Idx = Idx.getPrevIndex();
608  }
609  // We found an instruction. The insert point is after the instr.
610  DL = MI->getDebugLoc();
611  return llvm::next(MachineBasicBlock::iterator(MI));
612}
613
614void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
615                                 unsigned LocNo,
616                                 LiveIntervals &LIS,
617                                 const TargetInstrInfo &TII) {
618  DebugLoc DL;
619  MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, DL, LIS);
620  MachineOperand &Loc = locations[LocNo];
621
622  // Frame index locations may require a target callback.
623  if (Loc.isFI()) {
624    MachineInstr *MI = TII.emitFrameIndexDebugValue(*MBB->getParent(),
625                                          Loc.getIndex(), offset, variable, DL);
626    if (MI) {
627      MBB->insert(I, MI);
628      return;
629    }
630  }
631  // This is not a frame index, or the target is happy with a standard FI.
632  BuildMI(*MBB, I, DL, TII.get(TargetOpcode::DBG_VALUE))
633    .addOperand(Loc).addImm(offset).addMetadata(variable);
634}
635
636void UserValue::insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
637                               LiveIntervals &LIS, const TargetInstrInfo &TII) {
638  DebugLoc DL;
639  MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, DL, LIS);
640  BuildMI(*MBB, I, DL, TII.get(TargetOpcode::DBG_VALUE)).addReg(0)
641    .addImm(offset).addMetadata(variable);
642}
643
644void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
645                                const TargetInstrInfo &TII) {
646  MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
647
648  for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
649    SlotIndex Start = I.start();
650    SlotIndex Stop = I.stop();
651    unsigned LocNo = I.value();
652    DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
653    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
654    SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
655
656    DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
657    insertDebugValue(MBB, Start, LocNo, LIS, TII);
658
659    // This interval may span multiple basic blocks.
660    // Insert a DBG_VALUE into each one.
661    while(Stop > MBBEnd) {
662      // Move to the next block.
663      Start = MBBEnd;
664      if (++MBB == MFEnd)
665        break;
666      MBBEnd = LIS.getMBBEndIdx(MBB);
667      DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
668      insertDebugValue(MBB, Start, LocNo, LIS, TII);
669    }
670    DEBUG(dbgs() << '\n');
671    if (MBB == MFEnd)
672      break;
673
674    ++I;
675    if (Stop == MBBEnd)
676      continue;
677    // The current interval ends before MBB.
678    // Insert a kill if there is a gap.
679    if (!I.valid() || I.start() > Stop)
680      insertDebugKill(MBB, Stop, LIS, TII);
681  }
682}
683
684void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
685  DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
686  const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
687  for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
688    userValues[i]->rewriteLocations(*VRM, *TRI);
689    userValues[i]->emitDebugValues(VRM, *LIS, *TII);
690  }
691}
692
693void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
694  if (pImpl)
695    static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
696}
697
698
699#ifndef NDEBUG
700void LiveDebugVariables::dump() {
701  if (pImpl)
702    static_cast<LDVImpl*>(pImpl)->print(dbgs());
703}
704#endif
705
706