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