Update LiveDebugVariables during coalescing.
[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 "llvm/Constants.h"
25 #include "llvm/Metadata.h"
26 #include "llvm/Value.h"
27 #include "llvm/ADT/IntervalMap.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36
37 using namespace llvm;
38
39 static cl::opt<bool>
40 EnableLDV("live-debug-variables",
41           cl::desc("Enable the live debug variables pass"), cl::Hidden);
42
43 char LiveDebugVariables::ID = 0;
44
45 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
46                 "Debug Variable Analysis", false, false)
47 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
48 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
49 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
50                 "Debug Variable Analysis", false, false)
51
52 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
53   AU.addRequired<MachineDominatorTree>();
54   AU.addRequiredTransitive<LiveIntervals>();
55   AU.setPreservesAll();
56   MachineFunctionPass::getAnalysisUsage(AU);
57 }
58
59 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
60   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
61 }
62
63 /// Location - All the different places a user value can reside.
64 /// Note that this includes immediate values that technically aren't locations.
65 namespace {
66 struct Location {
67   /// kind - What kind of location is this?
68   enum Kind {
69     locUndef = 0,
70     locImm   = 0x80000000,
71     locFPImm
72   };
73   /// Kind - One of the following:
74   /// 1. locUndef
75   /// 2. Register number (physical or virtual), data.SubIdx is the subreg index.
76   /// 3. ~Frame index, data.Offset is the offset.
77   /// 4. locImm, data.ImmVal is the constant integer value.
78   /// 5. locFPImm, data.CFP points to the floating point constant.
79   unsigned Kind;
80
81   /// Data - Extra data about location.
82   union {
83     unsigned SubIdx;          ///< For virtual registers.
84     int64_t Offset;           ///< For frame indices.
85     int64_t ImmVal;           ///< For locImm.
86     const ConstantFP *CFP;    ///< For locFPImm.
87   } Data;
88
89   Location(const MachineOperand &MO) {
90     switch(MO.getType()) {
91     case MachineOperand::MO_Register:
92       Kind = MO.getReg();
93       Data.SubIdx = MO.getSubReg();
94       return;
95     case MachineOperand::MO_Immediate:
96       Kind = locImm;
97       Data.ImmVal = MO.getImm();
98       return;
99     case MachineOperand::MO_FPImmediate:
100       Kind = locFPImm;
101       Data.CFP = MO.getFPImm();
102       return;
103     case MachineOperand::MO_FrameIndex:
104       Kind = ~MO.getIndex();
105       // FIXME: MO_FrameIndex should support an offset.
106       Data.Offset = 0;
107       return;
108     default:
109       Kind = locUndef;
110       return;
111     }
112   }
113
114   bool operator==(const Location &RHS) const {
115     if (Kind != RHS.Kind)
116       return false;
117     switch (Kind) {
118     case locUndef:
119       return true;
120     case locImm:
121       return Data.ImmVal == RHS.Data.ImmVal;
122     case locFPImm:
123       return Data.CFP == RHS.Data.CFP;
124     default:
125       if (isReg())
126         return Data.SubIdx == RHS.Data.SubIdx;
127       else
128          return Data.Offset == RHS.Data.Offset;
129     }
130   }
131
132   /// isUndef - is this the singleton undef?
133   bool isUndef() const { return Kind == locUndef; }
134
135   /// isReg - is this a register location?
136   bool isReg() const { return Kind && Kind < locImm; }
137
138   void print(raw_ostream&, const TargetRegisterInfo*);
139 };
140 }
141
142 /// LocMap - Map of where a user value is live, and its location.
143 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
144
145 /// UserValue - A user value is a part of a debug info user variable.
146 ///
147 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
148 /// holds part of a user variable. The part is identified by a byte offset.
149 ///
150 /// UserValues are grouped into equivalence classes for easier searching. Two
151 /// user values are related if they refer to the same variable, or if they are
152 /// held by the same virtual register. The equivalence class is the transitive
153 /// closure of that relation.
154 namespace {
155 class UserValue {
156   const MDNode *variable; ///< The debug info variable we are part of.
157   unsigned offset;        ///< Byte offset into variable.
158
159   UserValue *leader;      ///< Equivalence class leader.
160   UserValue *next;        ///< Next value in equivalence class, or null.
161
162   /// Numbered locations referenced by locmap.
163   SmallVector<Location, 4> locations;
164
165   /// Map of slot indices where this value is live.
166   LocMap locInts;
167
168 public:
169   /// UserValue - Create a new UserValue.
170   UserValue(const MDNode *var, unsigned o, LocMap::Allocator &alloc)
171     : variable(var), offset(o), leader(this), next(0), locInts(alloc)
172   {}
173
174   /// getLeader - Get the leader of this value's equivalence class.
175   UserValue *getLeader() {
176     UserValue *l = leader;
177     while (l != l->leader)
178       l = l->leader;
179     return leader = l;
180   }
181
182   /// getNext - Return the next UserValue in the equivalence class.
183   UserValue *getNext() const { return next; }
184
185   /// match - Does this UserValue match the aprameters?
186   bool match(const MDNode *Var, unsigned Offset) const {
187     return Var == variable && Offset == offset;
188   }
189
190   /// merge - Merge equivalence classes.
191   static UserValue *merge(UserValue *L1, UserValue *L2) {
192     L2 = L2->getLeader();
193     if (!L1)
194       return L2;
195     L1 = L1->getLeader();
196     if (L1 == L2)
197       return L1;
198     // Splice L2 before L1's members.
199     UserValue *End = L2;
200     while (End->next)
201       End->leader = L1, End = End->next;
202     End->leader = L1;
203     End->next = L1->next;
204     L1->next = L2;
205     return L1;
206   }
207
208   /// getLocationNo - Return the location number that matches Loc.
209   unsigned getLocationNo(Location Loc) {
210     if (Loc.isUndef())
211       return ~0u;
212     unsigned n = std::find(locations.begin(), locations.end(), Loc) -
213                  locations.begin();
214     if (n == locations.size())
215       locations.push_back(Loc);
216     return n;
217   }
218
219   /// addDef - Add a definition point to this value.
220   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
221     // Add a singular (Idx,Idx) -> Loc mapping.
222     LocMap::iterator I = locInts.find(Idx);
223     if (!I.valid() || I.start() != Idx)
224       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
225   }
226
227   /// extendDef - Extend the current definition as far as possible down the
228   /// dominator tree. Stop when meeting an existing def or when leaving the live
229   /// range of VNI.
230   /// @param Idx   Starting point for the definition.
231   /// @param LocNo Location number to propagate.
232   /// @param LI    Restrict liveness to where LI has the value VNI. May be null.
233   /// @param VNI   When LI is not null, this is the value to restrict to.
234   /// @param LIS   Live intervals analysis.
235   /// @param MDT   Dominator tree.
236   void extendDef(SlotIndex Idx, unsigned LocNo,
237                  LiveInterval *LI, const VNInfo *VNI,
238                  LiveIntervals &LIS, MachineDominatorTree &MDT);
239
240   /// computeIntervals - Compute the live intervals of all locations after
241   /// collecting all their def points.
242   void computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT);
243
244   /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
245   void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
246                       const TargetRegisterInfo *TRI);
247
248   void print(raw_ostream&, const TargetRegisterInfo*);
249 };
250 } // namespace
251
252 /// LDVImpl - Implementation of the LiveDebugVariables pass.
253 namespace {
254 class LDVImpl {
255   LiveDebugVariables &pass;
256   LocMap::Allocator allocator;
257   MachineFunction *MF;
258   LiveIntervals *LIS;
259   MachineDominatorTree *MDT;
260   const TargetRegisterInfo *TRI;
261
262   /// userValues - All allocated UserValue instances.
263   SmallVector<UserValue*, 8> userValues;
264
265   /// Map virtual register to eq class leader.
266   typedef DenseMap<unsigned, UserValue*> VRMap;
267   VRMap virtRegMap;
268
269   /// Map user variable to eq class leader.
270   typedef DenseMap<const MDNode *, UserValue*> UVMap;
271   UVMap userVarMap;
272
273   /// getUserValue - Find or create a UserValue.
274   UserValue *getUserValue(const MDNode *Var, unsigned Offset);
275
276   /// lookupVirtReg - Find the EC leader for VirtReg or null.
277   UserValue *lookupVirtReg(unsigned VirtReg);
278
279   /// mapVirtReg - Map virtual register to an equivalence class.
280   void mapVirtReg(unsigned VirtReg, UserValue *EC);
281
282   /// handleDebugValue - Add DBG_VALUE instruction to our maps.
283   /// @param MI  DBG_VALUE instruction
284   /// @param Idx Last valid SLotIndex before instruction.
285   /// @return    True if the DBG_VALUE instruction should be deleted.
286   bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
287
288   /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
289   /// a UserValue def for each instruction.
290   /// @param mf MachineFunction to be scanned.
291   /// @return True if any debug values were found.
292   bool collectDebugValues(MachineFunction &mf);
293
294   /// computeIntervals - Compute the live intervals of all user values after
295   /// collecting all their def points.
296   void computeIntervals();
297
298 public:
299   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
300   bool runOnMachineFunction(MachineFunction &mf);
301
302   /// clear - Relase all memory.
303   void clear() {
304     DeleteContainerPointers(userValues);
305     userValues.clear();
306     virtRegMap.clear();
307     userVarMap.clear();
308   }
309
310   /// renameRegister - Replace all references to OldReg wiht NewReg:SubIdx.
311   void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
312
313   void print(raw_ostream&);
314 };
315 } // namespace
316
317 void Location::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
318   switch (Kind) {
319   case locUndef:
320     OS << "undef";
321     return;
322   case locImm:
323     OS << "int:" << Data.ImmVal;
324     return;
325   case locFPImm:
326     OS << "fp:" << Data.CFP->getValueAPF().convertToDouble();
327     return;
328   default:
329     if (isReg()) {
330       if (TargetRegisterInfo::isVirtualRegister(Kind)) {
331         OS << "%reg" << Kind;
332         if (Data.SubIdx)
333           OS << ':' << TRI->getSubRegIndexName(Data.SubIdx);
334       } else
335         OS << '%' << TRI->getName(Kind);
336     } else {
337       OS << "fi#" << ~Kind;
338       if (Data.Offset)
339         OS << '+' << Data.Offset;
340     }
341     return;
342   }
343 }
344
345 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
346   if (const MDString *MDS = dyn_cast<MDString>(variable->getOperand(2)))
347     OS << "!\"" << MDS->getString() << "\"\t";
348   if (offset)
349     OS << '+' << offset;
350   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
351     OS << " [" << I.start() << ';' << I.stop() << "):";
352     if (I.value() == ~0u)
353       OS << "undef";
354     else
355       OS << I.value();
356   }
357   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
358     OS << " Loc" << i << '=';
359     locations[i].print(OS, TRI);
360   }
361   OS << '\n';
362 }
363
364 void LDVImpl::print(raw_ostream &OS) {
365   OS << "********** DEBUG VARIABLES **********\n";
366   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
367     userValues[i]->print(OS, TRI);
368 }
369
370 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset) {
371   UserValue *&Leader = userVarMap[Var];
372   if (Leader) {
373     UserValue *UV = Leader->getLeader();
374     Leader = UV;
375     for (; UV; UV = UV->getNext())
376       if (UV->match(Var, Offset))
377         return UV;
378   }
379
380   UserValue *UV = new UserValue(Var, Offset, allocator);
381   userValues.push_back(UV);
382   Leader = UserValue::merge(Leader, UV);
383   return UV;
384 }
385
386 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
387   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
388   UserValue *&Leader = virtRegMap[VirtReg];
389   Leader = UserValue::merge(Leader, EC);
390 }
391
392 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
393   if (UserValue *UV = virtRegMap.lookup(VirtReg))
394     return UV->getLeader();
395   return 0;
396 }
397
398 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
399   // DBG_VALUE loc, offset, variable
400   if (MI->getNumOperands() != 3 ||
401       !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
402     DEBUG(dbgs() << "Can't handle " << *MI);
403     return false;
404   }
405
406   // Get or create the UserValue for (variable,offset).
407   unsigned Offset = MI->getOperand(1).getImm();
408   const MDNode *Var = MI->getOperand(2).getMetadata();
409   UserValue *UV = getUserValue(Var, Offset);
410
411   // If the location is a virtual register, make sure it is mapped.
412   if (MI->getOperand(0).isReg()) {
413     unsigned Reg = MI->getOperand(0).getReg();
414     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
415       mapVirtReg(Reg, UV);
416   }
417
418   UV->addDef(Idx, MI->getOperand(0));
419   return true;
420 }
421
422 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
423   bool Changed = false;
424   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
425        ++MFI) {
426     MachineBasicBlock *MBB = MFI;
427     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
428          MBBI != MBBE;) {
429       if (!MBBI->isDebugValue()) {
430         ++MBBI;
431         continue;
432       }
433       // DBG_VALUE has no slot index, use the previous instruction instead.
434       SlotIndex Idx = MBBI == MBB->begin() ?
435         LIS->getMBBStartIdx(MBB) :
436         LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
437       // Handle consecutive DBG_VALUE instructions with the same slot index.
438       do {
439         if (handleDebugValue(MBBI, Idx)) {
440           MBBI = MBB->erase(MBBI);
441           Changed = true;
442         } else
443           ++MBBI;
444       } while (MBBI != MBBE && MBBI->isDebugValue());
445     }
446   }
447   return Changed;
448 }
449
450 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
451                           LiveInterval *LI, const VNInfo *VNI,
452                           LiveIntervals &LIS, MachineDominatorTree &MDT) {
453   SmallVector<SlotIndex, 16> Todo;
454   Todo.push_back(Idx);
455
456   do {
457     SlotIndex Start = Todo.pop_back_val();
458     MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
459     SlotIndex Stop = LIS.getMBBEndIdx(MBB);
460     LocMap::iterator I = locInts.find(Idx);
461
462     // Limit to VNI's live range.
463     bool ToEnd = true;
464     if (LI && VNI) {
465       LiveRange *Range = LI->getLiveRangeContaining(Start);
466       if (!Range || Range->valno != VNI)
467         continue;
468       if (Range->end < Stop)
469         Stop = Range->end, ToEnd = false;
470     }
471
472     // There could already be a short def at Start.
473     if (I.valid() && I.start() <= Start) {
474       // Stop when meeting a different location or an already extended interval.
475       Start = Start.getNextSlot();
476       if (I.value() != LocNo || I.stop() != Start)
477         continue;
478       // This is a one-slot placeholder. Just skip it.
479       ++I;
480     }
481
482     // Limited by the next def.
483     if (I.valid() && I.start() < Stop)
484       Stop = I.start(), ToEnd = false;
485
486     if (Start >= Stop)
487       continue;
488
489     I.insert(Start, Stop, LocNo);
490
491     // If we extended to the MBB end, propagate down the dominator tree.
492     if (!ToEnd)
493       continue;
494     const std::vector<MachineDomTreeNode*> &Children =
495       MDT.getNode(MBB)->getChildren();
496     for (unsigned i = 0, e = Children.size(); i != e; ++i)
497       Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
498   } while (!Todo.empty());
499 }
500
501 void
502 UserValue::computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT) {
503   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
504
505   // Collect all defs to be extended (Skipping undefs).
506   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
507     if (I.value() != ~0u)
508       Defs.push_back(std::make_pair(I.start(), I.value()));
509
510   for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
511     SlotIndex Idx = Defs[i].first;
512     unsigned LocNo = Defs[i].second;
513     const Location &Loc = locations[LocNo];
514
515     // Register locations are constrained to where the register value is live.
516     if (Loc.isReg() && LIS.hasInterval(Loc.Kind)) {
517       LiveInterval *LI = &LIS.getInterval(Loc.Kind);
518       const VNInfo *VNI = LI->getVNInfoAt(Idx);
519       extendDef(Idx, LocNo, LI, VNI, LIS, MDT);
520     } else
521       extendDef(Idx, LocNo, 0, 0, LIS, MDT);
522   }
523
524   // Finally, erase all the undefs.
525   for (LocMap::iterator I = locInts.begin(); I.valid();)
526     if (I.value() == ~0u)
527       I.erase();
528     else
529       ++I;
530 }
531
532 void LDVImpl::computeIntervals() {
533   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
534     userValues[i]->computeIntervals(*LIS, *MDT);
535 }
536
537 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
538   MF = &mf;
539   LIS = &pass.getAnalysis<LiveIntervals>();
540   MDT = &pass.getAnalysis<MachineDominatorTree>();
541   TRI = mf.getTarget().getRegisterInfo();
542   clear();
543   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
544                << ((Value*)mf.getFunction())->getName()
545                << " **********\n");
546
547   bool Changed = collectDebugValues(mf);
548   computeIntervals();
549   DEBUG(print(dbgs()));
550   return Changed;
551 }
552
553 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
554   if (!EnableLDV)
555     return false;
556   if (!pImpl)
557     pImpl = new LDVImpl(this);
558   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
559 }
560
561 void LiveDebugVariables::releaseMemory() {
562   if (pImpl)
563     static_cast<LDVImpl*>(pImpl)->clear();
564 }
565
566 LiveDebugVariables::~LiveDebugVariables() {
567   if (pImpl)
568     delete static_cast<LDVImpl*>(pImpl);
569 }
570
571 void UserValue::
572 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
573                const TargetRegisterInfo *TRI) {
574   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
575     Location &Loc = locations[i];
576     if (Loc.Kind != OldReg)
577       continue;
578     Loc.Kind = NewReg;
579     if (SubIdx && Loc.Data.SubIdx)
580       Loc.Data.SubIdx = TRI->composeSubRegIndices(SubIdx, Loc.Data.SubIdx);
581   }
582 }
583
584 void LDVImpl::
585 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
586   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
587     UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
588 }
589
590 void LiveDebugVariables::
591 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
592   if (pImpl)
593     static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
594 }
595
596 #ifndef NDEBUG
597 void LiveDebugVariables::dump() {
598   if (pImpl)
599     static_cast<LDVImpl*>(pImpl)->print(dbgs());
600 }
601 #endif
602