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/LiveIntervalAnalysis.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/VirtRegMap.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.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;
78 /// UserValue - A user value is a part of a debug info user variable.
80 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
81 /// holds part of a user variable. The part is identified by a byte offset.
83 /// UserValues are grouped into equivalence classes for easier searching. Two
84 /// user values are related if they refer to the same variable, or if they are
85 /// held by the same virtual register. The equivalence class is the transitive
86 /// closure of that relation.
90 const MDNode *Variable; ///< The debug info variable we are part of.
91 const MDNode *Expression; ///< Any complex address expression.
92 unsigned offset; ///< Byte offset into variable.
93 bool IsIndirect; ///< true if this is a register-indirect+offset value.
94 DebugLoc dl; ///< The debug location for the variable. This is
95 ///< used by dwarf writer to find lexical scope.
96 UserValue *leader; ///< Equivalence class leader.
97 UserValue *next; ///< Next value in equivalence class, or null.
99 /// Numbered locations referenced by locmap.
100 SmallVector<MachineOperand, 4> locations;
102 /// Map of slot indices where this value is live.
105 /// coalesceLocation - After LocNo was changed, check if it has become
106 /// identical to another location, and coalesce them. This may cause LocNo or
107 /// a later location to be erased, but no earlier location will be erased.
108 void coalesceLocation(unsigned LocNo);
110 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
111 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
112 LiveIntervals &LIS, const TargetInstrInfo &TII);
114 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
115 /// is live. Returns true if any changes were made.
116 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
120 /// UserValue - Create a new UserValue.
121 UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
122 DebugLoc L, LocMap::Allocator &alloc)
123 : Variable(var), Expression(expr), offset(o), IsIndirect(i),
124 dl(std::move(L)), leader(this), next(nullptr), locInts(alloc) {}
126 /// getLeader - Get the leader of this value's equivalence class.
127 UserValue *getLeader() {
128 UserValue *l = leader;
129 while (l != l->leader)
134 /// getNext - Return the next UserValue in the equivalence class.
135 UserValue *getNext() const { return next; }
137 /// match - Does this UserValue match the parameters?
138 bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
139 unsigned Offset, bool indirect) const {
140 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
141 Offset == offset && indirect == IsIndirect;
144 /// merge - Merge equivalence classes.
145 static UserValue *merge(UserValue *L1, UserValue *L2) {
146 L2 = L2->getLeader();
149 L1 = L1->getLeader();
152 // Splice L2 before L1's members.
159 End->next = L1->next;
164 /// getLocationNo - Return the location number that matches Loc.
165 unsigned getLocationNo(const MachineOperand &LocMO) {
167 if (LocMO.getReg() == 0)
169 // For register locations we dont care about use/def and other flags.
170 for (unsigned i = 0, e = locations.size(); i != e; ++i)
171 if (locations[i].isReg() &&
172 locations[i].getReg() == LocMO.getReg() &&
173 locations[i].getSubReg() == LocMO.getSubReg())
176 for (unsigned i = 0, e = locations.size(); i != e; ++i)
177 if (LocMO.isIdenticalTo(locations[i]))
179 locations.push_back(LocMO);
180 // We are storing a MachineOperand outside a MachineInstr.
181 locations.back().clearParent();
182 // Don't store def operands.
183 if (locations.back().isReg())
184 locations.back().setIsUse();
185 return locations.size() - 1;
188 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
189 void mapVirtRegs(LDVImpl *LDV);
191 /// addDef - Add a definition point to this value.
192 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
193 // Add a singular (Idx,Idx) -> Loc mapping.
194 LocMap::iterator I = locInts.find(Idx);
195 if (!I.valid() || I.start() != Idx)
196 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
198 // A later DBG_VALUE at the same SlotIndex overrides the old location.
199 I.setValue(getLocationNo(LocMO));
202 /// extendDef - Extend the current definition as far as possible down.
203 /// Stop when meeting an existing def or when leaving the live
205 /// End points where VNI is no longer live are added to Kills.
206 /// @param Idx Starting point for the definition.
207 /// @param LocNo Location number to propagate.
208 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
209 /// @param VNI When LR is not null, this is the value to restrict to.
210 /// @param Kills Append end points of VNI's live range to Kills.
211 /// @param LIS Live intervals analysis.
212 void extendDef(SlotIndex Idx, unsigned LocNo,
213 LiveRange *LR, const VNInfo *VNI,
214 SmallVectorImpl<SlotIndex> *Kills,
217 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
218 /// registers. Determine if any of the copies are available at the kill
219 /// points, and add defs if possible.
220 /// @param LI Scan for copies of the value in LI->reg.
221 /// @param LocNo Location number of LI->reg.
222 /// @param Kills Points where the range of LocNo could be extended.
223 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
224 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
225 const SmallVectorImpl<SlotIndex> &Kills,
226 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
227 MachineRegisterInfo &MRI,
230 /// computeIntervals - Compute the live intervals of all locations after
231 /// collecting all their def points.
232 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
235 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
236 /// live. Returns true if any changes were made.
237 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
240 /// rewriteLocations - Rewrite virtual register locations according to the
241 /// provided virtual register map.
242 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
244 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
245 void emitDebugValues(VirtRegMap *VRM,
246 LiveIntervals &LIS, const TargetInstrInfo &TRI);
248 /// getDebugLoc - Return DebugLoc of this UserValue.
249 DebugLoc getDebugLoc() { return dl;}
250 void print(raw_ostream &, const TargetRegisterInfo *);
254 /// LDVImpl - Implementation of the LiveDebugVariables pass.
257 LiveDebugVariables &pass;
258 LocMap::Allocator allocator;
261 const TargetRegisterInfo *TRI;
263 /// Whether emitDebugValues is called.
265 /// Whether the machine function is modified during the pass.
268 /// userValues - All allocated UserValue instances.
269 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
271 /// Map virtual register to eq class leader.
272 typedef DenseMap<unsigned, UserValue*> VRMap;
273 VRMap virtRegToEqClass;
275 /// Map user variable to eq class leader.
276 typedef DenseMap<const MDNode *, UserValue*> UVMap;
279 /// getUserValue - Find or create a UserValue.
280 UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
281 unsigned Offset, bool IsIndirect, const DebugLoc &DL);
283 /// lookupVirtReg - Find the EC leader for VirtReg or null.
284 UserValue *lookupVirtReg(unsigned VirtReg);
286 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
287 /// @param MI DBG_VALUE instruction
288 /// @param Idx Last valid SLotIndex before instruction.
289 /// @return True if the DBG_VALUE instruction should be deleted.
290 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
292 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
293 /// a UserValue def for each instruction.
294 /// @param mf MachineFunction to be scanned.
295 /// @return True if any debug values were found.
296 bool collectDebugValues(MachineFunction &mf);
298 /// computeIntervals - Compute the live intervals of all user values after
299 /// collecting all their def points.
300 void computeIntervals();
303 LDVImpl(LiveDebugVariables *ps)
304 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
305 bool runOnMachineFunction(MachineFunction &mf);
307 /// clear - Release all memory.
311 virtRegToEqClass.clear();
313 // Make sure we call emitDebugValues if the machine function was modified.
314 assert((!ModifiedMF || EmitDone) &&
315 "Dbg values are not emitted in LDV");
320 /// mapVirtReg - Map virtual register to an equivalence class.
321 void mapVirtReg(unsigned VirtReg, UserValue *EC);
323 /// splitRegister - Replace all references to OldReg with NewRegs.
324 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
326 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
327 void emitDebugValues(VirtRegMap *VRM);
329 void print(raw_ostream&);
333 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
334 const LLVMContext &Ctx) {
338 auto *Scope = cast<DIScope>(DL.getScope());
339 // Omit the directory, because it's likely to be long and uninteresting.
340 CommentOS << Scope->getFilename();
341 CommentOS << ':' << DL.getLine();
342 if (DL.getCol() != 0)
343 CommentOS << ':' << DL.getCol();
345 DebugLoc InlinedAtDL = DL.getInlinedAt();
350 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
354 static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
355 const DILocation *DL) {
356 const LLVMContext &Ctx = V->getContext();
357 StringRef Res = V->getName();
359 OS << Res << "," << V->getLine();
360 if (auto *InlinedAt = DL->getInlinedAt()) {
361 if (DebugLoc InlinedAtDL = InlinedAt) {
363 printDebugLoc(InlinedAtDL, OS, Ctx);
369 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
370 auto *DV = cast<DILocalVariable>(Variable);
372 printExtendedName(OS, DV, dl);
377 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
378 OS << " [" << I.start() << ';' << I.stop() << "):";
379 if (I.value() == ~0u)
384 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
385 OS << " Loc" << i << '=';
386 locations[i].print(OS, TRI);
391 void LDVImpl::print(raw_ostream &OS) {
392 OS << "********** DEBUG VARIABLES **********\n";
393 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
394 userValues[i]->print(OS, TRI);
397 void UserValue::coalesceLocation(unsigned LocNo) {
398 unsigned KeepLoc = 0;
399 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
400 if (KeepLoc == LocNo)
402 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
406 if (KeepLoc == locations.size())
409 // Keep the smaller location, erase the larger one.
410 unsigned EraseLoc = LocNo;
411 if (KeepLoc > EraseLoc)
412 std::swap(KeepLoc, EraseLoc);
413 locations.erase(locations.begin() + EraseLoc);
416 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
417 unsigned v = I.value();
419 I.setValue(KeepLoc); // Coalesce when possible.
420 else if (v > EraseLoc)
421 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
425 void UserValue::mapVirtRegs(LDVImpl *LDV) {
426 for (unsigned i = 0, e = locations.size(); i != e; ++i)
427 if (locations[i].isReg() &&
428 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
429 LDV->mapVirtReg(locations[i].getReg(), this);
432 UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
433 unsigned Offset, bool IsIndirect,
434 const DebugLoc &DL) {
435 UserValue *&Leader = userVarMap[Var];
437 UserValue *UV = Leader->getLeader();
439 for (; UV; UV = UV->getNext())
440 if (UV->match(Var, Expr, DL->getInlinedAt(), Offset, IsIndirect))
444 userValues.push_back(
445 make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
446 UserValue *UV = userValues.back().get();
447 Leader = UserValue::merge(Leader, UV);
451 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
452 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
453 UserValue *&Leader = virtRegToEqClass[VirtReg];
454 Leader = UserValue::merge(Leader, EC);
457 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
458 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
459 return UV->getLeader();
463 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
464 // DBG_VALUE loc, offset, variable
465 if (MI.getNumOperands() != 4 ||
466 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
467 !MI.getOperand(2).isMetadata()) {
468 DEBUG(dbgs() << "Can't handle " << MI);
472 // Get or create the UserValue for (variable,offset).
473 bool IsIndirect = MI.isIndirectDebugValue();
474 unsigned Offset = IsIndirect ? MI.getOperand(1).getImm() : 0;
475 const MDNode *Var = MI.getDebugVariable();
476 const MDNode *Expr = MI.getDebugExpression();
478 UserValue *UV = getUserValue(Var, Expr, Offset, IsIndirect, MI.getDebugLoc());
479 UV->addDef(Idx, MI.getOperand(0));
483 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
484 bool Changed = false;
485 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
487 MachineBasicBlock *MBB = &*MFI;
488 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
490 if (!MBBI->isDebugValue()) {
494 // DBG_VALUE has no slot index, use the previous instruction instead.
497 ? LIS->getMBBStartIdx(MBB)
498 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
499 // Handle consecutive DBG_VALUE instructions with the same slot index.
501 if (handleDebugValue(*MBBI, Idx)) {
502 MBBI = MBB->erase(MBBI);
506 } while (MBBI != MBBE && MBBI->isDebugValue());
512 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
513 /// data-flow analysis to propagate them beyond basic block boundaries.
514 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
515 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
516 LiveIntervals &LIS) {
517 SlotIndex Start = Idx;
518 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
519 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
520 LocMap::iterator I = locInts.find(Start);
522 // Limit to VNI's live range.
525 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
526 if (!Segment || Segment->valno != VNI) {
528 Kills->push_back(Start);
531 if (Segment->end < Stop) {
537 // There could already be a short def at Start.
538 if (I.valid() && I.start() <= Start) {
539 // Stop when meeting a different location or an already extended interval.
540 Start = Start.getNextSlot();
541 if (I.value() != LocNo || I.stop() != Start)
543 // This is a one-slot placeholder. Just skip it.
547 // Limited by the next def.
548 if (I.valid() && I.start() < Stop) {
552 // Limited by VNI's live range.
553 else if (!ToEnd && Kills)
554 Kills->push_back(Stop);
557 I.insert(Start, Stop, LocNo);
561 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
562 const SmallVectorImpl<SlotIndex> &Kills,
563 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
564 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
567 // Don't track copies from physregs, there are too many uses.
568 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
571 // Collect all the (vreg, valno) pairs that are copies of LI.
572 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
573 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
574 MachineInstr *MI = MO.getParent();
575 // Copies of the full value.
576 if (MO.getSubReg() || !MI->isCopy())
578 unsigned DstReg = MI->getOperand(0).getReg();
580 // Don't follow copies to physregs. These are usually setting up call
581 // arguments, and the argument registers are always call clobbered. We are
582 // better off in the source register which could be a callee-saved register,
583 // or it could be spilled.
584 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
587 // Is LocNo extended to reach this copy? If not, another def may be blocking
588 // it, or we are looking at a wrong value of LI.
589 SlotIndex Idx = LIS.getInstructionIndex(*MI);
590 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
591 if (!I.valid() || I.value() != LocNo)
594 if (!LIS.hasInterval(DstReg))
596 LiveInterval *DstLI = &LIS.getInterval(DstReg);
597 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
598 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
599 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
602 if (CopyValues.empty())
605 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
607 // Try to add defs of the copied values for each kill point.
608 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
609 SlotIndex Idx = Kills[i];
610 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
611 LiveInterval *DstLI = CopyValues[j].first;
612 const VNInfo *DstVNI = CopyValues[j].second;
613 if (DstLI->getVNInfoAt(Idx) != DstVNI)
615 // Check that there isn't already a def at Idx
616 LocMap::iterator I = locInts.find(Idx);
617 if (I.valid() && I.start() <= Idx)
619 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
620 << DstVNI->id << " in " << *DstLI << '\n');
621 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
622 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
623 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
624 I.insert(Idx, Idx.getNextSlot(), LocNo);
625 NewDefs.push_back(std::make_pair(Idx, LocNo));
632 UserValue::computeIntervals(MachineRegisterInfo &MRI,
633 const TargetRegisterInfo &TRI,
634 LiveIntervals &LIS) {
635 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
637 // Collect all defs to be extended (Skipping undefs).
638 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
639 if (I.value() != ~0u)
640 Defs.push_back(std::make_pair(I.start(), I.value()));
642 // Extend all defs, and possibly add new ones along the way.
643 for (unsigned i = 0; i != Defs.size(); ++i) {
644 SlotIndex Idx = Defs[i].first;
645 unsigned LocNo = Defs[i].second;
646 const MachineOperand &Loc = locations[LocNo];
649 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS);
653 // Register locations are constrained to where the register value is live.
654 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
655 LiveInterval *LI = nullptr;
656 const VNInfo *VNI = nullptr;
657 if (LIS.hasInterval(Loc.getReg())) {
658 LI = &LIS.getInterval(Loc.getReg());
659 VNI = LI->getVNInfoAt(Idx);
661 SmallVector<SlotIndex, 16> Kills;
662 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS);
664 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
668 // For physregs, use the live range of the first regunit as a guide.
669 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
670 LiveRange *LR = &LIS.getRegUnit(Unit);
671 const VNInfo *VNI = LR->getVNInfoAt(Idx);
672 // Don't track copies from physregs, it is too expensive.
673 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS);
676 // Finally, erase all the undefs.
677 for (LocMap::iterator I = locInts.begin(); I.valid();)
678 if (I.value() == ~0u)
684 void LDVImpl::computeIntervals() {
685 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
686 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS);
687 userValues[i]->mapVirtRegs(this);
691 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
694 LIS = &pass.getAnalysis<LiveIntervals>();
695 TRI = mf.getSubtarget().getRegisterInfo();
696 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
697 << mf.getName() << " **********\n");
699 bool Changed = collectDebugValues(mf);
701 DEBUG(print(dbgs()));
702 ModifiedMF = Changed;
706 static void removeDebugValues(MachineFunction &mf) {
707 for (MachineBasicBlock &MBB : mf) {
708 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
709 if (!MBBI->isDebugValue()) {
713 MBBI = MBB.erase(MBBI);
718 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
721 if (!mf.getFunction()->getSubprogram()) {
722 removeDebugValues(mf);
726 pImpl = new LDVImpl(this);
727 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
730 void LiveDebugVariables::releaseMemory() {
732 static_cast<LDVImpl*>(pImpl)->clear();
735 LiveDebugVariables::~LiveDebugVariables() {
737 delete static_cast<LDVImpl*>(pImpl);
740 //===----------------------------------------------------------------------===//
741 // Live Range Splitting
742 //===----------------------------------------------------------------------===//
745 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
746 LiveIntervals& LIS) {
748 dbgs() << "Splitting Loc" << OldLocNo << '\t';
749 print(dbgs(), nullptr);
751 bool DidChange = false;
752 LocMap::iterator LocMapI;
753 LocMapI.setMap(locInts);
754 for (unsigned i = 0; i != NewRegs.size(); ++i) {
755 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
759 // Don't allocate the new LocNo until it is needed.
760 unsigned NewLocNo = ~0u;
762 // Iterate over the overlaps between locInts and LI.
763 LocMapI.find(LI->beginIndex());
764 if (!LocMapI.valid())
766 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
767 LiveInterval::iterator LIE = LI->end();
768 while (LocMapI.valid() && LII != LIE) {
769 // At this point, we know that LocMapI.stop() > LII->start.
770 LII = LI->advanceTo(LII, LocMapI.start());
774 // Now LII->end > LocMapI.start(). Do we have an overlap?
775 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
776 // Overlapping correct location. Allocate NewLocNo now.
777 if (NewLocNo == ~0u) {
778 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
779 MO.setSubReg(locations[OldLocNo].getSubReg());
780 NewLocNo = getLocationNo(MO);
784 SlotIndex LStart = LocMapI.start();
785 SlotIndex LStop = LocMapI.stop();
787 // Trim LocMapI down to the LII overlap.
788 if (LStart < LII->start)
789 LocMapI.setStartUnchecked(LII->start);
790 if (LStop > LII->end)
791 LocMapI.setStopUnchecked(LII->end);
793 // Change the value in the overlap. This may trigger coalescing.
794 LocMapI.setValue(NewLocNo);
796 // Re-insert any removed OldLocNo ranges.
797 if (LStart < LocMapI.start()) {
798 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
800 assert(LocMapI.valid() && "Unexpected coalescing");
802 if (LStop > LocMapI.stop()) {
804 LocMapI.insert(LII->end, LStop, OldLocNo);
809 // Advance to the next overlap.
810 if (LII->end < LocMapI.stop()) {
813 LocMapI.advanceTo(LII->start);
816 if (!LocMapI.valid())
818 LII = LI->advanceTo(LII, LocMapI.start());
823 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
824 locations.erase(locations.begin() + OldLocNo);
826 while (LocMapI.valid()) {
827 unsigned v = LocMapI.value();
829 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
830 << LocMapI.stop() << ")\n");
834 LocMapI.setValueUnchecked(v-1);
839 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
844 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
845 LiveIntervals &LIS) {
846 bool DidChange = false;
847 // Split locations referring to OldReg. Iterate backwards so splitLocation can
848 // safely erase unused locations.
849 for (unsigned i = locations.size(); i ; --i) {
850 unsigned LocNo = i-1;
851 const MachineOperand *Loc = &locations[LocNo];
852 if (!Loc->isReg() || Loc->getReg() != OldReg)
854 DidChange |= splitLocation(LocNo, NewRegs, LIS);
859 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
860 bool DidChange = false;
861 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
862 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
867 // Map all of the new virtual registers.
868 UserValue *UV = lookupVirtReg(OldReg);
869 for (unsigned i = 0; i != NewRegs.size(); ++i)
870 mapVirtReg(NewRegs[i], UV);
873 void LiveDebugVariables::
874 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
876 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
880 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
881 // Iterate over locations in reverse makes it easier to handle coalescing.
882 for (unsigned i = locations.size(); i ; --i) {
883 unsigned LocNo = i-1;
884 MachineOperand &Loc = locations[LocNo];
885 // Only virtual registers are rewritten.
886 if (!Loc.isReg() || !Loc.getReg() ||
887 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
889 unsigned VirtReg = Loc.getReg();
890 if (VRM.isAssignedReg(VirtReg) &&
891 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
892 // This can create a %noreg operand in rare cases when the sub-register
893 // index is no longer available. That means the user value is in a
894 // non-existent sub-register, and %noreg is exactly what we want.
895 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
896 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
897 // FIXME: Translate SubIdx to a stackslot offset.
898 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
903 coalesceLocation(LocNo);
907 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
909 static MachineBasicBlock::iterator
910 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
911 LiveIntervals &LIS) {
912 SlotIndex Start = LIS.getMBBStartIdx(MBB);
913 Idx = Idx.getBaseIndex();
915 // Try to find an insert location by going backwards from Idx.
917 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
918 // We've reached the beginning of MBB.
920 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
923 Idx = Idx.getPrevIndex();
926 // Don't insert anything after the first terminator, though.
927 return MI->isTerminator() ? MBB->getFirstTerminator() :
928 std::next(MachineBasicBlock::iterator(MI));
931 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
934 const TargetInstrInfo &TII) {
935 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
936 MachineOperand &Loc = locations[LocNo];
937 ++NumInsertedDebugValues;
939 assert(cast<DILocalVariable>(Variable)
940 ->isValidLocationForIntrinsic(getDebugLoc()) &&
941 "Expected inlined-at fields to agree");
943 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
944 IsIndirect, Loc.getReg(), offset, Variable, Expression);
946 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
949 .addMetadata(Variable)
950 .addMetadata(Expression);
953 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
954 const TargetInstrInfo &TII) {
955 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
957 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
958 SlotIndex Start = I.start();
959 SlotIndex Stop = I.stop();
960 unsigned LocNo = I.value();
961 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
962 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
963 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
965 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
966 insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
967 // This interval may span multiple basic blocks.
968 // Insert a DBG_VALUE into each one.
969 while(Stop > MBBEnd) {
970 // Move to the next block.
974 MBBEnd = LIS.getMBBEndIdx(&*MBB);
975 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
976 insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
978 DEBUG(dbgs() << '\n');
986 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
987 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
990 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
991 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
992 DEBUG(userValues[i]->print(dbgs(), TRI));
993 userValues[i]->rewriteLocations(*VRM, *TRI);
994 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
999 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1001 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1004 bool LiveDebugVariables::doInitialization(Module &M) {
1005 return Pass::doInitialization(M);
1008 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1009 LLVM_DUMP_METHOD void LiveDebugVariables::dump() {
1011 static_cast<LDVImpl*>(pImpl)->print(dbgs());