1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveDebugVariables analysis.
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.
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.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "livedebug"
23 #include "LiveDebugVariables.h"
24 #include "llvm/ADT/IntervalMap.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/CodeGen/LexicalScopes.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/VirtRegMap.h"
34 #include "llvm/DebugInfo.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
47 EnableLDV("live-debug-variables", cl::init(true),
48 cl::desc("Enable the live debug variables pass"), cl::Hidden);
50 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
51 char LiveDebugVariables::ID = 0;
53 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
54 "Debug Variable Analysis", false, false)
55 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
56 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
57 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
58 "Debug Variable Analysis", false, false)
60 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<MachineDominatorTree>();
62 AU.addRequiredTransitive<LiveIntervals>();
64 MachineFunctionPass::getAnalysisUsage(AU);
67 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
68 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
71 /// LocMap - Map of where a user value is live, and its location.
72 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
75 /// UserValueScopes - Keeps track of lexical scopes associated with an
76 /// user value's source location.
77 class UserValueScopes {
80 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
83 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {}
85 /// dominates - Return true if current scope dominates at least one machine
86 /// instruction in a given machine basic block.
87 bool dominates(MachineBasicBlock *MBB) {
89 LS.getMachineBasicBlocks(DL, LBlocks);
90 if (LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB))
95 } // end anonymous namespace
97 /// UserValue - A user value is a part of a debug info user variable.
99 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
100 /// holds part of a user variable. The part is identified by a byte offset.
102 /// UserValues are grouped into equivalence classes for easier searching. Two
103 /// user values are related if they refer to the same variable, or if they are
104 /// held by the same virtual register. The equivalence class is the transitive
105 /// closure of that relation.
109 const MDNode *variable; ///< The debug info variable we are part of.
110 unsigned offset; ///< Byte offset into variable.
111 bool IsIndirect; ///< true if this is a register-indirect+offset value.
112 DebugLoc dl; ///< The debug location for the variable. This is
113 ///< used by dwarf writer to find lexical scope.
114 UserValue *leader; ///< Equivalence class leader.
115 UserValue *next; ///< Next value in equivalence class, or null.
117 /// Numbered locations referenced by locmap.
118 SmallVector<MachineOperand, 4> locations;
120 /// Map of slot indices where this value is live.
123 /// coalesceLocation - After LocNo was changed, check if it has become
124 /// identical to another location, and coalesce them. This may cause LocNo or
125 /// a later location to be erased, but no earlier location will be erased.
126 void coalesceLocation(unsigned LocNo);
128 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
129 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
130 LiveIntervals &LIS, const TargetInstrInfo &TII);
132 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
133 /// is live. Returns true if any changes were made.
134 bool splitLocation(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs);
137 /// UserValue - Create a new UserValue.
138 UserValue(const MDNode *var, unsigned o, bool i, DebugLoc L,
139 LocMap::Allocator &alloc)
140 : variable(var), offset(o), IsIndirect(i), dl(L), leader(this),
141 next(0), locInts(alloc)
144 /// getLeader - Get the leader of this value's equivalence class.
145 UserValue *getLeader() {
146 UserValue *l = leader;
147 while (l != l->leader)
152 /// getNext - Return the next UserValue in the equivalence class.
153 UserValue *getNext() const { return next; }
155 /// match - Does this UserValue match the parameters?
156 bool match(const MDNode *Var, unsigned Offset) const {
157 return Var == variable && Offset == offset;
160 /// merge - Merge equivalence classes.
161 static UserValue *merge(UserValue *L1, UserValue *L2) {
162 L2 = L2->getLeader();
165 L1 = L1->getLeader();
168 // Splice L2 before L1's members.
171 End->leader = L1, End = End->next;
173 End->next = L1->next;
178 /// getLocationNo - Return the location number that matches Loc.
179 unsigned getLocationNo(const MachineOperand &LocMO) {
181 if (LocMO.getReg() == 0)
183 // For register locations we dont care about use/def and other flags.
184 for (unsigned i = 0, e = locations.size(); i != e; ++i)
185 if (locations[i].isReg() &&
186 locations[i].getReg() == LocMO.getReg() &&
187 locations[i].getSubReg() == LocMO.getSubReg())
190 for (unsigned i = 0, e = locations.size(); i != e; ++i)
191 if (LocMO.isIdenticalTo(locations[i]))
193 locations.push_back(LocMO);
194 // We are storing a MachineOperand outside a MachineInstr.
195 locations.back().clearParent();
196 // Don't store def operands.
197 if (locations.back().isReg())
198 locations.back().setIsUse();
199 return locations.size() - 1;
202 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
203 void mapVirtRegs(LDVImpl *LDV);
205 /// addDef - Add a definition point to this value.
206 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
207 // Add a singular (Idx,Idx) -> Loc mapping.
208 LocMap::iterator I = locInts.find(Idx);
209 if (!I.valid() || I.start() != Idx)
210 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
212 // A later DBG_VALUE at the same SlotIndex overrides the old location.
213 I.setValue(getLocationNo(LocMO));
216 /// extendDef - Extend the current definition as far as possible down the
217 /// dominator tree. Stop when meeting an existing def or when leaving the live
219 /// End points where VNI is no longer live are added to Kills.
220 /// @param Idx Starting point for the definition.
221 /// @param LocNo Location number to propagate.
222 /// @param LI Restrict liveness to where LI has the value VNI. May be null.
223 /// @param VNI When LI is not null, this is the value to restrict to.
224 /// @param Kills Append end points of VNI's live range to Kills.
225 /// @param LIS Live intervals analysis.
226 /// @param MDT Dominator tree.
227 void extendDef(SlotIndex Idx, unsigned LocNo,
228 LiveInterval *LI, const VNInfo *VNI,
229 SmallVectorImpl<SlotIndex> *Kills,
230 LiveIntervals &LIS, MachineDominatorTree &MDT,
231 UserValueScopes &UVS);
233 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
234 /// registers. Determine if any of the copies are available at the kill
235 /// points, and add defs if possible.
236 /// @param LI Scan for copies of the value in LI->reg.
237 /// @param LocNo Location number of LI->reg.
238 /// @param Kills Points where the range of LocNo could be extended.
239 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
240 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
241 const SmallVectorImpl<SlotIndex> &Kills,
242 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
243 MachineRegisterInfo &MRI,
246 /// computeIntervals - Compute the live intervals of all locations after
247 /// collecting all their def points.
248 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
249 LiveIntervals &LIS, MachineDominatorTree &MDT,
250 UserValueScopes &UVS);
252 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
253 /// live. Returns true if any changes were made.
254 bool splitRegister(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs);
256 /// rewriteLocations - Rewrite virtual register locations according to the
257 /// provided virtual register map.
258 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
260 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
261 void emitDebugValues(VirtRegMap *VRM,
262 LiveIntervals &LIS, const TargetInstrInfo &TRI);
264 /// findDebugLoc - Return DebugLoc used for this DBG_VALUE instruction. A
265 /// variable may have more than one corresponding DBG_VALUE instructions.
266 /// Only first one needs DebugLoc to identify variable's lexical scope
268 DebugLoc findDebugLoc();
270 /// getDebugLoc - Return DebugLoc of this UserValue.
271 DebugLoc getDebugLoc() { return dl;}
272 void print(raw_ostream&, const TargetMachine*);
276 /// LDVImpl - Implementation of the LiveDebugVariables pass.
279 LiveDebugVariables &pass;
280 LocMap::Allocator allocator;
284 MachineDominatorTree *MDT;
285 const TargetRegisterInfo *TRI;
287 /// Whether emitDebugValues is called.
289 /// Whether the machine function is modified during the pass.
292 /// userValues - All allocated UserValue instances.
293 SmallVector<UserValue*, 8> userValues;
295 /// Map virtual register to eq class leader.
296 typedef DenseMap<unsigned, UserValue*> VRMap;
297 VRMap virtRegToEqClass;
299 /// Map user variable to eq class leader.
300 typedef DenseMap<const MDNode *, UserValue*> UVMap;
303 /// getUserValue - Find or create a UserValue.
304 UserValue *getUserValue(const MDNode *Var, unsigned Offset,
305 bool IsIndirect, DebugLoc DL);
307 /// lookupVirtReg - Find the EC leader for VirtReg or null.
308 UserValue *lookupVirtReg(unsigned VirtReg);
310 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
311 /// @param MI DBG_VALUE instruction
312 /// @param Idx Last valid SLotIndex before instruction.
313 /// @return True if the DBG_VALUE instruction should be deleted.
314 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
316 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
317 /// a UserValue def for each instruction.
318 /// @param mf MachineFunction to be scanned.
319 /// @return True if any debug values were found.
320 bool collectDebugValues(MachineFunction &mf);
322 /// computeIntervals - Compute the live intervals of all user values after
323 /// collecting all their def points.
324 void computeIntervals();
327 LDVImpl(LiveDebugVariables *ps) : pass(*ps), EmitDone(false),
329 bool runOnMachineFunction(MachineFunction &mf);
331 /// clear - Release all memory.
333 DeleteContainerPointers(userValues);
335 virtRegToEqClass.clear();
337 // Make sure we call emitDebugValues if the machine function was modified.
338 assert((!ModifiedMF || EmitDone) &&
339 "Dbg values are not emitted in LDV");
344 /// mapVirtReg - Map virtual register to an equivalence class.
345 void mapVirtReg(unsigned VirtReg, UserValue *EC);
347 /// splitRegister - Replace all references to OldReg with NewRegs.
348 void splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs);
350 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
351 void emitDebugValues(VirtRegMap *VRM);
353 void print(raw_ostream&);
357 void UserValue::print(raw_ostream &OS, const TargetMachine *TM) {
358 DIVariable DV(variable);
360 DV.printExtendedName(OS);
364 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
365 OS << " [" << I.start() << ';' << I.stop() << "):";
366 if (I.value() == ~0u)
371 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
372 OS << " Loc" << i << '=';
373 locations[i].print(OS, TM);
378 void LDVImpl::print(raw_ostream &OS) {
379 OS << "********** DEBUG VARIABLES **********\n";
380 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
381 userValues[i]->print(OS, &MF->getTarget());
384 void UserValue::coalesceLocation(unsigned LocNo) {
385 unsigned KeepLoc = 0;
386 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
387 if (KeepLoc == LocNo)
389 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
393 if (KeepLoc == locations.size())
396 // Keep the smaller location, erase the larger one.
397 unsigned EraseLoc = LocNo;
398 if (KeepLoc > EraseLoc)
399 std::swap(KeepLoc, EraseLoc);
400 locations.erase(locations.begin() + EraseLoc);
403 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
404 unsigned v = I.value();
406 I.setValue(KeepLoc); // Coalesce when possible.
407 else if (v > EraseLoc)
408 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
412 void UserValue::mapVirtRegs(LDVImpl *LDV) {
413 for (unsigned i = 0, e = locations.size(); i != e; ++i)
414 if (locations[i].isReg() &&
415 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
416 LDV->mapVirtReg(locations[i].getReg(), this);
419 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset,
420 bool IsIndirect, DebugLoc DL) {
421 UserValue *&Leader = userVarMap[Var];
423 UserValue *UV = Leader->getLeader();
425 for (; UV; UV = UV->getNext())
426 if (UV->match(Var, Offset))
430 UserValue *UV = new UserValue(Var, Offset, IsIndirect, DL, allocator);
431 userValues.push_back(UV);
432 Leader = UserValue::merge(Leader, UV);
436 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
437 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
438 UserValue *&Leader = virtRegToEqClass[VirtReg];
439 Leader = UserValue::merge(Leader, EC);
442 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
443 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
444 return UV->getLeader();
448 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
449 // DBG_VALUE loc, offset, variable
450 if (MI->getNumOperands() != 3 ||
451 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
452 !MI->getOperand(2).isMetadata()) {
453 DEBUG(dbgs() << "Can't handle " << *MI);
457 // Get or create the UserValue for (variable,offset).
458 bool IsIndirect = MI->getOperand(1).isImm();
459 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
460 const MDNode *Var = MI->getOperand(2).getMetadata();
461 UserValue *UV = getUserValue(Var, Offset, IsIndirect, MI->getDebugLoc());
462 UV->addDef(Idx, MI->getOperand(0));
466 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
467 bool Changed = false;
468 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
470 MachineBasicBlock *MBB = MFI;
471 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
473 if (!MBBI->isDebugValue()) {
477 // DBG_VALUE has no slot index, use the previous instruction instead.
478 SlotIndex Idx = MBBI == MBB->begin() ?
479 LIS->getMBBStartIdx(MBB) :
480 LIS->getInstructionIndex(llvm::prior(MBBI)).getRegSlot();
481 // Handle consecutive DBG_VALUE instructions with the same slot index.
483 if (handleDebugValue(MBBI, Idx)) {
484 MBBI = MBB->erase(MBBI);
488 } while (MBBI != MBBE && MBBI->isDebugValue());
494 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
495 LiveInterval *LI, const VNInfo *VNI,
496 SmallVectorImpl<SlotIndex> *Kills,
497 LiveIntervals &LIS, MachineDominatorTree &MDT,
498 UserValueScopes &UVS) {
499 SmallVector<SlotIndex, 16> Todo;
502 SlotIndex Start = Todo.pop_back_val();
503 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
504 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
505 LocMap::iterator I = locInts.find(Start);
507 // Limit to VNI's live range.
510 LiveRange *Range = LI->getLiveRangeContaining(Start);
511 if (!Range || Range->valno != VNI) {
513 Kills->push_back(Start);
516 if (Range->end < Stop)
517 Stop = Range->end, ToEnd = false;
520 // There could already be a short def at Start.
521 if (I.valid() && I.start() <= Start) {
522 // Stop when meeting a different location or an already extended interval.
523 Start = Start.getNextSlot();
524 if (I.value() != LocNo || I.stop() != Start)
526 // This is a one-slot placeholder. Just skip it.
530 // Limited by the next def.
531 if (I.valid() && I.start() < Stop)
532 Stop = I.start(), ToEnd = false;
533 // Limited by VNI's live range.
534 else if (!ToEnd && Kills)
535 Kills->push_back(Stop);
540 I.insert(Start, Stop, LocNo);
542 // If we extended to the MBB end, propagate down the dominator tree.
545 const std::vector<MachineDomTreeNode*> &Children =
546 MDT.getNode(MBB)->getChildren();
547 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
548 MachineBasicBlock *MBB = Children[i]->getBlock();
549 if (UVS.dominates(MBB))
550 Todo.push_back(LIS.getMBBStartIdx(MBB));
552 } while (!Todo.empty());
556 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
557 const SmallVectorImpl<SlotIndex> &Kills,
558 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
559 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
562 // Don't track copies from physregs, there are too many uses.
563 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
566 // Collect all the (vreg, valno) pairs that are copies of LI.
567 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
568 for (MachineRegisterInfo::use_nodbg_iterator
569 UI = MRI.use_nodbg_begin(LI->reg),
570 UE = MRI.use_nodbg_end(); UI != UE; ++UI) {
571 // Copies of the full value.
572 if (UI.getOperand().getSubReg() || !UI->isCopy())
574 MachineInstr *MI = &*UI;
575 unsigned DstReg = MI->getOperand(0).getReg();
577 // Don't follow copies to physregs. These are usually setting up call
578 // arguments, and the argument registers are always call clobbered. We are
579 // better off in the source register which could be a callee-saved register,
580 // or it could be spilled.
581 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
584 // Is LocNo extended to reach this copy? If not, another def may be blocking
585 // it, or we are looking at a wrong value of LI.
586 SlotIndex Idx = LIS.getInstructionIndex(MI);
587 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
588 if (!I.valid() || I.value() != LocNo)
591 if (!LIS.hasInterval(DstReg))
593 LiveInterval *DstLI = &LIS.getInterval(DstReg);
594 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
595 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
596 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
599 if (CopyValues.empty())
602 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
604 // Try to add defs of the copied values for each kill point.
605 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
606 SlotIndex Idx = Kills[i];
607 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
608 LiveInterval *DstLI = CopyValues[j].first;
609 const VNInfo *DstVNI = CopyValues[j].second;
610 if (DstLI->getVNInfoAt(Idx) != DstVNI)
612 // Check that there isn't already a def at Idx
613 LocMap::iterator I = locInts.find(Idx);
614 if (I.valid() && I.start() <= Idx)
616 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
617 << DstVNI->id << " in " << *DstLI << '\n');
618 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
619 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
620 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
621 I.insert(Idx, Idx.getNextSlot(), LocNo);
622 NewDefs.push_back(std::make_pair(Idx, LocNo));
629 UserValue::computeIntervals(MachineRegisterInfo &MRI,
630 const TargetRegisterInfo &TRI,
632 MachineDominatorTree &MDT,
633 UserValueScopes &UVS) {
634 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
636 // Collect all defs to be extended (Skipping undefs).
637 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
638 if (I.value() != ~0u)
639 Defs.push_back(std::make_pair(I.start(), I.value()));
641 // Extend all defs, and possibly add new ones along the way.
642 for (unsigned i = 0; i != Defs.size(); ++i) {
643 SlotIndex Idx = Defs[i].first;
644 unsigned LocNo = Defs[i].second;
645 const MachineOperand &Loc = locations[LocNo];
648 extendDef(Idx, LocNo, 0, 0, 0, LIS, MDT, UVS);
652 // Register locations are constrained to where the register value is live.
653 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
654 LiveInterval *LI = 0;
655 const VNInfo *VNI = 0;
656 if (LIS.hasInterval(Loc.getReg())) {
657 LI = &LIS.getInterval(Loc.getReg());
658 VNI = LI->getVNInfoAt(Idx);
660 SmallVector<SlotIndex, 16> Kills;
661 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
663 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
667 // For physregs, use the live range of the first regunit as a guide.
668 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
669 LiveInterval *LI = &LIS.getRegUnit(Unit);
670 const VNInfo *VNI = LI->getVNInfoAt(Idx);
671 // Don't track copies from physregs, it is too expensive.
672 extendDef(Idx, LocNo, LI, VNI, 0, LIS, MDT, UVS);
675 // Finally, erase all the undefs.
676 for (LocMap::iterator I = locInts.begin(); I.valid();)
677 if (I.value() == ~0u)
683 void LDVImpl::computeIntervals() {
684 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
685 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
686 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
687 userValues[i]->mapVirtRegs(this);
691 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
693 LIS = &pass.getAnalysis<LiveIntervals>();
694 MDT = &pass.getAnalysis<MachineDominatorTree>();
695 TRI = mf.getTarget().getRegisterInfo();
698 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
699 << mf.getName() << " **********\n");
701 bool Changed = collectDebugValues(mf);
703 DEBUG(print(dbgs()));
705 ModifiedMF = Changed;
709 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
713 pImpl = new LDVImpl(this);
714 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
717 void LiveDebugVariables::releaseMemory() {
719 static_cast<LDVImpl*>(pImpl)->clear();
722 LiveDebugVariables::~LiveDebugVariables() {
724 delete static_cast<LDVImpl*>(pImpl);
727 //===----------------------------------------------------------------------===//
728 // Live Range Splitting
729 //===----------------------------------------------------------------------===//
732 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs) {
734 dbgs() << "Splitting Loc" << OldLocNo << '\t';
737 bool DidChange = false;
738 LocMap::iterator LocMapI;
739 LocMapI.setMap(locInts);
740 for (unsigned i = 0; i != NewRegs.size(); ++i) {
741 LiveInterval *LI = NewRegs[i];
745 // Don't allocate the new LocNo until it is needed.
746 unsigned NewLocNo = ~0u;
748 // Iterate over the overlaps between locInts and LI.
749 LocMapI.find(LI->beginIndex());
750 if (!LocMapI.valid())
752 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
753 LiveInterval::iterator LIE = LI->end();
754 while (LocMapI.valid() && LII != LIE) {
755 // At this point, we know that LocMapI.stop() > LII->start.
756 LII = LI->advanceTo(LII, LocMapI.start());
760 // Now LII->end > LocMapI.start(). Do we have an overlap?
761 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
762 // Overlapping correct location. Allocate NewLocNo now.
763 if (NewLocNo == ~0u) {
764 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
765 MO.setSubReg(locations[OldLocNo].getSubReg());
766 NewLocNo = getLocationNo(MO);
770 SlotIndex LStart = LocMapI.start();
771 SlotIndex LStop = LocMapI.stop();
773 // Trim LocMapI down to the LII overlap.
774 if (LStart < LII->start)
775 LocMapI.setStartUnchecked(LII->start);
776 if (LStop > LII->end)
777 LocMapI.setStopUnchecked(LII->end);
779 // Change the value in the overlap. This may trigger coalescing.
780 LocMapI.setValue(NewLocNo);
782 // Re-insert any removed OldLocNo ranges.
783 if (LStart < LocMapI.start()) {
784 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
786 assert(LocMapI.valid() && "Unexpected coalescing");
788 if (LStop > LocMapI.stop()) {
790 LocMapI.insert(LII->end, LStop, OldLocNo);
795 // Advance to the next overlap.
796 if (LII->end < LocMapI.stop()) {
799 LocMapI.advanceTo(LII->start);
802 if (!LocMapI.valid())
804 LII = LI->advanceTo(LII, LocMapI.start());
809 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
810 locations.erase(locations.begin() + OldLocNo);
812 while (LocMapI.valid()) {
813 unsigned v = LocMapI.value();
815 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
816 << LocMapI.stop() << ")\n");
820 LocMapI.setValueUnchecked(v-1);
825 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), 0);});
830 UserValue::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
831 bool DidChange = false;
832 // Split locations referring to OldReg. Iterate backwards so splitLocation can
833 // safely erase unused locations.
834 for (unsigned i = locations.size(); i ; --i) {
835 unsigned LocNo = i-1;
836 const MachineOperand *Loc = &locations[LocNo];
837 if (!Loc->isReg() || Loc->getReg() != OldReg)
839 DidChange |= splitLocation(LocNo, NewRegs);
844 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
845 bool DidChange = false;
846 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
847 DidChange |= UV->splitRegister(OldReg, NewRegs);
852 // Map all of the new virtual registers.
853 UserValue *UV = lookupVirtReg(OldReg);
854 for (unsigned i = 0; i != NewRegs.size(); ++i)
855 mapVirtReg(NewRegs[i]->reg, UV);
858 void LiveDebugVariables::
859 splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
861 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
865 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
866 // Iterate over locations in reverse makes it easier to handle coalescing.
867 for (unsigned i = locations.size(); i ; --i) {
868 unsigned LocNo = i-1;
869 MachineOperand &Loc = locations[LocNo];
870 // Only virtual registers are rewritten.
871 if (!Loc.isReg() || !Loc.getReg() ||
872 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
874 unsigned VirtReg = Loc.getReg();
875 if (VRM.isAssignedReg(VirtReg) &&
876 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
877 // This can create a %noreg operand in rare cases when the sub-register
878 // index is no longer available. That means the user value is in a
879 // non-existent sub-register, and %noreg is exactly what we want.
880 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
881 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
882 // FIXME: Translate SubIdx to a stackslot offset.
883 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
888 coalesceLocation(LocNo);
892 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
894 static MachineBasicBlock::iterator
895 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
896 LiveIntervals &LIS) {
897 SlotIndex Start = LIS.getMBBStartIdx(MBB);
898 Idx = Idx.getBaseIndex();
900 // Try to find an insert location by going backwards from Idx.
902 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
903 // We've reached the beginning of MBB.
905 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
908 Idx = Idx.getPrevIndex();
911 // Don't insert anything after the first terminator, though.
912 return MI->isTerminator() ? MBB->getFirstTerminator() :
913 llvm::next(MachineBasicBlock::iterator(MI));
916 DebugLoc UserValue::findDebugLoc() {
921 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
924 const TargetInstrInfo &TII) {
925 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
926 MachineOperand &Loc = locations[LocNo];
927 ++NumInsertedDebugValues;
930 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
931 IsIndirect, Loc.getReg(), offset, variable);
933 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
934 .addOperand(Loc).addImm(offset).addMetadata(variable);
937 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
938 const TargetInstrInfo &TII) {
939 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
941 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
942 SlotIndex Start = I.start();
943 SlotIndex Stop = I.stop();
944 unsigned LocNo = I.value();
945 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
946 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
947 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
949 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
950 insertDebugValue(MBB, Start, LocNo, LIS, TII);
951 // This interval may span multiple basic blocks.
952 // Insert a DBG_VALUE into each one.
953 while(Stop > MBBEnd) {
954 // Move to the next block.
958 MBBEnd = LIS.getMBBEndIdx(MBB);
959 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
960 insertDebugValue(MBB, Start, LocNo, LIS, TII);
962 DEBUG(dbgs() << '\n');
970 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
971 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
972 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
973 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
974 DEBUG(userValues[i]->print(dbgs(), &MF->getTarget()));
975 userValues[i]->rewriteLocations(*VRM, *TRI);
976 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
981 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
983 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
988 void LiveDebugVariables::dump() {
990 static_cast<LDVImpl*>(pImpl)->print(dbgs());