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