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/MachineDominators.h"
37#include "llvm/CodeGen/MachineFunction.h"
38#include "llvm/CodeGen/MachineInstr.h"
39#include "llvm/CodeGen/MachineInstrBuilder.h"
40#include "llvm/CodeGen/MachineOperand.h"
41#include "llvm/CodeGen/MachinePassManager.h"
42#include "llvm/CodeGen/MachineRegisterInfo.h"
43#include "llvm/CodeGen/SlotIndexes.h"
44#include "llvm/CodeGen/TargetInstrInfo.h"
45#include "llvm/CodeGen/TargetOpcodes.h"
46#include "llvm/CodeGen/TargetRegisterInfo.h"
47#include "llvm/CodeGen/TargetSubtargetInfo.h"
48#include "llvm/CodeGen/VirtRegMap.h"
49#include "llvm/Config/llvm-config.h"
50#include "llvm/IR/DebugInfoMetadata.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/Function.h"
53#include "llvm/InitializePasses.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/CommandLine.h"
57#include "llvm/Support/Debug.h"
58#include "llvm/Support/raw_ostream.h"
59#include <algorithm>
60#include <cassert>
61#include <iterator>
62#include <map>
63#include <memory>
64#include <optional>
65#include <utility>
66
67using namespace llvm;
68
69#define DEBUG_TYPE "livedebugvars"
70
71static cl::opt<bool>
72EnableLDV("live-debug-variables", cl::init(Val: true),
73 cl::desc("Enable the live debug variables pass"), cl::Hidden);
74
75STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
76STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
77
78char LiveDebugVariablesWrapperLegacy::ID = 0;
79
80INITIALIZE_PASS_BEGIN(LiveDebugVariablesWrapperLegacy, DEBUG_TYPE,
81 "Debug Variable Analysis", false, false)
82INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
83INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
84INITIALIZE_PASS_END(LiveDebugVariablesWrapperLegacy, DEBUG_TYPE,
85 "Debug Variable Analysis", false, true)
86
87void LiveDebugVariablesWrapperLegacy::getAnalysisUsage(
88 AnalysisUsage &AU) const {
89 AU.addRequired<MachineDominatorTreeWrapperPass>();
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 /// Rewrite virtual register locations according to the provided virtual
479 /// register map. Record the stack slot offsets for the locations that
480 /// were spilled.
481 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
482 const TargetInstrInfo &TII,
483 const TargetRegisterInfo &TRI,
484 SpillOffsetMap &SpillOffsets);
485
486 /// Recreate DBG_VALUE instruction from data structures.
487 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
488 const TargetInstrInfo &TII,
489 const TargetRegisterInfo &TRI,
490 const SpillOffsetMap &SpillOffsets,
491 BlockSkipInstsMap &BBSkipInstsMap);
492
493 /// Return DebugLoc of this UserValue.
494 const DebugLoc &getDebugLoc() { return dl; }
495
496 void print(raw_ostream &, const TargetRegisterInfo *);
497};
498
499/// A user label is a part of a debug info user label.
500class UserLabel {
501 const DILabel *Label; ///< The debug info label we are part of.
502 DebugLoc dl; ///< The debug location for the label. This is
503 ///< used by dwarf writer to find lexical scope.
504 SlotIndex loc; ///< Slot used by the debug label.
505
506 /// Insert a DBG_LABEL into MBB at Idx.
507 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
508 LiveIntervals &LIS, const TargetInstrInfo &TII,
509 BlockSkipInstsMap &BBSkipInstsMap);
510
511public:
512 /// Create a new UserLabel.
513 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
514 : Label(label), dl(std::move(L)), loc(Idx) {}
515
516 /// Does this UserLabel match the parameters?
517 bool matches(const DILabel *L, const DILocation *IA,
518 const SlotIndex Index) const {
519 return Label == L && dl->getInlinedAt() == IA && loc == Index;
520 }
521
522 /// Recreate DBG_LABEL instruction from data structures.
523 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
524 BlockSkipInstsMap &BBSkipInstsMap);
525
526 /// Return DebugLoc of this UserLabel.
527 const DebugLoc &getDebugLoc() { return dl; }
528
529 void print(raw_ostream &, const TargetRegisterInfo *);
530};
531
532} // end anonymous namespace
533
534namespace llvm {
535
536class LiveDebugVariables::LDVImpl {
537 LocMap::Allocator allocator;
538 MachineFunction *MF = nullptr;
539 LiveIntervals *LIS;
540 const TargetRegisterInfo *TRI;
541
542 /// Position and VReg of a PHI instruction during register allocation.
543 struct PHIValPos {
544 SlotIndex SI; /// Slot where this PHI occurs.
545 Register Reg; /// VReg this PHI occurs in.
546 unsigned SubReg; /// Qualifiying subregister for Reg.
547 };
548
549 /// Map from debug instruction number to PHI position during allocation.
550 std::map<unsigned, PHIValPos> PHIValToPos;
551 /// Index of, for each VReg, which debug instruction numbers and corresponding
552 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
553 /// at different positions.
554 DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
555
556 /// Record for any debug instructions unlinked from their blocks during
557 /// regalloc. Stores the instr and it's location, so that they can be
558 /// re-inserted after regalloc is over.
559 struct InstrPos {
560 MachineInstr *MI; ///< Debug instruction, unlinked from it's block.
561 SlotIndex Idx; ///< Slot position where MI should be re-inserted.
562 MachineBasicBlock *MBB; ///< Block that MI was in.
563 };
564
565 /// Collection of stored debug instructions, preserved until after regalloc.
566 SmallVector<InstrPos, 32> StashedDebugInstrs;
567
568 /// Whether emitDebugValues is called.
569 bool EmitDone = false;
570
571 /// Whether the machine function is modified during the pass.
572 bool ModifiedMF = false;
573
574 /// All allocated UserValue instances.
575 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
576
577 /// All allocated UserLabel instances.
578 SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
579
580 /// Map virtual register to eq class leader.
581 using VRMap = DenseMap<Register, UserValue *>;
582 VRMap virtRegToEqClass;
583
584 /// Map to find existing UserValue instances.
585 using UVMap = DenseMap<DebugVariable, UserValue *>;
586 UVMap userVarMap;
587
588 /// Find or create a UserValue.
589 UserValue *getUserValue(const DILocalVariable *Var,
590 std::optional<DIExpression::FragmentInfo> Fragment,
591 const DebugLoc &DL);
592
593 /// Find the EC leader for VirtReg or null.
594 UserValue *lookupVirtReg(Register VirtReg);
595
596 /// Add DBG_VALUE instruction to our maps.
597 ///
598 /// \param MI DBG_VALUE instruction
599 /// \param Idx Last valid SLotIndex before instruction.
600 ///
601 /// \returns True if the DBG_VALUE instruction should be deleted.
602 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
603
604 /// Track variable location debug instructions while using the instruction
605 /// referencing implementation. Such debug instructions do not need to be
606 /// updated during regalloc because they identify instructions rather than
607 /// register locations. However, they needs to be removed from the
608 /// MachineFunction during regalloc, then re-inserted later, to avoid
609 /// disrupting the allocator.
610 ///
611 /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
612 /// \param Idx Last valid SlotIndex before instruction
613 ///
614 /// \returns Iterator to continue processing from after unlinking.
615 MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
616
617 /// Add DBG_LABEL instruction to UserLabel.
618 ///
619 /// \param MI DBG_LABEL instruction
620 /// \param Idx Last valid SlotIndex before instruction.
621 ///
622 /// \returns True if the DBG_LABEL instruction should be deleted.
623 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
624
625 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
626 /// for each instruction.
627 ///
628 /// \param mf MachineFunction to be scanned.
629 /// \param InstrRef Whether to operate in instruction referencing mode. If
630 /// true, most of LiveDebugVariables doesn't run.
631 ///
632 /// \returns True if any debug values were found.
633 bool collectDebugValues(MachineFunction &mf, bool InstrRef);
634
635 /// Compute the live intervals of all user values after collecting all
636 /// their def points.
637 void computeIntervals();
638
639public:
640 LDVImpl(LiveIntervals *LIS) : LIS(LIS) {}
641
642 bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
643
644 /// Release all memory.
645 void clear() {
646 MF = nullptr;
647 PHIValToPos.clear();
648 RegToPHIIdx.clear();
649 StashedDebugInstrs.clear();
650 userValues.clear();
651 userLabels.clear();
652 virtRegToEqClass.clear();
653 userVarMap.clear();
654 // Make sure we call emitDebugValues if the machine function was modified.
655 assert((!ModifiedMF || EmitDone) &&
656 "Dbg values are not emitted in LDV");
657 EmitDone = false;
658 ModifiedMF = false;
659 }
660
661 /// Map virtual register to an equivalence class.
662 void mapVirtReg(Register VirtReg, UserValue *EC);
663
664 /// Replace any PHI referring to OldReg with its corresponding NewReg, if
665 /// present.
666 void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
667
668 /// Replace all references to OldReg with NewRegs.
669 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
670
671 /// Recreate DBG_VALUE instruction from data structures.
672 void emitDebugValues(VirtRegMap *VRM);
673
674 void print(raw_ostream&);
675};
676
677/// Implementation of the LiveDebugVariables pass.
678
679LiveDebugVariables::LiveDebugVariables() = default;
680LiveDebugVariables::~LiveDebugVariables() = default;
681LiveDebugVariables::LiveDebugVariables(LiveDebugVariables &&) = default;
682
683} // namespace llvm
684
685static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
686 const LLVMContext &Ctx) {
687 if (!DL)
688 return;
689
690 auto *Scope = cast<DIScope>(Val: DL.getScope());
691 // Omit the directory, because it's likely to be long and uninteresting.
692 CommentOS << Scope->getFilename();
693 CommentOS << ':' << DL.getLine();
694 if (DL.getCol() != 0)
695 CommentOS << ':' << DL.getCol();
696
697 DebugLoc InlinedAtDL = DL.getInlinedAt();
698 if (!InlinedAtDL)
699 return;
700
701 CommentOS << " @[ ";
702 printDebugLoc(DL: InlinedAtDL, CommentOS, Ctx);
703 CommentOS << " ]";
704}
705
706static void printExtendedName(raw_ostream &OS, const DINode *Node,
707 const DILocation *DL) {
708 const LLVMContext &Ctx = Node->getContext();
709 StringRef Res;
710 unsigned Line = 0;
711 if (const auto *V = dyn_cast<const DILocalVariable>(Val: Node)) {
712 Res = V->getName();
713 Line = V->getLine();
714 } else if (const auto *L = dyn_cast<const DILabel>(Val: Node)) {
715 Res = L->getName();
716 Line = L->getLine();
717 }
718
719 if (!Res.empty())
720 OS << Res << "," << Line;
721 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
722 if (InlinedAt) {
723 if (DebugLoc InlinedAtDL = InlinedAt) {
724 OS << " @[";
725 printDebugLoc(DL: InlinedAtDL, CommentOS&: OS, Ctx);
726 OS << "]";
727 }
728 }
729}
730
731void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
732 OS << "!\"";
733 printExtendedName(OS, Node: Variable, DL: dl);
734
735 OS << "\"\t";
736 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
737 OS << " [" << I.start() << ';' << I.stop() << "):";
738 if (I.value().isUndef())
739 OS << " undef";
740 else {
741 I.value().printLocNos(OS);
742 if (I.value().getWasIndirect())
743 OS << " ind";
744 else if (I.value().getWasList())
745 OS << " list";
746 }
747 }
748 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
749 OS << " Loc" << i << '=';
750 locations[i].print(os&: OS, TRI);
751 }
752 OS << '\n';
753}
754
755void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
756 OS << "!\"";
757 printExtendedName(OS, Node: Label, DL: dl);
758
759 OS << "\"\t";
760 OS << loc;
761 OS << '\n';
762}
763
764void LiveDebugVariables::LDVImpl::print(raw_ostream &OS) {
765 OS << "********** DEBUG VARIABLES **********\n";
766 for (auto &userValue : userValues)
767 userValue->print(OS, TRI);
768 OS << "********** DEBUG LABELS **********\n";
769 for (auto &userLabel : userLabels)
770 userLabel->print(OS, TRI);
771}
772
773void UserValue::mapVirtRegs(LiveDebugVariables::LDVImpl *LDV) {
774 for (const MachineOperand &MO : locations)
775 if (MO.isReg() && MO.getReg().isVirtual())
776 LDV->mapVirtReg(VirtReg: MO.getReg(), EC: this);
777}
778
779UserValue *LiveDebugVariables::LDVImpl::getUserValue(
780 const DILocalVariable *Var,
781 std::optional<DIExpression::FragmentInfo> Fragment, const DebugLoc &DL) {
782 // FIXME: Handle partially overlapping fragments. See
783 // https://reviews.llvm.org/D70121#1849741.
784 DebugVariable ID(Var, Fragment, DL->getInlinedAt());
785 UserValue *&UV = userVarMap[ID];
786 if (!UV) {
787 userValues.push_back(
788 Elt: std::make_unique<UserValue>(args&: Var, args&: Fragment, args: DL, args&: allocator));
789 UV = userValues.back().get();
790 }
791 return UV;
792}
793
794void LiveDebugVariables::LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
795 assert(VirtReg.isVirtual() && "Only map VirtRegs");
796 UserValue *&Leader = virtRegToEqClass[VirtReg];
797 Leader = UserValue::merge(L1: Leader, L2: EC);
798}
799
800UserValue *LiveDebugVariables::LDVImpl::lookupVirtReg(Register VirtReg) {
801 if (UserValue *UV = virtRegToEqClass.lookup(Val: VirtReg))
802 return UV->getLeader();
803 return nullptr;
804}
805
806bool LiveDebugVariables::LDVImpl::handleDebugValue(MachineInstr &MI,
807 SlotIndex Idx) {
808 // DBG_VALUE loc, offset, variable, expr
809 // DBG_VALUE_LIST variable, expr, locs...
810 if (!MI.isDebugValue()) {
811 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
812 return false;
813 }
814 if (!MI.getDebugVariableOp().isMetadata()) {
815 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
816 << MI);
817 return false;
818 }
819 if (MI.isNonListDebugValue() &&
820 (MI.getNumOperands() != 4 ||
821 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
822 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
823 return false;
824 }
825
826 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
827 // register that hasn't been defined yet. If we do not remove those here, then
828 // the re-insertion of the DBG_VALUE instruction after register allocation
829 // will be incorrect.
830 bool Discard = false;
831 for (const MachineOperand &Op : MI.debug_operands()) {
832 if (Op.isReg() && Op.getReg().isVirtual()) {
833 const Register Reg = Op.getReg();
834 if (!LIS->hasInterval(Reg)) {
835 // The DBG_VALUE is described by a virtual register that does not have a
836 // live interval. Discard the DBG_VALUE.
837 Discard = true;
838 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
839 << " " << MI);
840 } else {
841 // The DBG_VALUE is only valid if either Reg is live out from Idx, or
842 // Reg is defined dead at Idx (where Idx is the slot index for the
843 // instruction preceding the DBG_VALUE).
844 const LiveInterval &LI = LIS->getInterval(Reg);
845 LiveQueryResult LRQ = LI.Query(Idx);
846 if (!LRQ.valueOutOrDead()) {
847 // We have found a DBG_VALUE with the value in a virtual register that
848 // is not live. Discard the DBG_VALUE.
849 Discard = true;
850 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
851 << " " << MI);
852 }
853 }
854 }
855 }
856
857 // Get or create the UserValue for (variable,offset) here.
858 bool IsIndirect = MI.isDebugOffsetImm();
859 if (IsIndirect)
860 assert(MI.getDebugOffset().getImm() == 0 &&
861 "DBG_VALUE with nonzero offset");
862 bool IsList = MI.isDebugValueList();
863 const DILocalVariable *Var = MI.getDebugVariable();
864 const DIExpression *Expr = MI.getDebugExpression();
865 UserValue *UV = getUserValue(Var, Fragment: Expr->getFragmentInfo(), DL: MI.getDebugLoc());
866 if (!Discard)
867 UV->addDef(Idx,
868 LocMOs: ArrayRef<MachineOperand>(MI.debug_operands().begin(),
869 MI.debug_operands().end()),
870 IsIndirect, IsList, Expr: *Expr);
871 else {
872 MachineOperand MO = MachineOperand::CreateReg(Reg: 0U, isDef: false);
873 MO.setIsDebug();
874 // We should still pass a list the same size as MI.debug_operands() even if
875 // all MOs are undef, so that DbgVariableValue can correctly adjust the
876 // expression while removing the duplicated undefs.
877 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
878 UV->addDef(Idx, LocMOs: UndefMOs, IsIndirect: false, IsList, Expr: *Expr);
879 }
880 return true;
881}
882
883MachineBasicBlock::iterator
884LiveDebugVariables::LDVImpl::handleDebugInstr(MachineInstr &MI, SlotIndex Idx) {
885 assert(MI.isDebugValueLike() || MI.isDebugPHI());
886
887 // In instruction referencing mode, there should be no DBG_VALUE instructions
888 // that refer to virtual registers. They might still refer to constants.
889 if (MI.isDebugValueLike())
890 assert(none_of(MI.debug_operands(),
891 [](const MachineOperand &MO) {
892 return MO.isReg() && MO.getReg().isVirtual();
893 }) &&
894 "MIs should not refer to Virtual Registers in InstrRef mode.");
895
896 // Unlink the instruction, store it in the debug instructions collection.
897 auto NextInst = std::next(x: MI.getIterator());
898 auto *MBB = MI.getParent();
899 MI.removeFromParent();
900 StashedDebugInstrs.push_back(Elt: {.MI: &MI, .Idx: Idx, .MBB: MBB});
901 return NextInst;
902}
903
904bool LiveDebugVariables::LDVImpl::handleDebugLabel(MachineInstr &MI,
905 SlotIndex Idx) {
906 // DBG_LABEL label
907 if (MI.getNumOperands() != 1 || !MI.getOperand(i: 0).isMetadata()) {
908 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
909 return false;
910 }
911
912 // Get or create the UserLabel for label here.
913 const DILabel *Label = MI.getDebugLabel();
914 const DebugLoc &DL = MI.getDebugLoc();
915 bool Found = false;
916 for (auto const &L : userLabels) {
917 if (L->matches(L: Label, IA: DL->getInlinedAt(), Index: Idx)) {
918 Found = true;
919 break;
920 }
921 }
922 if (!Found)
923 userLabels.push_back(Elt: std::make_unique<UserLabel>(args&: Label, args: DL, args&: Idx));
924
925 return true;
926}
927
928bool LiveDebugVariables::LDVImpl::collectDebugValues(MachineFunction &mf,
929 bool InstrRef) {
930 bool Changed = false;
931 for (MachineBasicBlock &MBB : mf) {
932 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
933 MBBI != MBBE;) {
934 // Use the first debug instruction in the sequence to get a SlotIndex
935 // for following consecutive debug instructions.
936 if (!MBBI->isDebugOrPseudoInstr()) {
937 ++MBBI;
938 continue;
939 }
940 // Debug instructions has no slot index. Use the previous
941 // non-debug instruction's SlotIndex as its SlotIndex.
942 SlotIndex Idx =
943 MBBI == MBB.begin()
944 ? LIS->getMBBStartIdx(mbb: &MBB)
945 : LIS->getInstructionIndex(Instr: *std::prev(x: MBBI)).getRegSlot();
946 // Handle consecutive debug instructions with the same slot index.
947 do {
948 // In instruction referencing mode, pass each instr to handleDebugInstr
949 // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
950 // need to go through the normal live interval splitting process.
951 if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
952 MBBI->isDebugRef())) {
953 MBBI = handleDebugInstr(MI&: *MBBI, Idx);
954 Changed = true;
955 // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
956 // to track things through register allocation, and erase the instr.
957 } else if ((MBBI->isDebugValue() && handleDebugValue(MI&: *MBBI, Idx)) ||
958 (MBBI->isDebugLabel() && handleDebugLabel(MI&: *MBBI, Idx))) {
959 MBBI = MBB.erase(I: MBBI);
960 Changed = true;
961 } else
962 ++MBBI;
963 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
964 }
965 }
966 return Changed;
967}
968
969void UserValue::extendDef(
970 SlotIndex Idx, DbgVariableValue DbgValue,
971 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
972 &LiveIntervalInfo,
973 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
974 LiveIntervals &LIS) {
975 SlotIndex Start = Idx;
976 MachineBasicBlock *MBB = LIS.getMBBFromIndex(index: Start);
977 SlotIndex Stop = LIS.getMBBEndIdx(mbb: MBB);
978 LocMap::iterator I = locInts.find(x: Start);
979
980 // Limit to the intersection of the VNIs' live ranges.
981 for (auto &LII : LiveIntervalInfo) {
982 LiveRange *LR = LII.second.first;
983 assert(LR && LII.second.second && "Missing range info for Idx.");
984 LiveInterval::Segment *Segment = LR->getSegmentContaining(Idx: Start);
985 assert(Segment && Segment->valno == LII.second.second &&
986 "Invalid VNInfo for Idx given?");
987 if (Segment->end < Stop) {
988 Stop = Segment->end;
989 Kills = {Stop, {LII.first}};
990 } else if (Segment->end == Stop && Kills) {
991 // If multiple locations end at the same place, track all of them in
992 // Kills.
993 Kills->second.push_back(Elt: LII.first);
994 }
995 }
996
997 // There could already be a short def at Start.
998 if (I.valid() && I.start() <= Start) {
999 // Stop when meeting a different location or an already extended interval.
1000 Start = Start.getNextSlot();
1001 if (I.value() != DbgValue || I.stop() != Start) {
1002 // Clear `Kills`, as we have a new def available.
1003 Kills = std::nullopt;
1004 return;
1005 }
1006 // This is a one-slot placeholder. Just skip it.
1007 ++I;
1008 }
1009
1010 // Limited by the next def.
1011 if (I.valid() && I.start() < Stop) {
1012 Stop = I.start();
1013 // Clear `Kills`, as we have a new def available.
1014 Kills = std::nullopt;
1015 }
1016
1017 if (Start < Stop) {
1018 DbgVariableValue ExtDbgValue(DbgValue);
1019 I.insert(a: Start, b: Stop, y: std::move(ExtDbgValue));
1020 }
1021}
1022
1023void UserValue::addDefsFromCopies(
1024 DbgVariableValue DbgValue,
1025 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1026 SlotIndex KilledAt,
1027 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
1028 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
1029 // Don't track copies from physregs, there are too many uses.
1030 if (any_of(Range&: LocIntervals,
1031 P: [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
1032 return;
1033
1034 // Collect all the (vreg, valno) pairs that are copies of LI.
1035 SmallDenseMap<unsigned,
1036 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1037 CopyValues;
1038 for (auto &LocInterval : LocIntervals) {
1039 unsigned LocNo = LocInterval.first;
1040 LiveInterval *LI = LocInterval.second;
1041 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg: LI->reg())) {
1042 MachineInstr *MI = MO.getParent();
1043 // Copies of the full value.
1044 if (MO.getSubReg() || !MI->isCopy())
1045 continue;
1046 Register DstReg = MI->getOperand(i: 0).getReg();
1047
1048 // Don't follow copies to physregs. These are usually setting up call
1049 // arguments, and the argument registers are always call clobbered. We are
1050 // better off in the source register which could be a callee-saved
1051 // register, or it could be spilled.
1052 if (!DstReg.isVirtual())
1053 continue;
1054
1055 // Is the value extended to reach this copy? If not, another def may be
1056 // blocking it, or we are looking at a wrong value of LI.
1057 SlotIndex Idx = LIS.getInstructionIndex(Instr: *MI);
1058 LocMap::iterator I = locInts.find(x: Idx.getRegSlot(EC: true));
1059 if (!I.valid() || I.value() != DbgValue)
1060 continue;
1061
1062 if (!LIS.hasInterval(Reg: DstReg))
1063 continue;
1064 LiveInterval *DstLI = &LIS.getInterval(Reg: DstReg);
1065 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx: Idx.getRegSlot());
1066 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1067 CopyValues[LocNo].push_back(Elt: std::make_pair(x&: DstLI, y&: DstVNI));
1068 }
1069 }
1070
1071 if (CopyValues.empty())
1072 return;
1073
1074#if !defined(NDEBUG)
1075 for (auto &LocInterval : LocIntervals)
1076 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1077 << " copies of " << *LocInterval.second << '\n');
1078#endif
1079
1080 // Try to add defs of the copied values for the kill point. Check that there
1081 // isn't already a def at Idx.
1082 LocMap::iterator I = locInts.find(x: KilledAt);
1083 if (I.valid() && I.start() <= KilledAt)
1084 return;
1085 DbgVariableValue NewValue(DbgValue);
1086 for (auto &LocInterval : LocIntervals) {
1087 unsigned LocNo = LocInterval.first;
1088 bool FoundCopy = false;
1089 for (auto &LIAndVNI : CopyValues[LocNo]) {
1090 LiveInterval *DstLI = LIAndVNI.first;
1091 const VNInfo *DstVNI = LIAndVNI.second;
1092 if (DstLI->getVNInfoAt(Idx: KilledAt) != DstVNI)
1093 continue;
1094 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
1095 << DstVNI->id << " in " << *DstLI << '\n');
1096 MachineInstr *CopyMI = LIS.getInstructionFromIndex(index: DstVNI->def);
1097 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1098 unsigned NewLocNo = getLocationNo(LocMO: CopyMI->getOperand(i: 0));
1099 NewValue = NewValue.changeLocNo(OldLocNo: LocNo, NewLocNo);
1100 FoundCopy = true;
1101 break;
1102 }
1103 // If there are any killed locations we can't find a copy for, we can't
1104 // extend the variable value.
1105 if (!FoundCopy)
1106 return;
1107 }
1108 I.insert(a: KilledAt, b: KilledAt.getNextSlot(), y: NewValue);
1109 NewDefs.push_back(Elt: std::make_pair(x&: KilledAt, y&: NewValue));
1110}
1111
1112void UserValue::computeIntervals(MachineRegisterInfo &MRI,
1113 const TargetRegisterInfo &TRI,
1114 LiveIntervals &LIS, LexicalScopes &LS) {
1115 SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
1116
1117 // Collect all defs to be extended (Skipping undefs).
1118 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1119 if (!I.value().isUndef())
1120 Defs.push_back(Elt: std::make_pair(x: I.start(), y: I.value()));
1121
1122 // Extend all defs, and possibly add new ones along the way.
1123 for (unsigned i = 0; i != Defs.size(); ++i) {
1124 SlotIndex Idx = Defs[i].first;
1125 DbgVariableValue DbgValue = Defs[i].second;
1126 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1127 bool ShouldExtendDef = false;
1128 for (unsigned LocNo : DbgValue.loc_nos()) {
1129 const MachineOperand &LocMO = locations[LocNo];
1130 if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1131 ShouldExtendDef |= !LocMO.isReg();
1132 continue;
1133 }
1134 ShouldExtendDef = true;
1135 LiveInterval *LI = nullptr;
1136 const VNInfo *VNI = nullptr;
1137 if (LIS.hasInterval(Reg: LocMO.getReg())) {
1138 LI = &LIS.getInterval(Reg: LocMO.getReg());
1139 VNI = LI->getVNInfoAt(Idx);
1140 }
1141 if (LI && VNI)
1142 LIs[LocNo] = {LI, VNI};
1143 }
1144 if (ShouldExtendDef) {
1145 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1146 extendDef(Idx, DbgValue, LiveIntervalInfo&: LIs, Kills, LIS);
1147
1148 if (Kills) {
1149 SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1150 bool AnySubreg = false;
1151 for (unsigned LocNo : Kills->second) {
1152 const MachineOperand &LocMO = this->locations[LocNo];
1153 if (LocMO.getSubReg()) {
1154 AnySubreg = true;
1155 break;
1156 }
1157 LiveInterval *LI = &LIS.getInterval(Reg: LocMO.getReg());
1158 KilledLocIntervals.push_back(Elt: {LocNo, LI});
1159 }
1160
1161 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1162 // if the original location for example is %vreg0:sub_hi, and we find a
1163 // full register copy in addDefsFromCopies (at the moment it only
1164 // handles full register copies), then we must add the sub1 sub-register
1165 // index to the new location. However, that is only possible if the new
1166 // virtual register is of the same regclass (or if there is an
1167 // equivalent sub-register in that regclass). For now, simply skip
1168 // handling copies if a sub-register is involved.
1169 if (!AnySubreg)
1170 addDefsFromCopies(DbgValue, LocIntervals&: KilledLocIntervals, KilledAt: Kills->first, NewDefs&: Defs,
1171 MRI, LIS);
1172 }
1173 }
1174
1175 // For physregs, we only mark the start slot idx. DwarfDebug will see it
1176 // as if the DBG_VALUE is valid up until the end of the basic block, or
1177 // the next def of the physical register. So we do not need to extend the
1178 // range. It might actually happen that the DBG_VALUE is the last use of
1179 // the physical register (e.g. if this is an unused input argument to a
1180 // function).
1181 }
1182
1183 // The computed intervals may extend beyond the range of the debug
1184 // location's lexical scope. In this case, splitting of an interval
1185 // can result in an interval outside of the scope being created,
1186 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1187 // this, trim the intervals to the lexical scope in the case of inlined
1188 // variables, since heavy inlining may cause production of dramatically big
1189 // number of DBG_VALUEs to be generated.
1190 if (!dl.getInlinedAt())
1191 return;
1192
1193 LexicalScope *Scope = LS.findLexicalScope(DL: dl);
1194 if (!Scope)
1195 return;
1196
1197 SlotIndex PrevEnd;
1198 LocMap::iterator I = locInts.begin();
1199
1200 // Iterate over the lexical scope ranges. Each time round the loop
1201 // we check the intervals for overlap with the end of the previous
1202 // range and the start of the next. The first range is handled as
1203 // a special case where there is no PrevEnd.
1204 for (const InsnRange &Range : Scope->getRanges()) {
1205 SlotIndex RStart = LIS.getInstructionIndex(Instr: *Range.first);
1206 SlotIndex REnd = LIS.getInstructionIndex(Instr: *Range.second);
1207
1208 // Variable locations at the first instruction of a block should be
1209 // based on the block's SlotIndex, not the first instruction's index.
1210 if (Range.first == Range.first->getParent()->begin())
1211 RStart = LIS.getSlotIndexes()->getIndexBefore(MI: *Range.first);
1212
1213 // At the start of each iteration I has been advanced so that
1214 // I.stop() >= PrevEnd. Check for overlap.
1215 if (PrevEnd && I.start() < PrevEnd) {
1216 SlotIndex IStop = I.stop();
1217 DbgVariableValue DbgValue = I.value();
1218
1219 // Stop overlaps previous end - trim the end of the interval to
1220 // the scope range.
1221 I.setStopUnchecked(PrevEnd);
1222 ++I;
1223
1224 // If the interval also overlaps the start of the "next" (i.e.
1225 // current) range create a new interval for the remainder (which
1226 // may be further trimmed).
1227 if (RStart < IStop)
1228 I.insert(a: RStart, b: IStop, y: DbgValue);
1229 }
1230
1231 // Advance I so that I.stop() >= RStart, and check for overlap.
1232 I.advanceTo(x: RStart);
1233 if (!I.valid())
1234 return;
1235
1236 if (I.start() < RStart) {
1237 // Interval start overlaps range - trim to the scope range.
1238 I.setStartUnchecked(RStart);
1239 // Remember that this interval was trimmed.
1240 trimmedDefs.insert(V: RStart);
1241 }
1242
1243 // The end of a lexical scope range is the last instruction in the
1244 // range. To convert to an interval we need the index of the
1245 // instruction after it.
1246 REnd = REnd.getNextIndex();
1247
1248 // Advance I to first interval outside current range.
1249 I.advanceTo(x: REnd);
1250 if (!I.valid())
1251 return;
1252
1253 PrevEnd = REnd;
1254 }
1255
1256 // Check for overlap with end of final range.
1257 if (PrevEnd && I.start() < PrevEnd)
1258 I.setStopUnchecked(PrevEnd);
1259}
1260
1261void LiveDebugVariables::LDVImpl::computeIntervals() {
1262 LexicalScopes LS;
1263 LS.scanFunction(*MF);
1264
1265 for (const auto &UV : userValues) {
1266 UV->computeIntervals(MRI&: MF->getRegInfo(), TRI: *TRI, LIS&: *LIS, LS);
1267 UV->mapVirtRegs(LDV: this);
1268 }
1269}
1270
1271bool LiveDebugVariables::LDVImpl::runOnMachineFunction(MachineFunction &mf,
1272 bool InstrRef) {
1273 clear();
1274 MF = &mf;
1275 TRI = mf.getSubtarget().getRegisterInfo();
1276 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1277 << mf.getName() << " **********\n");
1278
1279 bool Changed = collectDebugValues(mf, InstrRef);
1280 computeIntervals();
1281 LLVM_DEBUG(print(dbgs()));
1282
1283 // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1284 // VRegs too, for when we're notified of a range split.
1285 SlotIndexes *Slots = LIS->getSlotIndexes();
1286 for (const auto &PHIIt : MF->DebugPHIPositions) {
1287 const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1288 MachineBasicBlock *MBB = Position.MBB;
1289 Register Reg = Position.Reg;
1290 unsigned SubReg = Position.SubReg;
1291 SlotIndex SI = Slots->getMBBStartIdx(mbb: MBB);
1292 PHIValPos VP = {.SI: SI, .Reg: Reg, .SubReg: SubReg};
1293 PHIValToPos.insert(x: std::make_pair(x: PHIIt.first, y&: VP));
1294 RegToPHIIdx[Reg].push_back(x: PHIIt.first);
1295 }
1296
1297 ModifiedMF = Changed;
1298 return Changed;
1299}
1300
1301static void removeDebugInstrs(MachineFunction &mf) {
1302 for (MachineBasicBlock &MBB : mf) {
1303 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: MBB))
1304 if (MI.isDebugInstr())
1305 MBB.erase(I: &MI);
1306 }
1307}
1308
1309bool LiveDebugVariablesWrapperLegacy::runOnMachineFunction(
1310 MachineFunction &mf) {
1311 auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1312
1313 Impl = std::make_unique<LiveDebugVariables>();
1314 Impl->analyze(MF&: mf, LIS);
1315 return false;
1316}
1317
1318AnalysisKey LiveDebugVariablesAnalysis::Key;
1319
1320LiveDebugVariables
1321LiveDebugVariablesAnalysis::run(MachineFunction &MF,
1322 MachineFunctionAnalysisManager &MFAM) {
1323 MFPropsModifier _(*this, MF);
1324
1325 auto *LIS = &MFAM.getResult<LiveIntervalsAnalysis>(IR&: MF);
1326 LiveDebugVariables LDV;
1327 LDV.analyze(MF, LIS);
1328 return LDV;
1329}
1330
1331PreservedAnalyses
1332LiveDebugVariablesPrinterPass::run(MachineFunction &MF,
1333 MachineFunctionAnalysisManager &MFAM) {
1334 auto &LDV = MFAM.getResult<LiveDebugVariablesAnalysis>(IR&: MF);
1335 LDV.print(OS);
1336 return PreservedAnalyses::all();
1337}
1338
1339void LiveDebugVariables::releaseMemory() {
1340 if (PImpl)
1341 PImpl->clear();
1342}
1343
1344bool LiveDebugVariables::invalidate(
1345 MachineFunction &, const PreservedAnalyses &PA,
1346 MachineFunctionAnalysisManager::Invalidator &) {
1347 auto PAC = PA.getChecker<LiveDebugVariablesAnalysis>();
1348 // Some architectures split the register allocation into multiple phases based
1349 // on register classes. This requires preserving analyses between the phases
1350 // by default.
1351 return !PAC.preservedWhenStateless();
1352}
1353
1354void LiveDebugVariables::analyze(MachineFunction &MF, LiveIntervals *LIS) {
1355 if (!EnableLDV)
1356 return;
1357 if (!MF.getFunction().getSubprogram()) {
1358 removeDebugInstrs(mf&: MF);
1359 return;
1360 }
1361
1362 PImpl.reset(p: new LDVImpl(LIS));
1363
1364 // Have we been asked to track variable locations using instruction
1365 // referencing?
1366 bool InstrRef = MF.useDebugInstrRef();
1367 PImpl->runOnMachineFunction(mf&: MF, InstrRef);
1368}
1369
1370//===----------------------------------------------------------------------===//
1371// Live Range Splitting
1372//===----------------------------------------------------------------------===//
1373
1374bool
1375UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1376 LiveIntervals& LIS) {
1377 LLVM_DEBUG({
1378 dbgs() << "Splitting Loc" << OldLocNo << '\t';
1379 print(dbgs(), nullptr);
1380 });
1381 bool DidChange = false;
1382 LocMap::iterator LocMapI;
1383 LocMapI.setMap(locInts);
1384 for (Register NewReg : NewRegs) {
1385 LiveInterval *LI = &LIS.getInterval(Reg: NewReg);
1386 if (LI->empty())
1387 continue;
1388
1389 // Don't allocate the new LocNo until it is needed.
1390 unsigned NewLocNo = UndefLocNo;
1391
1392 // Iterate over the overlaps between locInts and LI.
1393 LocMapI.find(x: LI->beginIndex());
1394 if (!LocMapI.valid())
1395 continue;
1396 LiveInterval::iterator LII = LI->advanceTo(I: LI->begin(), Pos: LocMapI.start());
1397 LiveInterval::iterator LIE = LI->end();
1398 while (LocMapI.valid() && LII != LIE) {
1399 // At this point, we know that LocMapI.stop() > LII->start.
1400 LII = LI->advanceTo(I: LII, Pos: LocMapI.start());
1401 if (LII == LIE)
1402 break;
1403
1404 // Now LII->end > LocMapI.start(). Do we have an overlap?
1405 if (LocMapI.value().containsLocNo(LocNo: OldLocNo) &&
1406 LII->start < LocMapI.stop()) {
1407 // Overlapping correct location. Allocate NewLocNo now.
1408 if (NewLocNo == UndefLocNo) {
1409 MachineOperand MO = MachineOperand::CreateReg(Reg: LI->reg(), isDef: false);
1410 MO.setSubReg(locations[OldLocNo].getSubReg());
1411 NewLocNo = getLocationNo(LocMO: MO);
1412 DidChange = true;
1413 }
1414
1415 SlotIndex LStart = LocMapI.start();
1416 SlotIndex LStop = LocMapI.stop();
1417 DbgVariableValue OldDbgValue = LocMapI.value();
1418
1419 // Trim LocMapI down to the LII overlap.
1420 if (LStart < LII->start)
1421 LocMapI.setStartUnchecked(LII->start);
1422 if (LStop > LII->end)
1423 LocMapI.setStopUnchecked(LII->end);
1424
1425 // Change the value in the overlap. This may trigger coalescing.
1426 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1427
1428 // Re-insert any removed OldDbgValue ranges.
1429 if (LStart < LocMapI.start()) {
1430 LocMapI.insert(a: LStart, b: LocMapI.start(), y: OldDbgValue);
1431 ++LocMapI;
1432 assert(LocMapI.valid() && "Unexpected coalescing");
1433 }
1434 if (LStop > LocMapI.stop()) {
1435 ++LocMapI;
1436 LocMapI.insert(a: LII->end, b: LStop, y: OldDbgValue);
1437 --LocMapI;
1438 }
1439 }
1440
1441 // Advance to the next overlap.
1442 if (LII->end < LocMapI.stop()) {
1443 if (++LII == LIE)
1444 break;
1445 LocMapI.advanceTo(x: LII->start);
1446 } else {
1447 ++LocMapI;
1448 if (!LocMapI.valid())
1449 break;
1450 LII = LI->advanceTo(I: LII, Pos: LocMapI.start());
1451 }
1452 }
1453 }
1454
1455 // Finally, remove OldLocNo unless it is still used by some interval in the
1456 // locInts map. One case when OldLocNo still is in use is when the register
1457 // has been spilled. In such situations the spilled register is kept as a
1458 // location until rewriteLocations is called (VirtRegMap is mapping the old
1459 // register to the spill slot). So for a while we can have locations that map
1460 // to virtual registers that have been removed from both the MachineFunction
1461 // and from LiveIntervals.
1462 //
1463 // We may also just be using the location for a value with a different
1464 // expression.
1465 removeLocationIfUnused(LocNo: OldLocNo);
1466
1467 LLVM_DEBUG({
1468 dbgs() << "Split result: \t";
1469 print(dbgs(), nullptr);
1470 });
1471 return DidChange;
1472}
1473
1474bool
1475UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1476 LiveIntervals &LIS) {
1477 bool DidChange = false;
1478 // Split locations referring to OldReg. Iterate backwards so splitLocation can
1479 // safely erase unused locations.
1480 for (unsigned i = locations.size(); i ; --i) {
1481 unsigned LocNo = i-1;
1482 const MachineOperand *Loc = &locations[LocNo];
1483 if (!Loc->isReg() || Loc->getReg() != OldReg)
1484 continue;
1485 DidChange |= splitLocation(OldLocNo: LocNo, NewRegs, LIS);
1486 }
1487 return DidChange;
1488}
1489
1490void LiveDebugVariables::LDVImpl::splitPHIRegister(Register OldReg,
1491 ArrayRef<Register> NewRegs) {
1492 auto RegIt = RegToPHIIdx.find(Val: OldReg);
1493 if (RegIt == RegToPHIIdx.end())
1494 return;
1495
1496 std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1497 // Iterate over all the debug instruction numbers affected by this split.
1498 for (unsigned InstrID : RegIt->second) {
1499 auto PHIIt = PHIValToPos.find(x: InstrID);
1500 assert(PHIIt != PHIValToPos.end());
1501 const SlotIndex &Slot = PHIIt->second.SI;
1502 assert(OldReg == PHIIt->second.Reg);
1503
1504 // Find the new register that covers this position.
1505 for (auto NewReg : NewRegs) {
1506 const LiveInterval &LI = LIS->getInterval(Reg: NewReg);
1507 auto LII = LI.find(Pos: Slot);
1508 if (LII != LI.end() && LII->start <= Slot) {
1509 // This new register covers this PHI position, record this for indexing.
1510 NewRegIdxes.push_back(x: std::make_pair(x&: NewReg, y&: InstrID));
1511 // Record that this value lives in a different VReg now.
1512 PHIIt->second.Reg = NewReg;
1513 break;
1514 }
1515 }
1516
1517 // If we do not find a new register covering this PHI, then register
1518 // allocation has dropped its location, for example because it's not live.
1519 // The old VReg will not be mapped to a physreg, and the instruction
1520 // number will have been optimized out.
1521 }
1522
1523 // Re-create register index using the new register numbers.
1524 RegToPHIIdx.erase(I: RegIt);
1525 for (auto &RegAndInstr : NewRegIdxes)
1526 RegToPHIIdx[RegAndInstr.first].push_back(x: RegAndInstr.second);
1527}
1528
1529void LiveDebugVariables::LDVImpl::splitRegister(Register OldReg,
1530 ArrayRef<Register> NewRegs) {
1531 // Consider whether this split range affects any PHI locations.
1532 splitPHIRegister(OldReg, NewRegs);
1533
1534 // Check whether any intervals mapped by a DBG_VALUE were split and need
1535 // updating.
1536 bool DidChange = false;
1537 for (UserValue *UV = lookupVirtReg(VirtReg: OldReg); UV; UV = UV->getNext())
1538 DidChange |= UV->splitRegister(OldReg, NewRegs, LIS&: *LIS);
1539
1540 if (!DidChange)
1541 return;
1542
1543 // Map all of the new virtual registers.
1544 UserValue *UV = lookupVirtReg(VirtReg: OldReg);
1545 for (Register NewReg : NewRegs)
1546 mapVirtReg(VirtReg: NewReg, EC: UV);
1547}
1548
1549void LiveDebugVariables::
1550splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
1551 if (PImpl)
1552 PImpl->splitRegister(OldReg, NewRegs);
1553}
1554
1555void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1556 const TargetInstrInfo &TII,
1557 const TargetRegisterInfo &TRI,
1558 SpillOffsetMap &SpillOffsets) {
1559 // Build a set of new locations with new numbers so we can coalesce our
1560 // IntervalMap if two vreg intervals collapse to the same physical location.
1561 // Use MapVector instead of SetVector because MapVector::insert returns the
1562 // position of the previously or newly inserted element. The boolean value
1563 // tracks if the location was produced by a spill.
1564 // FIXME: This will be problematic if we ever support direct and indirect
1565 // frame index locations, i.e. expressing both variables in memory and
1566 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1567 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1568 SmallVector<unsigned, 4> LocNoMap(locations.size());
1569 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1570 bool Spilled = false;
1571 unsigned SpillOffset = 0;
1572 MachineOperand Loc = locations[I];
1573 // Only virtual registers are rewritten.
1574 if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
1575 Register VirtReg = Loc.getReg();
1576 if (VRM.isAssignedReg(virtReg: VirtReg) && VRM.hasPhys(virtReg: VirtReg)) {
1577 // This can create a %noreg operand in rare cases when the sub-register
1578 // index is no longer available. That means the user value is in a
1579 // non-existent sub-register, and %noreg is exactly what we want.
1580 Loc.substPhysReg(Reg: VRM.getPhys(virtReg: VirtReg), TRI);
1581 } else if (VRM.getStackSlot(virtReg: VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1582 // Retrieve the stack slot offset.
1583 unsigned SpillSize;
1584 const MachineRegisterInfo &MRI = MF.getRegInfo();
1585 const TargetRegisterClass *TRC = MRI.getRegClass(Reg: VirtReg);
1586 bool Success = TII.getStackSlotRange(RC: TRC, SubIdx: Loc.getSubReg(), Size&: SpillSize,
1587 Offset&: SpillOffset, MF);
1588
1589 // FIXME: Invalidate the location if the offset couldn't be calculated.
1590 (void)Success;
1591
1592 Loc = MachineOperand::CreateFI(Idx: VRM.getStackSlot(virtReg: VirtReg));
1593 Spilled = true;
1594 } else {
1595 Loc.setReg(0);
1596 Loc.setSubReg(0);
1597 }
1598 }
1599
1600 // Insert this location if it doesn't already exist and record a mapping
1601 // from the old number to the new number.
1602 auto InsertResult = NewLocations.insert(KV: {Loc, {Spilled, SpillOffset}});
1603 unsigned NewLocNo = std::distance(first: NewLocations.begin(), last: InsertResult.first);
1604 LocNoMap[I] = NewLocNo;
1605 }
1606
1607 // Rewrite the locations and record the stack slot offsets for spills.
1608 locations.clear();
1609 SpillOffsets.clear();
1610 for (auto &Pair : NewLocations) {
1611 bool Spilled;
1612 unsigned SpillOffset;
1613 std::tie(args&: Spilled, args&: SpillOffset) = Pair.second;
1614 locations.push_back(Elt: Pair.first);
1615 if (Spilled) {
1616 unsigned NewLocNo = std::distance(first: &*NewLocations.begin(), last: &Pair);
1617 SpillOffsets[NewLocNo] = SpillOffset;
1618 }
1619 }
1620
1621 // Update the interval map, but only coalesce left, since intervals to the
1622 // right use the old location numbers. This should merge two contiguous
1623 // DBG_VALUE intervals with different vregs that were allocated to the same
1624 // physical register.
1625 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1626 I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1627 I.setStart(I.start());
1628 }
1629}
1630
1631/// Find an iterator for inserting a DBG_VALUE instruction.
1632static MachineBasicBlock::iterator
1633findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1634 BlockSkipInstsMap &BBSkipInstsMap) {
1635 SlotIndex Start = LIS.getMBBStartIdx(mbb: MBB);
1636 Idx = Idx.getBaseIndex();
1637
1638 // Try to find an insert location by going backwards from Idx.
1639 MachineInstr *MI;
1640 while (!(MI = LIS.getInstructionFromIndex(index: Idx))) {
1641 // We've reached the beginning of MBB.
1642 if (Idx == Start) {
1643 // Retrieve the last PHI/Label/Debug location found when calling
1644 // SkipPHIsLabelsAndDebug last time. Start searching from there.
1645 //
1646 // Note the iterator kept in BBSkipInstsMap is one step back based
1647 // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1648 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1649 // BBSkipInstsMap won't save it. This is to consider the case that
1650 // new instructions may be inserted at the beginning of MBB after
1651 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1652 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1653 // are inserted at the beginning of the MBB, the iterator in
1654 // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1655 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1656 // newly added instructions and that is unwanted.
1657 MachineBasicBlock::iterator BeginIt;
1658 auto MapIt = BBSkipInstsMap.find(Val: MBB);
1659 if (MapIt == BBSkipInstsMap.end())
1660 BeginIt = MBB->begin();
1661 else
1662 BeginIt = std::next(x: MapIt->second);
1663 auto I = MBB->SkipPHIsLabelsAndDebug(I: BeginIt);
1664 if (I != BeginIt)
1665 BBSkipInstsMap[MBB] = std::prev(x: I);
1666 return I;
1667 }
1668 Idx = Idx.getPrevIndex();
1669 }
1670
1671 // Don't insert anything after the first terminator, though.
1672 auto It = MI->isTerminator() ? MBB->getFirstTerminator()
1673 : std::next(x: MachineBasicBlock::iterator(MI));
1674 return skipDebugInstructionsForward(It, End: MBB->end());
1675}
1676
1677/// Find an iterator for inserting the next DBG_VALUE instruction
1678/// (or end if no more insert locations found).
1679static MachineBasicBlock::iterator
1680findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
1681 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1682 LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1683 SmallVector<Register, 4> Regs;
1684 for (const MachineOperand &LocMO : LocMOs)
1685 if (LocMO.isReg())
1686 Regs.push_back(Elt: LocMO.getReg());
1687 if (Regs.empty())
1688 return MBB->instr_end();
1689
1690 // Find the next instruction in the MBB that define the register Reg.
1691 while (I != MBB->end() && !I->isTerminator()) {
1692 if (!LIS.isNotInMIMap(Instr: *I) &&
1693 SlotIndex::isEarlierEqualInstr(A: StopIdx, B: LIS.getInstructionIndex(Instr: *I)))
1694 break;
1695 if (any_of(Range&: Regs, P: [&I, &TRI](Register &Reg) {
1696 return I->definesRegister(Reg, TRI: &TRI);
1697 }))
1698 // The insert location is directly after the instruction/bundle.
1699 return std::next(x: I);
1700 ++I;
1701 }
1702 return MBB->end();
1703}
1704
1705void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1706 SlotIndex StopIdx, DbgVariableValue DbgValue,
1707 ArrayRef<bool> LocSpills,
1708 ArrayRef<unsigned> SpillOffsets,
1709 LiveIntervals &LIS, const TargetInstrInfo &TII,
1710 const TargetRegisterInfo &TRI,
1711 BlockSkipInstsMap &BBSkipInstsMap) {
1712 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(mbb: &*MBB);
1713 // Only search within the current MBB.
1714 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1715 MachineBasicBlock::iterator I =
1716 findInsertLocation(MBB, Idx: StartIdx, LIS, BBSkipInstsMap);
1717 // Undef values don't exist in locations so create new "noreg" register MOs
1718 // for them. See getLocationNo().
1719 SmallVector<MachineOperand, 8> MOs;
1720 if (DbgValue.isUndef()) {
1721 MOs.assign(NumElts: DbgValue.loc_nos().size(),
1722 Elt: MachineOperand::CreateReg(
1723 /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1724 /* isKill */ false, /* isDead */ false,
1725 /* isUndef */ false, /* isEarlyClobber */ false,
1726 /* SubReg */ 0, /* isDebug */ true));
1727 } else {
1728 for (unsigned LocNo : DbgValue.loc_nos())
1729 MOs.push_back(Elt: locations[LocNo]);
1730 }
1731
1732 ++NumInsertedDebugValues;
1733
1734 assert(cast<DILocalVariable>(Variable)
1735 ->isValidLocationForIntrinsic(getDebugLoc()) &&
1736 "Expected inlined-at fields to agree");
1737
1738 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1739 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1740 // that the original virtual register was a pointer. Also, add the stack slot
1741 // offset for the spilled register to the expression.
1742 const DIExpression *Expr = DbgValue.getExpression();
1743 bool IsIndirect = DbgValue.getWasIndirect();
1744 bool IsList = DbgValue.getWasList();
1745 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1746 if (LocSpills[I]) {
1747 if (!IsList) {
1748 uint8_t DIExprFlags = DIExpression::ApplyOffset;
1749 if (IsIndirect)
1750 DIExprFlags |= DIExpression::DerefAfter;
1751 Expr = DIExpression::prepend(Expr, Flags: DIExprFlags, Offset: SpillOffsets[I]);
1752 IsIndirect = true;
1753 } else {
1754 SmallVector<uint64_t, 4> Ops;
1755 DIExpression::appendOffset(Ops, Offset: SpillOffsets[I]);
1756 Ops.push_back(Elt: dwarf::DW_OP_deref);
1757 Expr = DIExpression::appendOpsToArg(Expr, Ops, ArgNo: I);
1758 }
1759 }
1760
1761 assert((!LocSpills[I] || MOs[I].isFI()) &&
1762 "a spilled location must be a frame index");
1763 }
1764
1765 unsigned DbgValueOpcode =
1766 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1767 do {
1768 BuildMI(BB&: *MBB, I, DL: getDebugLoc(), MCID: TII.get(Opcode: DbgValueOpcode), IsIndirect, MOs,
1769 Variable, Expr);
1770
1771 // Continue and insert DBG_VALUES after every redefinition of a register
1772 // associated with the debug value within the range
1773 I = findNextInsertLocation(MBB, I, StopIdx, LocMOs: MOs, LIS, TRI);
1774 } while (I != MBB->end());
1775}
1776
1777void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1778 LiveIntervals &LIS, const TargetInstrInfo &TII,
1779 BlockSkipInstsMap &BBSkipInstsMap) {
1780 MachineBasicBlock::iterator I =
1781 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1782 ++NumInsertedDebugLabels;
1783 BuildMI(BB&: *MBB, I, MIMD: getDebugLoc(), MCID: TII.get(Opcode: TargetOpcode::DBG_LABEL))
1784 .addMetadata(MD: Label);
1785}
1786
1787void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1788 const TargetInstrInfo &TII,
1789 const TargetRegisterInfo &TRI,
1790 const SpillOffsetMap &SpillOffsets,
1791 BlockSkipInstsMap &BBSkipInstsMap) {
1792 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1793
1794 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1795 SlotIndex Start = I.start();
1796 SlotIndex Stop = I.stop();
1797 DbgVariableValue DbgValue = I.value();
1798
1799 SmallVector<bool> SpilledLocs;
1800 SmallVector<unsigned> LocSpillOffsets;
1801 for (unsigned LocNo : DbgValue.loc_nos()) {
1802 auto SpillIt =
1803 !DbgValue.isUndef() ? SpillOffsets.find(Val: LocNo) : SpillOffsets.end();
1804 bool Spilled = SpillIt != SpillOffsets.end();
1805 SpilledLocs.push_back(Elt: Spilled);
1806 LocSpillOffsets.push_back(Elt: Spilled ? SpillIt->second : 0);
1807 }
1808
1809 // If the interval start was trimmed to the lexical scope insert the
1810 // DBG_VALUE at the previous index (otherwise it appears after the
1811 // first instruction in the range).
1812 if (trimmedDefs.count(V: Start))
1813 Start = Start.getPrevIndex();
1814
1815 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1816 DbgValue.printLocNos(dbg));
1817 MachineFunction::iterator MBB = LIS.getMBBFromIndex(index: Start)->getIterator();
1818 SlotIndex MBBEnd = LIS.getMBBEndIdx(mbb: &*MBB);
1819
1820 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1821 insertDebugValue(MBB: &*MBB, StartIdx: Start, StopIdx: Stop, DbgValue, LocSpills: SpilledLocs, SpillOffsets: LocSpillOffsets,
1822 LIS, TII, TRI, BBSkipInstsMap);
1823 // This interval may span multiple basic blocks.
1824 // Insert a DBG_VALUE into each one.
1825 while (Stop > MBBEnd) {
1826 // Move to the next block.
1827 Start = MBBEnd;
1828 if (++MBB == MFEnd)
1829 break;
1830 MBBEnd = LIS.getMBBEndIdx(mbb: &*MBB);
1831 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1832 insertDebugValue(MBB: &*MBB, StartIdx: Start, StopIdx: Stop, DbgValue, LocSpills: SpilledLocs,
1833 SpillOffsets: LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1834 }
1835 LLVM_DEBUG(dbgs() << '\n');
1836 if (MBB == MFEnd)
1837 break;
1838
1839 ++I;
1840 }
1841}
1842
1843void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1844 BlockSkipInstsMap &BBSkipInstsMap) {
1845 LLVM_DEBUG(dbgs() << "\t" << loc);
1846 MachineFunction::iterator MBB = LIS.getMBBFromIndex(index: loc)->getIterator();
1847
1848 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1849 insertDebugLabel(MBB: &*MBB, Idx: loc, LIS, TII, BBSkipInstsMap);
1850
1851 LLVM_DEBUG(dbgs() << '\n');
1852}
1853
1854void LiveDebugVariables::LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1855 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1856 if (!MF)
1857 return;
1858
1859 BlockSkipInstsMap BBSkipInstsMap;
1860 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1861 SpillOffsetMap SpillOffsets;
1862 for (auto &userValue : userValues) {
1863 LLVM_DEBUG(userValue->print(dbgs(), TRI));
1864 userValue->rewriteLocations(VRM&: *VRM, MF: *MF, TII: *TII, TRI: *TRI, SpillOffsets);
1865 userValue->emitDebugValues(VRM, LIS&: *LIS, TII: *TII, TRI: *TRI, SpillOffsets,
1866 BBSkipInstsMap);
1867 }
1868 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1869 for (auto &userLabel : userLabels) {
1870 LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1871 userLabel->emitDebugLabel(LIS&: *LIS, TII: *TII, BBSkipInstsMap);
1872 }
1873
1874 LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
1875
1876 auto Slots = LIS->getSlotIndexes();
1877 for (auto &It : PHIValToPos) {
1878 // For each ex-PHI, identify its physreg location or stack slot, and emit
1879 // a DBG_PHI for it.
1880 unsigned InstNum = It.first;
1881 auto Slot = It.second.SI;
1882 Register Reg = It.second.Reg;
1883 unsigned SubReg = It.second.SubReg;
1884
1885 MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(index: Slot);
1886 if (VRM->isAssignedReg(virtReg: Reg) && VRM->hasPhys(virtReg: Reg)) {
1887 unsigned PhysReg = VRM->getPhys(virtReg: Reg);
1888 if (SubReg != 0)
1889 PhysReg = TRI->getSubReg(Reg: PhysReg, Idx: SubReg);
1890
1891 auto Builder = BuildMI(BB&: *OrigMBB, I: OrigMBB->begin(), MIMD: DebugLoc(),
1892 MCID: TII->get(Opcode: TargetOpcode::DBG_PHI));
1893 Builder.addReg(RegNo: PhysReg);
1894 Builder.addImm(Val: InstNum);
1895 } else if (VRM->getStackSlot(virtReg: Reg) != VirtRegMap::NO_STACK_SLOT) {
1896 const MachineRegisterInfo &MRI = MF->getRegInfo();
1897 const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
1898 unsigned SpillSize, SpillOffset;
1899
1900 unsigned regSizeInBits = TRI->getRegSizeInBits(RC: *TRC);
1901 if (SubReg)
1902 regSizeInBits = TRI->getSubRegIdxSize(Idx: SubReg);
1903
1904 // Test whether this location is legal with the given subreg. If the
1905 // subregister has a nonzero offset, drop this location, it's too complex
1906 // to describe. (TODO: future work).
1907 bool Success =
1908 TII->getStackSlotRange(RC: TRC, SubIdx: SubReg, Size&: SpillSize, Offset&: SpillOffset, MF: *MF);
1909
1910 if (Success && SpillOffset == 0) {
1911 auto Builder = BuildMI(BB&: *OrigMBB, I: OrigMBB->begin(), MIMD: DebugLoc(),
1912 MCID: TII->get(Opcode: TargetOpcode::DBG_PHI));
1913 Builder.addFrameIndex(Idx: VRM->getStackSlot(virtReg: Reg));
1914 Builder.addImm(Val: InstNum);
1915 // Record how large the original value is. The stack slot might be
1916 // merged and altered during optimisation, but we will want to know how
1917 // large the value is, at this DBG_PHI.
1918 Builder.addImm(Val: regSizeInBits);
1919 }
1920
1921 LLVM_DEBUG(if (SpillOffset != 0) {
1922 dbgs() << "DBG_PHI for " << printReg(Reg, TRI, SubReg)
1923 << " has nonzero offset\n";
1924 });
1925 }
1926 // If there was no mapping for a value ID, it's optimized out. Create no
1927 // DBG_PHI, and any variables using this value will become optimized out.
1928 }
1929 MF->DebugPHIPositions.clear();
1930
1931 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1932
1933 // Re-insert any debug instrs back in the position they were. We must
1934 // re-insert in the same order to ensure that debug instructions don't swap,
1935 // which could re-order assignments. Do so in a batch -- once we find the
1936 // insert position, insert all instructions at the same SlotIdx. They are
1937 // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
1938 // them in order.
1939 for (auto *StashIt = StashedDebugInstrs.begin();
1940 StashIt != StashedDebugInstrs.end(); ++StashIt) {
1941 SlotIndex Idx = StashIt->Idx;
1942 MachineBasicBlock *MBB = StashIt->MBB;
1943 MachineInstr *MI = StashIt->MI;
1944
1945 auto EmitInstsHere = [this, &StashIt, MBB, Idx,
1946 MI](MachineBasicBlock::iterator InsertPos) {
1947 // Insert this debug instruction.
1948 MBB->insert(I: InsertPos, MI);
1949
1950 // Look at subsequent stashed debug instructions: if they're at the same
1951 // index, insert those too.
1952 auto NextItem = std::next(x: StashIt);
1953 while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
1954 assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
1955 "in the same block");
1956 MBB->insert(I: InsertPos, MI: NextItem->MI);
1957 StashIt = NextItem;
1958 NextItem = std::next(x: StashIt);
1959 };
1960 };
1961
1962 // Start block index: find the first non-debug instr in the block, and
1963 // insert before it.
1964 if (Idx == Slots->getMBBStartIdx(mbb: MBB)) {
1965 MachineBasicBlock::iterator InsertPos =
1966 findInsertLocation(MBB, Idx, LIS&: *LIS, BBSkipInstsMap);
1967 EmitInstsHere(InsertPos);
1968 continue;
1969 }
1970
1971 if (MachineInstr *Pos = Slots->getInstructionFromIndex(index: Idx)) {
1972 // Insert at the end of any debug instructions.
1973 auto PostDebug = std::next(x: MachineBasicBlock::iterator(Pos));
1974 PostDebug = skipDebugInstructionsForward(It: PostDebug, End: MBB->end());
1975 EmitInstsHere(PostDebug);
1976 } else {
1977 // Insert position disappeared; walk forwards through slots until we
1978 // find a new one.
1979 SlotIndex End = Slots->getMBBEndIdx(mbb: MBB);
1980 for (; Idx < End; Idx = Slots->getNextNonNullIndex(Index: Idx)) {
1981 Pos = Slots->getInstructionFromIndex(index: Idx);
1982 if (Pos) {
1983 EmitInstsHere(Pos->getIterator());
1984 break;
1985 }
1986 }
1987
1988 // We have reached the end of the block and didn't find anywhere to
1989 // insert! It's not safe to discard any debug instructions; place them
1990 // in front of the first terminator, or in front of end().
1991 if (Idx >= End) {
1992 auto TermIt = MBB->getFirstTerminator();
1993 EmitInstsHere(TermIt);
1994 }
1995 }
1996 }
1997
1998 EmitDone = true;
1999 BBSkipInstsMap.clear();
2000}
2001
2002void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
2003 if (PImpl)
2004 PImpl->emitDebugValues(VRM);
2005}
2006
2007#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2008LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { print(dbgs()); }
2009#endif
2010
2011void LiveDebugVariables::print(raw_ostream &OS) const {
2012 if (PImpl)
2013 PImpl->print(OS);
2014}
2015