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/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #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 const MDNode *Expression; ///< Any complex address expression.
115 unsigned offset; ///< Byte offset into variable.
116 bool IsIndirect; ///< true if this is a register-indirect+offset value.
117 DebugLoc dl; ///< The debug location for the variable. This is
118 ///< used by dwarf writer to find lexical scope.
119 UserValue *leader; ///< Equivalence class leader.
120 UserValue *next; ///< Next value in equivalence class, or null.
122 /// Numbered locations referenced by locmap.
123 SmallVector<MachineOperand, 4> locations;
125 /// Map of slot indices where this value is live.
128 /// coalesceLocation - After LocNo was changed, check if it has become
129 /// identical to another location, and coalesce them. This may cause LocNo or
130 /// a later location to be erased, but no earlier location will be erased.
131 void coalesceLocation(unsigned LocNo);
133 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
134 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
135 LiveIntervals &LIS, const TargetInstrInfo &TII);
137 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
138 /// is live. Returns true if any changes were made.
139 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
143 /// UserValue - Create a new UserValue.
144 UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
145 DebugLoc L, LocMap::Allocator &alloc)
146 : Variable(var), Expression(expr), offset(o), IsIndirect(i), dl(L),
147 leader(this), 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, const MDNode *Expr, unsigned Offset,
162 bool indirect) const {
163 return Var == Variable && Expr == Expression && Offset == offset &&
164 indirect == IsIndirect;
167 /// merge - Merge equivalence classes.
168 static UserValue *merge(UserValue *L1, UserValue *L2) {
169 L2 = L2->getLeader();
172 L1 = L1->getLeader();
175 // Splice L2 before L1's members.
178 End->leader = L1, End = End->next;
180 End->next = L1->next;
185 /// getLocationNo - Return the location number that matches Loc.
186 unsigned getLocationNo(const MachineOperand &LocMO) {
188 if (LocMO.getReg() == 0)
190 // For register locations we dont care about use/def and other flags.
191 for (unsigned i = 0, e = locations.size(); i != e; ++i)
192 if (locations[i].isReg() &&
193 locations[i].getReg() == LocMO.getReg() &&
194 locations[i].getSubReg() == LocMO.getSubReg())
197 for (unsigned i = 0, e = locations.size(); i != e; ++i)
198 if (LocMO.isIdenticalTo(locations[i]))
200 locations.push_back(LocMO);
201 // We are storing a MachineOperand outside a MachineInstr.
202 locations.back().clearParent();
203 // Don't store def operands.
204 if (locations.back().isReg())
205 locations.back().setIsUse();
206 return locations.size() - 1;
209 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
210 void mapVirtRegs(LDVImpl *LDV);
212 /// addDef - Add a definition point to this value.
213 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
214 // Add a singular (Idx,Idx) -> Loc mapping.
215 LocMap::iterator I = locInts.find(Idx);
216 if (!I.valid() || I.start() != Idx)
217 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
219 // A later DBG_VALUE at the same SlotIndex overrides the old location.
220 I.setValue(getLocationNo(LocMO));
223 /// extendDef - Extend the current definition as far as possible down the
224 /// dominator tree. Stop when meeting an existing def or when leaving the live
226 /// End points where VNI is no longer live are added to Kills.
227 /// @param Idx Starting point for the definition.
228 /// @param LocNo Location number to propagate.
229 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
230 /// @param VNI When LR is not null, this is the value to restrict to.
231 /// @param Kills Append end points of VNI's live range to Kills.
232 /// @param LIS Live intervals analysis.
233 /// @param MDT Dominator tree.
234 void extendDef(SlotIndex Idx, unsigned LocNo,
235 LiveRange *LR, const VNInfo *VNI,
236 SmallVectorImpl<SlotIndex> *Kills,
237 LiveIntervals &LIS, MachineDominatorTree &MDT,
238 UserValueScopes &UVS);
240 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
241 /// registers. Determine if any of the copies are available at the kill
242 /// points, and add defs if possible.
243 /// @param LI Scan for copies of the value in LI->reg.
244 /// @param LocNo Location number of LI->reg.
245 /// @param Kills Points where the range of LocNo could be extended.
246 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
247 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
248 const SmallVectorImpl<SlotIndex> &Kills,
249 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
250 MachineRegisterInfo &MRI,
253 /// computeIntervals - Compute the live intervals of all locations after
254 /// collecting all their def points.
255 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
256 LiveIntervals &LIS, MachineDominatorTree &MDT,
257 UserValueScopes &UVS);
259 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
260 /// live. Returns true if any changes were made.
261 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
264 /// rewriteLocations - Rewrite virtual register locations according to the
265 /// provided virtual register map.
266 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
268 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
269 void emitDebugValues(VirtRegMap *VRM,
270 LiveIntervals &LIS, const TargetInstrInfo &TRI);
272 /// getDebugLoc - Return DebugLoc of this UserValue.
273 DebugLoc getDebugLoc() { return dl;}
274 void print(raw_ostream &, const TargetRegisterInfo *);
278 /// LDVImpl - Implementation of the LiveDebugVariables pass.
281 LiveDebugVariables &pass;
282 LocMap::Allocator allocator;
286 MachineDominatorTree *MDT;
287 const TargetRegisterInfo *TRI;
289 /// Whether emitDebugValues is called.
291 /// Whether the machine function is modified during the pass.
294 /// userValues - All allocated UserValue instances.
295 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
297 /// Map virtual register to eq class leader.
298 typedef DenseMap<unsigned, UserValue*> VRMap;
299 VRMap virtRegToEqClass;
301 /// Map user variable to eq class leader.
302 typedef DenseMap<const MDNode *, UserValue*> UVMap;
305 /// getUserValue - Find or create a UserValue.
306 UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
307 unsigned Offset, bool IsIndirect, DebugLoc DL);
309 /// lookupVirtReg - Find the EC leader for VirtReg or null.
310 UserValue *lookupVirtReg(unsigned VirtReg);
312 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
313 /// @param MI DBG_VALUE instruction
314 /// @param Idx Last valid SLotIndex before instruction.
315 /// @return True if the DBG_VALUE instruction should be deleted.
316 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
318 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
319 /// a UserValue def for each instruction.
320 /// @param mf MachineFunction to be scanned.
321 /// @return True if any debug values were found.
322 bool collectDebugValues(MachineFunction &mf);
324 /// computeIntervals - Compute the live intervals of all user values after
325 /// collecting all their def points.
326 void computeIntervals();
329 LDVImpl(LiveDebugVariables *ps)
330 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
331 bool runOnMachineFunction(MachineFunction &mf);
333 /// clear - Release all memory.
337 virtRegToEqClass.clear();
339 // Make sure we call emitDebugValues if the machine function was modified.
340 assert((!ModifiedMF || EmitDone) &&
341 "Dbg values are not emitted in LDV");
347 /// mapVirtReg - Map virtual register to an equivalence class.
348 void mapVirtReg(unsigned VirtReg, UserValue *EC);
350 /// splitRegister - Replace all references to OldReg with NewRegs.
351 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
353 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
354 void emitDebugValues(VirtRegMap *VRM);
356 void print(raw_ostream&);
360 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
361 const LLVMContext &Ctx) {
365 DIScope Scope = cast<MDScope>(DL.getScope());
366 // Omit the directory, because it's likely to be long and uninteresting.
367 CommentOS << Scope.getFilename();
368 CommentOS << ':' << DL.getLine();
369 if (DL.getCol() != 0)
370 CommentOS << ':' << DL.getCol();
372 DebugLoc InlinedAtDL = DL.getInlinedAt();
377 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
381 static void printExtendedName(raw_ostream &OS, const MDLocalVariable *V) {
382 const LLVMContext &Ctx = V->getContext();
383 StringRef Res = V->getName();
385 OS << Res << "," << V->getLine();
386 if (auto *InlinedAt = V->getInlinedAt()) {
387 if (DebugLoc InlinedAtDL = InlinedAt) {
389 printDebugLoc(InlinedAtDL, OS, Ctx);
395 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
396 DIVariable DV = cast<MDLocalVariable>(Variable);
398 printExtendedName(OS, DV);
403 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
404 OS << " [" << I.start() << ';' << I.stop() << "):";
405 if (I.value() == ~0u)
410 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
411 OS << " Loc" << i << '=';
412 locations[i].print(OS, TRI);
417 void LDVImpl::print(raw_ostream &OS) {
418 OS << "********** DEBUG VARIABLES **********\n";
419 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
420 userValues[i]->print(OS, TRI);
423 void UserValue::coalesceLocation(unsigned LocNo) {
424 unsigned KeepLoc = 0;
425 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
426 if (KeepLoc == LocNo)
428 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
432 if (KeepLoc == locations.size())
435 // Keep the smaller location, erase the larger one.
436 unsigned EraseLoc = LocNo;
437 if (KeepLoc > EraseLoc)
438 std::swap(KeepLoc, EraseLoc);
439 locations.erase(locations.begin() + EraseLoc);
442 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
443 unsigned v = I.value();
445 I.setValue(KeepLoc); // Coalesce when possible.
446 else if (v > EraseLoc)
447 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
451 void UserValue::mapVirtRegs(LDVImpl *LDV) {
452 for (unsigned i = 0, e = locations.size(); i != e; ++i)
453 if (locations[i].isReg() &&
454 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
455 LDV->mapVirtReg(locations[i].getReg(), this);
458 UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
459 unsigned Offset, bool IsIndirect,
461 UserValue *&Leader = userVarMap[Var];
463 UserValue *UV = Leader->getLeader();
465 for (; UV; UV = UV->getNext())
466 if (UV->match(Var, Expr, Offset, IsIndirect))
470 userValues.push_back(
471 make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
472 UserValue *UV = userValues.back().get();
473 Leader = UserValue::merge(Leader, UV);
477 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
478 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
479 UserValue *&Leader = virtRegToEqClass[VirtReg];
480 Leader = UserValue::merge(Leader, EC);
483 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
484 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
485 return UV->getLeader();
489 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
490 // DBG_VALUE loc, offset, variable
491 if (MI->getNumOperands() != 4 ||
492 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
493 !MI->getOperand(2).isMetadata()) {
494 DEBUG(dbgs() << "Can't handle " << *MI);
498 // Get or create the UserValue for (variable,offset).
499 bool IsIndirect = MI->isIndirectDebugValue();
500 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
501 const MDNode *Var = MI->getDebugVariable();
502 const MDNode *Expr = MI->getDebugExpression();
505 getUserValue(Var, Expr, Offset, IsIndirect, MI->getDebugLoc());
506 UV->addDef(Idx, MI->getOperand(0));
510 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
511 bool Changed = false;
512 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
514 MachineBasicBlock *MBB = MFI;
515 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
517 if (!MBBI->isDebugValue()) {
521 // DBG_VALUE has no slot index, use the previous instruction instead.
522 SlotIndex Idx = MBBI == MBB->begin() ?
523 LIS->getMBBStartIdx(MBB) :
524 LIS->getInstructionIndex(std::prev(MBBI)).getRegSlot();
525 // Handle consecutive DBG_VALUE instructions with the same slot index.
527 if (handleDebugValue(MBBI, Idx)) {
528 MBBI = MBB->erase(MBBI);
532 } while (MBBI != MBBE && MBBI->isDebugValue());
538 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
539 LiveRange *LR, const VNInfo *VNI,
540 SmallVectorImpl<SlotIndex> *Kills,
541 LiveIntervals &LIS, MachineDominatorTree &MDT,
542 UserValueScopes &UVS) {
543 SmallVector<SlotIndex, 16> Todo;
546 SlotIndex Start = Todo.pop_back_val();
547 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
548 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
549 LocMap::iterator I = locInts.find(Start);
551 // Limit to VNI's live range.
554 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
555 if (!Segment || Segment->valno != VNI) {
557 Kills->push_back(Start);
560 if (Segment->end < Stop)
561 Stop = Segment->end, ToEnd = false;
564 // There could already be a short def at Start.
565 if (I.valid() && I.start() <= Start) {
566 // Stop when meeting a different location or an already extended interval.
567 Start = Start.getNextSlot();
568 if (I.value() != LocNo || I.stop() != Start)
570 // This is a one-slot placeholder. Just skip it.
574 // Limited by the next def.
575 if (I.valid() && I.start() < Stop)
576 Stop = I.start(), ToEnd = false;
577 // Limited by VNI's live range.
578 else if (!ToEnd && Kills)
579 Kills->push_back(Stop);
584 I.insert(Start, Stop, LocNo);
586 // If we extended to the MBB end, propagate down the dominator tree.
589 const std::vector<MachineDomTreeNode*> &Children =
590 MDT.getNode(MBB)->getChildren();
591 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
592 MachineBasicBlock *MBB = Children[i]->getBlock();
593 if (UVS.dominates(MBB))
594 Todo.push_back(LIS.getMBBStartIdx(MBB));
596 } while (!Todo.empty());
600 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
601 const SmallVectorImpl<SlotIndex> &Kills,
602 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
603 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
606 // Don't track copies from physregs, there are too many uses.
607 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
610 // Collect all the (vreg, valno) pairs that are copies of LI.
611 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
612 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
613 MachineInstr *MI = MO.getParent();
614 // Copies of the full value.
615 if (MO.getSubReg() || !MI->isCopy())
617 unsigned DstReg = MI->getOperand(0).getReg();
619 // Don't follow copies to physregs. These are usually setting up call
620 // arguments, and the argument registers are always call clobbered. We are
621 // better off in the source register which could be a callee-saved register,
622 // or it could be spilled.
623 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
626 // Is LocNo extended to reach this copy? If not, another def may be blocking
627 // it, or we are looking at a wrong value of LI.
628 SlotIndex Idx = LIS.getInstructionIndex(MI);
629 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
630 if (!I.valid() || I.value() != LocNo)
633 if (!LIS.hasInterval(DstReg))
635 LiveInterval *DstLI = &LIS.getInterval(DstReg);
636 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
637 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
638 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
641 if (CopyValues.empty())
644 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
646 // Try to add defs of the copied values for each kill point.
647 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
648 SlotIndex Idx = Kills[i];
649 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
650 LiveInterval *DstLI = CopyValues[j].first;
651 const VNInfo *DstVNI = CopyValues[j].second;
652 if (DstLI->getVNInfoAt(Idx) != DstVNI)
654 // Check that there isn't already a def at Idx
655 LocMap::iterator I = locInts.find(Idx);
656 if (I.valid() && I.start() <= Idx)
658 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
659 << DstVNI->id << " in " << *DstLI << '\n');
660 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
661 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
662 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
663 I.insert(Idx, Idx.getNextSlot(), LocNo);
664 NewDefs.push_back(std::make_pair(Idx, LocNo));
671 UserValue::computeIntervals(MachineRegisterInfo &MRI,
672 const TargetRegisterInfo &TRI,
674 MachineDominatorTree &MDT,
675 UserValueScopes &UVS) {
676 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
678 // Collect all defs to be extended (Skipping undefs).
679 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
680 if (I.value() != ~0u)
681 Defs.push_back(std::make_pair(I.start(), I.value()));
683 // Extend all defs, and possibly add new ones along the way.
684 for (unsigned i = 0; i != Defs.size(); ++i) {
685 SlotIndex Idx = Defs[i].first;
686 unsigned LocNo = Defs[i].second;
687 const MachineOperand &Loc = locations[LocNo];
690 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
694 // Register locations are constrained to where the register value is live.
695 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
696 LiveInterval *LI = nullptr;
697 const VNInfo *VNI = nullptr;
698 if (LIS.hasInterval(Loc.getReg())) {
699 LI = &LIS.getInterval(Loc.getReg());
700 VNI = LI->getVNInfoAt(Idx);
702 SmallVector<SlotIndex, 16> Kills;
703 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
705 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
709 // For physregs, use the live range of the first regunit as a guide.
710 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
711 LiveRange *LR = &LIS.getRegUnit(Unit);
712 const VNInfo *VNI = LR->getVNInfoAt(Idx);
713 // Don't track copies from physregs, it is too expensive.
714 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
717 // Finally, erase all the undefs.
718 for (LocMap::iterator I = locInts.begin(); I.valid();)
719 if (I.value() == ~0u)
725 void LDVImpl::computeIntervals() {
726 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
727 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
728 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
729 userValues[i]->mapVirtRegs(this);
733 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
736 LIS = &pass.getAnalysis<LiveIntervals>();
737 MDT = &pass.getAnalysis<MachineDominatorTree>();
738 TRI = mf.getSubtarget().getRegisterInfo();
740 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
741 << mf.getName() << " **********\n");
743 bool Changed = collectDebugValues(mf);
745 DEBUG(print(dbgs()));
746 ModifiedMF = Changed;
750 static void removeDebugValues(MachineFunction &mf) {
751 for (MachineBasicBlock &MBB : mf) {
752 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
753 if (!MBBI->isDebugValue()) {
757 MBBI = MBB.erase(MBBI);
762 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
765 if (!FunctionDIs.count(mf.getFunction())) {
766 removeDebugValues(mf);
770 pImpl = new LDVImpl(this);
771 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
774 void LiveDebugVariables::releaseMemory() {
776 static_cast<LDVImpl*>(pImpl)->clear();
779 LiveDebugVariables::~LiveDebugVariables() {
781 delete static_cast<LDVImpl*>(pImpl);
784 //===----------------------------------------------------------------------===//
785 // Live Range Splitting
786 //===----------------------------------------------------------------------===//
789 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
790 LiveIntervals& LIS) {
792 dbgs() << "Splitting Loc" << OldLocNo << '\t';
793 print(dbgs(), nullptr);
795 bool DidChange = false;
796 LocMap::iterator LocMapI;
797 LocMapI.setMap(locInts);
798 for (unsigned i = 0; i != NewRegs.size(); ++i) {
799 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
803 // Don't allocate the new LocNo until it is needed.
804 unsigned NewLocNo = ~0u;
806 // Iterate over the overlaps between locInts and LI.
807 LocMapI.find(LI->beginIndex());
808 if (!LocMapI.valid())
810 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
811 LiveInterval::iterator LIE = LI->end();
812 while (LocMapI.valid() && LII != LIE) {
813 // At this point, we know that LocMapI.stop() > LII->start.
814 LII = LI->advanceTo(LII, LocMapI.start());
818 // Now LII->end > LocMapI.start(). Do we have an overlap?
819 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
820 // Overlapping correct location. Allocate NewLocNo now.
821 if (NewLocNo == ~0u) {
822 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
823 MO.setSubReg(locations[OldLocNo].getSubReg());
824 NewLocNo = getLocationNo(MO);
828 SlotIndex LStart = LocMapI.start();
829 SlotIndex LStop = LocMapI.stop();
831 // Trim LocMapI down to the LII overlap.
832 if (LStart < LII->start)
833 LocMapI.setStartUnchecked(LII->start);
834 if (LStop > LII->end)
835 LocMapI.setStopUnchecked(LII->end);
837 // Change the value in the overlap. This may trigger coalescing.
838 LocMapI.setValue(NewLocNo);
840 // Re-insert any removed OldLocNo ranges.
841 if (LStart < LocMapI.start()) {
842 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
844 assert(LocMapI.valid() && "Unexpected coalescing");
846 if (LStop > LocMapI.stop()) {
848 LocMapI.insert(LII->end, LStop, OldLocNo);
853 // Advance to the next overlap.
854 if (LII->end < LocMapI.stop()) {
857 LocMapI.advanceTo(LII->start);
860 if (!LocMapI.valid())
862 LII = LI->advanceTo(LII, LocMapI.start());
867 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
868 locations.erase(locations.begin() + OldLocNo);
870 while (LocMapI.valid()) {
871 unsigned v = LocMapI.value();
873 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
874 << LocMapI.stop() << ")\n");
878 LocMapI.setValueUnchecked(v-1);
883 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
888 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
889 LiveIntervals &LIS) {
890 bool DidChange = false;
891 // Split locations referring to OldReg. Iterate backwards so splitLocation can
892 // safely erase unused locations.
893 for (unsigned i = locations.size(); i ; --i) {
894 unsigned LocNo = i-1;
895 const MachineOperand *Loc = &locations[LocNo];
896 if (!Loc->isReg() || Loc->getReg() != OldReg)
898 DidChange |= splitLocation(LocNo, NewRegs, LIS);
903 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
904 bool DidChange = false;
905 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
906 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
911 // Map all of the new virtual registers.
912 UserValue *UV = lookupVirtReg(OldReg);
913 for (unsigned i = 0; i != NewRegs.size(); ++i)
914 mapVirtReg(NewRegs[i], UV);
917 void LiveDebugVariables::
918 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
920 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
924 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
925 // Iterate over locations in reverse makes it easier to handle coalescing.
926 for (unsigned i = locations.size(); i ; --i) {
927 unsigned LocNo = i-1;
928 MachineOperand &Loc = locations[LocNo];
929 // Only virtual registers are rewritten.
930 if (!Loc.isReg() || !Loc.getReg() ||
931 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
933 unsigned VirtReg = Loc.getReg();
934 if (VRM.isAssignedReg(VirtReg) &&
935 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
936 // This can create a %noreg operand in rare cases when the sub-register
937 // index is no longer available. That means the user value is in a
938 // non-existent sub-register, and %noreg is exactly what we want.
939 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
940 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
941 // FIXME: Translate SubIdx to a stackslot offset.
942 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
947 coalesceLocation(LocNo);
951 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
953 static MachineBasicBlock::iterator
954 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
955 LiveIntervals &LIS) {
956 SlotIndex Start = LIS.getMBBStartIdx(MBB);
957 Idx = Idx.getBaseIndex();
959 // Try to find an insert location by going backwards from Idx.
961 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
962 // We've reached the beginning of MBB.
964 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
967 Idx = Idx.getPrevIndex();
970 // Don't insert anything after the first terminator, though.
971 return MI->isTerminator() ? MBB->getFirstTerminator() :
972 std::next(MachineBasicBlock::iterator(MI));
975 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
978 const TargetInstrInfo &TII) {
979 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
980 MachineOperand &Loc = locations[LocNo];
981 ++NumInsertedDebugValues;
983 assert(cast<MDLocalVariable>(Variable)
984 ->isValidLocationForIntrinsic(getDebugLoc()) &&
985 "Expected inlined-at fields to agree");
987 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
988 IsIndirect, Loc.getReg(), offset, Variable, Expression);
990 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
993 .addMetadata(Variable)
994 .addMetadata(Expression);
997 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
998 const TargetInstrInfo &TII) {
999 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1001 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1002 SlotIndex Start = I.start();
1003 SlotIndex Stop = I.stop();
1004 unsigned LocNo = I.value();
1005 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
1006 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
1007 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
1009 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1010 insertDebugValue(MBB, Start, LocNo, LIS, TII);
1011 // This interval may span multiple basic blocks.
1012 // Insert a DBG_VALUE into each one.
1013 while(Stop > MBBEnd) {
1014 // Move to the next block.
1018 MBBEnd = LIS.getMBBEndIdx(MBB);
1019 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1020 insertDebugValue(MBB, Start, LocNo, LIS, TII);
1022 DEBUG(dbgs() << '\n');
1030 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1031 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1034 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1035 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1036 DEBUG(userValues[i]->print(dbgs(), TRI));
1037 userValues[i]->rewriteLocations(*VRM, *TRI);
1038 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
1043 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1045 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1048 bool LiveDebugVariables::doInitialization(Module &M) {
1049 FunctionDIs = makeSubprogramMap(M);
1050 return Pass::doInitialization(M);
1054 void LiveDebugVariables::dump() {
1056 static_cast<LDVImpl*>(pImpl)->print(dbgs());