1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the LiveDebugVariables analysis.
11 // Remove all DBG_VALUE instructions referencing virtual registers and replace
12 // them with a data structure tracking where live user variables are kept - in a
13 // virtual register or in a stack slot.
15 // Allow the data structure to be updated during register allocation when values
16 // are moved between registers and stack slots. Finally emit new DBG_VALUE
17 // instructions after register allocation is complete.
19 //===----------------------------------------------------------------------===//
21 #include "LiveDebugVariables.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/IntervalMap.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/CodeGen/LexicalScopes.h"
31 #include "llvm/CodeGen/LiveInterval.h"
32 #include "llvm/CodeGen/LiveIntervals.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineDominators.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/SlotIndexes.h"
41 #include "llvm/CodeGen/TargetInstrInfo.h"
42 #include "llvm/CodeGen/TargetOpcodes.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/VirtRegMap.h"
46 #include "llvm/Config/llvm-config.h"
47 #include "llvm/IR/DebugInfoMetadata.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
66 #define DEBUG_TYPE "livedebugvars"
69 EnableLDV("live-debug-variables", cl::init(true),
70 cl::desc("Enable the live debug variables pass"), cl::Hidden
);
72 STATISTIC(NumInsertedDebugValues
, "Number of DBG_VALUEs inserted");
73 STATISTIC(NumInsertedDebugLabels
, "Number of DBG_LABELs inserted");
75 char LiveDebugVariables::ID
= 0;
77 INITIALIZE_PASS_BEGIN(LiveDebugVariables
, DEBUG_TYPE
,
78 "Debug Variable Analysis", false, false)
79 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
80 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
81 INITIALIZE_PASS_END(LiveDebugVariables
, DEBUG_TYPE
,
82 "Debug Variable Analysis", false, false)
84 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage
&AU
) const {
85 AU
.addRequired
<MachineDominatorTree
>();
86 AU
.addRequiredTransitive
<LiveIntervals
>();
88 MachineFunctionPass::getAnalysisUsage(AU
);
91 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID
) {
92 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
95 enum : unsigned { UndefLocNo
= ~0U };
97 /// Describes a location by number along with some flags about the original
98 /// usage of the location.
99 class DbgValueLocation
{
101 DbgValueLocation(unsigned LocNo
, bool WasIndirect
)
102 : LocNo(LocNo
), WasIndirect(WasIndirect
) {
103 static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
104 assert(locNo() == LocNo
&& "location truncation");
107 DbgValueLocation() : LocNo(0), WasIndirect(0) {}
109 unsigned locNo() const {
110 // Fix up the undef location number, which gets truncated.
111 return LocNo
== INT_MAX
? UndefLocNo
: LocNo
;
113 bool wasIndirect() const { return WasIndirect
; }
114 bool isUndef() const { return locNo() == UndefLocNo
; }
116 DbgValueLocation
changeLocNo(unsigned NewLocNo
) const {
117 return DbgValueLocation(NewLocNo
, WasIndirect
);
120 friend inline bool operator==(const DbgValueLocation
&LHS
,
121 const DbgValueLocation
&RHS
) {
122 return LHS
.LocNo
== RHS
.LocNo
&& LHS
.WasIndirect
== RHS
.WasIndirect
;
125 friend inline bool operator!=(const DbgValueLocation
&LHS
,
126 const DbgValueLocation
&RHS
) {
127 return !(LHS
== RHS
);
132 unsigned WasIndirect
: 1;
135 /// Map of where a user value is live, and its location.
136 using LocMap
= IntervalMap
<SlotIndex
, DbgValueLocation
, 4>;
138 /// Map of stack slot offsets for spilled locations.
139 /// Non-spilled locations are not added to the map.
140 using SpillOffsetMap
= DenseMap
<unsigned, unsigned>;
146 /// A user value is a part of a debug info user variable.
148 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
149 /// holds part of a user variable. The part is identified by a byte offset.
151 /// UserValues are grouped into equivalence classes for easier searching. Two
152 /// user values are related if they refer to the same variable, or if they are
153 /// held by the same virtual register. The equivalence class is the transitive
154 /// closure of that relation.
156 const DILocalVariable
*Variable
; ///< The debug info variable we are part of.
157 const DIExpression
*Expression
; ///< Any complex address expression.
158 DebugLoc dl
; ///< The debug location for the variable. This is
159 ///< used by dwarf writer to find lexical scope.
160 UserValue
*leader
; ///< Equivalence class leader.
161 UserValue
*next
= nullptr; ///< Next value in equivalence class, or null.
163 /// Numbered locations referenced by locmap.
164 SmallVector
<MachineOperand
, 4> locations
;
166 /// Map of slot indices where this value is live.
169 /// Set of interval start indexes that have been trimmed to the
171 SmallSet
<SlotIndex
, 2> trimmedDefs
;
173 /// Insert a DBG_VALUE into MBB at Idx for LocNo.
174 void insertDebugValue(MachineBasicBlock
*MBB
, SlotIndex StartIdx
,
175 SlotIndex StopIdx
, DbgValueLocation Loc
, bool Spilled
,
176 unsigned SpillOffset
, LiveIntervals
&LIS
,
177 const TargetInstrInfo
&TII
,
178 const TargetRegisterInfo
&TRI
);
180 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
181 /// is live. Returns true if any changes were made.
182 bool splitLocation(unsigned OldLocNo
, ArrayRef
<unsigned> NewRegs
,
186 /// Create a new UserValue.
187 UserValue(const DILocalVariable
*var
, const DIExpression
*expr
, DebugLoc L
,
188 LocMap::Allocator
&alloc
)
189 : Variable(var
), Expression(expr
), dl(std::move(L
)), leader(this),
192 /// Get the leader of this value's equivalence class.
193 UserValue
*getLeader() {
194 UserValue
*l
= leader
;
195 while (l
!= l
->leader
)
200 /// Return the next UserValue in the equivalence class.
201 UserValue
*getNext() const { return next
; }
203 /// Does this UserValue match the parameters?
204 bool match(const DILocalVariable
*Var
, const DIExpression
*Expr
,
205 const DILocation
*IA
) const {
206 // FIXME: The fragment should be part of the equivalence class, but not
207 // other things in the expression like stack values.
208 return Var
== Variable
&& Expr
== Expression
&& dl
->getInlinedAt() == IA
;
211 /// Merge equivalence classes.
212 static UserValue
*merge(UserValue
*L1
, UserValue
*L2
) {
213 L2
= L2
->getLeader();
216 L1
= L1
->getLeader();
219 // Splice L2 before L1's members.
226 End
->next
= L1
->next
;
231 /// Return the location number that matches Loc.
233 /// For undef values we always return location number UndefLocNo without
234 /// inserting anything in locations. Since locations is a vector and the
235 /// location number is the position in the vector and UndefLocNo is ~0,
236 /// we would need a very big vector to put the value at the right position.
237 unsigned getLocationNo(const MachineOperand
&LocMO
) {
239 if (LocMO
.getReg() == 0)
241 // For register locations we dont care about use/def and other flags.
242 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
)
243 if (locations
[i
].isReg() &&
244 locations
[i
].getReg() == LocMO
.getReg() &&
245 locations
[i
].getSubReg() == LocMO
.getSubReg())
248 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
)
249 if (LocMO
.isIdenticalTo(locations
[i
]))
251 locations
.push_back(LocMO
);
252 // We are storing a MachineOperand outside a MachineInstr.
253 locations
.back().clearParent();
254 // Don't store def operands.
255 if (locations
.back().isReg()) {
256 if (locations
.back().isDef())
257 locations
.back().setIsDead(false);
258 locations
.back().setIsUse();
260 return locations
.size() - 1;
263 /// Ensure that all virtual register locations are mapped.
264 void mapVirtRegs(LDVImpl
*LDV
);
266 /// Add a definition point to this value.
267 void addDef(SlotIndex Idx
, const MachineOperand
&LocMO
, bool IsIndirect
) {
268 DbgValueLocation
Loc(getLocationNo(LocMO
), IsIndirect
);
269 // Add a singular (Idx,Idx) -> Loc mapping.
270 LocMap::iterator I
= locInts
.find(Idx
);
271 if (!I
.valid() || I
.start() != Idx
)
272 I
.insert(Idx
, Idx
.getNextSlot(), Loc
);
274 // A later DBG_VALUE at the same SlotIndex overrides the old location.
278 /// Extend the current definition as far as possible down.
280 /// Stop when meeting an existing def or when leaving the live
281 /// range of VNI. End points where VNI is no longer live are added to Kills.
283 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
284 /// data-flow analysis to propagate them beyond basic block boundaries.
286 /// \param Idx Starting point for the definition.
287 /// \param Loc Location number to propagate.
288 /// \param LR Restrict liveness to where LR has the value VNI. May be null.
289 /// \param VNI When LR is not null, this is the value to restrict to.
290 /// \param [out] Kills Append end points of VNI's live range to Kills.
291 /// \param LIS Live intervals analysis.
292 void extendDef(SlotIndex Idx
, DbgValueLocation Loc
,
293 LiveRange
*LR
, const VNInfo
*VNI
,
294 SmallVectorImpl
<SlotIndex
> *Kills
,
297 /// The value in LI/LocNo may be copies to other registers. Determine if
298 /// any of the copies are available at the kill points, and add defs if
301 /// \param LI Scan for copies of the value in LI->reg.
302 /// \param LocNo Location number of LI->reg.
303 /// \param WasIndirect Indicates if the original use of LI->reg was indirect
304 /// \param Kills Points where the range of LocNo could be extended.
305 /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here.
306 void addDefsFromCopies(
307 LiveInterval
*LI
, unsigned LocNo
, bool WasIndirect
,
308 const SmallVectorImpl
<SlotIndex
> &Kills
,
309 SmallVectorImpl
<std::pair
<SlotIndex
, DbgValueLocation
>> &NewDefs
,
310 MachineRegisterInfo
&MRI
, LiveIntervals
&LIS
);
312 /// Compute the live intervals of all locations after collecting all their
314 void computeIntervals(MachineRegisterInfo
&MRI
, const TargetRegisterInfo
&TRI
,
315 LiveIntervals
&LIS
, LexicalScopes
&LS
);
317 /// Replace OldReg ranges with NewRegs ranges where NewRegs is
318 /// live. Returns true if any changes were made.
319 bool splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
,
322 /// Rewrite virtual register locations according to the provided virtual
323 /// register map. Record the stack slot offsets for the locations that
325 void rewriteLocations(VirtRegMap
&VRM
, const MachineFunction
&MF
,
326 const TargetInstrInfo
&TII
,
327 const TargetRegisterInfo
&TRI
,
328 SpillOffsetMap
&SpillOffsets
);
330 /// Recreate DBG_VALUE instruction from data structures.
331 void emitDebugValues(VirtRegMap
*VRM
, LiveIntervals
&LIS
,
332 const TargetInstrInfo
&TII
,
333 const TargetRegisterInfo
&TRI
,
334 const SpillOffsetMap
&SpillOffsets
);
336 /// Return DebugLoc of this UserValue.
337 DebugLoc
getDebugLoc() { return dl
;}
339 void print(raw_ostream
&, const TargetRegisterInfo
*);
342 /// A user label is a part of a debug info user label.
344 const DILabel
*Label
; ///< The debug info label we are part of.
345 DebugLoc dl
; ///< The debug location for the label. This is
346 ///< used by dwarf writer to find lexical scope.
347 SlotIndex loc
; ///< Slot used by the debug label.
349 /// Insert a DBG_LABEL into MBB at Idx.
350 void insertDebugLabel(MachineBasicBlock
*MBB
, SlotIndex Idx
,
351 LiveIntervals
&LIS
, const TargetInstrInfo
&TII
);
354 /// Create a new UserLabel.
355 UserLabel(const DILabel
*label
, DebugLoc L
, SlotIndex Idx
)
356 : Label(label
), dl(std::move(L
)), loc(Idx
) {}
358 /// Does this UserLabel match the parameters?
359 bool match(const DILabel
*L
, const DILocation
*IA
,
360 const SlotIndex Index
) const {
361 return Label
== L
&& dl
->getInlinedAt() == IA
&& loc
== Index
;
364 /// Recreate DBG_LABEL instruction from data structures.
365 void emitDebugLabel(LiveIntervals
&LIS
, const TargetInstrInfo
&TII
);
367 /// Return DebugLoc of this UserLabel.
368 DebugLoc
getDebugLoc() { return dl
; }
370 void print(raw_ostream
&, const TargetRegisterInfo
*);
373 /// Implementation of the LiveDebugVariables pass.
375 LiveDebugVariables
&pass
;
376 LocMap::Allocator allocator
;
377 MachineFunction
*MF
= nullptr;
379 const TargetRegisterInfo
*TRI
;
381 /// Whether emitDebugValues is called.
382 bool EmitDone
= false;
384 /// Whether the machine function is modified during the pass.
385 bool ModifiedMF
= false;
387 /// All allocated UserValue instances.
388 SmallVector
<std::unique_ptr
<UserValue
>, 8> userValues
;
390 /// All allocated UserLabel instances.
391 SmallVector
<std::unique_ptr
<UserLabel
>, 2> userLabels
;
393 /// Map virtual register to eq class leader.
394 using VRMap
= DenseMap
<unsigned, UserValue
*>;
395 VRMap virtRegToEqClass
;
397 /// Map user variable to eq class leader.
398 using UVMap
= DenseMap
<const DILocalVariable
*, UserValue
*>;
401 /// Find or create a UserValue.
402 UserValue
*getUserValue(const DILocalVariable
*Var
, const DIExpression
*Expr
,
405 /// Find the EC leader for VirtReg or null.
406 UserValue
*lookupVirtReg(unsigned VirtReg
);
408 /// Add DBG_VALUE instruction to our maps.
410 /// \param MI DBG_VALUE instruction
411 /// \param Idx Last valid SLotIndex before instruction.
413 /// \returns True if the DBG_VALUE instruction should be deleted.
414 bool handleDebugValue(MachineInstr
&MI
, SlotIndex Idx
);
416 /// Add DBG_LABEL instruction to UserLabel.
418 /// \param MI DBG_LABEL instruction
419 /// \param Idx Last valid SlotIndex before instruction.
421 /// \returns True if the DBG_LABEL instruction should be deleted.
422 bool handleDebugLabel(MachineInstr
&MI
, SlotIndex Idx
);
424 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
425 /// for each instruction.
427 /// \param mf MachineFunction to be scanned.
429 /// \returns True if any debug values were found.
430 bool collectDebugValues(MachineFunction
&mf
);
432 /// Compute the live intervals of all user values after collecting all
433 /// their def points.
434 void computeIntervals();
437 LDVImpl(LiveDebugVariables
*ps
) : pass(*ps
) {}
439 bool runOnMachineFunction(MachineFunction
&mf
);
441 /// Release all memory.
446 virtRegToEqClass
.clear();
448 // Make sure we call emitDebugValues if the machine function was modified.
449 assert((!ModifiedMF
|| EmitDone
) &&
450 "Dbg values are not emitted in LDV");
455 /// Map virtual register to an equivalence class.
456 void mapVirtReg(unsigned VirtReg
, UserValue
*EC
);
458 /// Replace all references to OldReg with NewRegs.
459 void splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
);
461 /// Recreate DBG_VALUE instruction from data structures.
462 void emitDebugValues(VirtRegMap
*VRM
);
464 void print(raw_ostream
&);
467 } // end anonymous namespace
469 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
470 static void printDebugLoc(const DebugLoc
&DL
, raw_ostream
&CommentOS
,
471 const LLVMContext
&Ctx
) {
475 auto *Scope
= cast
<DIScope
>(DL
.getScope());
476 // Omit the directory, because it's likely to be long and uninteresting.
477 CommentOS
<< Scope
->getFilename();
478 CommentOS
<< ':' << DL
.getLine();
479 if (DL
.getCol() != 0)
480 CommentOS
<< ':' << DL
.getCol();
482 DebugLoc InlinedAtDL
= DL
.getInlinedAt();
487 printDebugLoc(InlinedAtDL
, CommentOS
, Ctx
);
491 static void printExtendedName(raw_ostream
&OS
, const DINode
*Node
,
492 const DILocation
*DL
) {
493 const LLVMContext
&Ctx
= Node
->getContext();
496 if (const auto *V
= dyn_cast
<const DILocalVariable
>(Node
)) {
499 } else if (const auto *L
= dyn_cast
<const DILabel
>(Node
)) {
505 OS
<< Res
<< "," << Line
;
506 if (auto *InlinedAt
= DL
->getInlinedAt()) {
507 if (DebugLoc InlinedAtDL
= InlinedAt
) {
509 printDebugLoc(InlinedAtDL
, OS
, Ctx
);
515 void UserValue::print(raw_ostream
&OS
, const TargetRegisterInfo
*TRI
) {
517 printExtendedName(OS
, Variable
, dl
);
520 for (LocMap::const_iterator I
= locInts
.begin(); I
.valid(); ++I
) {
521 OS
<< " [" << I
.start() << ';' << I
.stop() << "):";
522 if (I
.value().isUndef())
525 OS
<< I
.value().locNo();
526 if (I
.value().wasIndirect())
530 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
) {
531 OS
<< " Loc" << i
<< '=';
532 locations
[i
].print(OS
, TRI
);
537 void UserLabel::print(raw_ostream
&OS
, const TargetRegisterInfo
*TRI
) {
539 printExtendedName(OS
, Label
, dl
);
546 void LDVImpl::print(raw_ostream
&OS
) {
547 OS
<< "********** DEBUG VARIABLES **********\n";
548 for (auto &userValue
: userValues
)
549 userValue
->print(OS
, TRI
);
550 OS
<< "********** DEBUG LABELS **********\n";
551 for (auto &userLabel
: userLabels
)
552 userLabel
->print(OS
, TRI
);
556 void UserValue::mapVirtRegs(LDVImpl
*LDV
) {
557 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
)
558 if (locations
[i
].isReg() &&
559 TargetRegisterInfo::isVirtualRegister(locations
[i
].getReg()))
560 LDV
->mapVirtReg(locations
[i
].getReg(), this);
563 UserValue
*LDVImpl::getUserValue(const DILocalVariable
*Var
,
564 const DIExpression
*Expr
, const DebugLoc
&DL
) {
565 UserValue
*&Leader
= userVarMap
[Var
];
567 UserValue
*UV
= Leader
->getLeader();
569 for (; UV
; UV
= UV
->getNext())
570 if (UV
->match(Var
, Expr
, DL
->getInlinedAt()))
574 userValues
.push_back(
575 llvm::make_unique
<UserValue
>(Var
, Expr
, DL
, allocator
));
576 UserValue
*UV
= userValues
.back().get();
577 Leader
= UserValue::merge(Leader
, UV
);
581 void LDVImpl::mapVirtReg(unsigned VirtReg
, UserValue
*EC
) {
582 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) && "Only map VirtRegs");
583 UserValue
*&Leader
= virtRegToEqClass
[VirtReg
];
584 Leader
= UserValue::merge(Leader
, EC
);
587 UserValue
*LDVImpl::lookupVirtReg(unsigned VirtReg
) {
588 if (UserValue
*UV
= virtRegToEqClass
.lookup(VirtReg
))
589 return UV
->getLeader();
593 bool LDVImpl::handleDebugValue(MachineInstr
&MI
, SlotIndex Idx
) {
594 // DBG_VALUE loc, offset, variable
595 if (MI
.getNumOperands() != 4 ||
596 !(MI
.getOperand(1).isReg() || MI
.getOperand(1).isImm()) ||
597 !MI
.getOperand(2).isMetadata()) {
598 LLVM_DEBUG(dbgs() << "Can't handle " << MI
);
602 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
603 // register that hasn't been defined yet. If we do not remove those here, then
604 // the re-insertion of the DBG_VALUE instruction after register allocation
605 // will be incorrect.
606 // TODO: If earlier passes are corrected to generate sane debug information
607 // (and if the machine verifier is improved to catch this), then these checks
608 // could be removed or replaced by asserts.
609 bool Discard
= false;
610 if (MI
.getOperand(0).isReg() &&
611 TargetRegisterInfo::isVirtualRegister(MI
.getOperand(0).getReg())) {
612 const unsigned Reg
= MI
.getOperand(0).getReg();
613 if (!LIS
->hasInterval(Reg
)) {
614 // The DBG_VALUE is described by a virtual register that does not have a
615 // live interval. Discard the DBG_VALUE.
617 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
620 // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
621 // is defined dead at Idx (where Idx is the slot index for the instruction
622 // preceeding the DBG_VALUE).
623 const LiveInterval
&LI
= LIS
->getInterval(Reg
);
624 LiveQueryResult LRQ
= LI
.Query(Idx
);
625 if (!LRQ
.valueOutOrDead()) {
626 // We have found a DBG_VALUE with the value in a virtual register that
627 // is not live. Discard the DBG_VALUE.
629 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
635 // Get or create the UserValue for (variable,offset) here.
636 bool IsIndirect
= MI
.getOperand(1).isImm();
638 assert(MI
.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
639 const DILocalVariable
*Var
= MI
.getDebugVariable();
640 const DIExpression
*Expr
= MI
.getDebugExpression();
642 getUserValue(Var
, Expr
, MI
.getDebugLoc());
644 UV
->addDef(Idx
, MI
.getOperand(0), IsIndirect
);
646 MachineOperand MO
= MachineOperand::CreateReg(0U, false);
648 UV
->addDef(Idx
, MO
, false);
653 bool LDVImpl::handleDebugLabel(MachineInstr
&MI
, SlotIndex Idx
) {
655 if (MI
.getNumOperands() != 1 || !MI
.getOperand(0).isMetadata()) {
656 LLVM_DEBUG(dbgs() << "Can't handle " << MI
);
660 // Get or create the UserLabel for label here.
661 const DILabel
*Label
= MI
.getDebugLabel();
662 const DebugLoc
&DL
= MI
.getDebugLoc();
664 for (auto const &L
: userLabels
) {
665 if (L
->match(Label
, DL
->getInlinedAt(), Idx
)) {
671 userLabels
.push_back(llvm::make_unique
<UserLabel
>(Label
, DL
, Idx
));
676 bool LDVImpl::collectDebugValues(MachineFunction
&mf
) {
677 bool Changed
= false;
678 for (MachineFunction::iterator MFI
= mf
.begin(), MFE
= mf
.end(); MFI
!= MFE
;
680 MachineBasicBlock
*MBB
= &*MFI
;
681 for (MachineBasicBlock::iterator MBBI
= MBB
->begin(), MBBE
= MBB
->end();
683 // Use the first debug instruction in the sequence to get a SlotIndex
684 // for following consecutive debug instructions.
685 if (!MBBI
->isDebugInstr()) {
689 // Debug instructions has no slot index. Use the previous
690 // non-debug instruction's SlotIndex as its SlotIndex.
693 ? LIS
->getMBBStartIdx(MBB
)
694 : LIS
->getInstructionIndex(*std::prev(MBBI
)).getRegSlot();
695 // Handle consecutive debug instructions with the same slot index.
697 // Only handle DBG_VALUE in handleDebugValue(). Skip all other
698 // kinds of debug instructions.
699 if ((MBBI
->isDebugValue() && handleDebugValue(*MBBI
, Idx
)) ||
700 (MBBI
->isDebugLabel() && handleDebugLabel(*MBBI
, Idx
))) {
701 MBBI
= MBB
->erase(MBBI
);
705 } while (MBBI
!= MBBE
&& MBBI
->isDebugInstr());
711 void UserValue::extendDef(SlotIndex Idx
, DbgValueLocation Loc
, LiveRange
*LR
,
712 const VNInfo
*VNI
, SmallVectorImpl
<SlotIndex
> *Kills
,
713 LiveIntervals
&LIS
) {
714 SlotIndex Start
= Idx
;
715 MachineBasicBlock
*MBB
= LIS
.getMBBFromIndex(Start
);
716 SlotIndex Stop
= LIS
.getMBBEndIdx(MBB
);
717 LocMap::iterator I
= locInts
.find(Start
);
719 // Limit to VNI's live range.
722 LiveInterval::Segment
*Segment
= LR
->getSegmentContaining(Start
);
723 if (!Segment
|| Segment
->valno
!= VNI
) {
725 Kills
->push_back(Start
);
728 if (Segment
->end
< Stop
) {
734 // There could already be a short def at Start.
735 if (I
.valid() && I
.start() <= Start
) {
736 // Stop when meeting a different location or an already extended interval.
737 Start
= Start
.getNextSlot();
738 if (I
.value() != Loc
|| I
.stop() != Start
)
740 // This is a one-slot placeholder. Just skip it.
744 // Limited by the next def.
745 if (I
.valid() && I
.start() < Stop
) {
749 // Limited by VNI's live range.
750 else if (!ToEnd
&& Kills
)
751 Kills
->push_back(Stop
);
754 I
.insert(Start
, Stop
, Loc
);
757 void UserValue::addDefsFromCopies(
758 LiveInterval
*LI
, unsigned LocNo
, bool WasIndirect
,
759 const SmallVectorImpl
<SlotIndex
> &Kills
,
760 SmallVectorImpl
<std::pair
<SlotIndex
, DbgValueLocation
>> &NewDefs
,
761 MachineRegisterInfo
&MRI
, LiveIntervals
&LIS
) {
764 // Don't track copies from physregs, there are too many uses.
765 if (!TargetRegisterInfo::isVirtualRegister(LI
->reg
))
768 // Collect all the (vreg, valno) pairs that are copies of LI.
769 SmallVector
<std::pair
<LiveInterval
*, const VNInfo
*>, 8> CopyValues
;
770 for (MachineOperand
&MO
: MRI
.use_nodbg_operands(LI
->reg
)) {
771 MachineInstr
*MI
= MO
.getParent();
772 // Copies of the full value.
773 if (MO
.getSubReg() || !MI
->isCopy())
775 unsigned DstReg
= MI
->getOperand(0).getReg();
777 // Don't follow copies to physregs. These are usually setting up call
778 // arguments, and the argument registers are always call clobbered. We are
779 // better off in the source register which could be a callee-saved register,
780 // or it could be spilled.
781 if (!TargetRegisterInfo::isVirtualRegister(DstReg
))
784 // Is LocNo extended to reach this copy? If not, another def may be blocking
785 // it, or we are looking at a wrong value of LI.
786 SlotIndex Idx
= LIS
.getInstructionIndex(*MI
);
787 LocMap::iterator I
= locInts
.find(Idx
.getRegSlot(true));
788 if (!I
.valid() || I
.value().locNo() != LocNo
)
791 if (!LIS
.hasInterval(DstReg
))
793 LiveInterval
*DstLI
= &LIS
.getInterval(DstReg
);
794 const VNInfo
*DstVNI
= DstLI
->getVNInfoAt(Idx
.getRegSlot());
795 assert(DstVNI
&& DstVNI
->def
== Idx
.getRegSlot() && "Bad copy value");
796 CopyValues
.push_back(std::make_pair(DstLI
, DstVNI
));
799 if (CopyValues
.empty())
802 LLVM_DEBUG(dbgs() << "Got " << CopyValues
.size() << " copies of " << *LI
805 // Try to add defs of the copied values for each kill point.
806 for (unsigned i
= 0, e
= Kills
.size(); i
!= e
; ++i
) {
807 SlotIndex Idx
= Kills
[i
];
808 for (unsigned j
= 0, e
= CopyValues
.size(); j
!= e
; ++j
) {
809 LiveInterval
*DstLI
= CopyValues
[j
].first
;
810 const VNInfo
*DstVNI
= CopyValues
[j
].second
;
811 if (DstLI
->getVNInfoAt(Idx
) != DstVNI
)
813 // Check that there isn't already a def at Idx
814 LocMap::iterator I
= locInts
.find(Idx
);
815 if (I
.valid() && I
.start() <= Idx
)
817 LLVM_DEBUG(dbgs() << "Kill at " << Idx
<< " covered by valno #"
818 << DstVNI
->id
<< " in " << *DstLI
<< '\n');
819 MachineInstr
*CopyMI
= LIS
.getInstructionFromIndex(DstVNI
->def
);
820 assert(CopyMI
&& CopyMI
->isCopy() && "Bad copy value");
821 unsigned LocNo
= getLocationNo(CopyMI
->getOperand(0));
822 DbgValueLocation
NewLoc(LocNo
, WasIndirect
);
823 I
.insert(Idx
, Idx
.getNextSlot(), NewLoc
);
824 NewDefs
.push_back(std::make_pair(Idx
, NewLoc
));
830 void UserValue::computeIntervals(MachineRegisterInfo
&MRI
,
831 const TargetRegisterInfo
&TRI
,
832 LiveIntervals
&LIS
, LexicalScopes
&LS
) {
833 SmallVector
<std::pair
<SlotIndex
, DbgValueLocation
>, 16> Defs
;
835 // Collect all defs to be extended (Skipping undefs).
836 for (LocMap::const_iterator I
= locInts
.begin(); I
.valid(); ++I
)
837 if (!I
.value().isUndef())
838 Defs
.push_back(std::make_pair(I
.start(), I
.value()));
840 // Extend all defs, and possibly add new ones along the way.
841 for (unsigned i
= 0; i
!= Defs
.size(); ++i
) {
842 SlotIndex Idx
= Defs
[i
].first
;
843 DbgValueLocation Loc
= Defs
[i
].second
;
844 const MachineOperand
&LocMO
= locations
[Loc
.locNo()];
846 if (!LocMO
.isReg()) {
847 extendDef(Idx
, Loc
, nullptr, nullptr, nullptr, LIS
);
851 // Register locations are constrained to where the register value is live.
852 if (TargetRegisterInfo::isVirtualRegister(LocMO
.getReg())) {
853 LiveInterval
*LI
= nullptr;
854 const VNInfo
*VNI
= nullptr;
855 if (LIS
.hasInterval(LocMO
.getReg())) {
856 LI
= &LIS
.getInterval(LocMO
.getReg());
857 VNI
= LI
->getVNInfoAt(Idx
);
859 SmallVector
<SlotIndex
, 16> Kills
;
860 extendDef(Idx
, Loc
, LI
, VNI
, &Kills
, LIS
);
861 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
862 // if the original location for example is %vreg0:sub_hi, and we find a
863 // full register copy in addDefsFromCopies (at the moment it only handles
864 // full register copies), then we must add the sub1 sub-register index to
865 // the new location. However, that is only possible if the new virtual
866 // register is of the same regclass (or if there is an equivalent
867 // sub-register in that regclass). For now, simply skip handling copies if
868 // a sub-register is involved.
869 if (LI
&& !LocMO
.getSubReg())
870 addDefsFromCopies(LI
, Loc
.locNo(), Loc
.wasIndirect(), Kills
, Defs
, MRI
,
875 // For physregs, we only mark the start slot idx. DwarfDebug will see it
876 // as if the DBG_VALUE is valid up until the end of the basic block, or
877 // the next def of the physical register. So we do not need to extend the
878 // range. It might actually happen that the DBG_VALUE is the last use of
879 // the physical register (e.g. if this is an unused input argument to a
883 // The computed intervals may extend beyond the range of the debug
884 // location's lexical scope. In this case, splitting of an interval
885 // can result in an interval outside of the scope being created,
886 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
887 // this, trim the intervals to the lexical scope.
889 LexicalScope
*Scope
= LS
.findLexicalScope(dl
);
894 LocMap::iterator I
= locInts
.begin();
896 // Iterate over the lexical scope ranges. Each time round the loop
897 // we check the intervals for overlap with the end of the previous
898 // range and the start of the next. The first range is handled as
899 // a special case where there is no PrevEnd.
900 for (const InsnRange
&Range
: Scope
->getRanges()) {
901 SlotIndex RStart
= LIS
.getInstructionIndex(*Range
.first
);
902 SlotIndex REnd
= LIS
.getInstructionIndex(*Range
.second
);
904 // At the start of each iteration I has been advanced so that
905 // I.stop() >= PrevEnd. Check for overlap.
906 if (PrevEnd
&& I
.start() < PrevEnd
) {
907 SlotIndex IStop
= I
.stop();
908 DbgValueLocation Loc
= I
.value();
910 // Stop overlaps previous end - trim the end of the interval to
912 I
.setStopUnchecked(PrevEnd
);
915 // If the interval also overlaps the start of the "next" (i.e.
916 // current) range create a new interval for the remainder (which
917 // may be further trimmed).
919 I
.insert(RStart
, IStop
, Loc
);
922 // Advance I so that I.stop() >= RStart, and check for overlap.
927 if (I
.start() < RStart
) {
928 // Interval start overlaps range - trim to the scope range.
929 I
.setStartUnchecked(RStart
);
930 // Remember that this interval was trimmed.
931 trimmedDefs
.insert(RStart
);
934 // The end of a lexical scope range is the last instruction in the
935 // range. To convert to an interval we need the index of the
936 // instruction after it.
937 REnd
= REnd
.getNextIndex();
939 // Advance I to first interval outside current range.
947 // Check for overlap with end of final range.
948 if (PrevEnd
&& I
.start() < PrevEnd
)
949 I
.setStopUnchecked(PrevEnd
);
952 void LDVImpl::computeIntervals() {
956 for (unsigned i
= 0, e
= userValues
.size(); i
!= e
; ++i
) {
957 userValues
[i
]->computeIntervals(MF
->getRegInfo(), *TRI
, *LIS
, LS
);
958 userValues
[i
]->mapVirtRegs(this);
962 bool LDVImpl::runOnMachineFunction(MachineFunction
&mf
) {
965 LIS
= &pass
.getAnalysis
<LiveIntervals
>();
966 TRI
= mf
.getSubtarget().getRegisterInfo();
967 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
968 << mf
.getName() << " **********\n");
970 bool Changed
= collectDebugValues(mf
);
972 LLVM_DEBUG(print(dbgs()));
973 ModifiedMF
= Changed
;
977 static void removeDebugValues(MachineFunction
&mf
) {
978 for (MachineBasicBlock
&MBB
: mf
) {
979 for (auto MBBI
= MBB
.begin(), MBBE
= MBB
.end(); MBBI
!= MBBE
; ) {
980 if (!MBBI
->isDebugValue()) {
984 MBBI
= MBB
.erase(MBBI
);
989 bool LiveDebugVariables::runOnMachineFunction(MachineFunction
&mf
) {
992 if (!mf
.getFunction().getSubprogram()) {
993 removeDebugValues(mf
);
997 pImpl
= new LDVImpl(this);
998 return static_cast<LDVImpl
*>(pImpl
)->runOnMachineFunction(mf
);
1001 void LiveDebugVariables::releaseMemory() {
1003 static_cast<LDVImpl
*>(pImpl
)->clear();
1006 LiveDebugVariables::~LiveDebugVariables() {
1008 delete static_cast<LDVImpl
*>(pImpl
);
1011 //===----------------------------------------------------------------------===//
1012 // Live Range Splitting
1013 //===----------------------------------------------------------------------===//
1016 UserValue::splitLocation(unsigned OldLocNo
, ArrayRef
<unsigned> NewRegs
,
1017 LiveIntervals
& LIS
) {
1019 dbgs() << "Splitting Loc" << OldLocNo
<< '\t';
1020 print(dbgs(), nullptr);
1022 bool DidChange
= false;
1023 LocMap::iterator LocMapI
;
1024 LocMapI
.setMap(locInts
);
1025 for (unsigned i
= 0; i
!= NewRegs
.size(); ++i
) {
1026 LiveInterval
*LI
= &LIS
.getInterval(NewRegs
[i
]);
1030 // Don't allocate the new LocNo until it is needed.
1031 unsigned NewLocNo
= UndefLocNo
;
1033 // Iterate over the overlaps between locInts and LI.
1034 LocMapI
.find(LI
->beginIndex());
1035 if (!LocMapI
.valid())
1037 LiveInterval::iterator LII
= LI
->advanceTo(LI
->begin(), LocMapI
.start());
1038 LiveInterval::iterator LIE
= LI
->end();
1039 while (LocMapI
.valid() && LII
!= LIE
) {
1040 // At this point, we know that LocMapI.stop() > LII->start.
1041 LII
= LI
->advanceTo(LII
, LocMapI
.start());
1045 // Now LII->end > LocMapI.start(). Do we have an overlap?
1046 if (LocMapI
.value().locNo() == OldLocNo
&& LII
->start
< LocMapI
.stop()) {
1047 // Overlapping correct location. Allocate NewLocNo now.
1048 if (NewLocNo
== UndefLocNo
) {
1049 MachineOperand MO
= MachineOperand::CreateReg(LI
->reg
, false);
1050 MO
.setSubReg(locations
[OldLocNo
].getSubReg());
1051 NewLocNo
= getLocationNo(MO
);
1055 SlotIndex LStart
= LocMapI
.start();
1056 SlotIndex LStop
= LocMapI
.stop();
1057 DbgValueLocation OldLoc
= LocMapI
.value();
1059 // Trim LocMapI down to the LII overlap.
1060 if (LStart
< LII
->start
)
1061 LocMapI
.setStartUnchecked(LII
->start
);
1062 if (LStop
> LII
->end
)
1063 LocMapI
.setStopUnchecked(LII
->end
);
1065 // Change the value in the overlap. This may trigger coalescing.
1066 LocMapI
.setValue(OldLoc
.changeLocNo(NewLocNo
));
1068 // Re-insert any removed OldLocNo ranges.
1069 if (LStart
< LocMapI
.start()) {
1070 LocMapI
.insert(LStart
, LocMapI
.start(), OldLoc
);
1072 assert(LocMapI
.valid() && "Unexpected coalescing");
1074 if (LStop
> LocMapI
.stop()) {
1076 LocMapI
.insert(LII
->end
, LStop
, OldLoc
);
1081 // Advance to the next overlap.
1082 if (LII
->end
< LocMapI
.stop()) {
1085 LocMapI
.advanceTo(LII
->start
);
1088 if (!LocMapI
.valid())
1090 LII
= LI
->advanceTo(LII
, LocMapI
.start());
1095 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
1096 locations
.erase(locations
.begin() + OldLocNo
);
1097 LocMapI
.goToBegin();
1098 while (LocMapI
.valid()) {
1099 DbgValueLocation v
= LocMapI
.value();
1100 if (v
.locNo() == OldLocNo
) {
1101 LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI
.start() << ';'
1102 << LocMapI
.stop() << ")\n");
1105 // Undef values always have location number UndefLocNo, so don't change
1106 // locNo in that case. See getLocationNo().
1107 if (!v
.isUndef() && v
.locNo() > OldLocNo
)
1108 LocMapI
.setValueUnchecked(v
.changeLocNo(v
.locNo() - 1));
1114 dbgs() << "Split result: \t";
1115 print(dbgs(), nullptr);
1121 UserValue::splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
,
1122 LiveIntervals
&LIS
) {
1123 bool DidChange
= false;
1124 // Split locations referring to OldReg. Iterate backwards so splitLocation can
1125 // safely erase unused locations.
1126 for (unsigned i
= locations
.size(); i
; --i
) {
1127 unsigned LocNo
= i
-1;
1128 const MachineOperand
*Loc
= &locations
[LocNo
];
1129 if (!Loc
->isReg() || Loc
->getReg() != OldReg
)
1131 DidChange
|= splitLocation(LocNo
, NewRegs
, LIS
);
1136 void LDVImpl::splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
) {
1137 bool DidChange
= false;
1138 for (UserValue
*UV
= lookupVirtReg(OldReg
); UV
; UV
= UV
->getNext())
1139 DidChange
|= UV
->splitRegister(OldReg
, NewRegs
, *LIS
);
1144 // Map all of the new virtual registers.
1145 UserValue
*UV
= lookupVirtReg(OldReg
);
1146 for (unsigned i
= 0; i
!= NewRegs
.size(); ++i
)
1147 mapVirtReg(NewRegs
[i
], UV
);
1150 void LiveDebugVariables::
1151 splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
, LiveIntervals
&LIS
) {
1153 static_cast<LDVImpl
*>(pImpl
)->splitRegister(OldReg
, NewRegs
);
1156 void UserValue::rewriteLocations(VirtRegMap
&VRM
, const MachineFunction
&MF
,
1157 const TargetInstrInfo
&TII
,
1158 const TargetRegisterInfo
&TRI
,
1159 SpillOffsetMap
&SpillOffsets
) {
1160 // Build a set of new locations with new numbers so we can coalesce our
1161 // IntervalMap if two vreg intervals collapse to the same physical location.
1162 // Use MapVector instead of SetVector because MapVector::insert returns the
1163 // position of the previously or newly inserted element. The boolean value
1164 // tracks if the location was produced by a spill.
1165 // FIXME: This will be problematic if we ever support direct and indirect
1166 // frame index locations, i.e. expressing both variables in memory and
1167 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1168 MapVector
<MachineOperand
, std::pair
<bool, unsigned>> NewLocations
;
1169 SmallVector
<unsigned, 4> LocNoMap(locations
.size());
1170 for (unsigned I
= 0, E
= locations
.size(); I
!= E
; ++I
) {
1171 bool Spilled
= false;
1172 unsigned SpillOffset
= 0;
1173 MachineOperand Loc
= locations
[I
];
1174 // Only virtual registers are rewritten.
1175 if (Loc
.isReg() && Loc
.getReg() &&
1176 TargetRegisterInfo::isVirtualRegister(Loc
.getReg())) {
1177 unsigned VirtReg
= Loc
.getReg();
1178 if (VRM
.isAssignedReg(VirtReg
) &&
1179 TargetRegisterInfo::isPhysicalRegister(VRM
.getPhys(VirtReg
))) {
1180 // This can create a %noreg operand in rare cases when the sub-register
1181 // index is no longer available. That means the user value is in a
1182 // non-existent sub-register, and %noreg is exactly what we want.
1183 Loc
.substPhysReg(VRM
.getPhys(VirtReg
), TRI
);
1184 } else if (VRM
.getStackSlot(VirtReg
) != VirtRegMap::NO_STACK_SLOT
) {
1185 // Retrieve the stack slot offset.
1187 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1188 const TargetRegisterClass
*TRC
= MRI
.getRegClass(VirtReg
);
1189 bool Success
= TII
.getStackSlotRange(TRC
, Loc
.getSubReg(), SpillSize
,
1192 // FIXME: Invalidate the location if the offset couldn't be calculated.
1195 Loc
= MachineOperand::CreateFI(VRM
.getStackSlot(VirtReg
));
1203 // Insert this location if it doesn't already exist and record a mapping
1204 // from the old number to the new number.
1205 auto InsertResult
= NewLocations
.insert({Loc
, {Spilled
, SpillOffset
}});
1206 unsigned NewLocNo
= std::distance(NewLocations
.begin(), InsertResult
.first
);
1207 LocNoMap
[I
] = NewLocNo
;
1210 // Rewrite the locations and record the stack slot offsets for spills.
1212 SpillOffsets
.clear();
1213 for (auto &Pair
: NewLocations
) {
1215 unsigned SpillOffset
;
1216 std::tie(Spilled
, SpillOffset
) = Pair
.second
;
1217 locations
.push_back(Pair
.first
);
1219 unsigned NewLocNo
= std::distance(&*NewLocations
.begin(), &Pair
);
1220 SpillOffsets
[NewLocNo
] = SpillOffset
;
1224 // Update the interval map, but only coalesce left, since intervals to the
1225 // right use the old location numbers. This should merge two contiguous
1226 // DBG_VALUE intervals with different vregs that were allocated to the same
1227 // physical register.
1228 for (LocMap::iterator I
= locInts
.begin(); I
.valid(); ++I
) {
1229 DbgValueLocation Loc
= I
.value();
1230 // Undef values don't exist in locations (and thus not in LocNoMap either)
1231 // so skip over them. See getLocationNo().
1234 unsigned NewLocNo
= LocNoMap
[Loc
.locNo()];
1235 I
.setValueUnchecked(Loc
.changeLocNo(NewLocNo
));
1236 I
.setStart(I
.start());
1240 /// Find an iterator for inserting a DBG_VALUE instruction.
1241 static MachineBasicBlock::iterator
1242 findInsertLocation(MachineBasicBlock
*MBB
, SlotIndex Idx
,
1243 LiveIntervals
&LIS
) {
1244 SlotIndex Start
= LIS
.getMBBStartIdx(MBB
);
1245 Idx
= Idx
.getBaseIndex();
1247 // Try to find an insert location by going backwards from Idx.
1249 while (!(MI
= LIS
.getInstructionFromIndex(Idx
))) {
1250 // We've reached the beginning of MBB.
1252 MachineBasicBlock::iterator I
= MBB
->SkipPHIsLabelsAndDebug(MBB
->begin());
1255 Idx
= Idx
.getPrevIndex();
1258 // Don't insert anything after the first terminator, though.
1259 return MI
->isTerminator() ? MBB
->getFirstTerminator() :
1260 std::next(MachineBasicBlock::iterator(MI
));
1263 /// Find an iterator for inserting the next DBG_VALUE instruction
1264 /// (or end if no more insert locations found).
1265 static MachineBasicBlock::iterator
1266 findNextInsertLocation(MachineBasicBlock
*MBB
,
1267 MachineBasicBlock::iterator I
,
1268 SlotIndex StopIdx
, MachineOperand
&LocMO
,
1270 const TargetRegisterInfo
&TRI
) {
1272 return MBB
->instr_end();
1273 unsigned Reg
= LocMO
.getReg();
1275 // Find the next instruction in the MBB that define the register Reg.
1276 while (I
!= MBB
->end() && !I
->isTerminator()) {
1277 if (!LIS
.isNotInMIMap(*I
) &&
1278 SlotIndex::isEarlierEqualInstr(StopIdx
, LIS
.getInstructionIndex(*I
)))
1280 if (I
->definesRegister(Reg
, &TRI
))
1281 // The insert location is directly after the instruction/bundle.
1282 return std::next(I
);
1288 void UserValue::insertDebugValue(MachineBasicBlock
*MBB
, SlotIndex StartIdx
,
1289 SlotIndex StopIdx
, DbgValueLocation Loc
,
1290 bool Spilled
, unsigned SpillOffset
,
1291 LiveIntervals
&LIS
, const TargetInstrInfo
&TII
,
1292 const TargetRegisterInfo
&TRI
) {
1293 SlotIndex MBBEndIdx
= LIS
.getMBBEndIdx(&*MBB
);
1294 // Only search within the current MBB.
1295 StopIdx
= (MBBEndIdx
< StopIdx
) ? MBBEndIdx
: StopIdx
;
1296 MachineBasicBlock::iterator I
= findInsertLocation(MBB
, StartIdx
, LIS
);
1297 // Undef values don't exist in locations so create new "noreg" register MOs
1298 // for them. See getLocationNo().
1299 MachineOperand MO
= !Loc
.isUndef() ?
1300 locations
[Loc
.locNo()] :
1301 MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1302 /* isKill */ false, /* isDead */ false,
1303 /* isUndef */ false, /* isEarlyClobber */ false,
1304 /* SubReg */ 0, /* isDebug */ true);
1306 ++NumInsertedDebugValues
;
1308 assert(cast
<DILocalVariable
>(Variable
)
1309 ->isValidLocationForIntrinsic(getDebugLoc()) &&
1310 "Expected inlined-at fields to agree");
1312 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1313 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1314 // that the original virtual register was a pointer. Also, add the stack slot
1315 // offset for the spilled register to the expression.
1316 const DIExpression
*Expr
= Expression
;
1317 bool IsIndirect
= Loc
.wasIndirect();
1319 auto Deref
= IsIndirect
? DIExpression::WithDeref
: DIExpression::NoDeref
;
1321 DIExpression::prepend(Expr
, DIExpression::NoDeref
, SpillOffset
, Deref
);
1325 assert((!Spilled
|| MO
.isFI()) && "a spilled location must be a frame index");
1328 BuildMI(*MBB
, I
, getDebugLoc(), TII
.get(TargetOpcode::DBG_VALUE
),
1329 IsIndirect
, MO
, Variable
, Expr
);
1331 // Continue and insert DBG_VALUES after every redefinition of register
1332 // associated with the debug value within the range
1333 I
= findNextInsertLocation(MBB
, I
, StopIdx
, MO
, LIS
, TRI
);
1334 } while (I
!= MBB
->end());
1337 void UserLabel::insertDebugLabel(MachineBasicBlock
*MBB
, SlotIndex Idx
,
1339 const TargetInstrInfo
&TII
) {
1340 MachineBasicBlock::iterator I
= findInsertLocation(MBB
, Idx
, LIS
);
1341 ++NumInsertedDebugLabels
;
1342 BuildMI(*MBB
, I
, getDebugLoc(), TII
.get(TargetOpcode::DBG_LABEL
))
1343 .addMetadata(Label
);
1346 void UserValue::emitDebugValues(VirtRegMap
*VRM
, LiveIntervals
&LIS
,
1347 const TargetInstrInfo
&TII
,
1348 const TargetRegisterInfo
&TRI
,
1349 const SpillOffsetMap
&SpillOffsets
) {
1350 MachineFunction::iterator MFEnd
= VRM
->getMachineFunction().end();
1352 for (LocMap::const_iterator I
= locInts
.begin(); I
.valid();) {
1353 SlotIndex Start
= I
.start();
1354 SlotIndex Stop
= I
.stop();
1355 DbgValueLocation Loc
= I
.value();
1357 !Loc
.isUndef() ? SpillOffsets
.find(Loc
.locNo()) : SpillOffsets
.end();
1358 bool Spilled
= SpillIt
!= SpillOffsets
.end();
1359 unsigned SpillOffset
= Spilled
? SpillIt
->second
: 0;
1361 // If the interval start was trimmed to the lexical scope insert the
1362 // DBG_VALUE at the previous index (otherwise it appears after the
1363 // first instruction in the range).
1364 if (trimmedDefs
.count(Start
))
1365 Start
= Start
.getPrevIndex();
1367 LLVM_DEBUG(dbgs() << "\t[" << Start
<< ';' << Stop
<< "):" << Loc
.locNo());
1368 MachineFunction::iterator MBB
= LIS
.getMBBFromIndex(Start
)->getIterator();
1369 SlotIndex MBBEnd
= LIS
.getMBBEndIdx(&*MBB
);
1371 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB
) << '-' << MBBEnd
);
1372 insertDebugValue(&*MBB
, Start
, Stop
, Loc
, Spilled
, SpillOffset
, LIS
, TII
,
1374 // This interval may span multiple basic blocks.
1375 // Insert a DBG_VALUE into each one.
1376 while (Stop
> MBBEnd
) {
1377 // Move to the next block.
1381 MBBEnd
= LIS
.getMBBEndIdx(&*MBB
);
1382 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB
) << '-' << MBBEnd
);
1383 insertDebugValue(&*MBB
, Start
, Stop
, Loc
, Spilled
, SpillOffset
, LIS
, TII
,
1386 LLVM_DEBUG(dbgs() << '\n');
1394 void UserLabel::emitDebugLabel(LiveIntervals
&LIS
, const TargetInstrInfo
&TII
) {
1395 LLVM_DEBUG(dbgs() << "\t" << loc
);
1396 MachineFunction::iterator MBB
= LIS
.getMBBFromIndex(loc
)->getIterator();
1398 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB
));
1399 insertDebugLabel(&*MBB
, loc
, LIS
, TII
);
1401 LLVM_DEBUG(dbgs() << '\n');
1404 void LDVImpl::emitDebugValues(VirtRegMap
*VRM
) {
1405 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1408 const TargetInstrInfo
*TII
= MF
->getSubtarget().getInstrInfo();
1409 SpillOffsetMap SpillOffsets
;
1410 for (auto &userValue
: userValues
) {
1411 LLVM_DEBUG(userValue
->print(dbgs(), TRI
));
1412 userValue
->rewriteLocations(*VRM
, *MF
, *TII
, *TRI
, SpillOffsets
);
1413 userValue
->emitDebugValues(VRM
, *LIS
, *TII
, *TRI
, SpillOffsets
);
1415 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1416 for (auto &userLabel
: userLabels
) {
1417 LLVM_DEBUG(userLabel
->print(dbgs(), TRI
));
1418 userLabel
->emitDebugLabel(*LIS
, *TII
);
1423 void LiveDebugVariables::emitDebugValues(VirtRegMap
*VRM
) {
1425 static_cast<LDVImpl
*>(pImpl
)->emitDebugValues(VRM
);
1428 bool LiveDebugVariables::doInitialization(Module
&M
) {
1429 return Pass::doInitialization(M
);
1432 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1433 LLVM_DUMP_METHOD
void LiveDebugVariables::dump() const {
1435 static_cast<LDVImpl
*>(pImpl
)->print(dbgs());