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 #include "LiveDebugVariables.h"
23 #include "llvm/ADT/IntervalMap.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/LexicalScopes.h"
26 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
48 #define DEBUG_TYPE "livedebug"
51 EnableLDV("live-debug-variables", cl::init(true),
52 cl::desc("Enable the live debug variables pass"), cl::Hidden);
54 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
55 char LiveDebugVariables::ID = 0;
57 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
58 "Debug Variable Analysis", false, false)
59 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
60 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
61 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
62 "Debug Variable Analysis", false, false)
64 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<MachineDominatorTree>();
66 AU.addRequiredTransitive<LiveIntervals>();
68 MachineFunctionPass::getAnalysisUsage(AU);
71 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
72 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
75 /// LocMap - Map of where a user value is live, and its location.
76 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
79 /// UserValueScopes - Keeps track of lexical scopes associated with a
80 /// user value's source location.
81 class UserValueScopes {
84 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
87 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {}
89 /// dominates - Return true if current scope dominates at least one machine
90 /// instruction in a given machine basic block.
91 bool dominates(MachineBasicBlock *MBB) {
93 LS.getMachineBasicBlocks(DL, LBlocks);
94 if (LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB))
99 } // end anonymous namespace
101 /// UserValue - A user value is a part of a debug info user variable.
103 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
104 /// holds part of a user variable. The part is identified by a byte offset.
106 /// UserValues are grouped into equivalence classes for easier searching. Two
107 /// user values are related if they refer to the same variable, or if they are
108 /// held by the same virtual register. The equivalence class is the transitive
109 /// closure of that relation.
113 const MDNode *variable; ///< The debug info variable we are part of.
114 unsigned offset; ///< Byte offset into variable.
115 bool IsIndirect; ///< true if this is a register-indirect+offset value.
116 DebugLoc dl; ///< The debug location for the variable. This is
117 ///< used by dwarf writer to find lexical scope.
118 UserValue *leader; ///< Equivalence class leader.
119 UserValue *next; ///< Next value in equivalence class, or null.
121 /// Numbered locations referenced by locmap.
122 SmallVector<MachineOperand, 4> locations;
124 /// Map of slot indices where this value is live.
127 /// coalesceLocation - After LocNo was changed, check if it has become
128 /// identical to another location, and coalesce them. This may cause LocNo or
129 /// a later location to be erased, but no earlier location will be erased.
130 void coalesceLocation(unsigned LocNo);
132 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
133 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
134 LiveIntervals &LIS, const TargetInstrInfo &TII);
136 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
137 /// is live. Returns true if any changes were made.
138 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
142 /// UserValue - Create a new UserValue.
143 UserValue(const MDNode *var, unsigned o, bool i, DebugLoc L,
144 LocMap::Allocator &alloc)
145 : variable(var), offset(o), IsIndirect(i), dl(L), leader(this),
146 next(nullptr), locInts(alloc)
149 /// getLeader - Get the leader of this value's equivalence class.
150 UserValue *getLeader() {
151 UserValue *l = leader;
152 while (l != l->leader)
157 /// getNext - Return the next UserValue in the equivalence class.
158 UserValue *getNext() const { return next; }
160 /// match - Does this UserValue match the parameters?
161 bool match(const MDNode *Var, unsigned Offset, bool indirect) const {
162 return Var == variable && Offset == offset && indirect == IsIndirect;
165 /// merge - Merge equivalence classes.
166 static UserValue *merge(UserValue *L1, UserValue *L2) {
167 L2 = L2->getLeader();
170 L1 = L1->getLeader();
173 // Splice L2 before L1's members.
176 End->leader = L1, End = End->next;
178 End->next = L1->next;
183 /// getLocationNo - Return the location number that matches Loc.
184 unsigned getLocationNo(const MachineOperand &LocMO) {
186 if (LocMO.getReg() == 0)
188 // For register locations we dont care about use/def and other flags.
189 for (unsigned i = 0, e = locations.size(); i != e; ++i)
190 if (locations[i].isReg() &&
191 locations[i].getReg() == LocMO.getReg() &&
192 locations[i].getSubReg() == LocMO.getSubReg())
195 for (unsigned i = 0, e = locations.size(); i != e; ++i)
196 if (LocMO.isIdenticalTo(locations[i]))
198 locations.push_back(LocMO);
199 // We are storing a MachineOperand outside a MachineInstr.
200 locations.back().clearParent();
201 // Don't store def operands.
202 if (locations.back().isReg())
203 locations.back().setIsUse();
204 return locations.size() - 1;
207 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
208 void mapVirtRegs(LDVImpl *LDV);
210 /// addDef - Add a definition point to this value.
211 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
212 // Add a singular (Idx,Idx) -> Loc mapping.
213 LocMap::iterator I = locInts.find(Idx);
214 if (!I.valid() || I.start() != Idx)
215 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
217 // A later DBG_VALUE at the same SlotIndex overrides the old location.
218 I.setValue(getLocationNo(LocMO));
221 /// extendDef - Extend the current definition as far as possible down the
222 /// dominator tree. Stop when meeting an existing def or when leaving the live
224 /// End points where VNI is no longer live are added to Kills.
225 /// @param Idx Starting point for the definition.
226 /// @param LocNo Location number to propagate.
227 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
228 /// @param VNI When LR is not null, this is the value to restrict to.
229 /// @param Kills Append end points of VNI's live range to Kills.
230 /// @param LIS Live intervals analysis.
231 /// @param MDT Dominator tree.
232 void extendDef(SlotIndex Idx, unsigned LocNo,
233 LiveRange *LR, const VNInfo *VNI,
234 SmallVectorImpl<SlotIndex> *Kills,
235 LiveIntervals &LIS, MachineDominatorTree &MDT,
236 UserValueScopes &UVS);
238 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
239 /// registers. Determine if any of the copies are available at the kill
240 /// points, and add defs if possible.
241 /// @param LI Scan for copies of the value in LI->reg.
242 /// @param LocNo Location number of LI->reg.
243 /// @param Kills Points where the range of LocNo could be extended.
244 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
245 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
246 const SmallVectorImpl<SlotIndex> &Kills,
247 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
248 MachineRegisterInfo &MRI,
251 /// computeIntervals - Compute the live intervals of all locations after
252 /// collecting all their def points.
253 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
254 LiveIntervals &LIS, MachineDominatorTree &MDT,
255 UserValueScopes &UVS);
257 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
258 /// live. Returns true if any changes were made.
259 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
262 /// rewriteLocations - Rewrite virtual register locations according to the
263 /// provided virtual register map.
264 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
266 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
267 void emitDebugValues(VirtRegMap *VRM,
268 LiveIntervals &LIS, const TargetInstrInfo &TRI);
270 /// findDebugLoc - Return DebugLoc used for this DBG_VALUE instruction. A
271 /// variable may have more than one corresponding DBG_VALUE instructions.
272 /// Only first one needs DebugLoc to identify variable's lexical scope
274 DebugLoc findDebugLoc();
276 /// getDebugLoc - Return DebugLoc of this UserValue.
277 DebugLoc getDebugLoc() { return dl;}
278 void print(raw_ostream&, const TargetMachine*);
282 /// LDVImpl - Implementation of the LiveDebugVariables pass.
285 LiveDebugVariables &pass;
286 LocMap::Allocator allocator;
290 MachineDominatorTree *MDT;
291 const TargetRegisterInfo *TRI;
293 /// Whether emitDebugValues is called.
295 /// Whether the machine function is modified during the pass.
298 /// userValues - All allocated UserValue instances.
299 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
301 /// Map virtual register to eq class leader.
302 typedef DenseMap<unsigned, UserValue*> VRMap;
303 VRMap virtRegToEqClass;
305 /// Map user variable to eq class leader.
306 typedef DenseMap<const MDNode *, UserValue*> UVMap;
309 /// getUserValue - Find or create a UserValue.
310 UserValue *getUserValue(const MDNode *Var, unsigned Offset,
311 bool IsIndirect, DebugLoc DL);
313 /// lookupVirtReg - Find the EC leader for VirtReg or null.
314 UserValue *lookupVirtReg(unsigned VirtReg);
316 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
317 /// @param MI DBG_VALUE instruction
318 /// @param Idx Last valid SLotIndex before instruction.
319 /// @return True if the DBG_VALUE instruction should be deleted.
320 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
322 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
323 /// a UserValue def for each instruction.
324 /// @param mf MachineFunction to be scanned.
325 /// @return True if any debug values were found.
326 bool collectDebugValues(MachineFunction &mf);
328 /// computeIntervals - Compute the live intervals of all user values after
329 /// collecting all their def points.
330 void computeIntervals();
333 LDVImpl(LiveDebugVariables *ps)
334 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
335 bool runOnMachineFunction(MachineFunction &mf);
337 /// clear - Release all memory.
341 virtRegToEqClass.clear();
343 // Make sure we call emitDebugValues if the machine function was modified.
344 assert((!ModifiedMF || EmitDone) &&
345 "Dbg values are not emitted in LDV");
350 /// mapVirtReg - Map virtual register to an equivalence class.
351 void mapVirtReg(unsigned VirtReg, UserValue *EC);
353 /// splitRegister - Replace all references to OldReg with NewRegs.
354 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
356 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
357 void emitDebugValues(VirtRegMap *VRM);
359 void print(raw_ostream&);
363 void UserValue::print(raw_ostream &OS, const TargetMachine *TM) {
364 DIVariable DV(variable);
366 DV.printExtendedName(OS);
370 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
371 OS << " [" << I.start() << ';' << I.stop() << "):";
372 if (I.value() == ~0u)
377 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
378 OS << " Loc" << i << '=';
379 locations[i].print(OS, TM);
384 void LDVImpl::print(raw_ostream &OS) {
385 OS << "********** DEBUG VARIABLES **********\n";
386 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
387 userValues[i]->print(OS, &MF->getTarget());
390 void UserValue::coalesceLocation(unsigned LocNo) {
391 unsigned KeepLoc = 0;
392 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
393 if (KeepLoc == LocNo)
395 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
399 if (KeepLoc == locations.size())
402 // Keep the smaller location, erase the larger one.
403 unsigned EraseLoc = LocNo;
404 if (KeepLoc > EraseLoc)
405 std::swap(KeepLoc, EraseLoc);
406 locations.erase(locations.begin() + EraseLoc);
409 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
410 unsigned v = I.value();
412 I.setValue(KeepLoc); // Coalesce when possible.
413 else if (v > EraseLoc)
414 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
418 void UserValue::mapVirtRegs(LDVImpl *LDV) {
419 for (unsigned i = 0, e = locations.size(); i != e; ++i)
420 if (locations[i].isReg() &&
421 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
422 LDV->mapVirtReg(locations[i].getReg(), this);
425 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset,
426 bool IsIndirect, DebugLoc DL) {
427 UserValue *&Leader = userVarMap[Var];
429 UserValue *UV = Leader->getLeader();
431 for (; UV; UV = UV->getNext())
432 if (UV->match(Var, Offset, IsIndirect))
436 userValues.push_back(
437 make_unique<UserValue>(Var, Offset, IsIndirect, DL, allocator));
438 UserValue *UV = userValues.back().get();
439 Leader = UserValue::merge(Leader, UV);
443 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
444 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
445 UserValue *&Leader = virtRegToEqClass[VirtReg];
446 Leader = UserValue::merge(Leader, EC);
449 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
450 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
451 return UV->getLeader();
455 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
456 // DBG_VALUE loc, offset, variable
457 if (MI->getNumOperands() != 3 ||
458 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
459 !MI->getOperand(2).isMetadata()) {
460 DEBUG(dbgs() << "Can't handle " << *MI);
464 // Get or create the UserValue for (variable,offset).
465 bool IsIndirect = MI->isIndirectDebugValue();
466 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
467 const MDNode *Var = MI->getOperand(2).getMetadata();
469 UserValue *UV = getUserValue(Var, Offset, IsIndirect, MI->getDebugLoc());
470 UV->addDef(Idx, MI->getOperand(0));
474 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
475 bool Changed = false;
476 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
478 MachineBasicBlock *MBB = MFI;
479 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
481 if (!MBBI->isDebugValue()) {
485 // DBG_VALUE has no slot index, use the previous instruction instead.
486 SlotIndex Idx = MBBI == MBB->begin() ?
487 LIS->getMBBStartIdx(MBB) :
488 LIS->getInstructionIndex(std::prev(MBBI)).getRegSlot();
489 // Handle consecutive DBG_VALUE instructions with the same slot index.
491 if (handleDebugValue(MBBI, Idx)) {
492 MBBI = MBB->erase(MBBI);
496 } while (MBBI != MBBE && MBBI->isDebugValue());
502 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
503 LiveRange *LR, const VNInfo *VNI,
504 SmallVectorImpl<SlotIndex> *Kills,
505 LiveIntervals &LIS, MachineDominatorTree &MDT,
506 UserValueScopes &UVS) {
507 SmallVector<SlotIndex, 16> Todo;
510 SlotIndex Start = Todo.pop_back_val();
511 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
512 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
513 LocMap::iterator I = locInts.find(Start);
515 // Limit to VNI's live range.
518 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
519 if (!Segment || Segment->valno != VNI) {
521 Kills->push_back(Start);
524 if (Segment->end < Stop)
525 Stop = Segment->end, ToEnd = false;
528 // There could already be a short def at Start.
529 if (I.valid() && I.start() <= Start) {
530 // Stop when meeting a different location or an already extended interval.
531 Start = Start.getNextSlot();
532 if (I.value() != LocNo || I.stop() != Start)
534 // This is a one-slot placeholder. Just skip it.
538 // Limited by the next def.
539 if (I.valid() && I.start() < Stop)
540 Stop = I.start(), ToEnd = false;
541 // Limited by VNI's live range.
542 else if (!ToEnd && Kills)
543 Kills->push_back(Stop);
548 I.insert(Start, Stop, LocNo);
550 // If we extended to the MBB end, propagate down the dominator tree.
553 const std::vector<MachineDomTreeNode*> &Children =
554 MDT.getNode(MBB)->getChildren();
555 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
556 MachineBasicBlock *MBB = Children[i]->getBlock();
557 if (UVS.dominates(MBB))
558 Todo.push_back(LIS.getMBBStartIdx(MBB));
560 } while (!Todo.empty());
564 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
565 const SmallVectorImpl<SlotIndex> &Kills,
566 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
567 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
570 // Don't track copies from physregs, there are too many uses.
571 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
574 // Collect all the (vreg, valno) pairs that are copies of LI.
575 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
576 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
577 MachineInstr *MI = MO.getParent();
578 // Copies of the full value.
579 if (MO.getSubReg() || !MI->isCopy())
581 unsigned DstReg = MI->getOperand(0).getReg();
583 // Don't follow copies to physregs. These are usually setting up call
584 // arguments, and the argument registers are always call clobbered. We are
585 // better off in the source register which could be a callee-saved register,
586 // or it could be spilled.
587 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
590 // Is LocNo extended to reach this copy? If not, another def may be blocking
591 // it, or we are looking at a wrong value of LI.
592 SlotIndex Idx = LIS.getInstructionIndex(MI);
593 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
594 if (!I.valid() || I.value() != LocNo)
597 if (!LIS.hasInterval(DstReg))
599 LiveInterval *DstLI = &LIS.getInterval(DstReg);
600 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
601 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
602 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
605 if (CopyValues.empty())
608 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
610 // Try to add defs of the copied values for each kill point.
611 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
612 SlotIndex Idx = Kills[i];
613 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
614 LiveInterval *DstLI = CopyValues[j].first;
615 const VNInfo *DstVNI = CopyValues[j].second;
616 if (DstLI->getVNInfoAt(Idx) != DstVNI)
618 // Check that there isn't already a def at Idx
619 LocMap::iterator I = locInts.find(Idx);
620 if (I.valid() && I.start() <= Idx)
622 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
623 << DstVNI->id << " in " << *DstLI << '\n');
624 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
625 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
626 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
627 I.insert(Idx, Idx.getNextSlot(), LocNo);
628 NewDefs.push_back(std::make_pair(Idx, LocNo));
635 UserValue::computeIntervals(MachineRegisterInfo &MRI,
636 const TargetRegisterInfo &TRI,
638 MachineDominatorTree &MDT,
639 UserValueScopes &UVS) {
640 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
642 // Collect all defs to be extended (Skipping undefs).
643 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
644 if (I.value() != ~0u)
645 Defs.push_back(std::make_pair(I.start(), I.value()));
647 // Extend all defs, and possibly add new ones along the way.
648 for (unsigned i = 0; i != Defs.size(); ++i) {
649 SlotIndex Idx = Defs[i].first;
650 unsigned LocNo = Defs[i].second;
651 const MachineOperand &Loc = locations[LocNo];
654 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
658 // Register locations are constrained to where the register value is live.
659 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
660 LiveInterval *LI = nullptr;
661 const VNInfo *VNI = nullptr;
662 if (LIS.hasInterval(Loc.getReg())) {
663 LI = &LIS.getInterval(Loc.getReg());
664 VNI = LI->getVNInfoAt(Idx);
666 SmallVector<SlotIndex, 16> Kills;
667 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
669 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
673 // For physregs, use the live range of the first regunit as a guide.
674 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
675 LiveRange *LR = &LIS.getRegUnit(Unit);
676 const VNInfo *VNI = LR->getVNInfoAt(Idx);
677 // Don't track copies from physregs, it is too expensive.
678 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
681 // Finally, erase all the undefs.
682 for (LocMap::iterator I = locInts.begin(); I.valid();)
683 if (I.value() == ~0u)
689 void LDVImpl::computeIntervals() {
690 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
691 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
692 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
693 userValues[i]->mapVirtRegs(this);
697 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
700 LIS = &pass.getAnalysis<LiveIntervals>();
701 MDT = &pass.getAnalysis<MachineDominatorTree>();
702 TRI = mf.getSubtarget().getRegisterInfo();
704 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
705 << mf.getName() << " **********\n");
707 bool Changed = collectDebugValues(mf);
709 DEBUG(print(dbgs()));
710 ModifiedMF = Changed;
714 static void removeDebugValues(MachineFunction &mf) {
715 for (MachineBasicBlock &MBB : mf) {
716 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
717 if (!MBBI->isDebugValue()) {
721 MBBI = MBB.erase(MBBI);
726 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
729 if (!FunctionDIs.count(mf.getFunction())) {
730 removeDebugValues(mf);
734 pImpl = new LDVImpl(this);
735 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
738 void LiveDebugVariables::releaseMemory() {
740 static_cast<LDVImpl*>(pImpl)->clear();
743 LiveDebugVariables::~LiveDebugVariables() {
745 delete static_cast<LDVImpl*>(pImpl);
748 //===----------------------------------------------------------------------===//
749 // Live Range Splitting
750 //===----------------------------------------------------------------------===//
753 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
754 LiveIntervals& LIS) {
756 dbgs() << "Splitting Loc" << OldLocNo << '\t';
757 print(dbgs(), nullptr);
759 bool DidChange = false;
760 LocMap::iterator LocMapI;
761 LocMapI.setMap(locInts);
762 for (unsigned i = 0; i != NewRegs.size(); ++i) {
763 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
767 // Don't allocate the new LocNo until it is needed.
768 unsigned NewLocNo = ~0u;
770 // Iterate over the overlaps between locInts and LI.
771 LocMapI.find(LI->beginIndex());
772 if (!LocMapI.valid())
774 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
775 LiveInterval::iterator LIE = LI->end();
776 while (LocMapI.valid() && LII != LIE) {
777 // At this point, we know that LocMapI.stop() > LII->start.
778 LII = LI->advanceTo(LII, LocMapI.start());
782 // Now LII->end > LocMapI.start(). Do we have an overlap?
783 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
784 // Overlapping correct location. Allocate NewLocNo now.
785 if (NewLocNo == ~0u) {
786 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
787 MO.setSubReg(locations[OldLocNo].getSubReg());
788 NewLocNo = getLocationNo(MO);
792 SlotIndex LStart = LocMapI.start();
793 SlotIndex LStop = LocMapI.stop();
795 // Trim LocMapI down to the LII overlap.
796 if (LStart < LII->start)
797 LocMapI.setStartUnchecked(LII->start);
798 if (LStop > LII->end)
799 LocMapI.setStopUnchecked(LII->end);
801 // Change the value in the overlap. This may trigger coalescing.
802 LocMapI.setValue(NewLocNo);
804 // Re-insert any removed OldLocNo ranges.
805 if (LStart < LocMapI.start()) {
806 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
808 assert(LocMapI.valid() && "Unexpected coalescing");
810 if (LStop > LocMapI.stop()) {
812 LocMapI.insert(LII->end, LStop, OldLocNo);
817 // Advance to the next overlap.
818 if (LII->end < LocMapI.stop()) {
821 LocMapI.advanceTo(LII->start);
824 if (!LocMapI.valid())
826 LII = LI->advanceTo(LII, LocMapI.start());
831 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
832 locations.erase(locations.begin() + OldLocNo);
834 while (LocMapI.valid()) {
835 unsigned v = LocMapI.value();
837 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
838 << LocMapI.stop() << ")\n");
842 LocMapI.setValueUnchecked(v-1);
847 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
852 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
853 LiveIntervals &LIS) {
854 bool DidChange = false;
855 // Split locations referring to OldReg. Iterate backwards so splitLocation can
856 // safely erase unused locations.
857 for (unsigned i = locations.size(); i ; --i) {
858 unsigned LocNo = i-1;
859 const MachineOperand *Loc = &locations[LocNo];
860 if (!Loc->isReg() || Loc->getReg() != OldReg)
862 DidChange |= splitLocation(LocNo, NewRegs, LIS);
867 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
868 bool DidChange = false;
869 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
870 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
875 // Map all of the new virtual registers.
876 UserValue *UV = lookupVirtReg(OldReg);
877 for (unsigned i = 0; i != NewRegs.size(); ++i)
878 mapVirtReg(NewRegs[i], UV);
881 void LiveDebugVariables::
882 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
884 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
888 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
889 // Iterate over locations in reverse makes it easier to handle coalescing.
890 for (unsigned i = locations.size(); i ; --i) {
891 unsigned LocNo = i-1;
892 MachineOperand &Loc = locations[LocNo];
893 // Only virtual registers are rewritten.
894 if (!Loc.isReg() || !Loc.getReg() ||
895 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
897 unsigned VirtReg = Loc.getReg();
898 if (VRM.isAssignedReg(VirtReg) &&
899 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
900 // This can create a %noreg operand in rare cases when the sub-register
901 // index is no longer available. That means the user value is in a
902 // non-existent sub-register, and %noreg is exactly what we want.
903 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
904 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
905 // FIXME: Translate SubIdx to a stackslot offset.
906 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
911 coalesceLocation(LocNo);
915 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
917 static MachineBasicBlock::iterator
918 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
919 LiveIntervals &LIS) {
920 SlotIndex Start = LIS.getMBBStartIdx(MBB);
921 Idx = Idx.getBaseIndex();
923 // Try to find an insert location by going backwards from Idx.
925 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
926 // We've reached the beginning of MBB.
928 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
931 Idx = Idx.getPrevIndex();
934 // Don't insert anything after the first terminator, though.
935 return MI->isTerminator() ? MBB->getFirstTerminator() :
936 std::next(MachineBasicBlock::iterator(MI));
939 DebugLoc UserValue::findDebugLoc() {
944 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
947 const TargetInstrInfo &TII) {
948 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
949 MachineOperand &Loc = locations[LocNo];
950 ++NumInsertedDebugValues;
953 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
954 IsIndirect, Loc.getReg(), offset, variable);
956 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
957 .addOperand(Loc).addImm(offset).addMetadata(variable);
960 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
961 const TargetInstrInfo &TII) {
962 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
964 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
965 SlotIndex Start = I.start();
966 SlotIndex Stop = I.stop();
967 unsigned LocNo = I.value();
968 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
969 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
970 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
972 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
973 insertDebugValue(MBB, Start, LocNo, LIS, TII);
974 // This interval may span multiple basic blocks.
975 // Insert a DBG_VALUE into each one.
976 while(Stop > MBBEnd) {
977 // Move to the next block.
981 MBBEnd = LIS.getMBBEndIdx(MBB);
982 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
983 insertDebugValue(MBB, Start, LocNo, LIS, TII);
985 DEBUG(dbgs() << '\n');
993 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
994 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
997 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
998 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
999 DEBUG(userValues[i]->print(dbgs(), &MF->getTarget()));
1000 userValues[i]->rewriteLocations(*VRM, *TRI);
1001 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
1006 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1008 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1011 bool LiveDebugVariables::doInitialization(Module &M) {
1012 FunctionDIs = makeSubprogramMap(M);
1013 return Pass::doInitialization(M);
1017 void LiveDebugVariables::dump() {
1019 static_cast<LDVImpl*>(pImpl)->print(dbgs());