1//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the LiveDebugVariables analysis.
10//
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.
14//
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.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/CodeGen/LiveDebugVariables.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/IntervalMap.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/BinaryFormat/Dwarf.h"
32#include "llvm/CodeGen/LexicalScopes.h"
33#include "llvm/CodeGen/LiveInterval.h"
34#include "llvm/CodeGen/LiveIntervals.h"
35#include "llvm/CodeGen/MachineBasicBlock.h"
36#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
38#include "llvm/CodeGen/MachineInstrBuilder.h"
39#include "llvm/CodeGen/MachineOperand.h"
40#include "llvm/CodeGen/MachinePassManager.h"
41#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/SlotIndexes.h"
43#include "llvm/CodeGen/TargetInstrInfo.h"
44#include "llvm/CodeGen/TargetOpcodes.h"
45#include "llvm/CodeGen/TargetRegisterInfo.h"
46#include "llvm/CodeGen/TargetSubtargetInfo.h"
47#include "llvm/CodeGen/VirtRegMap.h"
48#include "llvm/Config/llvm-config.h"
49#include "llvm/IR/DebugInfoMetadata.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Function.h"
52#include "llvm/InitializePasses.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
58#include <algorithm>
59#include <cassert>
60#include <iterator>
61#include <map>
62#include <memory>
63#include <optional>
64#include <utility>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "livedebugvars"
69
70static cl::opt<bool>
71EnableLDV("live-debug-variables", cl::init(Val: true),
72 cl::desc("Enable the live debug variables pass"), cl::Hidden);
73
74STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
75STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
76STATISTIC(NumStaleIndexes, "Number of stale SlotIndexes repaired");
77STATISTIC(NumMergedIntervals,
78 "Number of debug value intervals merged while repairing indexes");
79
80char LiveDebugVariablesWrapperLegacy::ID = 0;
81
82INITIALIZE_PASS_BEGIN(LiveDebugVariablesWrapperLegacy, DEBUG_TYPE,
83 "Debug Variable Analysis", false, false)
84INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
85INITIALIZE_PASS_END(LiveDebugVariablesWrapperLegacy, DEBUG_TYPE,
86 "Debug Variable Analysis", false, true)
87
88void LiveDebugVariablesWrapperLegacy::getAnalysisUsage(
89 AnalysisUsage &AU) const {
90 AU.addRequiredTransitive<LiveIntervalsWrapperPass>();
91 AU.setPreservesAll();
92 MachineFunctionPass::getAnalysisUsage(AU);
93}
94
95LiveDebugVariablesWrapperLegacy::LiveDebugVariablesWrapperLegacy()
96 : MachineFunctionPass(ID) {}
97
98enum : unsigned { UndefLocNo = ~0U };
99
100namespace {
101/// Describes a debug variable value by location number and expression along
102/// with some flags about the original usage of the location.
103class DbgVariableValue {
104public:
105 DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
106 const DIExpression &Expr)
107 : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
108 assert(!(WasIndirect && WasList) &&
109 "DBG_VALUE_LISTs should not be indirect.");
110 SmallVector<unsigned> LocNoVec;
111 for (unsigned LocNo : NewLocs) {
112 auto It = find(Range&: LocNoVec, Val: LocNo);
113 if (It == LocNoVec.end())
114 LocNoVec.push_back(Elt: LocNo);
115 else {
116 // Loc duplicates an element in LocNos; replace references to Op
117 // with references to the duplicating element.
118 unsigned OpIdx = LocNoVec.size();
119 unsigned DuplicatingIdx = std::distance(first: LocNoVec.begin(), last: It);
120 Expression =
121 DIExpression::replaceArg(Expr: Expression, OldArg: OpIdx, NewArg: DuplicatingIdx);
122 }
123 }
124 // FIXME: Debug values referencing 64+ unique machine locations are rare and
125 // currently unsupported for performance reasons. If we can verify that
126 // performance is acceptable for such debug values, we can increase the
127 // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
128 // locations. We will also need to verify that this does not cause issues
129 // with LiveDebugVariables' use of IntervalMap.
130 if (LocNoVec.size() < 64) {
131 LocNoCount = LocNoVec.size();
132 if (LocNoCount > 0) {
133 LocNos = std::make_unique<unsigned[]>(num: LocNoCount);
134 llvm::copy(Range&: LocNoVec, Out: loc_nos_begin());
135 }
136 } else {
137 LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
138 "locations, dropping...\n");
139 LocNoCount = 1;
140 // Turn this into an undef debug value list; right now, the simplest form
141 // of this is an expression with one arg, and an undef debug operand.
142 Expression =
143 DIExpression::get(Context&: Expr.getContext(), Elements: {dwarf::DW_OP_LLVM_arg, 0});
144 if (auto FragmentInfoOpt = Expr.getFragmentInfo())
145 Expression = *DIExpression::createFragmentExpression(
146 Expr: Expression, OffsetInBits: FragmentInfoOpt->OffsetInBits,
147 SizeInBits: FragmentInfoOpt->SizeInBits);
148 LocNos = std::make_unique<unsigned[]>(num: LocNoCount);
149 LocNos[0] = UndefLocNo;
150 }
151 }
152
153 DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
154 DbgVariableValue(const DbgVariableValue &Other)
155 : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
156 WasList(Other.getWasList()), Expression(Other.getExpression()) {
157 if (Other.getLocNoCount()) {
158 LocNos.reset(p: new unsigned[Other.getLocNoCount()]);
159 std::copy(first: Other.loc_nos_begin(), last: Other.loc_nos_end(), result: loc_nos_begin());
160 }
161 }
162
163 DbgVariableValue &operator=(const DbgVariableValue &Other) {
164 if (this == &Other)
165 return *this;
166 if (Other.getLocNoCount()) {
167 LocNos.reset(p: new unsigned[Other.getLocNoCount()]);
168 std::copy(first: Other.loc_nos_begin(), last: Other.loc_nos_end(), result: loc_nos_begin());
169 } else {
170 LocNos.release();
171 }
172 LocNoCount = Other.getLocNoCount();
173 WasIndirect = Other.getWasIndirect();
174 WasList = Other.getWasList();
175 Expression = Other.getExpression();
176 return *this;
177 }
178
179 const DIExpression *getExpression() const { return Expression; }
180 uint8_t getLocNoCount() const { return LocNoCount; }
181 bool containsLocNo(unsigned LocNo) const {
182 return is_contained(Range: loc_nos(), Element: LocNo);
183 }
184 bool getWasIndirect() const { return WasIndirect; }
185 bool getWasList() const { return WasList; }
186 bool isUndef() const { return LocNoCount == 0 || containsLocNo(LocNo: UndefLocNo); }
187
188 DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
189 SmallVector<unsigned, 4> NewLocNos;
190 for (unsigned LocNo : loc_nos())
191 NewLocNos.push_back(Elt: LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
192 : LocNo);
193 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
194 }
195
196 DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
197 SmallVector<unsigned> NewLocNos;
198 for (unsigned LocNo : loc_nos())
199 // Undef values don't exist in locations (and thus not in LocNoMap
200 // either) so skip over them. See getLocationNo().
201 NewLocNos.push_back(Elt: LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
202 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
203 }
204
205 DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
206 SmallVector<unsigned> NewLocNos;
207 NewLocNos.assign(in_start: loc_nos_begin(), in_end: loc_nos_end());
208 auto OldLocIt = find(Range&: NewLocNos, Val: OldLocNo);
209 assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
210 *OldLocIt = NewLocNo;
211 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
212 }
213
214 bool hasLocNoGreaterThan(unsigned LocNo) const {
215 return any_of(Range: loc_nos(),
216 P: [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
217 }
218
219 void printLocNos(llvm::raw_ostream &OS) const {
220 for (const unsigned &Loc : loc_nos())
221 OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
222 }
223
224 friend inline bool operator==(const DbgVariableValue &LHS,
225 const DbgVariableValue &RHS) {
226 if (std::tie(args: LHS.LocNoCount, args: LHS.WasIndirect, args: LHS.WasList,
227 args: LHS.Expression) !=
228 std::tie(args: RHS.LocNoCount, args: RHS.WasIndirect, args: RHS.WasList, args: RHS.Expression))
229 return false;
230 return std::equal(first1: LHS.loc_nos_begin(), last1: LHS.loc_nos_end(),
231 first2: RHS.loc_nos_begin());
232 }
233
234 friend inline bool operator!=(const DbgVariableValue &LHS,
235 const DbgVariableValue &RHS) {
236 return !(LHS == RHS);
237 }
238
239 unsigned *loc_nos_begin() { return LocNos.get(); }
240 const unsigned *loc_nos_begin() const { return LocNos.get(); }
241 unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
242 const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
243 ArrayRef<unsigned> loc_nos() const {
244 return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
245 }
246
247private:
248 // IntervalMap requires the value object to be very small, to the extent
249 // that we do not have enough room for an std::vector. Using a C-style array
250 // (with a unique_ptr wrapper for convenience) allows us to optimize for this
251 // specific case by packing the array size into only 6 bits (it is highly
252 // unlikely that any debug value will need 64+ locations).
253 std::unique_ptr<unsigned[]> LocNos;
254 uint8_t LocNoCount : 6;
255 bool WasIndirect : 1;
256 bool WasList : 1;
257 const DIExpression *Expression = nullptr;
258};
259} // namespace
260
261/// Map of where a user value is live to that value.
262using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
263
264/// Map of stack slot offsets for spilled locations.
265/// Non-spilled locations are not added to the map.
266using SpillOffsetMap = DenseMap<unsigned, unsigned>;
267
268/// Cache to save the location where it can be used as the starting
269/// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
270/// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
271/// repeatedly searching the same set of PHIs/Labels/Debug instructions
272/// if it is called many times for the same block.
273using BlockSkipInstsMap =
274 DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
275
276namespace {
277
278/// A user value is a part of a debug info user variable.
279///
280/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
281/// holds part of a user variable. The part is identified by a byte offset.
282///
283/// UserValues are grouped into equivalence classes for easier searching. Two
284/// user values are related if they are held by the same virtual register. The
285/// equivalence class is the transitive closure of that relation.
286class UserValue {
287 using LDVImpl = LiveDebugVariables::LDVImpl;
288
289 const DILocalVariable *Variable; ///< The debug info variable we are part of.
290 /// The part of the variable we describe.
291 const std::optional<DIExpression::FragmentInfo> Fragment;
292 DebugLoc dl; ///< The debug location for the variable. This is
293 ///< used by dwarf writer to find lexical scope.
294 UserValue *leader; ///< Equivalence class leader.
295 UserValue *next = nullptr; ///< Next value in equivalence class, or null.
296
297 /// Numbered locations referenced by locmap.
298 SmallVector<MachineOperand, 4> locations;
299
300 /// Map of slot indices where this value is live.
301 LocMap locInts;
302
303 /// Set of interval start indexes that have been trimmed to the
304 /// lexical scope.
305 SmallSet<SlotIndex, 2> trimmedDefs;
306
307 /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
308 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
309 SlotIndex StopIdx, DbgVariableValue DbgValue,
310 ArrayRef<bool> LocSpills,
311 ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
312 const TargetInstrInfo &TII,
313 const TargetRegisterInfo &TRI,
314 BlockSkipInstsMap &BBSkipInstsMap);
315
316 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
317 /// is live. Returns true if any changes were made.
318 bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
319 LiveIntervals &LIS);
320
321public:
322 /// Create a new UserValue.
323 UserValue(const DILocalVariable *var,
324 std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
325 LocMap::Allocator &alloc)
326 : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
327 locInts(alloc) {}
328
329 /// Get the leader of this value's equivalence class.
330 UserValue *getLeader() {
331 UserValue *l = leader;
332 while (l != l->leader)
333 l = l->leader;
334 return leader = l;
335 }
336
337 /// Return the next UserValue in the equivalence class.
338 UserValue *getNext() const { return next; }
339
340 /// Merge equivalence classes.
341 static UserValue *merge(UserValue *L1, UserValue *L2) {
342 L2 = L2->getLeader();
343 if (!L1)
344 return L2;
345 L1 = L1->getLeader();
346 if (L1 == L2)
347 return L1;
348 // Splice L2 before L1's members.
349 UserValue *End = L2;
350 while (End->next) {
351 End->leader = L1;
352 End = End->next;
353 }
354 End->leader = L1;
355 End->next = L1->next;
356 L1->next = L2;
357 return L1;
358 }
359
360 /// Return the location number that matches Loc.
361 ///
362 /// For undef values we always return location number UndefLocNo without
363 /// inserting anything in locations. Since locations is a vector and the
364 /// location number is the position in the vector and UndefLocNo is ~0,
365 /// we would need a very big vector to put the value at the right position.
366 unsigned getLocationNo(const MachineOperand &LocMO) {
367 if (LocMO.isReg()) {
368 if (LocMO.getReg() == 0)
369 return UndefLocNo;
370 // For register locations we dont care about use/def and other flags.
371 for (unsigned i = 0, e = locations.size(); i != e; ++i)
372 if (locations[i].isReg() &&
373 locations[i].getReg() == LocMO.getReg() &&
374 locations[i].getSubReg() == LocMO.getSubReg())
375 return i;
376 } else
377 for (unsigned i = 0, e = locations.size(); i != e; ++i)
378 if (LocMO.isIdenticalTo(Other: locations[i]))
379 return i;
380 locations.push_back(Elt: LocMO);
381 // We are storing a MachineOperand outside a MachineInstr.
382 locations.back().clearParent();
383 // Don't store def operands.
384 if (locations.back().isReg()) {
385 if (locations.back().isDef())
386 locations.back().setIsDead(false);
387 locations.back().setIsUse();
388 }
389 return locations.size() - 1;
390 }
391
392 /// Remove (recycle) a location number. If \p LocNo still is used by the
393 /// locInts nothing is done.
394 void removeLocationIfUnused(unsigned LocNo) {
395 // Bail out if LocNo still is used.
396 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
397 const DbgVariableValue &DbgValue = I.value();
398 if (DbgValue.containsLocNo(LocNo))
399 return;
400 }
401 // Remove the entry in the locations vector, and adjust all references to
402 // location numbers above the removed entry.
403 locations.erase(CI: locations.begin() + LocNo);
404 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
405 const DbgVariableValue &DbgValue = I.value();
406 if (DbgValue.hasLocNoGreaterThan(LocNo))
407 I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(Pivot: LocNo));
408 }
409 }
410
411 /// Ensure that all virtual register locations are mapped.
412 void mapVirtRegs(LDVImpl *LDV);
413
414 /// Add a definition point to this user value.
415 void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
416 bool IsList, const DIExpression &Expr) {
417 SmallVector<unsigned> Locs;
418 for (const MachineOperand &Op : LocMOs)
419 Locs.push_back(Elt: getLocationNo(LocMO: Op));
420 DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
421 // Add a singular (Idx,Idx) -> value mapping.
422 LocMap::iterator I = locInts.find(x: Idx);
423 if (!I.valid() || I.start() != Idx)
424 I.insert(a: Idx, b: Idx.getNextSlot(), y: std::move(DbgValue));
425 else
426 // A later DBG_VALUE at the same SlotIndex overrides the old location.
427 I.setValue(std::move(DbgValue));
428 }
429
430 /// Extend the current definition as far as possible down.
431 ///
432 /// Stop when meeting an existing def or when leaving the live
433 /// range of VNI. End points where VNI is no longer live are added to Kills.
434 ///
435 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
436 /// data-flow analysis to propagate them beyond basic block boundaries.
437 ///
438 /// \param Idx Starting point for the definition.
439 /// \param DbgValue value to propagate.
440 /// \param LiveIntervalInfo For each location number key in this map,
441 /// restricts liveness to where the LiveRange has the value equal to the\
442 /// VNInfo.
443 /// \param [out] Kills Append end points of VNI's live range to Kills.
444 /// \param LIS Live intervals analysis.
445 void
446 extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
447 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
448 &LiveIntervalInfo,
449 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
450 LiveIntervals &LIS);
451
452 /// The value in LI may be copies to other registers. Determine if
453 /// any of the copies are available at the kill points, and add defs if
454 /// possible.
455 ///
456 /// \param DbgValue Location number of LI->reg, and DIExpression.
457 /// \param LocIntervals Scan for copies of the value for each location in the
458 /// corresponding LiveInterval->reg.
459 /// \param KilledAt The point where the range of DbgValue could be extended.
460 /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
461 void addDefsFromCopies(
462 DbgVariableValue DbgValue,
463 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
464 SlotIndex KilledAt,
465 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
466 MachineRegisterInfo &MRI, LiveIntervals &LIS);
467
468 /// Compute the live intervals of all locations after collecting all their
469 /// def points.
470 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
471 LiveIntervals &LIS, LexicalScopes &LS);
472
473 /// Replace OldReg ranges with NewRegs ranges where NewRegs is
474 /// live. Returns true if any changes were made.
475 bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
476 LiveIntervals &LIS);
477
478 /// Replace the stale indexes in locInts and trimmedDefs.
479 void canonicalizeIndexes(const SlotIndexes &SI);
480
481 /// Rewrite virtual register locations according to the provided virtual
482 /// register map. Record the stack slot offsets for the locations that
483 /// were spilled.
484 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
485 const TargetInstrInfo &TII,
486 const TargetRegisterInfo &TRI,
487 SpillOffsetMap &SpillOffsets);
488
489 /// Recreate DBG_VALUE instruction from data structures.
490 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
491 const TargetInstrInfo &TII,
492 const TargetRegisterInfo &TRI,
493 const SpillOffsetMap &SpillOffsets,
494 BlockSkipInstsMap &BBSkipInstsMap);
495
496 /// Return DebugLoc of this UserValue.
497 const DebugLoc &getDebugLoc() { return dl; }
498
499 void print(raw_ostream &, const TargetRegisterInfo *);
500};
501
502/// A user label is a part of a debug info user label.
503class UserLabel {
504 const DILabel *Label; ///< The debug info label we are part of.
505 DebugLoc dl; ///< The debug location for the label. This is
506 ///< used by dwarf writer to find lexical scope.
507 SlotIndex loc; ///< Slot used by the debug label.
508
509 /// Insert a DBG_LABEL into MBB at Idx.
510 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
511 LiveIntervals &LIS, const TargetInstrInfo &TII,
512 BlockSkipInstsMap &BBSkipInstsMap);
513
514public:
515 /// Create a new UserLabel.
516 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
517 : Label(label), dl(std::move(L)), loc(Idx) {}
518
519 /// Does this UserLabel match the parameters?
520 bool matches(const DILabel *L, const DILocation *IA,
521 const SlotIndex Index) const {
522 return Label == L && dl->getInlinedAt() == IA && loc == Index;
523 }
524
525 /// Recreate DBG_LABEL instruction from data structures.
526 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
527 BlockSkipInstsMap &BBSkipInstsMap);
528
529 /// Replace loc if it is stale, and report whether it was.
530 bool canonicalizeIndex(const SlotIndexes &SI) {
531 bool WasStale = SI.isStaleIndex(Idx: loc);
532 loc = SI.canonicalizeIndex(Idx: loc);
533 assert(!SI.isStaleIndex(loc) &&
534 "Canonicalized label still refers to an erased instruction");
535 return WasStale;
536 }
537
538 /// Return DebugLoc of this UserLabel.
539 const DebugLoc &getDebugLoc() { return dl; }
540
541 void print(raw_ostream &, const TargetRegisterInfo *);
542};
543
544} // end anonymous namespace
545
546namespace llvm {
547
548class LiveDebugVariables::LDVImpl {
549 LocMap::Allocator allocator;
550 MachineFunction *MF = nullptr;
551 LiveIntervals *LIS;
552 const TargetRegisterInfo *TRI;
553
554 /// Position and VReg of a PHI instruction during register allocation.
555 struct PHIValPos {
556 SlotIndex SI; /// Slot where this PHI occurs.
557 Register Reg; /// VReg this PHI occurs in.
558 unsigned SubReg; /// Qualifiying subregister for Reg.
559 };
560
561 /// Map from debug instruction number to PHI position during allocation.
562 std::map<unsigned, PHIValPos> PHIValToPos;
563 /// Index of, for each VReg, which debug instruction numbers and corresponding
564 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
565 /// at different positions.
566 DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
567
568 /// Record for any debug instructions unlinked from their blocks during
569 /// regalloc. Stores the instr and it's location, so that they can be
570 /// re-inserted after regalloc is over.
571 struct InstrPos {
572 MachineInstr *MI; ///< Debug instruction, unlinked from it's block.
573 SlotIndex Idx; ///< Slot position where MI should be re-inserted.
574 MachineBasicBlock *MBB; ///< Block that MI was in.
575 };
576
577 /// Collection of stored debug instructions, preserved until after regalloc.
578 SmallVector<InstrPos, 32> StashedDebugInstrs;
579
580 /// Whether emitDebugValues is called.
581 bool EmitDone = false;
582
583 /// Whether the machine function is modified during the pass.
584 bool ModifiedMF = false;
585
586 /// All allocated UserValue instances.
587 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
588
589 /// All allocated UserLabel instances.
590 SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
591
592 /// Map virtual register to eq class leader.
593 using VRMap = DenseMap<Register, UserValue *>;
594 VRMap virtRegToEqClass;
595
596 /// Map to find existing UserValue instances.
597 using UVMap = DenseMap<DebugVariable, UserValue *>;
598 UVMap userVarMap;
599
600 /// Find or create a UserValue.
601 UserValue *getUserValue(const DILocalVariable *Var,
602 std::optional<DIExpression::FragmentInfo> Fragment,
603 const DebugLoc &DL);
604
605 /// Find the EC leader for VirtReg or null.
606 UserValue *lookupVirtReg(Register VirtReg);
607
608 /// Add DBG_VALUE instruction to our maps.
609 ///
610 /// \param MI DBG_VALUE instruction
611 /// \param Idx Last valid SLotIndex before instruction.
612 ///
613 /// \returns True if the DBG_VALUE instruction should be deleted.
614 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
615
616 /// Track variable location debug instructions while using the instruction
617 /// referencing implementation. Such debug instructions do not need to be
618 /// updated during regalloc because they identify instructions rather than
619 /// register locations. However, they needs to be removed from the
620 /// MachineFunction during regalloc, then re-inserted later, to avoid
621 /// disrupting the allocator.
622 ///
623 /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
624 /// \param Idx Last valid SlotIndex before instruction
625 ///
626 /// \returns Iterator to continue processing from after unlinking.
627 MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
628
629 /// Add DBG_LABEL instruction to UserLabel.
630 ///
631 /// \param MI DBG_LABEL instruction
632 /// \param Idx Last valid SlotIndex before instruction.
633 ///
634 /// \returns True if the DBG_LABEL instruction should be deleted.
635 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
636
637 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
638 /// for each instruction.
639 ///
640 /// \param mf MachineFunction to be scanned.
641 /// \param InstrRef Whether to operate in instruction referencing mode. If
642 /// true, most of LiveDebugVariables doesn't run.
643 ///
644 /// \returns True if any debug values were found.
645 bool collectDebugValues(MachineFunction &mf, bool InstrRef);
646
647 /// Compute the live intervals of all user values after collecting all
648 /// their def points.
649 void computeIntervals();
650
651public:
652 LDVImpl(LiveIntervals *LIS) : LIS(LIS) {}
653
654 bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
655
656 /// Release all memory.
657 void clear() {
658 MF = nullptr;
659 PHIValToPos.clear();
660 RegToPHIIdx.clear();
661 StashedDebugInstrs.clear();
662 userValues.clear();
663 userLabels.clear();
664 virtRegToEqClass.clear();
665 userVarMap.clear();
666 // Make sure we call emitDebugValues if the machine function was modified.
667 assert((!ModifiedMF || EmitDone) &&
668 "Dbg values are not emitted in LDV");
669 EmitDone = false;
670 ModifiedMF = false;
671 }
672
673 /// Map virtual register to an equivalence class.
674 void mapVirtReg(Register VirtReg, UserValue *EC);
675
676 /// Replace any PHI referring to OldReg with its corresponding NewReg, if
677 /// present.
678 void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
679
680 /// Replace all references to OldReg with NewRegs.
681 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
682
683 /// Replace every stale index held by this analysis.
684 void canonicalizeIndexes(const SlotIndexes &SI);
685
686 /// Recreate DBG_VALUE instruction from data structures.
687 void emitDebugValues(VirtRegMap *VRM);
688
689 void print(raw_ostream&);
690};
691
692/// Implementation of the LiveDebugVariables pass.
693
694LiveDebugVariables::LiveDebugVariables() = default;
695LiveDebugVariables::~LiveDebugVariables() = default;
696LiveDebugVariables::LiveDebugVariables(LiveDebugVariables &&) = default;
697
698} // namespace llvm
699
700static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
701 const LLVMContext &Ctx) {
702 if (!DL)
703 return;
704
705 auto *Scope = cast<DIScope>(Val: DL.getScope());
706 // Omit the directory, because it's likely to be long and uninteresting.
707 CommentOS << Scope->getFilename();
708 CommentOS << ':' << DL.getLine();
709 if (DL.getCol() != 0)
710 CommentOS << ':' << DL.getCol();
711
712 DebugLoc InlinedAtDL = DL.getInlinedAt();
713 if (!InlinedAtDL)
714 return;
715
716 CommentOS << " @[ ";
717 printDebugLoc(DL: InlinedAtDL, CommentOS, Ctx);
718 CommentOS << " ]";
719}
720
721static void printExtendedName(raw_ostream &OS, const DINode *Node,
722 const DILocation *DL) {
723 const LLVMContext &Ctx = Node->getContext();
724 StringRef Res;
725 unsigned Line = 0;
726 if (const auto *V = dyn_cast<const DILocalVariable>(Val: Node)) {
727 Res = V->getName();
728 Line = V->getLine();
729 } else if (const auto *L = dyn_cast<const DILabel>(Val: Node)) {
730 Res = L->getName();
731 Line = L->getLine();
732 }
733
734 if (!Res.empty())
735 OS << Res << "," << Line;
736 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
737 if (InlinedAt) {
738 if (DebugLoc InlinedAtDL = InlinedAt) {
739 OS << " @[";
740 printDebugLoc(DL: InlinedAtDL, CommentOS&: OS, Ctx);
741 OS << "]";
742 }
743 }
744}
745
746void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
747 OS << "!\"";
748 printExtendedName(OS, Node: Variable, DL: dl);
749
750 OS << "\"\t";
751 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
752 OS << " [" << I.start() << ';' << I.stop() << "):";
753 if (I.value().isUndef())
754 OS << " undef";
755 else {
756 I.value().printLocNos(OS);
757 if (I.value().getWasIndirect())
758 OS << " ind";
759 else if (I.value().getWasList())
760 OS << " list";
761 }
762 }
763 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
764 OS << " Loc" << i << '=';
765 locations[i].print(os&: OS, TRI);
766 }
767 OS << '\n';
768}
769
770void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
771 OS << "!\"";
772 printExtendedName(OS, Node: Label, DL: dl);
773
774 OS << "\"\t";
775 OS << loc;
776 OS << '\n';
777}
778
779void LiveDebugVariables::LDVImpl::print(raw_ostream &OS) {
780 OS << "********** DEBUG VARIABLES **********\n";
781 for (auto &userValue : userValues)
782 userValue->print(OS, TRI);
783 OS << "********** DEBUG LABELS **********\n";
784 for (auto &userLabel : userLabels)
785 userLabel->print(OS, TRI);
786}
787
788void UserValue::mapVirtRegs(LiveDebugVariables::LDVImpl *LDV) {
789 for (const MachineOperand &MO : locations)
790 if (MO.isReg() && MO.getReg().isVirtual())
791 LDV->mapVirtReg(VirtReg: MO.getReg(), EC: this);
792}
793
794UserValue *LiveDebugVariables::LDVImpl::getUserValue(
795 const DILocalVariable *Var,
796 std::optional<DIExpression::FragmentInfo> Fragment, const DebugLoc &DL) {
797 // FIXME: Handle partially overlapping fragments. See
798 // https://reviews.llvm.org/D70121#1849741.
799 DebugVariable ID(Var, Fragment, DL->getInlinedAt());
800 UserValue *&UV = userVarMap[ID];
801 if (!UV) {
802 userValues.push_back(
803 Elt: std::make_unique<UserValue>(args&: Var, args&: Fragment, args: DL, args&: allocator));
804 UV = userValues.back().get();
805 }
806 return UV;
807}
808
809void LiveDebugVariables::LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
810 assert(VirtReg.isVirtual() && "Only map VirtRegs");
811 UserValue *&Leader = virtRegToEqClass[VirtReg];
812 Leader = UserValue::merge(L1: Leader, L2: EC);
813}
814
815UserValue *LiveDebugVariables::LDVImpl::lookupVirtReg(Register VirtReg) {
816 if (UserValue *UV = virtRegToEqClass.lookup(Val: VirtReg))
817 return UV->getLeader();
818 return nullptr;
819}
820
821bool LiveDebugVariables::LDVImpl::handleDebugValue(MachineInstr &MI,
822 SlotIndex Idx) {
823 // DBG_VALUE loc, offset, variable, expr
824 // DBG_VALUE_LIST variable, expr, locs...
825 if (!MI.isDebugValue()) {
826 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
827 return false;
828 }
829 if (!MI.getDebugVariableOp().isMetadata()) {
830 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
831 << MI);
832 return false;
833 }
834 if (MI.isNonListDebugValue() &&
835 (MI.getNumOperands() != 4 ||
836 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
837 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
838 return false;
839 }
840
841 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
842 // register that hasn't been defined yet. If we do not remove those here, then
843 // the re-insertion of the DBG_VALUE instruction after register allocation
844 // will be incorrect.
845 bool Discard = false;
846 for (const MachineOperand &Op : MI.debug_operands()) {
847 if (Op.isReg() && Op.getReg().isVirtual()) {
848 const Register Reg = Op.getReg();
849 if (!LIS->hasInterval(Reg)) {
850 // The DBG_VALUE is described by a virtual register that does not have a
851 // live interval. Discard the DBG_VALUE.
852 Discard = true;
853 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
854 << " " << MI);
855 } else {
856 // The DBG_VALUE is only valid if either Reg is live out from Idx, or
857 // Reg is defined dead at Idx (where Idx is the slot index for the
858 // instruction preceding the DBG_VALUE).
859 const LiveInterval &LI = LIS->getInterval(Reg);
860 LiveQueryResult LRQ = LI.Query(Idx);
861 if (!LRQ.valueOutOrDead()) {
862 // We have found a DBG_VALUE with the value in a virtual register that
863 // is not live. Discard the DBG_VALUE.
864 Discard = true;
865 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
866 << " " << MI);
867 }
868 }
869 }
870 }
871
872 // Get or create the UserValue for (variable,offset) here.
873 bool IsIndirect = MI.isDebugOffsetImm();
874 if (IsIndirect)
875 assert(MI.getDebugOffset().getImm() == 0 &&
876 "DBG_VALUE with nonzero offset");
877 bool IsList = MI.isDebugValueList();
878 const DILocalVariable *Var = MI.getDebugVariable();
879 const DIExpression *Expr = MI.getDebugExpression();
880 UserValue *UV = getUserValue(Var, Fragment: Expr->getFragmentInfo(), DL: MI.getDebugLoc());
881 if (!Discard)
882 UV->addDef(Idx,
883 LocMOs: ArrayRef<MachineOperand>(MI.debug_operands().begin(),
884 MI.debug_operands().end()),
885 IsIndirect, IsList, Expr: *Expr);
886 else {
887 MachineOperand MO = MachineOperand::CreateReg(Reg: 0U, isDef: false);
888 MO.setIsDebug();
889 // We should still pass a list the same size as MI.debug_operands() even if
890 // all MOs are undef, so that DbgVariableValue can correctly adjust the
891 // expression while removing the duplicated undefs.
892 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
893 UV->addDef(Idx, LocMOs: UndefMOs, IsIndirect: false, IsList, Expr: *Expr);
894 }
895 return true;
896}
897
898MachineBasicBlock::iterator
899LiveDebugVariables::LDVImpl::handleDebugInstr(MachineInstr &MI, SlotIndex Idx) {
900 assert(MI.isDebugValueLike() || MI.isDebugPHI());
901
902 // In instruction referencing mode, there should be no DBG_VALUE instructions
903 // that refer to virtual registers. They might still refer to constants.
904 if (MI.isDebugValueLike())
905 assert(none_of(MI.debug_operands(),
906 [](const MachineOperand &MO) {
907 return MO.isReg() && MO.getReg().isVirtual();
908 }) &&
909 "MIs should not refer to Virtual Registers in InstrRef mode.");
910
911 // Unlink the instruction, store it in the debug instructions collection.
912 auto NextInst = std::next(x: MI.getIterator());
913 auto *MBB = MI.getParent();
914 MI.removeFromParent();
915 StashedDebugInstrs.push_back(Elt: {.MI: &MI, .Idx: Idx, .MBB: MBB});
916 return NextInst;
917}
918
919bool LiveDebugVariables::LDVImpl::handleDebugLabel(MachineInstr &MI,
920 SlotIndex Idx) {
921 // DBG_LABEL label
922 if (MI.getNumOperands() != 1 || !MI.getOperand(i: 0).isMetadata()) {
923 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
924 return false;
925 }
926
927 // Get or create the UserLabel for label here.
928 const DILabel *Label = MI.getDebugLabel();
929 const DebugLoc &DL = MI.getDebugLoc();
930 bool Found = false;
931 for (auto const &L : userLabels) {
932 if (L->matches(L: Label, IA: DL->getInlinedAt(), Index: Idx)) {
933 Found = true;
934 break;
935 }
936 }
937 if (!Found)
938 userLabels.push_back(Elt: std::make_unique<UserLabel>(args&: Label, args: DL, args&: Idx));
939
940 return true;
941}
942
943bool LiveDebugVariables::LDVImpl::collectDebugValues(MachineFunction &mf,
944 bool InstrRef) {
945 bool Changed = false;
946 for (MachineBasicBlock &MBB : mf) {
947 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
948 MBBI != MBBE;) {
949 // Use the first debug instruction in the sequence to get a SlotIndex
950 // for following consecutive debug instructions.
951 if (!MBBI->isDebugOrPseudoInstr()) {
952 ++MBBI;
953 continue;
954 }
955 // Debug instructions has no slot index. Use the previous
956 // non-debug instruction's SlotIndex as its SlotIndex.
957 SlotIndex Idx =
958 MBBI == MBB.begin()
959 ? LIS->getMBBStartIdx(mbb: &MBB)
960 : LIS->getInstructionIndex(Instr: *std::prev(x: MBBI)).getRegSlot();
961 // Handle consecutive debug instructions with the same slot index.
962 do {
963 // In instruction referencing mode, pass each instr to handleDebugInstr
964 // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
965 // need to go through the normal live interval splitting process.
966 if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
967 MBBI->isDebugRef())) {
968 MBBI = handleDebugInstr(MI&: *MBBI, Idx);
969 Changed = true;
970 // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
971 // to track things through register allocation, and erase the instr.
972 } else if ((MBBI->isDebugValue() && handleDebugValue(MI&: *MBBI, Idx)) ||
973 (MBBI->isDebugLabel() && handleDebugLabel(MI&: *MBBI, Idx))) {
974 MBBI = MBB.erase(I: MBBI);
975 Changed = true;
976 } else
977 ++MBBI;
978 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
979 }
980 }
981 return Changed;
982}
983
984void UserValue::extendDef(
985 SlotIndex Idx, DbgVariableValue DbgValue,
986 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
987 &LiveIntervalInfo,
988 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
989 LiveIntervals &LIS) {
990 SlotIndex Start = Idx;
991 MachineBasicBlock *MBB = LIS.getMBBFromIndex(index: Start);
992 SlotIndex Stop = LIS.getMBBEndIdx(mbb: MBB);
993 LocMap::iterator I = locInts.find(x: Start);
994
995 // Limit to the intersection of the VNIs' live ranges.
996 for (auto &LII : LiveIntervalInfo) {
997 LiveRange *LR = LII.second.first;
998 assert(LR && LII.second.second && "Missing range info for Idx.");
999 LiveInterval::Segment *Segment = LR->getSegmentContaining(Idx: Start);
1000 assert(Segment && Segment->valno == LII.second.second &&
1001 "Invalid VNInfo for Idx given?");
1002 if (Segment->end < Stop) {
1003 Stop = Segment->end;
1004 Kills = {Stop, {LII.first}};
1005 } else if (Segment->end == Stop && Kills) {
1006 // If multiple locations end at the same place, track all of them in
1007 // Kills.
1008 Kills->second.push_back(Elt: LII.first);
1009 }
1010 }
1011
1012 // There could already be a short def at Start.
1013 if (I.valid() && I.start() <= Start) {
1014 // Stop when meeting a different location or an already extended interval.
1015 Start = Start.getNextSlot();
1016 if (I.value() != DbgValue || I.stop() != Start) {
1017 // Clear `Kills`, as we have a new def available.
1018 Kills = std::nullopt;
1019 return;
1020 }
1021 // This is a one-slot placeholder. Just skip it.
1022 ++I;
1023 }
1024
1025 // Limited by the next def.
1026 if (I.valid() && I.start() < Stop) {
1027 Stop = I.start();
1028 // Clear `Kills`, as we have a new def available.
1029 Kills = std::nullopt;
1030 }
1031
1032 if (Start < Stop) {
1033 DbgVariableValue ExtDbgValue(DbgValue);
1034 I.insert(a: Start, b: Stop, y: std::move(ExtDbgValue));
1035 }
1036}
1037
1038void UserValue::addDefsFromCopies(
1039 DbgVariableValue DbgValue,
1040 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1041 SlotIndex KilledAt,
1042 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
1043 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
1044 // Don't track copies from physregs, there are too many uses.
1045 if (any_of(Range&: LocIntervals,
1046 P: [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
1047 return;
1048
1049 // Collect all the (vreg, valno) pairs that are copies of LI.
1050 SmallDenseMap<unsigned,
1051 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1052 CopyValues;
1053 for (auto &LocInterval : LocIntervals) {
1054 unsigned LocNo = LocInterval.first;
1055 LiveInterval *LI = LocInterval.second;
1056 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg: LI->reg())) {
1057 MachineInstr *MI = MO.getParent();
1058 // Copies of the full value.
1059 if (MO.getSubReg() || !MI->isCopy())
1060 continue;
1061 Register DstReg = MI->getOperand(i: 0).getReg();
1062
1063 // Don't follow copies to physregs. These are usually setting up call
1064 // arguments, and the argument registers are always call clobbered. We are
1065 // better off in the source register which could be a callee-saved
1066 // register, or it could be spilled.
1067 if (!DstReg.isVirtual())
1068 continue;
1069
1070 // Is the value extended to reach this copy? If not, another def may be
1071 // blocking it, or we are looking at a wrong value of LI.
1072 SlotIndex Idx = LIS.getInstructionIndex(Instr: *MI);
1073 LocMap::iterator I = locInts.find(x: Idx.getRegSlot(EC: true));
1074 if (!I.valid() || I.value() != DbgValue)
1075 continue;
1076
1077 if (!LIS.hasInterval(Reg: DstReg))
1078 continue;
1079 LiveInterval *DstLI = &LIS.getInterval(Reg: DstReg);
1080 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx: Idx.getRegSlot());
1081 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1082 CopyValues[LocNo].push_back(Elt: std::make_pair(x&: DstLI, y&: DstVNI));
1083 }
1084 }
1085
1086 if (CopyValues.empty())
1087 return;
1088
1089#if !defined(NDEBUG)
1090 for (auto &LocInterval : LocIntervals)
1091 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1092 << " copies of " << *LocInterval.second << '\n');
1093#endif
1094
1095 // Try to add defs of the copied values for the kill point. Check that there
1096 // isn't already a def at Idx.
1097 LocMap::iterator I = locInts.find(x: KilledAt);
1098 if (I.valid() && I.start() <= KilledAt)
1099 return;
1100 DbgVariableValue NewValue(DbgValue);
1101 for (auto &LocInterval : LocIntervals) {
1102 unsigned LocNo = LocInterval.first;
1103 bool FoundCopy = false;
1104 for (auto &LIAndVNI : CopyValues[LocNo]) {
1105 LiveInterval *DstLI = LIAndVNI.first;
1106 const VNInfo *DstVNI = LIAndVNI.second;
1107 if (DstLI->getVNInfoAt(Idx: KilledAt) != DstVNI)
1108 continue;
1109 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
1110 << DstVNI->id << " in " << *DstLI << '\n');
1111 MachineInstr *CopyMI = LIS.getInstructionFromIndex(index: DstVNI->def);
1112 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1113 unsigned NewLocNo = getLocationNo(LocMO: CopyMI->getOperand(i: 0));
1114 NewValue = NewValue.changeLocNo(OldLocNo: LocNo, NewLocNo);
1115 FoundCopy = true;
1116 break;
1117 }
1118 // If there are any killed locations we can't find a copy for, we can't
1119 // extend the variable value.
1120 if (!FoundCopy)
1121 return;
1122 }
1123 I.insert(a: KilledAt, b: KilledAt.getNextSlot(), y: NewValue);
1124 NewDefs.push_back(Elt: std::make_pair(x&: KilledAt, y&: NewValue));
1125}
1126
1127void UserValue::computeIntervals(MachineRegisterInfo &MRI,
1128 const TargetRegisterInfo &TRI,
1129 LiveIntervals &LIS, LexicalScopes &LS) {
1130 SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
1131
1132 // Collect all defs to be extended (Skipping undefs).
1133 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1134 if (!I.value().isUndef())
1135 Defs.push_back(Elt: std::make_pair(x: I.start(), y: I.value()));
1136
1137 // Extend all defs, and possibly add new ones along the way.
1138 for (unsigned i = 0; i != Defs.size(); ++i) {
1139 SlotIndex Idx = Defs[i].first;
1140 DbgVariableValue DbgValue = Defs[i].second;
1141 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1142 bool ShouldExtendDef = false;
1143 for (unsigned LocNo : DbgValue.loc_nos()) {
1144 const MachineOperand &LocMO = locations[LocNo];
1145 if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1146 ShouldExtendDef |= !LocMO.isReg();
1147 continue;
1148 }
1149 ShouldExtendDef = true;
1150 LiveInterval *LI = nullptr;
1151 const VNInfo *VNI = nullptr;
1152 if (LIS.hasInterval(Reg: LocMO.getReg())) {
1153 LI = &LIS.getInterval(Reg: LocMO.getReg());
1154 VNI = LI->getVNInfoAt(Idx);
1155 }
1156 if (LI && VNI)
1157 LIs[LocNo] = {LI, VNI};
1158 }
1159 if (ShouldExtendDef) {
1160 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1161 extendDef(Idx, DbgValue, LiveIntervalInfo&: LIs, Kills, LIS);
1162
1163 if (Kills) {
1164 SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1165 bool AnySubreg = false;
1166 for (unsigned LocNo : Kills->second) {
1167 const MachineOperand &LocMO = this->locations[LocNo];
1168 if (LocMO.getSubReg()) {
1169 AnySubreg = true;
1170 break;
1171 }
1172 LiveInterval *LI = &LIS.getInterval(Reg: LocMO.getReg());
1173 KilledLocIntervals.push_back(Elt: {LocNo, LI});
1174 }
1175
1176 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1177 // if the original location for example is %vreg0:sub_hi, and we find a
1178 // full register copy in addDefsFromCopies (at the moment it only
1179 // handles full register copies), then we must add the sub1 sub-register
1180 // index to the new location. However, that is only possible if the new
1181 // virtual register is of the same regclass (or if there is an
1182 // equivalent sub-register in that regclass). For now, simply skip
1183 // handling copies if a sub-register is involved.
1184 if (!AnySubreg)
1185 addDefsFromCopies(DbgValue, LocIntervals&: KilledLocIntervals, KilledAt: Kills->first, NewDefs&: Defs,
1186 MRI, LIS);
1187 }
1188 }
1189
1190 // For physregs, we only mark the start slot idx. DwarfDebug will see it
1191 // as if the DBG_VALUE is valid up until the end of the basic block, or
1192 // the next def of the physical register. So we do not need to extend the
1193 // range. It might actually happen that the DBG_VALUE is the last use of
1194 // the physical register (e.g. if this is an unused input argument to a
1195 // function).
1196 }
1197
1198 // The computed intervals may extend beyond the range of the debug
1199 // location's lexical scope. In this case, splitting of an interval
1200 // can result in an interval outside of the scope being created,
1201 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1202 // this, trim the intervals to the lexical scope in the case of inlined
1203 // variables, since heavy inlining may cause production of dramatically big
1204 // number of DBG_VALUEs to be generated.
1205 if (!dl.getInlinedAt())
1206 return;
1207
1208 LexicalScope *Scope = LS.findLexicalScope(DL: dl);
1209 if (!Scope)
1210 return;
1211
1212 SlotIndex PrevEnd;
1213 LocMap::iterator I = locInts.begin();
1214
1215 // Iterate over the lexical scope ranges. Each time round the loop
1216 // we check the intervals for overlap with the end of the previous
1217 // range and the start of the next. The first range is handled as
1218 // a special case where there is no PrevEnd.
1219 for (const InsnRange &Range : Scope->getRanges()) {
1220 SlotIndex RStart = LIS.getInstructionIndex(Instr: *Range.first);
1221 SlotIndex REnd = LIS.getInstructionIndex(Instr: *Range.second);
1222
1223 // Variable locations at the first instruction of a block should be
1224 // based on the block's SlotIndex, not the first instruction's index.
1225 if (Range.first == Range.first->getParent()->begin())
1226 RStart = LIS.getSlotIndexes()->getIndexBefore(MI: *Range.first);
1227
1228 // At the start of each iteration I has been advanced so that
1229 // I.stop() >= PrevEnd. Check for overlap.
1230 if (PrevEnd && I.start() < PrevEnd) {
1231 SlotIndex IStop = I.stop();
1232 DbgVariableValue DbgValue = I.value();
1233
1234 // Stop overlaps previous end - trim the end of the interval to
1235 // the scope range.
1236 I.setStopUnchecked(PrevEnd);
1237 ++I;
1238
1239 // If the interval also overlaps the start of the "next" (i.e.
1240 // current) range create a new interval for the remainder (which
1241 // may be further trimmed).
1242 if (RStart < IStop)
1243 I.insert(a: RStart, b: IStop, y: DbgValue);
1244 }
1245
1246 // Advance I so that I.stop() >= RStart, and check for overlap.
1247 I.advanceTo(x: RStart);
1248 if (!I.valid())
1249 return;
1250
1251 if (I.start() < RStart) {
1252 // Interval start overlaps range - trim to the scope range.
1253 I.setStartUnchecked(RStart);
1254 // Remember that this interval was trimmed.
1255 trimmedDefs.insert(V: RStart);
1256 }
1257
1258 // The end of a lexical scope range is the last instruction in the
1259 // range. To convert to an interval we need the index of the
1260 // instruction after it.
1261 REnd = REnd.getNextIndex();
1262
1263 // Advance I to first interval outside current range.
1264 I.advanceTo(x: REnd);
1265 if (!I.valid())
1266 return;
1267
1268 PrevEnd = REnd;
1269 }
1270
1271 // Check for overlap with end of final range.
1272 if (PrevEnd && I.start() < PrevEnd)
1273 I.setStopUnchecked(PrevEnd);
1274}
1275
1276void LiveDebugVariables::LDVImpl::computeIntervals() {
1277 LexicalScopes LS;
1278 LS.scanFunction(*MF);
1279
1280 for (const auto &UV : userValues) {
1281 UV->computeIntervals(MRI&: MF->getRegInfo(), TRI: *TRI, LIS&: *LIS, LS);
1282 UV->mapVirtRegs(LDV: this);
1283 }
1284}
1285
1286bool LiveDebugVariables::LDVImpl::runOnMachineFunction(MachineFunction &mf,
1287 bool InstrRef) {
1288 clear();
1289 MF = &mf;
1290 TRI = mf.getSubtarget().getRegisterInfo();
1291 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1292 << mf.getName() << " **********\n");
1293
1294 bool Changed = collectDebugValues(mf, InstrRef);
1295 computeIntervals();
1296 LLVM_DEBUG(print(dbgs()));
1297
1298 // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1299 // VRegs too, for when we're notified of a range split.
1300 SlotIndexes *Slots = LIS->getSlotIndexes();
1301 for (const auto &PHIIt : MF->DebugPHIPositions) {
1302 const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1303 MachineBasicBlock *MBB = Position.MBB;
1304 Register Reg = Position.Reg;
1305 unsigned SubReg = Position.SubReg;
1306 SlotIndex SI = Slots->getMBBStartIdx(mbb: MBB);
1307 PHIValPos VP = {.SI: SI, .Reg: Reg, .SubReg: SubReg};
1308 PHIValToPos.insert(x: std::make_pair(x: PHIIt.first, y&: VP));
1309 RegToPHIIdx[Reg].push_back(x: PHIIt.first);
1310 }
1311
1312 ModifiedMF = Changed;
1313 return Changed;
1314}
1315
1316static void removeDebugInstrs(MachineFunction &mf) {
1317 for (MachineBasicBlock &MBB : mf) {
1318 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: MBB))
1319 if (MI.isDebugInstr())
1320 MBB.erase(I: &MI);
1321 }
1322}
1323
1324bool LiveDebugVariablesWrapperLegacy::runOnMachineFunction(
1325 MachineFunction &mf) {
1326 auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1327
1328 Impl = std::make_unique<LiveDebugVariables>();
1329 Impl->analyze(MF&: mf, LIS);
1330 return false;
1331}
1332
1333AnalysisKey LiveDebugVariablesAnalysis::Key;
1334
1335LiveDebugVariables
1336LiveDebugVariablesAnalysis::run(MachineFunction &MF,
1337 MachineFunctionAnalysisManager &MFAM) {
1338 MFPropsModifier _(*this, MF);
1339
1340 auto *LIS = &MFAM.getResult<LiveIntervalsAnalysis>(IR&: MF);
1341 LiveDebugVariables LDV;
1342 LDV.analyze(MF, LIS);
1343 return LDV;
1344}
1345
1346PreservedAnalyses
1347LiveDebugVariablesPrinterPass::run(MachineFunction &MF,
1348 MachineFunctionAnalysisManager &MFAM) {
1349 auto &LDV = MFAM.getResult<LiveDebugVariablesAnalysis>(IR&: MF);
1350 LDV.print(OS);
1351 return PreservedAnalyses::all();
1352}
1353
1354void LiveDebugVariables::releaseMemory() {
1355 if (PImpl)
1356 PImpl->clear();
1357}
1358
1359bool LiveDebugVariables::invalidate(
1360 MachineFunction &, const PreservedAnalyses &PA,
1361 MachineFunctionAnalysisManager::Invalidator &) {
1362 auto PAC = PA.getChecker<LiveDebugVariablesAnalysis>();
1363 // Some architectures split the register allocation into multiple phases based
1364 // on register classes. This requires preserving analyses between the phases
1365 // by default.
1366 return !PAC.preservedWhenStateless();
1367}
1368
1369void LiveDebugVariables::analyze(MachineFunction &MF, LiveIntervals *LIS) {
1370 if (!EnableLDV)
1371 return;
1372 if (!MF.getFunction().getSubprogram()) {
1373 removeDebugInstrs(mf&: MF);
1374 return;
1375 }
1376
1377 PImpl.reset(p: new LDVImpl(LIS));
1378
1379 // Have we been asked to track variable locations using instruction
1380 // referencing?
1381 bool InstrRef = MF.useDebugInstrRef();
1382 PImpl->runOnMachineFunction(mf&: MF, InstrRef);
1383}
1384
1385//===----------------------------------------------------------------------===//
1386// Live Range Splitting
1387//===----------------------------------------------------------------------===//
1388
1389bool
1390UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1391 LiveIntervals& LIS) {
1392 LLVM_DEBUG({
1393 dbgs() << "Splitting Loc" << OldLocNo << '\t';
1394 print(dbgs(), nullptr);
1395 });
1396 bool DidChange = false;
1397 LocMap::iterator LocMapI;
1398 LocMapI.setMap(locInts);
1399 for (Register NewReg : NewRegs) {
1400 LiveInterval *LI = &LIS.getInterval(Reg: NewReg);
1401 if (LI->empty())
1402 continue;
1403
1404 // Don't allocate the new LocNo until it is needed.
1405 unsigned NewLocNo = UndefLocNo;
1406
1407 // Iterate over the overlaps between locInts and LI.
1408 LocMapI.find(x: LI->beginIndex());
1409 if (!LocMapI.valid())
1410 continue;
1411 LiveInterval::iterator LII = LI->advanceTo(I: LI->begin(), Pos: LocMapI.start());
1412 LiveInterval::iterator LIE = LI->end();
1413 while (LocMapI.valid() && LII != LIE) {
1414 // At this point, we know that LocMapI.stop() > LII->start.
1415 LII = LI->advanceTo(I: LII, Pos: LocMapI.start());
1416 if (LII == LIE)
1417 break;
1418
1419 // Now LII->end > LocMapI.start(). Do we have an overlap?
1420 if (LocMapI.value().containsLocNo(LocNo: OldLocNo) &&
1421 LII->start < LocMapI.stop()) {
1422 // Overlapping correct location. Allocate NewLocNo now.
1423 if (NewLocNo == UndefLocNo) {
1424 MachineOperand MO = MachineOperand::CreateReg(Reg: LI->reg(), isDef: false);
1425 MO.setSubReg(locations[OldLocNo].getSubReg());
1426 NewLocNo = getLocationNo(LocMO: MO);
1427 DidChange = true;
1428 }
1429
1430 SlotIndex LStart = LocMapI.start();
1431 SlotIndex LStop = LocMapI.stop();
1432 DbgVariableValue OldDbgValue = LocMapI.value();
1433
1434 // Trim LocMapI down to the LII overlap.
1435 if (LStart < LII->start)
1436 LocMapI.setStartUnchecked(LII->start);
1437 if (LStop > LII->end)
1438 LocMapI.setStopUnchecked(LII->end);
1439
1440 // Change the value in the overlap. This may trigger coalescing.
1441 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1442
1443 // Re-insert any removed OldDbgValue ranges.
1444 if (LStart < LocMapI.start()) {
1445 LocMapI.insert(a: LStart, b: LocMapI.start(), y: OldDbgValue);
1446 ++LocMapI;
1447 assert(LocMapI.valid() && "Unexpected coalescing");
1448 }
1449 if (LStop > LocMapI.stop()) {
1450 ++LocMapI;
1451 LocMapI.insert(a: LII->end, b: LStop, y: OldDbgValue);
1452 --LocMapI;
1453 }
1454 }
1455
1456 // Advance to the next overlap.
1457 if (LII->end < LocMapI.stop()) {
1458 if (++LII == LIE)
1459 break;
1460 LocMapI.advanceTo(x: LII->start);
1461 } else {
1462 ++LocMapI;
1463 if (!LocMapI.valid())
1464 break;
1465 LII = LI->advanceTo(I: LII, Pos: LocMapI.start());
1466 }
1467 }
1468 }
1469
1470 // Finally, remove OldLocNo unless it is still used by some interval in the
1471 // locInts map. One case when OldLocNo still is in use is when the register
1472 // has been spilled. In such situations the spilled register is kept as a
1473 // location until rewriteLocations is called (VirtRegMap is mapping the old
1474 // register to the spill slot). So for a while we can have locations that map
1475 // to virtual registers that have been removed from both the MachineFunction
1476 // and from LiveIntervals.
1477 //
1478 // We may also just be using the location for a value with a different
1479 // expression.
1480 removeLocationIfUnused(LocNo: OldLocNo);
1481
1482 LLVM_DEBUG({
1483 dbgs() << "Split result: \t";
1484 print(dbgs(), nullptr);
1485 });
1486 return DidChange;
1487}
1488
1489bool
1490UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1491 LiveIntervals &LIS) {
1492 bool DidChange = false;
1493 // Split locations referring to OldReg. Iterate backwards so splitLocation can
1494 // safely erase unused locations.
1495 for (unsigned i = locations.size(); i ; --i) {
1496 unsigned LocNo = i-1;
1497 const MachineOperand *Loc = &locations[LocNo];
1498 if (!Loc->isReg() || Loc->getReg() != OldReg)
1499 continue;
1500 DidChange |= splitLocation(OldLocNo: LocNo, NewRegs, LIS);
1501 }
1502 return DidChange;
1503}
1504
1505void LiveDebugVariables::LDVImpl::splitPHIRegister(Register OldReg,
1506 ArrayRef<Register> NewRegs) {
1507 auto RegIt = RegToPHIIdx.find(Val: OldReg);
1508 if (RegIt == RegToPHIIdx.end())
1509 return;
1510
1511 std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1512 // Iterate over all the debug instruction numbers affected by this split.
1513 for (unsigned InstrID : RegIt->second) {
1514 auto PHIIt = PHIValToPos.find(x: InstrID);
1515 assert(PHIIt != PHIValToPos.end());
1516 const SlotIndex &Slot = PHIIt->second.SI;
1517 assert(OldReg == PHIIt->second.Reg);
1518
1519 // Find the new register that covers this position.
1520 for (auto NewReg : NewRegs) {
1521 const LiveInterval &LI = LIS->getInterval(Reg: NewReg);
1522 auto LII = LI.find(Pos: Slot);
1523 if (LII != LI.end() && LII->start <= Slot) {
1524 // This new register covers this PHI position, record this for indexing.
1525 NewRegIdxes.push_back(x: std::make_pair(x&: NewReg, y&: InstrID));
1526 // Record that this value lives in a different VReg now.
1527 PHIIt->second.Reg = NewReg;
1528 break;
1529 }
1530 }
1531
1532 // If we do not find a new register covering this PHI, then register
1533 // allocation has dropped its location, for example because it's not live.
1534 // The old VReg will not be mapped to a physreg, and the instruction
1535 // number will have been optimized out.
1536 }
1537
1538 // Re-create register index using the new register numbers.
1539 RegToPHIIdx.erase(I: RegIt);
1540 for (auto &RegAndInstr : NewRegIdxes)
1541 RegToPHIIdx[RegAndInstr.first].push_back(x: RegAndInstr.second);
1542}
1543
1544void LiveDebugVariables::LDVImpl::splitRegister(Register OldReg,
1545 ArrayRef<Register> NewRegs) {
1546 // Consider whether this split range affects any PHI locations.
1547 splitPHIRegister(OldReg, NewRegs);
1548
1549 // Check whether any intervals mapped by a DBG_VALUE were split and need
1550 // updating.
1551 bool DidChange = false;
1552 for (UserValue *UV = lookupVirtReg(VirtReg: OldReg); UV; UV = UV->getNext())
1553 DidChange |= UV->splitRegister(OldReg, NewRegs, LIS&: *LIS);
1554
1555 if (!DidChange)
1556 return;
1557
1558 // Map all of the new virtual registers.
1559 UserValue *UV = lookupVirtReg(VirtReg: OldReg);
1560 for (Register NewReg : NewRegs)
1561 mapVirtReg(VirtReg: NewReg, EC: UV);
1562}
1563
1564void LiveDebugVariables::
1565splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
1566 if (PImpl)
1567 PImpl->splitRegister(OldReg, NewRegs);
1568}
1569
1570//===----------------------------------------------------------------------===//
1571// Stale Index Canonicalization
1572//===----------------------------------------------------------------------===//
1573
1574void UserValue::canonicalizeIndexes(const SlotIndexes &SI) {
1575 unsigned NumStale = 0;
1576 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1577 NumStale += SI.isStaleIndex(Idx: I.start()) + SI.isStaleIndex(Idx: I.stop());
1578 for (SlotIndex Idx : trimmedDefs)
1579 NumStale += SI.isStaleIndex(Idx);
1580 NumStaleIndexes += NumStale;
1581
1582 if (NumStale) {
1583 // trimmedDefs is looked up by interval start. Remapping it here is safe:
1584 // trimmed starts are block slots, so the Stop < Start case below cannot
1585 // reach them, and a merge drops a start that then matches nothing.
1586 if (!trimmedDefs.empty()) {
1587 SmallVector<SlotIndex, 8> Defs(trimmedDefs.begin(), trimmedDefs.end());
1588 trimmedDefs.clear();
1589 for (SlotIndex Idx : Defs) {
1590 SlotIndex Canon = SI.canonicalizeIndex(Idx);
1591 if (!SI.isBlockBoundaryIndex(Idx: Canon))
1592 trimmedDefs.insert(V: Canon);
1593 }
1594 }
1595
1596 // Rebuild rather than move the keys of the existing map: it has to stay
1597 // ordered and non-empty at every step, which canonicalization does not
1598 // respect.
1599 struct CanonicalInterval {
1600 SlotIndex Start;
1601 SlotIndex Stop;
1602 DbgVariableValue Value;
1603 };
1604 SmallVector<CanonicalInterval, 8> Intervals;
1605
1606 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
1607 SlotIndex Start = SI.canonicalizeIndex(Idx: I.start());
1608 SlotIndex Stop = SI.canonicalizeIndex(Idx: I.stop());
1609
1610 // A stale stop can land below a start that sat on the same instruction's
1611 // dead slot. Both resolve to the same insert location.
1612 if (Stop < Start)
1613 Start = Stop;
1614
1615 if (!Intervals.empty()) {
1616 CanonicalInterval &Prev = Intervals.back();
1617 if (Start <= Prev.Start) {
1618 // Both DBG_VALUEs would be emitted at the same position, where the
1619 // later one overrides the earlier before it covers anything.
1620 Prev.Stop = std::max(a: Prev.Stop, b: Stop);
1621 Prev.Value = I.value();
1622 ++NumMergedIntervals;
1623 continue;
1624 }
1625 Prev.Stop = std::min(a: Prev.Stop, b: Start);
1626 }
1627 Intervals.push_back(Elt: {.Start: Start, .Stop: Stop, .Value: I.value()});
1628 }
1629
1630 // The map cannot hold empty intervals. Use the smallest extent there is: a
1631 // wider one would span more blocks, and emitDebugValues() emits a DBG_VALUE
1632 // per block covered.
1633 for (CanonicalInterval &Interval : Intervals) {
1634 if (Interval.Stop > Interval.Start)
1635 continue;
1636 Interval.Stop = Interval.Start.getNextSlot();
1637 assert(!SI.isStaleIndex(Interval.Stop) &&
1638 "No room left for a canonicalized interval");
1639 }
1640
1641 locInts.clear();
1642 for (const CanonicalInterval &Interval : Intervals)
1643 locInts.insert(a: Interval.Start, b: Interval.Stop, y: Interval.Value);
1644 }
1645
1646#ifndef NDEBUG
1647 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1648 assert(!SI.isStaleIndex(I.start()) && !SI.isStaleIndex(I.stop()) &&
1649 "Canonicalized interval still refers to an erased instruction");
1650 for (SlotIndex Idx : trimmedDefs)
1651 assert(!SI.isStaleIndex(Idx) &&
1652 "Canonicalized trimmed def still refers to an erased instruction");
1653#endif
1654}
1655
1656void LiveDebugVariables::LDVImpl::canonicalizeIndexes(const SlotIndexes &SI) {
1657 for (auto &userValue : userValues)
1658 userValue->canonicalizeIndexes(SI);
1659 for (auto &userLabel : userLabels)
1660 NumStaleIndexes += userLabel->canonicalizeIndex(SI);
1661
1662 // emitDebugValues() walks forwards to the next live instruction, which is the
1663 // same iterator as inserting after the preceding one, and stays inside
1664 // InstrPos::MBB. Canonicalization is monotonic, so entries sharing a slot are
1665 // still re-inserted as one batch.
1666 for (InstrPos &Stashed : StashedDebugInstrs) {
1667 if (!SI.isStaleIndex(Idx: Stashed.Idx))
1668 continue;
1669 ++NumStaleIndexes;
1670 Stashed.Idx = SI.canonicalizeIndex(Idx: Stashed.Idx);
1671 assert(!SI.isStaleIndex(Stashed.Idx) &&
1672 "Canonicalized debug instr still refers to an erased instruction");
1673 }
1674
1675#ifndef NDEBUG
1676 // PHI positions are block starts, which are boundaries. A block erased by
1677 // removeMBBFromMaps() would make one look stale.
1678 for (const auto &P : PHIValToPos)
1679 assert(!SI.isStaleIndex(P.second.SI) &&
1680 "PHI position refers to an erased instruction");
1681#endif
1682}
1683
1684void LiveDebugVariables::canonicalizeIndexes(const SlotIndexes &SI) {
1685 if (PImpl)
1686 PImpl->canonicalizeIndexes(SI);
1687}
1688
1689void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1690 const TargetInstrInfo &TII,
1691 const TargetRegisterInfo &TRI,
1692 SpillOffsetMap &SpillOffsets) {
1693 // Build a set of new locations with new numbers so we can coalesce our
1694 // IntervalMap if two vreg intervals collapse to the same physical location.
1695 // Use MapVector instead of SetVector because MapVector::insert returns the
1696 // position of the previously or newly inserted element. The boolean value
1697 // tracks if the location was produced by a spill.
1698 // FIXME: This will be problematic if we ever support direct and indirect
1699 // frame index locations, i.e. expressing both variables in memory and
1700 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1701 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1702 SmallVector<unsigned, 4> LocNoMap(locations.size());
1703 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1704 bool Spilled = false;
1705 unsigned SpillOffset = 0;
1706 MachineOperand Loc = locations[I];
1707 // Only virtual registers are rewritten.
1708 if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
1709 Register VirtReg = Loc.getReg();
1710 if (VRM.isAssignedReg(virtReg: VirtReg) && VRM.hasPhys(virtReg: VirtReg)) {
1711 // This can create a %noreg operand in rare cases when the sub-register
1712 // index is no longer available. That means the user value is in a
1713 // non-existent sub-register, and %noreg is exactly what we want.
1714 Loc.substPhysReg(Reg: VRM.getPhys(virtReg: VirtReg), TRI);
1715 } else if (VRM.getStackSlot(virtReg: VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1716 // Retrieve the stack slot offset.
1717 unsigned SpillSize;
1718 const MachineRegisterInfo &MRI = MF.getRegInfo();
1719 const TargetRegisterClass *TRC = MRI.getRegClass(Reg: VirtReg);
1720 bool Success = TII.getStackSlotRange(RC: TRC, SubIdx: Loc.getSubReg(), Size&: SpillSize,
1721 Offset&: SpillOffset, MF);
1722
1723 // FIXME: Invalidate the location if the offset couldn't be calculated.
1724 (void)Success;
1725
1726 Loc = MachineOperand::CreateFI(Idx: VRM.getStackSlot(virtReg: VirtReg));
1727 Spilled = true;
1728 } else {
1729 Loc.setReg(0);
1730 Loc.setSubReg(0);
1731 }
1732 }
1733
1734 // Insert this location if it doesn't already exist and record a mapping
1735 // from the old number to the new number.
1736 auto InsertResult = NewLocations.insert(KV: {Loc, {Spilled, SpillOffset}});
1737 unsigned NewLocNo = std::distance(first: NewLocations.begin(), last: InsertResult.first);
1738 LocNoMap[I] = NewLocNo;
1739 }
1740
1741 // Rewrite the locations and record the stack slot offsets for spills.
1742 locations.clear();
1743 SpillOffsets.clear();
1744 for (auto &Pair : NewLocations) {
1745 bool Spilled;
1746 unsigned SpillOffset;
1747 std::tie(args&: Spilled, args&: SpillOffset) = Pair.second;
1748 locations.push_back(Elt: Pair.first);
1749 if (Spilled) {
1750 unsigned NewLocNo = std::distance(first: &*NewLocations.begin(), last: &Pair);
1751 SpillOffsets[NewLocNo] = SpillOffset;
1752 }
1753 }
1754
1755 // Update the interval map, but only coalesce left, since intervals to the
1756 // right use the old location numbers. This should merge two contiguous
1757 // DBG_VALUE intervals with different vregs that were allocated to the same
1758 // physical register.
1759 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1760 I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1761 I.setStart(I.start());
1762 }
1763}
1764
1765/// Find an iterator for inserting a DBG_VALUE instruction.
1766static MachineBasicBlock::iterator
1767findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1768 BlockSkipInstsMap &BBSkipInstsMap) {
1769 SlotIndex Start = LIS.getMBBStartIdx(mbb: MBB);
1770 Idx = Idx.getBaseIndex();
1771
1772 // Try to find an insert location by going backwards from Idx.
1773 MachineInstr *MI;
1774 while (!(MI = LIS.getInstructionFromIndex(index: Idx))) {
1775 // We've reached the beginning of MBB.
1776 if (Idx == Start) {
1777 // Retrieve the last PHI/Label/Debug location found when calling
1778 // SkipPHIsLabelsAndDebug last time. Start searching from there.
1779 //
1780 // Note the iterator kept in BBSkipInstsMap is one step back based
1781 // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1782 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1783 // BBSkipInstsMap won't save it. This is to consider the case that
1784 // new instructions may be inserted at the beginning of MBB after
1785 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1786 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1787 // are inserted at the beginning of the MBB, the iterator in
1788 // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1789 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1790 // newly added instructions and that is unwanted.
1791 MachineBasicBlock::iterator BeginIt;
1792 auto MapIt = BBSkipInstsMap.find(Val: MBB);
1793 if (MapIt == BBSkipInstsMap.end())
1794 BeginIt = MBB->begin();
1795 else
1796 BeginIt = std::next(x: MapIt->second);
1797 auto I = MBB->SkipPHIsLabelsAndDebug(I: BeginIt);
1798 if (I != BeginIt)
1799 BBSkipInstsMap[MBB] = std::prev(x: I);
1800 return I;
1801 }
1802 Idx = Idx.getPrevIndex();
1803 }
1804
1805 // Don't insert anything after the first terminator, though.
1806 auto It = MI->isTerminator() ? MBB->getFirstTerminator()
1807 : std::next(x: MachineBasicBlock::iterator(MI));
1808 return skipDebugInstructionsForward(It, End: MBB->end());
1809}
1810
1811/// Find an iterator for inserting the next DBG_VALUE instruction
1812/// (or end if no more insert locations found).
1813static MachineBasicBlock::iterator
1814findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
1815 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1816 LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1817 SmallVector<Register, 4> Regs;
1818 for (const MachineOperand &LocMO : LocMOs)
1819 if (LocMO.isReg())
1820 Regs.push_back(Elt: LocMO.getReg());
1821 if (Regs.empty())
1822 return MBB->instr_end();
1823
1824 // Find the next instruction in the MBB that define the register Reg.
1825 while (I != MBB->end() && !I->isTerminator()) {
1826 if (!LIS.isNotInMIMap(Instr: *I) &&
1827 SlotIndex::isEarlierEqualInstr(A: StopIdx, B: LIS.getInstructionIndex(Instr: *I)))
1828 break;
1829 if (any_of(Range&: Regs, P: [&I, &TRI](Register &Reg) {
1830 return I->definesRegister(Reg, TRI: &TRI);
1831 }))
1832 // The insert location is directly after the instruction/bundle.
1833 return std::next(x: I);
1834 ++I;
1835 }
1836 return MBB->end();
1837}
1838
1839void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1840 SlotIndex StopIdx, DbgVariableValue DbgValue,
1841 ArrayRef<bool> LocSpills,
1842 ArrayRef<unsigned> SpillOffsets,
1843 LiveIntervals &LIS, const TargetInstrInfo &TII,
1844 const TargetRegisterInfo &TRI,
1845 BlockSkipInstsMap &BBSkipInstsMap) {
1846 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(mbb: &*MBB);
1847 // Only search within the current MBB.
1848 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1849 MachineBasicBlock::iterator I =
1850 findInsertLocation(MBB, Idx: StartIdx, LIS, BBSkipInstsMap);
1851 // Undef values don't exist in locations so create new "noreg" register MOs
1852 // for them. See getLocationNo().
1853 SmallVector<MachineOperand, 8> MOs;
1854 if (DbgValue.isUndef()) {
1855 MOs.assign(NumElts: DbgValue.loc_nos().size(),
1856 Elt: MachineOperand::CreateReg(
1857 /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1858 /* isKill */ false, /* isDead */ false,
1859 /* isUndef */ false, /* isEarlyClobber */ false,
1860 /* SubReg */ 0, /* isDebug */ true));
1861 } else {
1862 for (unsigned LocNo : DbgValue.loc_nos())
1863 MOs.push_back(Elt: locations[LocNo]);
1864 }
1865
1866 ++NumInsertedDebugValues;
1867
1868 assert(cast<DILocalVariable>(Variable)
1869 ->isValidLocationForIntrinsic(getDebugLoc()) &&
1870 "Expected inlined-at fields to agree");
1871
1872 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1873 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1874 // that the original virtual register was a pointer. Also, add the stack slot
1875 // offset for the spilled register to the expression.
1876 const DIExpression *Expr = DbgValue.getExpression();
1877 bool IsIndirect = DbgValue.getWasIndirect();
1878 bool IsList = DbgValue.getWasList();
1879 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1880 if (LocSpills[I]) {
1881 if (!IsList) {
1882 uint8_t DIExprFlags = DIExpression::ApplyOffset;
1883 if (IsIndirect)
1884 DIExprFlags |= DIExpression::DerefAfter;
1885 Expr = DIExpression::prepend(Expr, Flags: DIExprFlags, Offset: SpillOffsets[I]);
1886 IsIndirect = true;
1887 } else {
1888 SmallVector<uint64_t, 4> Ops;
1889 DIExpression::appendOffset(Ops, Offset: SpillOffsets[I]);
1890 Ops.push_back(Elt: dwarf::DW_OP_deref);
1891 Expr = DIExpression::appendOpsToArg(Expr, Ops, ArgNo: I);
1892 }
1893 }
1894
1895 assert((!LocSpills[I] || MOs[I].isFI()) &&
1896 "a spilled location must be a frame index");
1897 }
1898
1899 unsigned DbgValueOpcode =
1900 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1901 do {
1902 BuildMI(BB&: *MBB, I, DL: getDebugLoc(), MCID: TII.get(Opcode: DbgValueOpcode), IsIndirect, MOs,
1903 Variable, Expr);
1904
1905 // Continue and insert DBG_VALUES after every redefinition of a register
1906 // associated with the debug value within the range
1907 I = findNextInsertLocation(MBB, I, StopIdx, LocMOs: MOs, LIS, TRI);
1908 } while (I != MBB->end());
1909}
1910
1911void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1912 LiveIntervals &LIS, const TargetInstrInfo &TII,
1913 BlockSkipInstsMap &BBSkipInstsMap) {
1914 MachineBasicBlock::iterator I =
1915 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1916 ++NumInsertedDebugLabels;
1917 BuildMI(BB&: *MBB, I, MIMD: getDebugLoc(), MCID: TII.get(Opcode: TargetOpcode::DBG_LABEL))
1918 .addMetadata(MD: Label);
1919}
1920
1921void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1922 const TargetInstrInfo &TII,
1923 const TargetRegisterInfo &TRI,
1924 const SpillOffsetMap &SpillOffsets,
1925 BlockSkipInstsMap &BBSkipInstsMap) {
1926 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1927
1928 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1929 SlotIndex Start = I.start();
1930 SlotIndex Stop = I.stop();
1931 DbgVariableValue DbgValue = I.value();
1932
1933 SmallVector<bool> SpilledLocs;
1934 SmallVector<unsigned> LocSpillOffsets;
1935 for (unsigned LocNo : DbgValue.loc_nos()) {
1936 auto SpillIt =
1937 !DbgValue.isUndef() ? SpillOffsets.find(Val: LocNo) : SpillOffsets.end();
1938 bool Spilled = SpillIt != SpillOffsets.end();
1939 SpilledLocs.push_back(Elt: Spilled);
1940 LocSpillOffsets.push_back(Elt: Spilled ? SpillIt->second : 0);
1941 }
1942
1943 // If the interval start was trimmed to the lexical scope insert the
1944 // DBG_VALUE at the previous index (otherwise it appears after the
1945 // first instruction in the range).
1946 if (trimmedDefs.count(V: Start))
1947 Start = Start.getPrevIndex();
1948
1949 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1950 DbgValue.printLocNos(dbg));
1951 MachineFunction::iterator MBB = LIS.getMBBFromIndex(index: Start)->getIterator();
1952 SlotIndex MBBEnd = LIS.getMBBEndIdx(mbb: &*MBB);
1953
1954 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1955 insertDebugValue(MBB: &*MBB, StartIdx: Start, StopIdx: Stop, DbgValue, LocSpills: SpilledLocs, SpillOffsets: LocSpillOffsets,
1956 LIS, TII, TRI, BBSkipInstsMap);
1957 // This interval may span multiple basic blocks.
1958 // Insert a DBG_VALUE into each one.
1959 while (Stop > MBBEnd) {
1960 // Move to the next block.
1961 Start = MBBEnd;
1962 if (++MBB == MFEnd)
1963 break;
1964 MBBEnd = LIS.getMBBEndIdx(mbb: &*MBB);
1965 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1966 insertDebugValue(MBB: &*MBB, StartIdx: Start, StopIdx: Stop, DbgValue, LocSpills: SpilledLocs,
1967 SpillOffsets: LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1968 }
1969 LLVM_DEBUG(dbgs() << '\n');
1970 if (MBB == MFEnd)
1971 break;
1972
1973 ++I;
1974 }
1975}
1976
1977void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1978 BlockSkipInstsMap &BBSkipInstsMap) {
1979 LLVM_DEBUG(dbgs() << "\t" << loc);
1980 MachineFunction::iterator MBB = LIS.getMBBFromIndex(index: loc)->getIterator();
1981
1982 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1983 insertDebugLabel(MBB: &*MBB, Idx: loc, LIS, TII, BBSkipInstsMap);
1984
1985 LLVM_DEBUG(dbgs() << '\n');
1986}
1987
1988void LiveDebugVariables::LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1989 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1990 if (!MF)
1991 return;
1992
1993 // Instructions may have been erased since the last allocator run.
1994 canonicalizeIndexes(SI: *LIS->getSlotIndexes());
1995
1996 BlockSkipInstsMap BBSkipInstsMap;
1997 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1998 SpillOffsetMap SpillOffsets;
1999 for (auto &userValue : userValues) {
2000 LLVM_DEBUG(userValue->print(dbgs(), TRI));
2001 userValue->rewriteLocations(VRM&: *VRM, MF: *MF, TII: *TII, TRI: *TRI, SpillOffsets);
2002 userValue->emitDebugValues(VRM, LIS&: *LIS, TII: *TII, TRI: *TRI, SpillOffsets,
2003 BBSkipInstsMap);
2004 }
2005 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
2006 for (auto &userLabel : userLabels) {
2007 LLVM_DEBUG(userLabel->print(dbgs(), TRI));
2008 userLabel->emitDebugLabel(LIS&: *LIS, TII: *TII, BBSkipInstsMap);
2009 }
2010
2011 LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
2012
2013 auto Slots = LIS->getSlotIndexes();
2014 for (auto &It : PHIValToPos) {
2015 // For each ex-PHI, identify its physreg location or stack slot, and emit
2016 // a DBG_PHI for it.
2017 unsigned InstNum = It.first;
2018 auto Slot = It.second.SI;
2019 Register Reg = It.second.Reg;
2020 unsigned SubReg = It.second.SubReg;
2021
2022 MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(index: Slot);
2023 if (VRM->isAssignedReg(virtReg: Reg) && VRM->hasPhys(virtReg: Reg)) {
2024 unsigned PhysReg = VRM->getPhys(virtReg: Reg);
2025 if (SubReg != 0)
2026 PhysReg = TRI->getSubReg(Reg: PhysReg, Idx: SubReg);
2027
2028 auto Builder = BuildMI(BB&: *OrigMBB, I: OrigMBB->begin(), MIMD: DebugLoc(),
2029 MCID: TII->get(Opcode: TargetOpcode::DBG_PHI));
2030 Builder.addReg(RegNo: PhysReg);
2031 Builder.addImm(Val: InstNum);
2032 } else if (VRM->getStackSlot(virtReg: Reg) != VirtRegMap::NO_STACK_SLOT) {
2033 const MachineRegisterInfo &MRI = MF->getRegInfo();
2034 const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
2035 unsigned SpillSize, SpillOffset;
2036
2037 unsigned regSizeInBits = TRI->getRegSizeInBits(RC: *TRC);
2038 if (SubReg)
2039 regSizeInBits = TRI->getSubRegIdxSize(Idx: SubReg);
2040
2041 // Test whether this location is legal with the given subreg. If the
2042 // subregister has a nonzero offset, drop this location, it's too complex
2043 // to describe. (TODO: future work).
2044 bool Success =
2045 TII->getStackSlotRange(RC: TRC, SubIdx: SubReg, Size&: SpillSize, Offset&: SpillOffset, MF: *MF);
2046
2047 if (Success && SpillOffset == 0) {
2048 auto Builder = BuildMI(BB&: *OrigMBB, I: OrigMBB->begin(), MIMD: DebugLoc(),
2049 MCID: TII->get(Opcode: TargetOpcode::DBG_PHI));
2050 Builder.addFrameIndex(Idx: VRM->getStackSlot(virtReg: Reg));
2051 Builder.addImm(Val: InstNum);
2052 // Record how large the original value is. The stack slot might be
2053 // merged and altered during optimisation, but we will want to know how
2054 // large the value is, at this DBG_PHI.
2055 Builder.addImm(Val: regSizeInBits);
2056 }
2057
2058 LLVM_DEBUG(if (SpillOffset != 0) {
2059 dbgs() << "DBG_PHI for " << printReg(Reg, TRI, SubReg)
2060 << " has nonzero offset\n";
2061 });
2062 }
2063 // If there was no mapping for a value ID, it's optimized out. Create no
2064 // DBG_PHI, and any variables using this value will become optimized out.
2065 }
2066 MF->DebugPHIPositions.clear();
2067
2068 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
2069
2070 // Re-insert any debug instrs back in the position they were. We must
2071 // re-insert in the same order to ensure that debug instructions don't swap,
2072 // which could re-order assignments. Do so in a batch -- once we find the
2073 // insert position, insert all instructions at the same SlotIdx. They are
2074 // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
2075 // them in order.
2076 for (auto *StashIt = StashedDebugInstrs.begin();
2077 StashIt != StashedDebugInstrs.end(); ++StashIt) {
2078 SlotIndex Idx = StashIt->Idx;
2079 MachineBasicBlock *MBB = StashIt->MBB;
2080 MachineInstr *MI = StashIt->MI;
2081
2082 auto EmitInstsHere = [this, &StashIt, MBB, Idx,
2083 MI](MachineBasicBlock::iterator InsertPos) {
2084 // Insert this debug instruction.
2085 MBB->insert(I: InsertPos, MI);
2086
2087 // Look at subsequent stashed debug instructions: if they're at the same
2088 // index, insert those too.
2089 auto NextItem = std::next(x: StashIt);
2090 while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
2091 assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
2092 "in the same block");
2093 MBB->insert(I: InsertPos, MI: NextItem->MI);
2094 StashIt = NextItem;
2095 NextItem = std::next(x: StashIt);
2096 };
2097 };
2098
2099 // Start block index: find the first non-debug instr in the block, and
2100 // insert before it.
2101 if (Idx == Slots->getMBBStartIdx(mbb: MBB)) {
2102 MachineBasicBlock::iterator InsertPos =
2103 findInsertLocation(MBB, Idx, LIS&: *LIS, BBSkipInstsMap);
2104 EmitInstsHere(InsertPos);
2105 continue;
2106 }
2107
2108 if (MachineInstr *Pos = Slots->getInstructionFromIndex(index: Idx)) {
2109 // Insert at the end of any debug instructions.
2110 auto PostDebug = std::next(x: MachineBasicBlock::iterator(Pos));
2111 PostDebug = skipDebugInstructionsForward(It: PostDebug, End: MBB->end());
2112 EmitInstsHere(PostDebug);
2113 } else {
2114 // Insert position disappeared; walk forwards through slots until we
2115 // find a new one.
2116 SlotIndex End = Slots->getMBBEndIdx(mbb: MBB);
2117 for (; Idx < End; Idx = Slots->getNextNonNullIndex(Index: Idx)) {
2118 Pos = Slots->getInstructionFromIndex(index: Idx);
2119 if (Pos) {
2120 EmitInstsHere(Pos->getIterator());
2121 break;
2122 }
2123 }
2124
2125 // We have reached the end of the block and didn't find anywhere to
2126 // insert! It's not safe to discard any debug instructions; place them
2127 // in front of the first terminator, or in front of end().
2128 if (Idx >= End) {
2129 auto TermIt = MBB->getFirstTerminator();
2130 EmitInstsHere(TermIt);
2131 }
2132 }
2133 }
2134
2135 EmitDone = true;
2136 BBSkipInstsMap.clear();
2137}
2138
2139void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
2140 if (PImpl)
2141 PImpl->emitDebugValues(VRM);
2142}
2143
2144#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2145LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { print(dbgs()); }
2146#endif
2147
2148void LiveDebugVariables::print(raw_ostream &OS) const {
2149 if (PImpl)
2150 PImpl->print(OS);
2151}
2152