xref: /src/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1b60736ecSDimitry Andric //===- VarLocBasedImpl.cpp - Tracking Debug Value MIs with VarLoc class----===//
2dd58ef01SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dd58ef01SDimitry Andric //
7dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
8dd58ef01SDimitry Andric ///
9b60736ecSDimitry Andric /// \file VarLocBasedImpl.cpp
10dd58ef01SDimitry Andric ///
11cfca06d7SDimitry Andric /// LiveDebugValues is an optimistic "available expressions" dataflow
12cfca06d7SDimitry Andric /// algorithm. The set of expressions is the set of machine locations
13e3b55780SDimitry Andric /// (registers, spill slots, constants, and target indices) that a variable
14e3b55780SDimitry Andric /// fragment might be located, qualified by a DIExpression and indirect-ness
15e3b55780SDimitry Andric /// flag, while each variable is identified by a DebugVariable object. The
16e3b55780SDimitry Andric /// availability of an expression begins when a DBG_VALUE instruction specifies
17e3b55780SDimitry Andric /// the location of a DebugVariable, and continues until that location is
18e3b55780SDimitry Andric /// clobbered or re-specified by a different DBG_VALUE for the same
19e3b55780SDimitry Andric /// DebugVariable.
20dd58ef01SDimitry Andric ///
21b60736ecSDimitry Andric /// The output of LiveDebugValues is additional DBG_VALUE instructions,
22b60736ecSDimitry Andric /// placed to extend variable locations as far they're available. This file
23b60736ecSDimitry Andric /// and the VarLocBasedLDV class is an implementation that explicitly tracks
24b60736ecSDimitry Andric /// locations, using the VarLoc class.
25b60736ecSDimitry Andric ///
26b60736ecSDimitry Andric /// The canonical "available expressions" problem doesn't have expression
27cfca06d7SDimitry Andric /// clobbering, instead when a variable is re-assigned, any expressions using
28cfca06d7SDimitry Andric /// that variable get invalidated. LiveDebugValues can map onto "available
29cfca06d7SDimitry Andric /// expressions" by having every register represented by a variable, which is
30cfca06d7SDimitry Andric /// used in an expression that becomes available at a DBG_VALUE instruction.
31cfca06d7SDimitry Andric /// When the register is clobbered, its variable is effectively reassigned, and
32cfca06d7SDimitry Andric /// expressions computed from it become unavailable. A similar construct is
33cfca06d7SDimitry Andric /// needed when a DebugVariable has its location re-specified, to invalidate
34cfca06d7SDimitry Andric /// all other locations for that DebugVariable.
35cfca06d7SDimitry Andric ///
36cfca06d7SDimitry Andric /// Using the dataflow analysis to compute the available expressions, we create
37cfca06d7SDimitry Andric /// a DBG_VALUE at the beginning of each block where the expression is
38cfca06d7SDimitry Andric /// live-in. This propagates variable locations into every basic block where
39cfca06d7SDimitry Andric /// the location can be determined, rather than only having DBG_VALUEs in blocks
40cfca06d7SDimitry Andric /// where locations are specified due to an assignment or some optimization.
41cfca06d7SDimitry Andric /// Movements of values between registers and spill slots are annotated with
42cfca06d7SDimitry Andric /// DBG_VALUEs too to track variable values bewteen locations. All this allows
43cfca06d7SDimitry Andric /// DbgEntityHistoryCalculator to focus on only the locations within individual
44cfca06d7SDimitry Andric /// blocks, facilitating testing and improving modularity.
45cfca06d7SDimitry Andric ///
46cfca06d7SDimitry Andric /// We follow an optimisic dataflow approach, with this lattice:
47cfca06d7SDimitry Andric ///
48cfca06d7SDimitry Andric /// \verbatim
49cfca06d7SDimitry Andric ///                    ┬ "Unknown"
50cfca06d7SDimitry Andric ///                          |
51cfca06d7SDimitry Andric ///                          v
52cfca06d7SDimitry Andric ///                         True
53cfca06d7SDimitry Andric ///                          |
54cfca06d7SDimitry Andric ///                          v
55cfca06d7SDimitry Andric ///                      ⊥ False
56cfca06d7SDimitry Andric /// \endverbatim With "True" signifying that the expression is available (and
57cfca06d7SDimitry Andric /// thus a DebugVariable's location is the corresponding register), while
58cfca06d7SDimitry Andric /// "False" signifies that the expression is unavailable. "Unknown"s never
59cfca06d7SDimitry Andric /// survive to the end of the analysis (see below).
60cfca06d7SDimitry Andric ///
61cfca06d7SDimitry Andric /// Formally, all DebugVariable locations that are live-out of a block are
62cfca06d7SDimitry Andric /// initialized to \top.  A blocks live-in values take the meet of the lattice
63cfca06d7SDimitry Andric /// value for every predecessors live-outs, except for the entry block, where
64cfca06d7SDimitry Andric /// all live-ins are \bot. The usual dataflow propagation occurs: the transfer
65cfca06d7SDimitry Andric /// function for a block assigns an expression for a DebugVariable to be "True"
66cfca06d7SDimitry Andric /// if a DBG_VALUE in the block specifies it; "False" if the location is
67cfca06d7SDimitry Andric /// clobbered; or the live-in value if it is unaffected by the block. We
68cfca06d7SDimitry Andric /// visit each block in reverse post order until a fixedpoint is reached. The
69cfca06d7SDimitry Andric /// solution produced is maximal.
70cfca06d7SDimitry Andric ///
71cfca06d7SDimitry Andric /// Intuitively, we start by assuming that every expression / variable location
72cfca06d7SDimitry Andric /// is at least "True", and then propagate "False" from the entry block and any
73cfca06d7SDimitry Andric /// clobbers until there are no more changes to make. This gives us an accurate
74cfca06d7SDimitry Andric /// solution because all incorrect locations will have a "False" propagated into
75cfca06d7SDimitry Andric /// them. It also gives us a solution that copes well with loops by assuming
76cfca06d7SDimitry Andric /// that variable locations are live-through every loop, and then removing those
77cfca06d7SDimitry Andric /// that are not through dataflow.
78cfca06d7SDimitry Andric ///
79cfca06d7SDimitry Andric /// Within LiveDebugValues: each variable location is represented by a
80344a3780SDimitry Andric /// VarLoc object that identifies the source variable, the set of
81344a3780SDimitry Andric /// machine-locations that currently describe it (a single location for
82344a3780SDimitry Andric /// DBG_VALUE or multiple for DBG_VALUE_LIST), and the DBG_VALUE inst that
83344a3780SDimitry Andric /// specifies the location. Each VarLoc is indexed in the (function-scope) \p
84344a3780SDimitry Andric /// VarLocMap, giving each VarLoc a set of unique indexes, each of which
85344a3780SDimitry Andric /// corresponds to one of the VarLoc's machine-locations and can be used to
86344a3780SDimitry Andric /// lookup the VarLoc in the VarLocMap. Rather than operate directly on machine
87344a3780SDimitry Andric /// locations, the dataflow analysis in this pass identifies locations by their
88344a3780SDimitry Andric /// indices in the VarLocMap, meaning all the variable locations in a block can
89ac9a064cSDimitry Andric /// be described by a sparse vector of VarLocMap indices.
90cfca06d7SDimitry Andric ///
91cfca06d7SDimitry Andric /// All the storage for the dataflow analysis is local to the ExtendRanges
92cfca06d7SDimitry Andric /// method and passed down to helper methods. "OutLocs" and "InLocs" record the
93cfca06d7SDimitry Andric /// in and out lattice values for each block. "OpenRanges" maintains a list of
94cfca06d7SDimitry Andric /// variable locations and, with the "process" method, evaluates the transfer
95344a3780SDimitry Andric /// function of each block. "flushPendingLocs" installs debug value instructions
96344a3780SDimitry Andric /// for each live-in location at the start of blocks, while "Transfers" records
97cfca06d7SDimitry Andric /// transfers of values between machine-locations.
98cfca06d7SDimitry Andric ///
99cfca06d7SDimitry Andric /// We avoid explicitly representing the "Unknown" (\top) lattice value in the
100cfca06d7SDimitry Andric /// implementation. Instead, unvisited blocks implicitly have all lattice
101cfca06d7SDimitry Andric /// values set as "Unknown". After being visited, there will be path back to
102cfca06d7SDimitry Andric /// the entry block where the lattice value is "False", and as the transfer
103cfca06d7SDimitry Andric /// function cannot make new "Unknown" locations, there are no scenarios where
104cfca06d7SDimitry Andric /// a block can have an "Unknown" location after being visited. Similarly, we
105cfca06d7SDimitry Andric /// don't enumerate all possible variable locations before exploring the
106cfca06d7SDimitry Andric /// function: when a new location is discovered, all blocks previously explored
107cfca06d7SDimitry Andric /// were implicitly "False" but unrecorded, and become explicitly "False" when
108cfca06d7SDimitry Andric /// a new VarLoc is created with its bit not set in predecessor InLocs or
109cfca06d7SDimitry Andric /// OutLocs.
1101d5ae102SDimitry Andric ///
111dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
112dd58ef01SDimitry Andric 
113b60736ecSDimitry Andric #include "LiveDebugValues.h"
114b60736ecSDimitry Andric 
115cfca06d7SDimitry Andric #include "llvm/ADT/CoalescingBitVector.h"
116044eb2f6SDimitry Andric #include "llvm/ADT/DenseMap.h"
117050e163aSDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
118050e163aSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
119e6d15924SDimitry Andric #include "llvm/ADT/SmallSet.h"
120044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
12101095a5dSDimitry Andric #include "llvm/ADT/Statistic.h"
122145449b1SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
123b915e9e0SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
124044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
125dd58ef01SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
126044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
127dd58ef01SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
12871d5a254SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
129044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
130044eb2f6SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
131044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
132044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
133044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
134e6d15924SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
135044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
136044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
137eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
138044eb2f6SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
139044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
140044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
141044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
142044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
143dd58ef01SDimitry Andric #include "llvm/Support/Debug.h"
144b60736ecSDimitry Andric #include "llvm/Support/TypeSize.h"
145dd58ef01SDimitry Andric #include "llvm/Support/raw_ostream.h"
146cfca06d7SDimitry Andric #include "llvm/Target/TargetMachine.h"
147044eb2f6SDimitry Andric #include <algorithm>
148044eb2f6SDimitry Andric #include <cassert>
149044eb2f6SDimitry Andric #include <cstdint>
150044eb2f6SDimitry Andric #include <functional>
151c0981da4SDimitry Andric #include <map>
152e3b55780SDimitry Andric #include <optional>
15301095a5dSDimitry Andric #include <queue>
154e6d15924SDimitry Andric #include <tuple>
155044eb2f6SDimitry Andric #include <utility>
156044eb2f6SDimitry Andric #include <vector>
157dd58ef01SDimitry Andric 
158dd58ef01SDimitry Andric using namespace llvm;
159dd58ef01SDimitry Andric 
160ab44ce3dSDimitry Andric #define DEBUG_TYPE "livedebugvalues"
161dd58ef01SDimitry Andric 
162dd58ef01SDimitry Andric STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
163cfca06d7SDimitry Andric 
164706b4fc4SDimitry Andric /// If \p Op is a stack or frame register return true, otherwise return false.
165706b4fc4SDimitry Andric /// This is used to avoid basing the debug entry values on the registers, since
166706b4fc4SDimitry Andric /// we do not support it at the moment.
isRegOtherThanSPAndFP(const MachineOperand & Op,const MachineInstr & MI,const TargetRegisterInfo * TRI)167706b4fc4SDimitry Andric static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
168706b4fc4SDimitry Andric                                   const MachineInstr &MI,
169706b4fc4SDimitry Andric                                   const TargetRegisterInfo *TRI) {
170706b4fc4SDimitry Andric   if (!Op.isReg())
171706b4fc4SDimitry Andric     return false;
172706b4fc4SDimitry Andric 
173706b4fc4SDimitry Andric   const MachineFunction *MF = MI.getParent()->getParent();
174706b4fc4SDimitry Andric   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
175cfca06d7SDimitry Andric   Register SP = TLI->getStackPointerRegisterToSaveRestore();
176706b4fc4SDimitry Andric   Register FP = TRI->getFrameRegister(*MF);
177706b4fc4SDimitry Andric   Register Reg = Op.getReg();
178706b4fc4SDimitry Andric 
179706b4fc4SDimitry Andric   return Reg && Reg != SP && Reg != FP;
180706b4fc4SDimitry Andric }
181706b4fc4SDimitry Andric 
182044eb2f6SDimitry Andric namespace {
183dd58ef01SDimitry Andric 
184cfca06d7SDimitry Andric // Max out the number of statically allocated elements in DefinedRegsSet, as
185cfca06d7SDimitry Andric // this prevents fallback to std::set::count() operations.
186706b4fc4SDimitry Andric using DefinedRegsSet = SmallSet<Register, 32>;
187706b4fc4SDimitry Andric 
188344a3780SDimitry Andric // The IDs in this set correspond to MachineLocs in VarLocs, as well as VarLocs
189344a3780SDimitry Andric // that represent Entry Values; every VarLoc in the set will also appear
190344a3780SDimitry Andric // exactly once at Location=0.
191344a3780SDimitry Andric // As a result, each VarLoc may appear more than once in this "set", but each
192344a3780SDimitry Andric // range corresponding to a Reg, SpillLoc, or EntryValue type will still be a
193344a3780SDimitry Andric // "true" set (i.e. each VarLoc may appear only once), and the range Location=0
194344a3780SDimitry Andric // is the set of all VarLocs.
195cfca06d7SDimitry Andric using VarLocSet = CoalescingBitVector<uint64_t>;
196cfca06d7SDimitry Andric 
197cfca06d7SDimitry Andric /// A type-checked pair of {Register Location (or 0), Index}, used to index
198cfca06d7SDimitry Andric /// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int
199cfca06d7SDimitry Andric /// for insertion into a \ref VarLocSet, and efficiently converted back. The
200cfca06d7SDimitry Andric /// type-checker helps ensure that the conversions aren't lossy.
201cfca06d7SDimitry Andric ///
202cfca06d7SDimitry Andric /// Why encode a location /into/ the VarLocMap index? This makes it possible
203cfca06d7SDimitry Andric /// to find the open VarLocs killed by a register def very quickly. This is a
204cfca06d7SDimitry Andric /// performance-critical operation for LiveDebugValues.
205cfca06d7SDimitry Andric struct LocIndex {
206cfca06d7SDimitry Andric   using u32_location_t = uint32_t;
207cfca06d7SDimitry Andric   using u32_index_t = uint32_t;
208cfca06d7SDimitry Andric 
209cfca06d7SDimitry Andric   u32_location_t Location; // Physical registers live in the range [1;2^30) (see
210cfca06d7SDimitry Andric                            // \ref MCRegister), so we have plenty of range left
211cfca06d7SDimitry Andric                            // here to encode non-register locations.
212cfca06d7SDimitry Andric   u32_index_t Index;
213cfca06d7SDimitry Andric 
214344a3780SDimitry Andric   /// The location that has an entry for every VarLoc in the map.
215344a3780SDimitry Andric   static constexpr u32_location_t kUniversalLocation = 0;
216344a3780SDimitry Andric 
217344a3780SDimitry Andric   /// The first location that is reserved for VarLocs with locations of kind
218344a3780SDimitry Andric   /// RegisterKind.
219344a3780SDimitry Andric   static constexpr u32_location_t kFirstRegLocation = 1;
220344a3780SDimitry Andric 
221344a3780SDimitry Andric   /// The first location greater than 0 that is not reserved for VarLocs with
222344a3780SDimitry Andric   /// locations of kind RegisterKind.
223cfca06d7SDimitry Andric   static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30;
224cfca06d7SDimitry Andric 
225344a3780SDimitry Andric   /// A special location reserved for VarLocs with locations of kind
226344a3780SDimitry Andric   /// SpillLocKind.
227cfca06d7SDimitry Andric   static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation;
228cfca06d7SDimitry Andric 
229cfca06d7SDimitry Andric   /// A special location reserved for VarLocs of kind EntryValueBackupKind and
230cfca06d7SDimitry Andric   /// EntryValueCopyBackupKind.
231cfca06d7SDimitry Andric   static constexpr u32_location_t kEntryValueBackupLocation =
232cfca06d7SDimitry Andric       kFirstInvalidRegLocation + 1;
233cfca06d7SDimitry Andric 
234e3b55780SDimitry Andric   /// A special location reserved for VarLocs with locations of kind
235e3b55780SDimitry Andric   /// WasmLocKind.
236e3b55780SDimitry Andric   /// TODO Placing all Wasm target index locations in this single kWasmLocation
237e3b55780SDimitry Andric   /// may cause slowdown in compilation time in very large functions. Consider
238e3b55780SDimitry Andric   /// giving a each target index/offset pair its own u32_location_t if this
239e3b55780SDimitry Andric   /// becomes a problem.
240e3b55780SDimitry Andric   static constexpr u32_location_t kWasmLocation = kFirstInvalidRegLocation + 2;
241e3b55780SDimitry Andric 
LocIndex__anond6891cb70111::LocIndex242cfca06d7SDimitry Andric   LocIndex(u32_location_t Location, u32_index_t Index)
243cfca06d7SDimitry Andric       : Location(Location), Index(Index) {}
244cfca06d7SDimitry Andric 
getAsRawInteger__anond6891cb70111::LocIndex245cfca06d7SDimitry Andric   uint64_t getAsRawInteger() const {
246cfca06d7SDimitry Andric     return (static_cast<uint64_t>(Location) << 32) | Index;
247cfca06d7SDimitry Andric   }
248cfca06d7SDimitry Andric 
fromRawInteger__anond6891cb70111::LocIndex249cfca06d7SDimitry Andric   template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
250e3b55780SDimitry Andric     static_assert(std::is_unsigned_v<IntT> && sizeof(ID) == sizeof(uint64_t),
251cfca06d7SDimitry Andric                   "Cannot convert raw integer to LocIndex");
252cfca06d7SDimitry Andric     return {static_cast<u32_location_t>(ID >> 32),
253cfca06d7SDimitry Andric             static_cast<u32_index_t>(ID)};
254cfca06d7SDimitry Andric   }
255cfca06d7SDimitry Andric 
256cfca06d7SDimitry Andric   /// Get the start of the interval reserved for VarLocs of kind RegisterKind
257cfca06d7SDimitry Andric   /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1.
rawIndexForReg__anond6891cb70111::LocIndex258344a3780SDimitry Andric   static uint64_t rawIndexForReg(Register Reg) {
259cfca06d7SDimitry Andric     return LocIndex(Reg, 0).getAsRawInteger();
260cfca06d7SDimitry Andric   }
261cfca06d7SDimitry Andric 
262cfca06d7SDimitry Andric   /// Return a range covering all set indices in the interval reserved for
263cfca06d7SDimitry Andric   /// \p Location in \p Set.
indexRangeForLocation__anond6891cb70111::LocIndex264cfca06d7SDimitry Andric   static auto indexRangeForLocation(const VarLocSet &Set,
265cfca06d7SDimitry Andric                                     u32_location_t Location) {
266cfca06d7SDimitry Andric     uint64_t Start = LocIndex(Location, 0).getAsRawInteger();
267cfca06d7SDimitry Andric     uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger();
268cfca06d7SDimitry Andric     return Set.half_open_range(Start, End);
269cfca06d7SDimitry Andric   }
270cfca06d7SDimitry Andric };
271cfca06d7SDimitry Andric 
272344a3780SDimitry Andric // Simple Set for storing all the VarLoc Indices at a Location bucket.
273344a3780SDimitry Andric using VarLocsInRange = SmallSet<LocIndex::u32_index_t, 32>;
274344a3780SDimitry Andric // Vector of all `LocIndex`s for a given VarLoc; the same Location should not
275344a3780SDimitry Andric // appear in any two of these, as each VarLoc appears at most once in any
276344a3780SDimitry Andric // Location bucket.
277344a3780SDimitry Andric using LocIndices = SmallVector<LocIndex, 2>;
278344a3780SDimitry Andric 
279b60736ecSDimitry Andric class VarLocBasedLDV : public LDVImpl {
280dd58ef01SDimitry Andric private:
281dd58ef01SDimitry Andric   const TargetRegisterInfo *TRI;
282dd58ef01SDimitry Andric   const TargetInstrInfo *TII;
28371d5a254SDimitry Andric   const TargetFrameLowering *TFI;
284b60736ecSDimitry Andric   TargetPassConfig *TPC;
285eb11fae6SDimitry Andric   BitVector CalleeSavedRegs;
286b915e9e0SDimitry Andric   LexicalScopes LS;
287cfca06d7SDimitry Andric   VarLocSet::Allocator Alloc;
288b915e9e0SDimitry Andric 
289c0981da4SDimitry Andric   const MachineInstr *LastNonDbgMI;
290c0981da4SDimitry Andric 
291e6d15924SDimitry Andric   enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
292e6d15924SDimitry Andric 
293e6d15924SDimitry Andric   using FragmentInfo = DIExpression::FragmentInfo;
294e3b55780SDimitry Andric   using OptFragmentInfo = std::optional<DIExpression::FragmentInfo>;
295dd58ef01SDimitry Andric 
29601095a5dSDimitry Andric   /// A pair of debug variable and value location.
297dd58ef01SDimitry Andric   struct VarLoc {
298e6d15924SDimitry Andric     // The location at which a spilled variable resides. It consists of a
299e6d15924SDimitry Andric     // register and an offset.
300e6d15924SDimitry Andric     struct SpillLoc {
301e6d15924SDimitry Andric       unsigned SpillBase;
302b60736ecSDimitry Andric       StackOffset SpillOffset;
operator ==__anond6891cb70111::VarLocBasedLDV::VarLoc::SpillLoc303e6d15924SDimitry Andric       bool operator==(const SpillLoc &Other) const {
304e6d15924SDimitry Andric         return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
305e6d15924SDimitry Andric       }
operator !=__anond6891cb70111::VarLocBasedLDV::VarLoc::SpillLoc306cfca06d7SDimitry Andric       bool operator!=(const SpillLoc &Other) const {
307cfca06d7SDimitry Andric         return !(*this == Other);
308cfca06d7SDimitry Andric       }
309e6d15924SDimitry Andric     };
310e6d15924SDimitry Andric 
311e3b55780SDimitry Andric     // Target indices used for wasm-specific locations.
312e3b55780SDimitry Andric     struct WasmLoc {
313e3b55780SDimitry Andric       // One of TargetIndex values defined in WebAssembly.h. We deal with
314e3b55780SDimitry Andric       // local-related TargetIndex in this analysis (TI_LOCAL and
315e3b55780SDimitry Andric       // TI_LOCAL_INDIRECT). Stack operands (TI_OPERAND_STACK) will be handled
316e3b55780SDimitry Andric       // separately WebAssemblyDebugFixup pass, and we don't associate debug
317e3b55780SDimitry Andric       // info with values in global operands (TI_GLOBAL_RELOC) at the moment.
318e3b55780SDimitry Andric       int Index;
319e3b55780SDimitry Andric       int64_t Offset;
operator ==__anond6891cb70111::VarLocBasedLDV::VarLoc::WasmLoc320e3b55780SDimitry Andric       bool operator==(const WasmLoc &Other) const {
321e3b55780SDimitry Andric         return Index == Other.Index && Offset == Other.Offset;
322e3b55780SDimitry Andric       }
operator !=__anond6891cb70111::VarLocBasedLDV::VarLoc::WasmLoc323e3b55780SDimitry Andric       bool operator!=(const WasmLoc &Other) const { return !(*this == Other); }
324e3b55780SDimitry Andric     };
325e3b55780SDimitry Andric 
3261d5ae102SDimitry Andric     /// Identity of the variable at this location.
32701095a5dSDimitry Andric     const DebugVariable Var;
3281d5ae102SDimitry Andric 
3291d5ae102SDimitry Andric     /// The expression applied to this location.
3301d5ae102SDimitry Andric     const DIExpression *Expr;
3311d5ae102SDimitry Andric 
3321d5ae102SDimitry Andric     /// DBG_VALUE to clone var/expr information from if this location
3331d5ae102SDimitry Andric     /// is moved.
3341d5ae102SDimitry Andric     const MachineInstr &MI;
3351d5ae102SDimitry Andric 
336344a3780SDimitry Andric     enum class MachineLocKind {
337e6d15924SDimitry Andric       InvalidKind = 0,
338e6d15924SDimitry Andric       RegisterKind,
339e6d15924SDimitry Andric       SpillLocKind,
340e3b55780SDimitry Andric       ImmediateKind,
341e3b55780SDimitry Andric       WasmLocKind
342344a3780SDimitry Andric     };
343344a3780SDimitry Andric 
344344a3780SDimitry Andric     enum class EntryValueLocKind {
345344a3780SDimitry Andric       NonEntryValueKind = 0,
346706b4fc4SDimitry Andric       EntryValueKind,
347706b4fc4SDimitry Andric       EntryValueBackupKind,
348706b4fc4SDimitry Andric       EntryValueCopyBackupKind
349ecbca9f5SDimitry Andric     } EVKind = EntryValueLocKind::NonEntryValueKind;
350dd58ef01SDimitry Andric 
35101095a5dSDimitry Andric     /// The value location. Stored separately to avoid repeatedly
35201095a5dSDimitry Andric     /// extracting it from MI.
353344a3780SDimitry Andric     union MachineLocValue {
354044eb2f6SDimitry Andric       uint64_t RegNo;
355e6d15924SDimitry Andric       SpillLoc SpillLocation;
35601095a5dSDimitry Andric       uint64_t Hash;
357e6d15924SDimitry Andric       int64_t Immediate;
358e6d15924SDimitry Andric       const ConstantFP *FPImm;
359e6d15924SDimitry Andric       const ConstantInt *CImm;
360e3b55780SDimitry Andric       WasmLoc WasmLocation;
MachineLocValue()361344a3780SDimitry Andric       MachineLocValue() : Hash(0) {}
362344a3780SDimitry Andric     };
363344a3780SDimitry Andric 
364344a3780SDimitry Andric     /// A single machine location; its Kind is either a register, spill
365344a3780SDimitry Andric     /// location, or immediate value.
366344a3780SDimitry Andric     /// If the VarLoc is not a NonEntryValueKind, then it will use only a
367344a3780SDimitry Andric     /// single MachineLoc of RegisterKind.
368344a3780SDimitry Andric     struct MachineLoc {
369344a3780SDimitry Andric       MachineLocKind Kind;
370344a3780SDimitry Andric       MachineLocValue Value;
operator ==__anond6891cb70111::VarLocBasedLDV::VarLoc::MachineLoc371344a3780SDimitry Andric       bool operator==(const MachineLoc &Other) const {
372344a3780SDimitry Andric         if (Kind != Other.Kind)
373344a3780SDimitry Andric           return false;
374344a3780SDimitry Andric         switch (Kind) {
375344a3780SDimitry Andric         case MachineLocKind::SpillLocKind:
376344a3780SDimitry Andric           return Value.SpillLocation == Other.Value.SpillLocation;
377e3b55780SDimitry Andric         case MachineLocKind::WasmLocKind:
378e3b55780SDimitry Andric           return Value.WasmLocation == Other.Value.WasmLocation;
379344a3780SDimitry Andric         case MachineLocKind::RegisterKind:
380344a3780SDimitry Andric         case MachineLocKind::ImmediateKind:
381344a3780SDimitry Andric           return Value.Hash == Other.Value.Hash;
382344a3780SDimitry Andric         default:
383344a3780SDimitry Andric           llvm_unreachable("Invalid kind");
384344a3780SDimitry Andric         }
385344a3780SDimitry Andric       }
operator <__anond6891cb70111::VarLocBasedLDV::VarLoc::MachineLoc386344a3780SDimitry Andric       bool operator<(const MachineLoc &Other) const {
387344a3780SDimitry Andric         switch (Kind) {
388344a3780SDimitry Andric         case MachineLocKind::SpillLocKind:
389344a3780SDimitry Andric           return std::make_tuple(
390344a3780SDimitry Andric                      Kind, Value.SpillLocation.SpillBase,
391344a3780SDimitry Andric                      Value.SpillLocation.SpillOffset.getFixed(),
392344a3780SDimitry Andric                      Value.SpillLocation.SpillOffset.getScalable()) <
393344a3780SDimitry Andric                  std::make_tuple(
394344a3780SDimitry Andric                      Other.Kind, Other.Value.SpillLocation.SpillBase,
395344a3780SDimitry Andric                      Other.Value.SpillLocation.SpillOffset.getFixed(),
396344a3780SDimitry Andric                      Other.Value.SpillLocation.SpillOffset.getScalable());
397e3b55780SDimitry Andric         case MachineLocKind::WasmLocKind:
398e3b55780SDimitry Andric           return std::make_tuple(Kind, Value.WasmLocation.Index,
399e3b55780SDimitry Andric                                  Value.WasmLocation.Offset) <
400e3b55780SDimitry Andric                  std::make_tuple(Other.Kind, Other.Value.WasmLocation.Index,
401e3b55780SDimitry Andric                                  Other.Value.WasmLocation.Offset);
402344a3780SDimitry Andric         case MachineLocKind::RegisterKind:
403344a3780SDimitry Andric         case MachineLocKind::ImmediateKind:
404344a3780SDimitry Andric           return std::tie(Kind, Value.Hash) <
405344a3780SDimitry Andric                  std::tie(Other.Kind, Other.Value.Hash);
406344a3780SDimitry Andric         default:
407344a3780SDimitry Andric           llvm_unreachable("Invalid kind");
408344a3780SDimitry Andric         }
409344a3780SDimitry Andric       }
410344a3780SDimitry Andric     };
411344a3780SDimitry Andric 
412344a3780SDimitry Andric     /// The set of machine locations used to determine the variable's value, in
413344a3780SDimitry Andric     /// conjunction with Expr. Initially populated with MI's debug operands,
414344a3780SDimitry Andric     /// but may be transformed independently afterwards.
415344a3780SDimitry Andric     SmallVector<MachineLoc, 8> Locs;
416344a3780SDimitry Andric     /// Used to map the index of each location in Locs back to the index of its
417344a3780SDimitry Andric     /// original debug operand in MI. Used when multiple location operands are
418344a3780SDimitry Andric     /// coalesced and the original MI's operands need to be accessed while
419344a3780SDimitry Andric     /// emitting a debug value.
420344a3780SDimitry Andric     SmallVector<unsigned, 8> OrigLocMap;
42101095a5dSDimitry Andric 
VarLoc__anond6891cb70111::VarLocBasedLDV::VarLoc422e3b55780SDimitry Andric     VarLoc(const MachineInstr &MI)
423706b4fc4SDimitry Andric         : Var(MI.getDebugVariable(), MI.getDebugExpression(),
424706b4fc4SDimitry Andric               MI.getDebugLoc()->getInlinedAt()),
425ecbca9f5SDimitry Andric           Expr(MI.getDebugExpression()), MI(MI) {
42601095a5dSDimitry Andric       assert(MI.isDebugValue() && "not a DBG_VALUE");
427344a3780SDimitry Andric       assert((MI.isDebugValueList() || MI.getNumOperands() == 4) &&
428344a3780SDimitry Andric              "malformed DBG_VALUE");
429344a3780SDimitry Andric       for (const MachineOperand &Op : MI.debug_operands()) {
430344a3780SDimitry Andric         MachineLoc ML = GetLocForOp(Op);
431344a3780SDimitry Andric         auto It = find(Locs, ML);
432344a3780SDimitry Andric         if (It == Locs.end()) {
433344a3780SDimitry Andric           Locs.push_back(ML);
434344a3780SDimitry Andric           OrigLocMap.push_back(MI.getDebugOperandIndex(&Op));
435344a3780SDimitry Andric         } else {
436344a3780SDimitry Andric           // ML duplicates an element in Locs; replace references to Op
437344a3780SDimitry Andric           // with references to the duplicating element.
438344a3780SDimitry Andric           unsigned OpIdx = Locs.size();
439344a3780SDimitry Andric           unsigned DuplicatingIdx = std::distance(Locs.begin(), It);
440344a3780SDimitry Andric           Expr = DIExpression::replaceArg(Expr, OpIdx, DuplicatingIdx);
441344a3780SDimitry Andric         }
44201095a5dSDimitry Andric       }
443706b4fc4SDimitry Andric 
444344a3780SDimitry Andric       // We create the debug entry values from the factory functions rather
445344a3780SDimitry Andric       // than from this ctor.
446344a3780SDimitry Andric       assert(EVKind != EntryValueLocKind::EntryValueKind &&
447344a3780SDimitry Andric              !isEntryBackupLoc());
448344a3780SDimitry Andric     }
449344a3780SDimitry Andric 
GetLocForOp__anond6891cb70111::VarLocBasedLDV::VarLoc450344a3780SDimitry Andric     static MachineLoc GetLocForOp(const MachineOperand &Op) {
451344a3780SDimitry Andric       MachineLocKind Kind;
452344a3780SDimitry Andric       MachineLocValue Loc;
453344a3780SDimitry Andric       if (Op.isReg()) {
454344a3780SDimitry Andric         Kind = MachineLocKind::RegisterKind;
455344a3780SDimitry Andric         Loc.RegNo = Op.getReg();
456344a3780SDimitry Andric       } else if (Op.isImm()) {
457344a3780SDimitry Andric         Kind = MachineLocKind::ImmediateKind;
458344a3780SDimitry Andric         Loc.Immediate = Op.getImm();
459344a3780SDimitry Andric       } else if (Op.isFPImm()) {
460344a3780SDimitry Andric         Kind = MachineLocKind::ImmediateKind;
461344a3780SDimitry Andric         Loc.FPImm = Op.getFPImm();
462344a3780SDimitry Andric       } else if (Op.isCImm()) {
463344a3780SDimitry Andric         Kind = MachineLocKind::ImmediateKind;
464344a3780SDimitry Andric         Loc.CImm = Op.getCImm();
465e3b55780SDimitry Andric       } else if (Op.isTargetIndex()) {
466e3b55780SDimitry Andric         Kind = MachineLocKind::WasmLocKind;
467e3b55780SDimitry Andric         Loc.WasmLocation = {Op.getIndex(), Op.getOffset()};
468344a3780SDimitry Andric       } else
469344a3780SDimitry Andric         llvm_unreachable("Invalid Op kind for MachineLoc.");
470344a3780SDimitry Andric       return {Kind, Loc};
47101095a5dSDimitry Andric     }
47201095a5dSDimitry Andric 
4731d5ae102SDimitry Andric     /// Take the variable and machine-location in DBG_VALUE MI, and build an
4741d5ae102SDimitry Andric     /// entry location using the given expression.
CreateEntryLoc__anond6891cb70111::VarLocBasedLDV::VarLoc475e3b55780SDimitry Andric     static VarLoc CreateEntryLoc(const MachineInstr &MI,
476cfca06d7SDimitry Andric                                  const DIExpression *EntryExpr, Register Reg) {
477e3b55780SDimitry Andric       VarLoc VL(MI);
478344a3780SDimitry Andric       assert(VL.Locs.size() == 1 &&
479344a3780SDimitry Andric              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
480344a3780SDimitry Andric       VL.EVKind = EntryValueLocKind::EntryValueKind;
4811d5ae102SDimitry Andric       VL.Expr = EntryExpr;
482344a3780SDimitry Andric       VL.Locs[0].Value.RegNo = Reg;
483706b4fc4SDimitry Andric       return VL;
484706b4fc4SDimitry Andric     }
485706b4fc4SDimitry Andric 
486706b4fc4SDimitry Andric     /// Take the variable and machine-location from the DBG_VALUE (from the
487706b4fc4SDimitry Andric     /// function entry), and build an entry value backup location. The backup
488706b4fc4SDimitry Andric     /// location will turn into the normal location if the backup is valid at
489706b4fc4SDimitry Andric     /// the time of the primary location clobbering.
CreateEntryBackupLoc__anond6891cb70111::VarLocBasedLDV::VarLoc490706b4fc4SDimitry Andric     static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
491706b4fc4SDimitry Andric                                        const DIExpression *EntryExpr) {
492e3b55780SDimitry Andric       VarLoc VL(MI);
493344a3780SDimitry Andric       assert(VL.Locs.size() == 1 &&
494344a3780SDimitry Andric              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
495344a3780SDimitry Andric       VL.EVKind = EntryValueLocKind::EntryValueBackupKind;
496706b4fc4SDimitry Andric       VL.Expr = EntryExpr;
497706b4fc4SDimitry Andric       return VL;
498706b4fc4SDimitry Andric     }
499706b4fc4SDimitry Andric 
500706b4fc4SDimitry Andric     /// Take the variable and machine-location from the DBG_VALUE (from the
501706b4fc4SDimitry Andric     /// function entry), and build a copy of an entry value backup location by
502706b4fc4SDimitry Andric     /// setting the register location to NewReg.
CreateEntryCopyBackupLoc__anond6891cb70111::VarLocBasedLDV::VarLoc503706b4fc4SDimitry Andric     static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
504706b4fc4SDimitry Andric                                            const DIExpression *EntryExpr,
505cfca06d7SDimitry Andric                                            Register NewReg) {
506e3b55780SDimitry Andric       VarLoc VL(MI);
507344a3780SDimitry Andric       assert(VL.Locs.size() == 1 &&
508344a3780SDimitry Andric              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
509344a3780SDimitry Andric       VL.EVKind = EntryValueLocKind::EntryValueCopyBackupKind;
510706b4fc4SDimitry Andric       VL.Expr = EntryExpr;
511344a3780SDimitry Andric       VL.Locs[0].Value.RegNo = NewReg;
5121d5ae102SDimitry Andric       return VL;
513e6d15924SDimitry Andric     }
514e6d15924SDimitry Andric 
5151d5ae102SDimitry Andric     /// Copy the register location in DBG_VALUE MI, updating the register to
5161d5ae102SDimitry Andric     /// be NewReg.
CreateCopyLoc__anond6891cb70111::VarLocBasedLDV::VarLoc517344a3780SDimitry Andric     static VarLoc CreateCopyLoc(const VarLoc &OldVL, const MachineLoc &OldML,
518cfca06d7SDimitry Andric                                 Register NewReg) {
519344a3780SDimitry Andric       VarLoc VL = OldVL;
52077fc4c14SDimitry Andric       for (MachineLoc &ML : VL.Locs)
52177fc4c14SDimitry Andric         if (ML == OldML) {
52277fc4c14SDimitry Andric           ML.Kind = MachineLocKind::RegisterKind;
52377fc4c14SDimitry Andric           ML.Value.RegNo = NewReg;
5241d5ae102SDimitry Andric           return VL;
5251d5ae102SDimitry Andric         }
526344a3780SDimitry Andric       llvm_unreachable("Should have found OldML in new VarLoc.");
527344a3780SDimitry Andric     }
5281d5ae102SDimitry Andric 
529344a3780SDimitry Andric     /// Take the variable described by DBG_VALUE* MI, and create a VarLoc
5301d5ae102SDimitry Andric     /// locating it in the specified spill location.
CreateSpillLoc__anond6891cb70111::VarLocBasedLDV::VarLoc531344a3780SDimitry Andric     static VarLoc CreateSpillLoc(const VarLoc &OldVL, const MachineLoc &OldML,
532344a3780SDimitry Andric                                  unsigned SpillBase, StackOffset SpillOffset) {
533344a3780SDimitry Andric       VarLoc VL = OldVL;
53477fc4c14SDimitry Andric       for (MachineLoc &ML : VL.Locs)
53577fc4c14SDimitry Andric         if (ML == OldML) {
53677fc4c14SDimitry Andric           ML.Kind = MachineLocKind::SpillLocKind;
53777fc4c14SDimitry Andric           ML.Value.SpillLocation = {SpillBase, SpillOffset};
5381d5ae102SDimitry Andric           return VL;
5391d5ae102SDimitry Andric         }
540344a3780SDimitry Andric       llvm_unreachable("Should have found OldML in new VarLoc.");
541344a3780SDimitry Andric     }
5421d5ae102SDimitry Andric 
5431d5ae102SDimitry Andric     /// Create a DBG_VALUE representing this VarLoc in the given function.
5441d5ae102SDimitry Andric     /// Copies variable-specific information such as DILocalVariable and
5451d5ae102SDimitry Andric     /// inlining information from the original DBG_VALUE instruction, which may
5461d5ae102SDimitry Andric     /// have been several transfers ago.
BuildDbgValue__anond6891cb70111::VarLocBasedLDV::VarLoc5471d5ae102SDimitry Andric     MachineInstr *BuildDbgValue(MachineFunction &MF) const {
548344a3780SDimitry Andric       assert(!isEntryBackupLoc() &&
549344a3780SDimitry Andric              "Tried to produce DBG_VALUE for backup VarLoc");
5501d5ae102SDimitry Andric       const DebugLoc &DbgLoc = MI.getDebugLoc();
5511d5ae102SDimitry Andric       bool Indirect = MI.isIndirectDebugValue();
5521d5ae102SDimitry Andric       const auto &IID = MI.getDesc();
5531d5ae102SDimitry Andric       const DILocalVariable *Var = MI.getDebugVariable();
554cfca06d7SDimitry Andric       NumInserted++;
5551d5ae102SDimitry Andric 
556344a3780SDimitry Andric       const DIExpression *DIExpr = Expr;
557344a3780SDimitry Andric       SmallVector<MachineOperand, 8> MOs;
558344a3780SDimitry Andric       for (unsigned I = 0, E = Locs.size(); I < E; ++I) {
559344a3780SDimitry Andric         MachineLocKind LocKind = Locs[I].Kind;
560344a3780SDimitry Andric         MachineLocValue Loc = Locs[I].Value;
561344a3780SDimitry Andric         const MachineOperand &Orig = MI.getDebugOperand(OrigLocMap[I]);
562344a3780SDimitry Andric         switch (LocKind) {
563344a3780SDimitry Andric         case MachineLocKind::RegisterKind:
5641d5ae102SDimitry Andric           // An entry value is a register location -- but with an updated
565344a3780SDimitry Andric           // expression. The register location of such DBG_VALUE is always the
566344a3780SDimitry Andric           // one from the entry DBG_VALUE, it does not matter if the entry value
567344a3780SDimitry Andric           // was copied in to another register due to some optimizations.
568344a3780SDimitry Andric           // Non-entry value register locations are like the source
569344a3780SDimitry Andric           // DBG_VALUE, but with the register number from this VarLoc.
570344a3780SDimitry Andric           MOs.push_back(MachineOperand::CreateReg(
571344a3780SDimitry Andric               EVKind == EntryValueLocKind::EntryValueKind ? Orig.getReg()
572344a3780SDimitry Andric                                                           : Register(Loc.RegNo),
573344a3780SDimitry Andric               false));
574344a3780SDimitry Andric           break;
575344a3780SDimitry Andric         case MachineLocKind::SpillLocKind: {
5761d5ae102SDimitry Andric           // Spills are indirect DBG_VALUEs, with a base register and offset.
5771d5ae102SDimitry Andric           // Use the original DBG_VALUEs expression to build the spilt location
5781d5ae102SDimitry Andric           // on top of. FIXME: spill locations created before this pass runs
5791d5ae102SDimitry Andric           // are not recognized, and not handled here.
5801d5ae102SDimitry Andric           unsigned Base = Loc.SpillLocation.SpillBase;
581344a3780SDimitry Andric           auto *TRI = MF.getSubtarget().getRegisterInfo();
582344a3780SDimitry Andric           if (MI.isNonListDebugValue()) {
583c0981da4SDimitry Andric             auto Deref = Indirect ? DIExpression::DerefAfter : 0;
584c0981da4SDimitry Andric             DIExpr = TRI->prependOffsetExpression(
585c0981da4SDimitry Andric                 DIExpr, DIExpression::ApplyOffset | Deref,
586344a3780SDimitry Andric                 Loc.SpillLocation.SpillOffset);
587344a3780SDimitry Andric             Indirect = true;
588344a3780SDimitry Andric           } else {
589344a3780SDimitry Andric             SmallVector<uint64_t, 4> Ops;
590344a3780SDimitry Andric             TRI->getOffsetOpcodes(Loc.SpillLocation.SpillOffset, Ops);
591344a3780SDimitry Andric             Ops.push_back(dwarf::DW_OP_deref);
592344a3780SDimitry Andric             DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, I);
5931d5ae102SDimitry Andric           }
594344a3780SDimitry Andric           MOs.push_back(MachineOperand::CreateReg(Base, false));
595344a3780SDimitry Andric           break;
5961d5ae102SDimitry Andric         }
597344a3780SDimitry Andric         case MachineLocKind::ImmediateKind: {
598344a3780SDimitry Andric           MOs.push_back(Orig);
599344a3780SDimitry Andric           break;
6001d5ae102SDimitry Andric         }
601e3b55780SDimitry Andric         case MachineLocKind::WasmLocKind: {
602e3b55780SDimitry Andric           MOs.push_back(Orig);
603e3b55780SDimitry Andric           break;
604e3b55780SDimitry Andric         }
605344a3780SDimitry Andric         case MachineLocKind::InvalidKind:
606344a3780SDimitry Andric           llvm_unreachable("Tried to produce DBG_VALUE for invalid VarLoc");
607344a3780SDimitry Andric         }
608344a3780SDimitry Andric       }
609344a3780SDimitry Andric       return BuildMI(MF, DbgLoc, IID, Indirect, MOs, Var, DIExpr);
6101d5ae102SDimitry Andric     }
6111d5ae102SDimitry Andric 
6121d5ae102SDimitry Andric     /// Is the Loc field a constant or constant object?
isConstant__anond6891cb70111::VarLocBasedLDV::VarLoc613344a3780SDimitry Andric     bool isConstant(MachineLocKind Kind) const {
614344a3780SDimitry Andric       return Kind == MachineLocKind::ImmediateKind;
615344a3780SDimitry Andric     }
616e6d15924SDimitry Andric 
617706b4fc4SDimitry Andric     /// Check if the Loc field is an entry backup location.
isEntryBackupLoc__anond6891cb70111::VarLocBasedLDV::VarLoc618706b4fc4SDimitry Andric     bool isEntryBackupLoc() const {
619344a3780SDimitry Andric       return EVKind == EntryValueLocKind::EntryValueBackupKind ||
620344a3780SDimitry Andric              EVKind == EntryValueLocKind::EntryValueCopyBackupKind;
621706b4fc4SDimitry Andric     }
622706b4fc4SDimitry Andric 
623344a3780SDimitry Andric     /// If this variable is described by register \p Reg holding the entry
624344a3780SDimitry Andric     /// value, return true.
isEntryValueBackupReg__anond6891cb70111::VarLocBasedLDV::VarLoc625344a3780SDimitry Andric     bool isEntryValueBackupReg(Register Reg) const {
626344a3780SDimitry Andric       return EVKind == EntryValueLocKind::EntryValueBackupKind && usesReg(Reg);
627706b4fc4SDimitry Andric     }
628706b4fc4SDimitry Andric 
629344a3780SDimitry Andric     /// If this variable is described by register \p Reg holding a copy of the
630344a3780SDimitry Andric     /// entry value, return true.
isEntryValueCopyBackupReg__anond6891cb70111::VarLocBasedLDV::VarLoc631344a3780SDimitry Andric     bool isEntryValueCopyBackupReg(Register Reg) const {
632344a3780SDimitry Andric       return EVKind == EntryValueLocKind::EntryValueCopyBackupKind &&
633344a3780SDimitry Andric              usesReg(Reg);
634706b4fc4SDimitry Andric     }
635706b4fc4SDimitry Andric 
636344a3780SDimitry Andric     /// If this variable is described in whole or part by \p Reg, return true.
usesReg__anond6891cb70111::VarLocBasedLDV::VarLoc637344a3780SDimitry Andric     bool usesReg(Register Reg) const {
638344a3780SDimitry Andric       MachineLoc RegML;
639344a3780SDimitry Andric       RegML.Kind = MachineLocKind::RegisterKind;
640344a3780SDimitry Andric       RegML.Value.RegNo = Reg;
641344a3780SDimitry Andric       return is_contained(Locs, RegML);
642344a3780SDimitry Andric     }
643344a3780SDimitry Andric 
644344a3780SDimitry Andric     /// If this variable is described in whole or part by \p Reg, return true.
getRegIdx__anond6891cb70111::VarLocBasedLDV::VarLoc645344a3780SDimitry Andric     unsigned getRegIdx(Register Reg) const {
646344a3780SDimitry Andric       for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
647344a3780SDimitry Andric         if (Locs[Idx].Kind == MachineLocKind::RegisterKind &&
648c0981da4SDimitry Andric             Register{static_cast<unsigned>(Locs[Idx].Value.RegNo)} == Reg)
649344a3780SDimitry Andric           return Idx;
650344a3780SDimitry Andric       llvm_unreachable("Could not find given Reg in Locs");
651344a3780SDimitry Andric     }
652344a3780SDimitry Andric 
653344a3780SDimitry Andric     /// If this variable is described in whole or part by 1 or more registers,
654344a3780SDimitry Andric     /// add each of them to \p Regs and return true.
getDescribingRegs__anond6891cb70111::VarLocBasedLDV::VarLoc655344a3780SDimitry Andric     bool getDescribingRegs(SmallVectorImpl<uint32_t> &Regs) const {
656344a3780SDimitry Andric       bool AnyRegs = false;
657c0981da4SDimitry Andric       for (const auto &Loc : Locs)
658344a3780SDimitry Andric         if (Loc.Kind == MachineLocKind::RegisterKind) {
659344a3780SDimitry Andric           Regs.push_back(Loc.Value.RegNo);
660344a3780SDimitry Andric           AnyRegs = true;
661344a3780SDimitry Andric         }
662344a3780SDimitry Andric       return AnyRegs;
663344a3780SDimitry Andric     }
664344a3780SDimitry Andric 
containsSpillLocs__anond6891cb70111::VarLocBasedLDV::VarLoc665344a3780SDimitry Andric     bool containsSpillLocs() const {
666344a3780SDimitry Andric       return any_of(Locs, [](VarLoc::MachineLoc ML) {
667344a3780SDimitry Andric         return ML.Kind == VarLoc::MachineLocKind::SpillLocKind;
668344a3780SDimitry Andric       });
669344a3780SDimitry Andric     }
670344a3780SDimitry Andric 
671344a3780SDimitry Andric     /// If this variable is described in whole or part by \p SpillLocation,
672344a3780SDimitry Andric     /// return true.
usesSpillLoc__anond6891cb70111::VarLocBasedLDV::VarLoc673344a3780SDimitry Andric     bool usesSpillLoc(SpillLoc SpillLocation) const {
674344a3780SDimitry Andric       MachineLoc SpillML;
675344a3780SDimitry Andric       SpillML.Kind = MachineLocKind::SpillLocKind;
676344a3780SDimitry Andric       SpillML.Value.SpillLocation = SpillLocation;
677344a3780SDimitry Andric       return is_contained(Locs, SpillML);
678344a3780SDimitry Andric     }
679344a3780SDimitry Andric 
680344a3780SDimitry Andric     /// If this variable is described in whole or part by \p SpillLocation,
681344a3780SDimitry Andric     /// return the index .
getSpillLocIdx__anond6891cb70111::VarLocBasedLDV::VarLoc682344a3780SDimitry Andric     unsigned getSpillLocIdx(SpillLoc SpillLocation) const {
683344a3780SDimitry Andric       for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
684344a3780SDimitry Andric         if (Locs[Idx].Kind == MachineLocKind::SpillLocKind &&
685344a3780SDimitry Andric             Locs[Idx].Value.SpillLocation == SpillLocation)
686344a3780SDimitry Andric           return Idx;
687344a3780SDimitry Andric       llvm_unreachable("Could not find given SpillLoc in Locs");
68801095a5dSDimitry Andric     }
68901095a5dSDimitry Andric 
containsWasmLocs__anond6891cb70111::VarLocBasedLDV::VarLoc690e3b55780SDimitry Andric     bool containsWasmLocs() const {
691e3b55780SDimitry Andric       return any_of(Locs, [](VarLoc::MachineLoc ML) {
692e3b55780SDimitry Andric         return ML.Kind == VarLoc::MachineLocKind::WasmLocKind;
693e3b55780SDimitry Andric       });
694e3b55780SDimitry Andric     }
695e3b55780SDimitry Andric 
696e3b55780SDimitry Andric     /// If this variable is described in whole or part by \p WasmLocation,
697e3b55780SDimitry Andric     /// return true.
usesWasmLoc__anond6891cb70111::VarLocBasedLDV::VarLoc698e3b55780SDimitry Andric     bool usesWasmLoc(WasmLoc WasmLocation) const {
699e3b55780SDimitry Andric       MachineLoc WasmML;
700e3b55780SDimitry Andric       WasmML.Kind = MachineLocKind::WasmLocKind;
701e3b55780SDimitry Andric       WasmML.Value.WasmLocation = WasmLocation;
702e3b55780SDimitry Andric       return is_contained(Locs, WasmML);
703e3b55780SDimitry Andric     }
704e3b55780SDimitry Andric 
705b915e9e0SDimitry Andric     /// Determine whether the lexical scope of this value's debug location
706b915e9e0SDimitry Andric     /// dominates MBB.
dominates__anond6891cb70111::VarLocBasedLDV::VarLoc707cfca06d7SDimitry Andric     bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const {
708cfca06d7SDimitry Andric       return LS.dominates(MI.getDebugLoc().get(), &MBB);
709cfca06d7SDimitry Andric     }
710b915e9e0SDimitry Andric 
71171d5a254SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
712e3b55780SDimitry Andric     // TRI and TII can be null.
dump__anond6891cb70111::VarLocBasedLDV::VarLoc713e3b55780SDimitry Andric     void dump(const TargetRegisterInfo *TRI, const TargetInstrInfo *TII,
714e3b55780SDimitry Andric               raw_ostream &Out = dbgs()) const {
715cfca06d7SDimitry Andric       Out << "VarLoc(";
716344a3780SDimitry Andric       for (const MachineLoc &MLoc : Locs) {
717344a3780SDimitry Andric         if (Locs.begin() != &MLoc)
718344a3780SDimitry Andric           Out << ", ";
719344a3780SDimitry Andric         switch (MLoc.Kind) {
720344a3780SDimitry Andric         case MachineLocKind::RegisterKind:
721344a3780SDimitry Andric           Out << printReg(MLoc.Value.RegNo, TRI);
7221d5ae102SDimitry Andric           break;
723344a3780SDimitry Andric         case MachineLocKind::SpillLocKind:
724344a3780SDimitry Andric           Out << printReg(MLoc.Value.SpillLocation.SpillBase, TRI);
725344a3780SDimitry Andric           Out << "[" << MLoc.Value.SpillLocation.SpillOffset.getFixed() << " + "
726344a3780SDimitry Andric               << MLoc.Value.SpillLocation.SpillOffset.getScalable()
727344a3780SDimitry Andric               << "x vscale"
728b60736ecSDimitry Andric               << "]";
7291d5ae102SDimitry Andric           break;
730344a3780SDimitry Andric         case MachineLocKind::ImmediateKind:
731344a3780SDimitry Andric           Out << MLoc.Value.Immediate;
7321d5ae102SDimitry Andric           break;
733e3b55780SDimitry Andric         case MachineLocKind::WasmLocKind: {
734e3b55780SDimitry Andric           if (TII) {
735e3b55780SDimitry Andric             auto Indices = TII->getSerializableTargetIndices();
736e3b55780SDimitry Andric             auto Found =
737e3b55780SDimitry Andric                 find_if(Indices, [&](const std::pair<int, const char *> &I) {
738e3b55780SDimitry Andric                   return I.first == MLoc.Value.WasmLocation.Index;
739e3b55780SDimitry Andric                 });
740e3b55780SDimitry Andric             assert(Found != Indices.end());
741e3b55780SDimitry Andric             Out << Found->second;
742e3b55780SDimitry Andric             if (MLoc.Value.WasmLocation.Offset > 0)
743e3b55780SDimitry Andric               Out << " + " << MLoc.Value.WasmLocation.Offset;
744e3b55780SDimitry Andric           } else {
745e3b55780SDimitry Andric             Out << "WasmLoc";
746e3b55780SDimitry Andric           }
747e3b55780SDimitry Andric           break;
748e3b55780SDimitry Andric         }
749344a3780SDimitry Andric         case MachineLocKind::InvalidKind:
7501d5ae102SDimitry Andric           llvm_unreachable("Invalid VarLoc in dump method");
7511d5ae102SDimitry Andric         }
752344a3780SDimitry Andric       }
7531d5ae102SDimitry Andric 
754cfca06d7SDimitry Andric       Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", ";
7551d5ae102SDimitry Andric       if (Var.getInlinedAt())
756cfca06d7SDimitry Andric         Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
7571d5ae102SDimitry Andric       else
758cfca06d7SDimitry Andric         Out << "(null))";
759706b4fc4SDimitry Andric 
760706b4fc4SDimitry Andric       if (isEntryBackupLoc())
761cfca06d7SDimitry Andric         Out << " (backup loc)\n";
762706b4fc4SDimitry Andric       else
763cfca06d7SDimitry Andric         Out << "\n";
7641d5ae102SDimitry Andric     }
76571d5a254SDimitry Andric #endif
76601095a5dSDimitry Andric 
operator ==__anond6891cb70111::VarLocBasedLDV::VarLoc76701095a5dSDimitry Andric     bool operator==(const VarLoc &Other) const {
768344a3780SDimitry Andric       return std::tie(EVKind, Var, Expr, Locs) ==
769344a3780SDimitry Andric              std::tie(Other.EVKind, Other.Var, Other.Expr, Other.Locs);
77001095a5dSDimitry Andric     }
77101095a5dSDimitry Andric 
77201095a5dSDimitry Andric     /// This operator guarantees that VarLocs are sorted by Variable first.
operator <__anond6891cb70111::VarLocBasedLDV::VarLoc77301095a5dSDimitry Andric     bool operator<(const VarLoc &Other) const {
774344a3780SDimitry Andric       return std::tie(Var, EVKind, Locs, Expr) <
775344a3780SDimitry Andric              std::tie(Other.Var, Other.EVKind, Other.Locs, Other.Expr);
77601095a5dSDimitry Andric     }
777dd58ef01SDimitry Andric   };
778dd58ef01SDimitry Andric 
779344a3780SDimitry Andric #ifndef NDEBUG
780344a3780SDimitry Andric   using VarVec = SmallVector<VarLoc, 32>;
781344a3780SDimitry Andric #endif
782344a3780SDimitry Andric 
783cfca06d7SDimitry Andric   /// VarLocMap is used for two things:
784344a3780SDimitry Andric   /// 1) Assigning LocIndices to a VarLoc. The LocIndices can be used to
785cfca06d7SDimitry Andric   ///    virtually insert a VarLoc into a VarLocSet.
786cfca06d7SDimitry Andric   /// 2) Given a LocIndex, look up the unique associated VarLoc.
787cfca06d7SDimitry Andric   class VarLocMap {
788cfca06d7SDimitry Andric     /// Map a VarLoc to an index within the vector reserved for its location
789cfca06d7SDimitry Andric     /// within Loc2Vars.
790344a3780SDimitry Andric     std::map<VarLoc, LocIndices> Var2Indices;
791cfca06d7SDimitry Andric 
792cfca06d7SDimitry Andric     /// Map a location to a vector which holds VarLocs which live in that
793cfca06d7SDimitry Andric     /// location.
794cfca06d7SDimitry Andric     SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars;
795cfca06d7SDimitry Andric 
796344a3780SDimitry Andric   public:
797344a3780SDimitry Andric     /// Retrieve LocIndices for \p VL.
insert(const VarLoc & VL)798344a3780SDimitry Andric     LocIndices insert(const VarLoc &VL) {
799344a3780SDimitry Andric       LocIndices &Indices = Var2Indices[VL];
800344a3780SDimitry Andric       // If Indices is not empty, VL is already in the map.
801344a3780SDimitry Andric       if (!Indices.empty())
802344a3780SDimitry Andric         return Indices;
803344a3780SDimitry Andric       SmallVector<LocIndex::u32_location_t, 4> Locations;
804344a3780SDimitry Andric       // LocIndices are determined by EVKind and MLs; each Register has a
805344a3780SDimitry Andric       // unique location, while all SpillLocs use a single bucket, and any EV
806344a3780SDimitry Andric       // VarLocs use only the Backup bucket or none at all (except the
807344a3780SDimitry Andric       // compulsory entry at the universal location index). LocIndices will
808344a3780SDimitry Andric       // always have an index at the universal location index as the last index.
809344a3780SDimitry Andric       if (VL.EVKind == VarLoc::EntryValueLocKind::NonEntryValueKind) {
810344a3780SDimitry Andric         VL.getDescribingRegs(Locations);
811344a3780SDimitry Andric         assert(all_of(Locations,
812344a3780SDimitry Andric                       [](auto RegNo) {
813344a3780SDimitry Andric                         return RegNo < LocIndex::kFirstInvalidRegLocation;
814344a3780SDimitry Andric                       }) &&
815cfca06d7SDimitry Andric                "Physreg out of range?");
816e3b55780SDimitry Andric         if (VL.containsSpillLocs())
817e3b55780SDimitry Andric           Locations.push_back(LocIndex::kSpillLocation);
818e3b55780SDimitry Andric         if (VL.containsWasmLocs())
819e3b55780SDimitry Andric           Locations.push_back(LocIndex::kWasmLocation);
820344a3780SDimitry Andric       } else if (VL.EVKind != VarLoc::EntryValueLocKind::EntryValueKind) {
821344a3780SDimitry Andric         LocIndex::u32_location_t Loc = LocIndex::kEntryValueBackupLocation;
822344a3780SDimitry Andric         Locations.push_back(Loc);
823344a3780SDimitry Andric       }
824344a3780SDimitry Andric       Locations.push_back(LocIndex::kUniversalLocation);
825344a3780SDimitry Andric       for (LocIndex::u32_location_t Location : Locations) {
826344a3780SDimitry Andric         auto &Vars = Loc2Vars[Location];
827344a3780SDimitry Andric         Indices.push_back(
828344a3780SDimitry Andric             {Location, static_cast<LocIndex::u32_index_t>(Vars.size())});
829344a3780SDimitry Andric         Vars.push_back(VL);
830344a3780SDimitry Andric       }
831344a3780SDimitry Andric       return Indices;
832cfca06d7SDimitry Andric     }
833cfca06d7SDimitry Andric 
getAllIndices(const VarLoc & VL) const834344a3780SDimitry Andric     LocIndices getAllIndices(const VarLoc &VL) const {
835344a3780SDimitry Andric       auto IndIt = Var2Indices.find(VL);
836344a3780SDimitry Andric       assert(IndIt != Var2Indices.end() && "VarLoc not tracked");
837344a3780SDimitry Andric       return IndIt->second;
838cfca06d7SDimitry Andric     }
839cfca06d7SDimitry Andric 
840cfca06d7SDimitry Andric     /// Retrieve the unique VarLoc associated with \p ID.
operator [](LocIndex ID) const841cfca06d7SDimitry Andric     const VarLoc &operator[](LocIndex ID) const {
842cfca06d7SDimitry Andric       auto LocIt = Loc2Vars.find(ID.Location);
843cfca06d7SDimitry Andric       assert(LocIt != Loc2Vars.end() && "Location not tracked");
844cfca06d7SDimitry Andric       return LocIt->second[ID.Index];
845cfca06d7SDimitry Andric     }
846cfca06d7SDimitry Andric   };
847cfca06d7SDimitry Andric 
848cfca06d7SDimitry Andric   using VarLocInMBB =
849cfca06d7SDimitry Andric       SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>;
850eb11fae6SDimitry Andric   struct TransferDebugPair {
851cfca06d7SDimitry Andric     MachineInstr *TransferInst; ///< Instruction where this transfer occurs.
852cfca06d7SDimitry Andric     LocIndex LocationID;        ///< Location number for the transfer dest.
85371d5a254SDimitry Andric   };
854eb11fae6SDimitry Andric   using TransferMap = SmallVector<TransferDebugPair, 4>;
855c0981da4SDimitry Andric   // Types for recording Entry Var Locations emitted by a single MachineInstr,
856c0981da4SDimitry Andric   // as well as recording MachineInstr which last defined a register.
857c0981da4SDimitry Andric   using InstToEntryLocMap = std::multimap<const MachineInstr *, LocIndex>;
858c0981da4SDimitry Andric   using RegDefToInstMap = DenseMap<Register, MachineInstr *>;
859dd58ef01SDimitry Andric 
860e6d15924SDimitry Andric   // Types for recording sets of variable fragments that overlap. For a given
861e6d15924SDimitry Andric   // local variable, we record all other fragments of that variable that could
862e6d15924SDimitry Andric   // overlap it, to reduce search time.
863e6d15924SDimitry Andric   using FragmentOfVar =
864e6d15924SDimitry Andric       std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
865e6d15924SDimitry Andric   using OverlapMap =
866e6d15924SDimitry Andric       DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
867e6d15924SDimitry Andric 
868e6d15924SDimitry Andric   // Helper while building OverlapMap, a map of all fragments seen for a given
869e6d15924SDimitry Andric   // DILocalVariable.
870e6d15924SDimitry Andric   using VarToFragments =
871e6d15924SDimitry Andric       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
872e6d15924SDimitry Andric 
873344a3780SDimitry Andric   /// Collects all VarLocs from \p CollectFrom. Each unique VarLoc is added
874344a3780SDimitry Andric   /// to \p Collected once, in order of insertion into \p VarLocIDs.
875344a3780SDimitry Andric   static void collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
876344a3780SDimitry Andric                                 const VarLocSet &CollectFrom,
877344a3780SDimitry Andric                                 const VarLocMap &VarLocIDs);
878344a3780SDimitry Andric 
879344a3780SDimitry Andric   /// Get the registers which are used by VarLocs of kind RegisterKind tracked
880344a3780SDimitry Andric   /// by \p CollectFrom.
881344a3780SDimitry Andric   void getUsedRegs(const VarLocSet &CollectFrom,
882344a3780SDimitry Andric                    SmallVectorImpl<Register> &UsedRegs) const;
883344a3780SDimitry Andric 
88401095a5dSDimitry Andric   /// This holds the working set of currently open ranges. For fast
88501095a5dSDimitry Andric   /// access, this is done both as a set of VarLocIDs, and a map of
88601095a5dSDimitry Andric   /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
887706b4fc4SDimitry Andric   /// previous open ranges for the same variable. In addition, we keep
888706b4fc4SDimitry Andric   /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
889706b4fc4SDimitry Andric   /// methods act differently depending on whether a VarLoc is primary
890706b4fc4SDimitry Andric   /// location or backup one. In the case the VarLoc is backup location
891706b4fc4SDimitry Andric   /// we will erase/insert from the EntryValuesBackupVars map, otherwise
892706b4fc4SDimitry Andric   /// we perform the operation on the Vars.
89301095a5dSDimitry Andric   class OpenRangesSet {
894344a3780SDimitry Andric     VarLocSet::Allocator &Alloc;
89501095a5dSDimitry Andric     VarLocSet VarLocs;
896706b4fc4SDimitry Andric     // Map the DebugVariable to recent primary location ID.
897344a3780SDimitry Andric     SmallDenseMap<DebugVariable, LocIndices, 8> Vars;
898706b4fc4SDimitry Andric     // Map the DebugVariable to recent backup location ID.
899344a3780SDimitry Andric     SmallDenseMap<DebugVariable, LocIndices, 8> EntryValuesBackupVars;
900e6d15924SDimitry Andric     OverlapMap &OverlappingFragments;
901dd58ef01SDimitry Andric 
90201095a5dSDimitry Andric   public:
OpenRangesSet(VarLocSet::Allocator & Alloc,OverlapMap & _OLapMap)903cfca06d7SDimitry Andric     OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
904344a3780SDimitry Andric         : Alloc(Alloc), VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
905e6d15924SDimitry Andric 
getVarLocs() const90601095a5dSDimitry Andric     const VarLocSet &getVarLocs() const { return VarLocs; }
90701095a5dSDimitry Andric 
908344a3780SDimitry Andric     // Fetches all VarLocs in \p VarLocIDs and inserts them into \p Collected.
909344a3780SDimitry Andric     // This method is needed to get every VarLoc once, as each VarLoc may have
910344a3780SDimitry Andric     // multiple indices in a VarLocMap (corresponding to each applicable
911344a3780SDimitry Andric     // location), but all VarLocs appear exactly once at the universal location
912344a3780SDimitry Andric     // index.
getUniqueVarLocs(SmallVectorImpl<VarLoc> & Collected,const VarLocMap & VarLocIDs) const913344a3780SDimitry Andric     void getUniqueVarLocs(SmallVectorImpl<VarLoc> &Collected,
914344a3780SDimitry Andric                           const VarLocMap &VarLocIDs) const {
915344a3780SDimitry Andric       collectAllVarLocs(Collected, VarLocs, VarLocIDs);
916344a3780SDimitry Andric     }
917344a3780SDimitry Andric 
918706b4fc4SDimitry Andric     /// Terminate all open ranges for VL.Var by removing it from the set.
919706b4fc4SDimitry Andric     void erase(const VarLoc &VL);
92001095a5dSDimitry Andric 
921344a3780SDimitry Andric     /// Terminate all open ranges listed as indices in \c KillSet with
922344a3780SDimitry Andric     /// \c Location by removing them from the set.
923344a3780SDimitry Andric     void erase(const VarLocsInRange &KillSet, const VarLocMap &VarLocIDs,
924344a3780SDimitry Andric                LocIndex::u32_location_t Location);
92501095a5dSDimitry Andric 
92601095a5dSDimitry Andric     /// Insert a new range into the set.
927344a3780SDimitry Andric     void insert(LocIndices VarLocIDs, const VarLoc &VL);
92801095a5dSDimitry Andric 
9291d5ae102SDimitry Andric     /// Insert a set of ranges.
930344a3780SDimitry Andric     void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map);
9311d5ae102SDimitry Andric 
932e3b55780SDimitry Andric     std::optional<LocIndices> getEntryValueBackup(DebugVariable Var);
933706b4fc4SDimitry Andric 
93401095a5dSDimitry Andric     /// Empty the set.
clear()93501095a5dSDimitry Andric     void clear() {
93601095a5dSDimitry Andric       VarLocs.clear();
93701095a5dSDimitry Andric       Vars.clear();
938706b4fc4SDimitry Andric       EntryValuesBackupVars.clear();
93901095a5dSDimitry Andric     }
94001095a5dSDimitry Andric 
94101095a5dSDimitry Andric     /// Return whether the set is empty or not.
empty() const94201095a5dSDimitry Andric     bool empty() const {
943706b4fc4SDimitry Andric       assert(Vars.empty() == EntryValuesBackupVars.empty() &&
944706b4fc4SDimitry Andric              Vars.empty() == VarLocs.empty() &&
945706b4fc4SDimitry Andric              "open ranges are inconsistent");
94601095a5dSDimitry Andric       return VarLocs.empty();
94701095a5dSDimitry Andric     }
948cfca06d7SDimitry Andric 
949cfca06d7SDimitry Andric     /// Get an empty range of VarLoc IDs.
getEmptyVarLocRange() const950cfca06d7SDimitry Andric     auto getEmptyVarLocRange() const {
951cfca06d7SDimitry Andric       return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(),
952cfca06d7SDimitry Andric                                                        getVarLocs().end());
953cfca06d7SDimitry Andric     }
954cfca06d7SDimitry Andric 
955344a3780SDimitry Andric     /// Get all set IDs for VarLocs with MLs of kind RegisterKind in \p Reg.
getRegisterVarLocs(Register Reg) const956cfca06d7SDimitry Andric     auto getRegisterVarLocs(Register Reg) const {
957cfca06d7SDimitry Andric       return LocIndex::indexRangeForLocation(getVarLocs(), Reg);
958cfca06d7SDimitry Andric     }
959cfca06d7SDimitry Andric 
960344a3780SDimitry Andric     /// Get all set IDs for VarLocs with MLs of kind SpillLocKind.
getSpillVarLocs() const961cfca06d7SDimitry Andric     auto getSpillVarLocs() const {
962cfca06d7SDimitry Andric       return LocIndex::indexRangeForLocation(getVarLocs(),
963cfca06d7SDimitry Andric                                              LocIndex::kSpillLocation);
964cfca06d7SDimitry Andric     }
965cfca06d7SDimitry Andric 
966344a3780SDimitry Andric     /// Get all set IDs for VarLocs of EVKind EntryValueBackupKind or
967cfca06d7SDimitry Andric     /// EntryValueCopyBackupKind.
getEntryValueBackupVarLocs() const968cfca06d7SDimitry Andric     auto getEntryValueBackupVarLocs() const {
969cfca06d7SDimitry Andric       return LocIndex::indexRangeForLocation(
970cfca06d7SDimitry Andric           getVarLocs(), LocIndex::kEntryValueBackupLocation);
971cfca06d7SDimitry Andric     }
972e3b55780SDimitry Andric 
973e3b55780SDimitry Andric     /// Get all set IDs for VarLocs with MLs of kind WasmLocKind.
getWasmVarLocs() const974e3b55780SDimitry Andric     auto getWasmVarLocs() const {
975e3b55780SDimitry Andric       return LocIndex::indexRangeForLocation(getVarLocs(),
976e3b55780SDimitry Andric                                              LocIndex::kWasmLocation);
977e3b55780SDimitry Andric     }
97801095a5dSDimitry Andric   };
97901095a5dSDimitry Andric 
980344a3780SDimitry Andric   /// Collect all VarLoc IDs from \p CollectFrom for VarLocs with MLs of kind
981344a3780SDimitry Andric   /// RegisterKind which are located in any reg in \p Regs. The IDs for each
982344a3780SDimitry Andric   /// VarLoc correspond to entries in the universal location bucket, which every
983344a3780SDimitry Andric   /// VarLoc has exactly 1 entry for. Insert collected IDs into \p Collected.
984344a3780SDimitry Andric   static void collectIDsForRegs(VarLocsInRange &Collected,
985344a3780SDimitry Andric                                 const DefinedRegsSet &Regs,
986344a3780SDimitry Andric                                 const VarLocSet &CollectFrom,
987344a3780SDimitry Andric                                 const VarLocMap &VarLocIDs);
988cfca06d7SDimitry Andric 
getVarLocsInMBB(const MachineBasicBlock * MBB,VarLocInMBB & Locs)989cfca06d7SDimitry Andric   VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
990cfca06d7SDimitry Andric     std::unique_ptr<VarLocSet> &VLS = Locs[MBB];
991cfca06d7SDimitry Andric     if (!VLS)
992cfca06d7SDimitry Andric       VLS = std::make_unique<VarLocSet>(Alloc);
993145449b1SDimitry Andric     return *VLS;
994cfca06d7SDimitry Andric   }
995cfca06d7SDimitry Andric 
getVarLocsInMBB(const MachineBasicBlock * MBB,const VarLocInMBB & Locs) const996cfca06d7SDimitry Andric   const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
997cfca06d7SDimitry Andric                                    const VarLocInMBB &Locs) const {
998cfca06d7SDimitry Andric     auto It = Locs.find(MBB);
999cfca06d7SDimitry Andric     assert(It != Locs.end() && "MBB not in map");
1000145449b1SDimitry Andric     return *It->second;
1001cfca06d7SDimitry Andric   }
1002cfca06d7SDimitry Andric 
10031d5ae102SDimitry Andric   /// Tests whether this instruction is a spill to a stack location.
10041d5ae102SDimitry Andric   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
10051d5ae102SDimitry Andric 
10061d5ae102SDimitry Andric   /// Decide if @MI is a spill instruction and return true if it is. We use 2
10071d5ae102SDimitry Andric   /// criteria to make this decision:
10081d5ae102SDimitry Andric   /// - Is this instruction a store to a spill slot?
10091d5ae102SDimitry Andric   /// - Is there a register operand that is both used and killed?
10101d5ae102SDimitry Andric   /// TODO: Store optimization can fold spills into other stores (including
10111d5ae102SDimitry Andric   /// other spills). We do not handle this yet (more than one memory operand).
10121d5ae102SDimitry Andric   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1013cfca06d7SDimitry Andric                        Register &Reg);
10141d5ae102SDimitry Andric 
1015706b4fc4SDimitry Andric   /// Returns true if the given machine instruction is a debug value which we
1016706b4fc4SDimitry Andric   /// can emit entry values for.
1017706b4fc4SDimitry Andric   ///
1018706b4fc4SDimitry Andric   /// Currently, we generate debug entry values only for parameters that are
1019706b4fc4SDimitry Andric   /// unmodified throughout the function and located in a register.
1020706b4fc4SDimitry Andric   bool isEntryValueCandidate(const MachineInstr &MI,
1021706b4fc4SDimitry Andric                              const DefinedRegsSet &Regs) const;
1022706b4fc4SDimitry Andric 
1023e6d15924SDimitry Andric   /// If a given instruction is identified as a spill, return the spill location
1024e6d15924SDimitry Andric   /// and set \p Reg to the spilled register.
1025e3b55780SDimitry Andric   std::optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
1026e6d15924SDimitry Andric                                                        MachineFunction *MF,
1027cfca06d7SDimitry Andric                                                        Register &Reg);
1028e6d15924SDimitry Andric   /// Given a spill instruction, extract the register and offset used to
1029e6d15924SDimitry Andric   /// address the spill location in a target independent way.
1030e6d15924SDimitry Andric   VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
1031eb11fae6SDimitry Andric   void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
1032eb11fae6SDimitry Andric                                TransferMap &Transfers, VarLocMap &VarLocIDs,
1033cfca06d7SDimitry Andric                                LocIndex OldVarID, TransferKind Kind,
1034344a3780SDimitry Andric                                const VarLoc::MachineLoc &OldLoc,
1035cfca06d7SDimitry Andric                                Register NewReg = Register());
103671d5a254SDimitry Andric 
103701095a5dSDimitry Andric   void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
1038c0981da4SDimitry Andric                           VarLocMap &VarLocIDs,
1039c0981da4SDimitry Andric                           InstToEntryLocMap &EntryValTransfers,
1040c0981da4SDimitry Andric                           RegDefToInstMap &RegSetInstrs);
1041e6d15924SDimitry Andric   void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
1042eb11fae6SDimitry Andric                                   VarLocMap &VarLocIDs, TransferMap &Transfers);
1043c0981da4SDimitry Andric   void cleanupEntryValueTransfers(const MachineInstr *MI,
1044c0981da4SDimitry Andric                                   OpenRangesSet &OpenRanges,
1045c0981da4SDimitry Andric                                   VarLocMap &VarLocIDs, const VarLoc &EntryVL,
1046c0981da4SDimitry Andric                                   InstToEntryLocMap &EntryValTransfers);
1047c0981da4SDimitry Andric   void removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
1048c0981da4SDimitry Andric                         VarLocMap &VarLocIDs, const VarLoc &EntryVL,
1049c0981da4SDimitry Andric                         InstToEntryLocMap &EntryValTransfers,
1050c0981da4SDimitry Andric                         RegDefToInstMap &RegSetInstrs);
1051e6d15924SDimitry Andric   void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
1052c0981da4SDimitry Andric                        VarLocMap &VarLocIDs,
1053c0981da4SDimitry Andric                        InstToEntryLocMap &EntryValTransfers,
1054344a3780SDimitry Andric                        VarLocsInRange &KillSet);
1055706b4fc4SDimitry Andric   void recordEntryValue(const MachineInstr &MI,
1056706b4fc4SDimitry Andric                         const DefinedRegsSet &DefinedRegs,
1057706b4fc4SDimitry Andric                         OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
1058eb11fae6SDimitry Andric   void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
1059eb11fae6SDimitry Andric                             VarLocMap &VarLocIDs, TransferMap &Transfers);
106001095a5dSDimitry Andric   void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
1061c0981da4SDimitry Andric                            VarLocMap &VarLocIDs,
1062c0981da4SDimitry Andric                            InstToEntryLocMap &EntryValTransfers,
1063c0981da4SDimitry Andric                            RegDefToInstMap &RegSetInstrs);
1064e3b55780SDimitry Andric   void transferWasmDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
1065e3b55780SDimitry Andric                        VarLocMap &VarLocIDs);
10661d5ae102SDimitry Andric   bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
106701095a5dSDimitry Andric                           VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
1068e6d15924SDimitry Andric 
10691d5ae102SDimitry Andric   void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1070c0981da4SDimitry Andric                VarLocMap &VarLocIDs, TransferMap &Transfers,
1071c0981da4SDimitry Andric                InstToEntryLocMap &EntryValTransfers,
1072c0981da4SDimitry Andric                RegDefToInstMap &RegSetInstrs);
1073e6d15924SDimitry Andric 
1074e6d15924SDimitry Andric   void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
1075e6d15924SDimitry Andric                              OverlapMap &OLapMap);
107601095a5dSDimitry Andric 
107701095a5dSDimitry Andric   bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1078b915e9e0SDimitry Andric             const VarLocMap &VarLocIDs,
1079d8e91e46SDimitry Andric             SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1080cfca06d7SDimitry Andric             SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
10811d5ae102SDimitry Andric 
10821d5ae102SDimitry Andric   /// Create DBG_VALUE insts for inlocs that have been propagated but
10831d5ae102SDimitry Andric   /// had their instruction creation deferred.
10841d5ae102SDimitry Andric   void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
1085dd58ef01SDimitry Andric 
1086c0981da4SDimitry Andric   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1087c0981da4SDimitry Andric                     TargetPassConfig *TPC, unsigned InputBBLimit,
1088c0981da4SDimitry Andric                     unsigned InputDbgValLimit) override;
1089dd58ef01SDimitry Andric 
1090dd58ef01SDimitry Andric public:
1091dd58ef01SDimitry Andric   /// Default construct and initialize the pass.
1092b60736ecSDimitry Andric   VarLocBasedLDV();
1093dd58ef01SDimitry Andric 
1094b60736ecSDimitry Andric   ~VarLocBasedLDV();
109501095a5dSDimitry Andric 
1096dd58ef01SDimitry Andric   /// Print to ostream with a message.
109701095a5dSDimitry Andric   void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
109801095a5dSDimitry Andric                         const VarLocMap &VarLocIDs, const char *msg,
1099dd58ef01SDimitry Andric                         raw_ostream &Out) const;
1100dd58ef01SDimitry Andric };
1101b915e9e0SDimitry Andric 
1102044eb2f6SDimitry Andric } // end anonymous namespace
1103dd58ef01SDimitry Andric 
1104dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
1105dd58ef01SDimitry Andric //            Implementation
1106dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
1107dd58ef01SDimitry Andric 
1108145449b1SDimitry Andric VarLocBasedLDV::VarLocBasedLDV() = default;
1109044eb2f6SDimitry Andric 
1110145449b1SDimitry Andric VarLocBasedLDV::~VarLocBasedLDV() = default;
1111dd58ef01SDimitry Andric 
1112e6d15924SDimitry Andric /// Erase a variable from the set of open ranges, and additionally erase any
1113b60736ecSDimitry Andric /// fragments that may overlap it. If the VarLoc is a backup location, erase
1114706b4fc4SDimitry Andric /// the variable from the EntryValuesBackupVars set, indicating we should stop
1115706b4fc4SDimitry Andric /// tracking its backup entry location. Otherwise, if the VarLoc is primary
1116706b4fc4SDimitry Andric /// location, erase the variable from the Vars set.
erase(const VarLoc & VL)1117b60736ecSDimitry Andric void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) {
1118e6d15924SDimitry Andric   // Erasure helper.
11197fa27ce4SDimitry Andric   auto DoErase = [&VL, this](DebugVariable VarToErase) {
1120706b4fc4SDimitry Andric     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1121706b4fc4SDimitry Andric     auto It = EraseFrom->find(VarToErase);
1122706b4fc4SDimitry Andric     if (It != EraseFrom->end()) {
1123344a3780SDimitry Andric       LocIndices IDs = It->second;
1124344a3780SDimitry Andric       for (LocIndex ID : IDs)
1125cfca06d7SDimitry Andric         VarLocs.reset(ID.getAsRawInteger());
1126706b4fc4SDimitry Andric       EraseFrom->erase(It);
1127e6d15924SDimitry Andric     }
1128e6d15924SDimitry Andric   };
1129e6d15924SDimitry Andric 
1130706b4fc4SDimitry Andric   DebugVariable Var = VL.Var;
1131706b4fc4SDimitry Andric 
1132e6d15924SDimitry Andric   // Erase the variable/fragment that ends here.
1133e6d15924SDimitry Andric   DoErase(Var);
1134e6d15924SDimitry Andric 
1135e6d15924SDimitry Andric   // Extract the fragment. Interpret an empty fragment as one that covers all
1136e6d15924SDimitry Andric   // possible bits.
1137706b4fc4SDimitry Andric   FragmentInfo ThisFragment = Var.getFragmentOrDefault();
1138e6d15924SDimitry Andric 
1139e6d15924SDimitry Andric   // There may be fragments that overlap the designated fragment. Look them up
1140e6d15924SDimitry Andric   // in the pre-computed overlap map, and erase them too.
1141706b4fc4SDimitry Andric   auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
1142e6d15924SDimitry Andric   if (MapIt != OverlappingFragments.end()) {
1143e6d15924SDimitry Andric     for (auto Fragment : MapIt->second) {
1144b60736ecSDimitry Andric       VarLocBasedLDV::OptFragmentInfo FragmentHolder;
1145706b4fc4SDimitry Andric       if (!DebugVariable::isDefaultFragment(Fragment))
1146b60736ecSDimitry Andric         FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment);
1147706b4fc4SDimitry Andric       DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
1148e6d15924SDimitry Andric     }
1149e6d15924SDimitry Andric   }
1150e6d15924SDimitry Andric }
1151e6d15924SDimitry Andric 
erase(const VarLocsInRange & KillSet,const VarLocMap & VarLocIDs,LocIndex::u32_location_t Location)1152344a3780SDimitry Andric void VarLocBasedLDV::OpenRangesSet::erase(const VarLocsInRange &KillSet,
1153344a3780SDimitry Andric                                           const VarLocMap &VarLocIDs,
1154344a3780SDimitry Andric                                           LocIndex::u32_location_t Location) {
1155344a3780SDimitry Andric   VarLocSet RemoveSet(Alloc);
1156344a3780SDimitry Andric   for (LocIndex::u32_index_t ID : KillSet) {
1157344a3780SDimitry Andric     const VarLoc &VL = VarLocIDs[LocIndex(Location, ID)];
1158344a3780SDimitry Andric     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1159344a3780SDimitry Andric     EraseFrom->erase(VL.Var);
1160344a3780SDimitry Andric     LocIndices VLI = VarLocIDs.getAllIndices(VL);
1161344a3780SDimitry Andric     for (LocIndex ID : VLI)
1162344a3780SDimitry Andric       RemoveSet.set(ID.getAsRawInteger());
1163344a3780SDimitry Andric   }
1164344a3780SDimitry Andric   VarLocs.intersectWithComplement(RemoveSet);
1165344a3780SDimitry Andric }
1166344a3780SDimitry Andric 
insertFromLocSet(const VarLocSet & ToLoad,const VarLocMap & Map)1167344a3780SDimitry Andric void VarLocBasedLDV::OpenRangesSet::insertFromLocSet(const VarLocSet &ToLoad,
1168344a3780SDimitry Andric                                                      const VarLocMap &Map) {
1169344a3780SDimitry Andric   VarLocsInRange UniqueVarLocIDs;
1170344a3780SDimitry Andric   DefinedRegsSet Regs;
1171344a3780SDimitry Andric   Regs.insert(LocIndex::kUniversalLocation);
1172344a3780SDimitry Andric   collectIDsForRegs(UniqueVarLocIDs, Regs, ToLoad, Map);
1173344a3780SDimitry Andric   for (uint64_t ID : UniqueVarLocIDs) {
1174344a3780SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1175344a3780SDimitry Andric     const VarLoc &VarL = Map[Idx];
1176344a3780SDimitry Andric     const LocIndices Indices = Map.getAllIndices(VarL);
1177344a3780SDimitry Andric     insert(Indices, VarL);
1178706b4fc4SDimitry Andric   }
1179706b4fc4SDimitry Andric }
1180706b4fc4SDimitry Andric 
insert(LocIndices VarLocIDs,const VarLoc & VL)1181344a3780SDimitry Andric void VarLocBasedLDV::OpenRangesSet::insert(LocIndices VarLocIDs,
1182706b4fc4SDimitry Andric                                            const VarLoc &VL) {
1183706b4fc4SDimitry Andric   auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1184344a3780SDimitry Andric   for (LocIndex ID : VarLocIDs)
1185344a3780SDimitry Andric     VarLocs.set(ID.getAsRawInteger());
1186344a3780SDimitry Andric   InsertInto->insert({VL.Var, VarLocIDs});
1187706b4fc4SDimitry Andric }
1188706b4fc4SDimitry Andric 
1189706b4fc4SDimitry Andric /// Return the Loc ID of an entry value backup location, if it exists for the
1190706b4fc4SDimitry Andric /// variable.
1191e3b55780SDimitry Andric std::optional<LocIndices>
getEntryValueBackup(DebugVariable Var)1192b60736ecSDimitry Andric VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
1193706b4fc4SDimitry Andric   auto It = EntryValuesBackupVars.find(Var);
1194706b4fc4SDimitry Andric   if (It != EntryValuesBackupVars.end())
1195706b4fc4SDimitry Andric     return It->second;
1196706b4fc4SDimitry Andric 
1197e3b55780SDimitry Andric   return std::nullopt;
1198706b4fc4SDimitry Andric }
1199706b4fc4SDimitry Andric 
collectIDsForRegs(VarLocsInRange & Collected,const DefinedRegsSet & Regs,const VarLocSet & CollectFrom,const VarLocMap & VarLocIDs)1200344a3780SDimitry Andric void VarLocBasedLDV::collectIDsForRegs(VarLocsInRange &Collected,
1201cfca06d7SDimitry Andric                                        const DefinedRegsSet &Regs,
1202344a3780SDimitry Andric                                        const VarLocSet &CollectFrom,
1203344a3780SDimitry Andric                                        const VarLocMap &VarLocIDs) {
1204cfca06d7SDimitry Andric   assert(!Regs.empty() && "Nothing to collect");
1205344a3780SDimitry Andric   SmallVector<Register, 32> SortedRegs;
1206344a3780SDimitry Andric   append_range(SortedRegs, Regs);
1207cfca06d7SDimitry Andric   array_pod_sort(SortedRegs.begin(), SortedRegs.end());
1208cfca06d7SDimitry Andric   auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front()));
1209cfca06d7SDimitry Andric   auto End = CollectFrom.end();
1210344a3780SDimitry Andric   for (Register Reg : SortedRegs) {
1211344a3780SDimitry Andric     // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains
1212344a3780SDimitry Andric     // all possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which
1213344a3780SDimitry Andric     // live in Reg.
1214cfca06d7SDimitry Andric     uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
1215cfca06d7SDimitry Andric     uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
1216cfca06d7SDimitry Andric     It.advanceToLowerBound(FirstIndexForReg);
1217cfca06d7SDimitry Andric 
1218cfca06d7SDimitry Andric     // Iterate through that half-open interval and collect all the set IDs.
1219344a3780SDimitry Andric     for (; It != End && *It < FirstInvalidIndex; ++It) {
1220344a3780SDimitry Andric       LocIndex ItIdx = LocIndex::fromRawInteger(*It);
1221344a3780SDimitry Andric       const VarLoc &VL = VarLocIDs[ItIdx];
1222344a3780SDimitry Andric       LocIndices LI = VarLocIDs.getAllIndices(VL);
1223344a3780SDimitry Andric       // For now, the back index is always the universal location index.
1224344a3780SDimitry Andric       assert(LI.back().Location == LocIndex::kUniversalLocation &&
1225344a3780SDimitry Andric              "Unexpected order of LocIndices for VarLoc; was it inserted into "
1226344a3780SDimitry Andric              "the VarLocMap correctly?");
1227344a3780SDimitry Andric       Collected.insert(LI.back().Index);
1228344a3780SDimitry Andric     }
1229cfca06d7SDimitry Andric 
1230cfca06d7SDimitry Andric     if (It == End)
1231cfca06d7SDimitry Andric       return;
1232cfca06d7SDimitry Andric   }
1233cfca06d7SDimitry Andric }
1234cfca06d7SDimitry Andric 
getUsedRegs(const VarLocSet & CollectFrom,SmallVectorImpl<Register> & UsedRegs) const1235b60736ecSDimitry Andric void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom,
1236344a3780SDimitry Andric                                  SmallVectorImpl<Register> &UsedRegs) const {
1237cfca06d7SDimitry Andric   // All register-based VarLocs are assigned indices greater than or equal to
1238cfca06d7SDimitry Andric   // FirstRegIndex.
1239344a3780SDimitry Andric   uint64_t FirstRegIndex =
1240344a3780SDimitry Andric       LocIndex::rawIndexForReg(LocIndex::kFirstRegLocation);
1241cfca06d7SDimitry Andric   uint64_t FirstInvalidIndex =
1242cfca06d7SDimitry Andric       LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation);
1243cfca06d7SDimitry Andric   for (auto It = CollectFrom.find(FirstRegIndex),
1244cfca06d7SDimitry Andric             End = CollectFrom.find(FirstInvalidIndex);
1245cfca06d7SDimitry Andric        It != End;) {
1246cfca06d7SDimitry Andric     // We found a VarLoc ID for a VarLoc that lives in a register. Figure out
1247cfca06d7SDimitry Andric     // which register and add it to UsedRegs.
1248cfca06d7SDimitry Andric     uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
1249cfca06d7SDimitry Andric     assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
1250cfca06d7SDimitry Andric            "Duplicate used reg");
1251cfca06d7SDimitry Andric     UsedRegs.push_back(FoundReg);
1252cfca06d7SDimitry Andric 
1253cfca06d7SDimitry Andric     // Skip to the next /set/ register. Note that this finds a lower bound, so
1254cfca06d7SDimitry Andric     // even if there aren't any VarLocs living in `FoundReg+1`, we're still
1255cfca06d7SDimitry Andric     // guaranteed to move on to the next register (or to end()).
1256cfca06d7SDimitry Andric     uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
1257cfca06d7SDimitry Andric     It.advanceToLowerBound(NextRegIndex);
1258cfca06d7SDimitry Andric   }
1259cfca06d7SDimitry Andric }
1260cfca06d7SDimitry Andric 
1261dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
1262dd58ef01SDimitry Andric //            Debug Range Extension Implementation
1263dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
1264dd58ef01SDimitry Andric 
126571d5a254SDimitry Andric #ifndef NDEBUG
printVarLocInMBB(const MachineFunction & MF,const VarLocInMBB & V,const VarLocMap & VarLocIDs,const char * msg,raw_ostream & Out) const1266b60736ecSDimitry Andric void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF,
126701095a5dSDimitry Andric                                        const VarLocInMBB &V,
126801095a5dSDimitry Andric                                        const VarLocMap &VarLocIDs,
126901095a5dSDimitry Andric                                        const char *msg,
1270dd58ef01SDimitry Andric                                        raw_ostream &Out) const {
1271b915e9e0SDimitry Andric   Out << '\n' << msg << '\n';
127201095a5dSDimitry Andric   for (const MachineBasicBlock &BB : MF) {
1273cfca06d7SDimitry Andric     if (!V.count(&BB))
1274cfca06d7SDimitry Andric       continue;
1275cfca06d7SDimitry Andric     const VarLocSet &L = getVarLocsInMBB(&BB, V);
1276d8e91e46SDimitry Andric     if (L.empty())
1277d8e91e46SDimitry Andric       continue;
1278344a3780SDimitry Andric     SmallVector<VarLoc, 32> VarLocs;
1279344a3780SDimitry Andric     collectAllVarLocs(VarLocs, L, VarLocIDs);
1280d8e91e46SDimitry Andric     Out << "MBB: " << BB.getNumber() << ":\n";
1281344a3780SDimitry Andric     for (const VarLoc &VL : VarLocs) {
1282706b4fc4SDimitry Andric       Out << " Var: " << VL.Var.getVariable()->getName();
1283dd58ef01SDimitry Andric       Out << " MI: ";
1284e3b55780SDimitry Andric       VL.dump(TRI, TII, Out);
1285dd58ef01SDimitry Andric     }
1286dd58ef01SDimitry Andric   }
1287dd58ef01SDimitry Andric   Out << "\n";
1288dd58ef01SDimitry Andric }
128971d5a254SDimitry Andric #endif
129071d5a254SDimitry Andric 
1291b60736ecSDimitry Andric VarLocBasedLDV::VarLoc::SpillLoc
extractSpillBaseRegAndOffset(const MachineInstr & MI)1292b60736ecSDimitry Andric VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
129371d5a254SDimitry Andric   assert(MI.hasOneMemOperand() &&
129471d5a254SDimitry Andric          "Spill instruction does not have exactly one memory operand?");
129571d5a254SDimitry Andric   auto MMOI = MI.memoperands_begin();
129671d5a254SDimitry Andric   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
129771d5a254SDimitry Andric   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
129871d5a254SDimitry Andric          "Inconsistent memory operand in spill instruction");
129971d5a254SDimitry Andric   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
130071d5a254SDimitry Andric   const MachineBasicBlock *MBB = MI.getParent();
1301cfca06d7SDimitry Andric   Register Reg;
1302b60736ecSDimitry Andric   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1303e6d15924SDimitry Andric   return {Reg, Offset};
130471d5a254SDimitry Andric }
1305dd58ef01SDimitry Andric 
1306c0981da4SDimitry Andric /// Do cleanup of \p EntryValTransfers created by \p TRInst, by removing the
1307c0981da4SDimitry Andric /// Transfer, which uses the to-be-deleted \p EntryVL.
cleanupEntryValueTransfers(const MachineInstr * TRInst,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,const VarLoc & EntryVL,InstToEntryLocMap & EntryValTransfers)1308c0981da4SDimitry Andric void VarLocBasedLDV::cleanupEntryValueTransfers(
1309c0981da4SDimitry Andric     const MachineInstr *TRInst, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
1310c0981da4SDimitry Andric     const VarLoc &EntryVL, InstToEntryLocMap &EntryValTransfers) {
1311c0981da4SDimitry Andric   if (EntryValTransfers.empty() || TRInst == nullptr)
1312c0981da4SDimitry Andric     return;
1313c0981da4SDimitry Andric 
1314c0981da4SDimitry Andric   auto TransRange = EntryValTransfers.equal_range(TRInst);
13157fa27ce4SDimitry Andric   for (auto &TDPair : llvm::make_range(TransRange.first, TransRange.second)) {
1316c0981da4SDimitry Andric     const VarLoc &EmittedEV = VarLocIDs[TDPair.second];
1317c0981da4SDimitry Andric     if (std::tie(EntryVL.Var, EntryVL.Locs[0].Value.RegNo, EntryVL.Expr) ==
1318c0981da4SDimitry Andric         std::tie(EmittedEV.Var, EmittedEV.Locs[0].Value.RegNo,
1319c0981da4SDimitry Andric                  EmittedEV.Expr)) {
1320c0981da4SDimitry Andric       OpenRanges.erase(EmittedEV);
1321c0981da4SDimitry Andric       EntryValTransfers.erase(TRInst);
1322c0981da4SDimitry Andric       break;
1323c0981da4SDimitry Andric     }
1324c0981da4SDimitry Andric   }
1325c0981da4SDimitry Andric }
1326c0981da4SDimitry Andric 
1327706b4fc4SDimitry Andric /// Try to salvage the debug entry value if we encounter a new debug value
1328706b4fc4SDimitry Andric /// describing the same parameter, otherwise stop tracking the value. Return
1329c0981da4SDimitry Andric /// true if we should stop tracking the entry value and do the cleanup of
1330c0981da4SDimitry Andric /// emitted Entry Value Transfers, otherwise return false.
removeEntryValue(const MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,const VarLoc & EntryVL,InstToEntryLocMap & EntryValTransfers,RegDefToInstMap & RegSetInstrs)1331c0981da4SDimitry Andric void VarLocBasedLDV::removeEntryValue(const MachineInstr &MI,
1332706b4fc4SDimitry Andric                                       OpenRangesSet &OpenRanges,
1333706b4fc4SDimitry Andric                                       VarLocMap &VarLocIDs,
1334c0981da4SDimitry Andric                                       const VarLoc &EntryVL,
1335c0981da4SDimitry Andric                                       InstToEntryLocMap &EntryValTransfers,
1336c0981da4SDimitry Andric                                       RegDefToInstMap &RegSetInstrs) {
1337706b4fc4SDimitry Andric   // Skip the DBG_VALUE which is the debug entry value itself.
1338c0981da4SDimitry Andric   if (&MI == &EntryVL.MI)
1339c0981da4SDimitry Andric     return;
1340706b4fc4SDimitry Andric 
1341706b4fc4SDimitry Andric   // If the parameter's location is not register location, we can not track
1342c0981da4SDimitry Andric   // the entry value any more. It doesn't have the TransferInst which defines
1343c0981da4SDimitry Andric   // register, so no Entry Value Transfers have been emitted already.
1344c0981da4SDimitry Andric   if (!MI.getDebugOperand(0).isReg())
1345c0981da4SDimitry Andric     return;
1346706b4fc4SDimitry Andric 
1347c0981da4SDimitry Andric   // Try to get non-debug instruction responsible for the DBG_VALUE.
1348c0981da4SDimitry Andric   const MachineInstr *TransferInst = nullptr;
1349cfca06d7SDimitry Andric   Register Reg = MI.getDebugOperand(0).getReg();
13507fa27ce4SDimitry Andric   if (Reg.isValid() && RegSetInstrs.contains(Reg))
1351c0981da4SDimitry Andric     TransferInst = RegSetInstrs.find(Reg)->second;
1352344a3780SDimitry Andric 
1353c0981da4SDimitry Andric   // Case of the parameter's DBG_VALUE at the start of entry MBB.
1354c0981da4SDimitry Andric   if (!TransferInst && !LastNonDbgMI && MI.getParent()->isEntryBlock())
1355c0981da4SDimitry Andric     return;
1356c0981da4SDimitry Andric 
1357c0981da4SDimitry Andric   // If the debug expression from the DBG_VALUE is not empty, we can assume the
1358c0981da4SDimitry Andric   // parameter's value has changed indicating that we should stop tracking its
1359c0981da4SDimitry Andric   // entry value as well.
1360c0981da4SDimitry Andric   if (MI.getDebugExpression()->getNumElements() == 0 && TransferInst) {
1361c0981da4SDimitry Andric     // If the DBG_VALUE comes from a copy instruction that copies the entry
1362c0981da4SDimitry Andric     // value, it means the parameter's value has not changed and we should be
1363c0981da4SDimitry Andric     // able to use its entry value.
1364706b4fc4SDimitry Andric     // TODO: Try to keep tracking of an entry value if we encounter a propagated
1365706b4fc4SDimitry Andric     // DBG_VALUE describing the copy of the entry value. (Propagated entry value
1366706b4fc4SDimitry Andric     // does not indicate the parameter modification.)
1367312c0ed1SDimitry Andric     auto DestSrc = TII->isCopyLikeInstr(*TransferInst);
1368c0981da4SDimitry Andric     if (DestSrc) {
1369c0981da4SDimitry Andric       const MachineOperand *SrcRegOp, *DestRegOp;
1370706b4fc4SDimitry Andric       SrcRegOp = DestSrc->Source;
1371706b4fc4SDimitry Andric       DestRegOp = DestSrc->Destination;
1372c0981da4SDimitry Andric       if (Reg == DestRegOp->getReg()) {
1373cfca06d7SDimitry Andric         for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1374cfca06d7SDimitry Andric           const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
1375344a3780SDimitry Andric           if (VL.isEntryValueCopyBackupReg(Reg) &&
1376344a3780SDimitry Andric               // Entry Values should not be variadic.
1377cfca06d7SDimitry Andric               VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg())
1378c0981da4SDimitry Andric             return;
1379c0981da4SDimitry Andric         }
1380c0981da4SDimitry Andric       }
1381706b4fc4SDimitry Andric     }
1382706b4fc4SDimitry Andric   }
1383706b4fc4SDimitry Andric 
1384c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
1385c0981da4SDimitry Andric              MI.print(dbgs(), /*IsStandalone*/ false,
1386c0981da4SDimitry Andric                       /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
1387c0981da4SDimitry Andric                       /*AddNewLine*/ true, TII));
1388c0981da4SDimitry Andric   cleanupEntryValueTransfers(TransferInst, OpenRanges, VarLocIDs, EntryVL,
1389c0981da4SDimitry Andric                              EntryValTransfers);
1390c0981da4SDimitry Andric   OpenRanges.erase(EntryVL);
1391706b4fc4SDimitry Andric }
1392706b4fc4SDimitry Andric 
1393dd58ef01SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI
1394dd58ef01SDimitry Andric /// if it is a DBG_VALUE instr.
transferDebugValue(const MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,InstToEntryLocMap & EntryValTransfers,RegDefToInstMap & RegSetInstrs)1395b60736ecSDimitry Andric void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI,
139601095a5dSDimitry Andric                                         OpenRangesSet &OpenRanges,
1397c0981da4SDimitry Andric                                         VarLocMap &VarLocIDs,
1398c0981da4SDimitry Andric                                         InstToEntryLocMap &EntryValTransfers,
1399c0981da4SDimitry Andric                                         RegDefToInstMap &RegSetInstrs) {
1400dd58ef01SDimitry Andric   if (!MI.isDebugValue())
1401dd58ef01SDimitry Andric     return;
140201095a5dSDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
1403e6d15924SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
140401095a5dSDimitry Andric   const DILocation *DebugLoc = MI.getDebugLoc();
140501095a5dSDimitry Andric   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
140601095a5dSDimitry Andric   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1407dd58ef01SDimitry Andric          "Expected inlined-at fields to agree");
1408dd58ef01SDimitry Andric 
1409e6d15924SDimitry Andric   DebugVariable V(Var, Expr, InlinedAt);
1410dd58ef01SDimitry Andric 
1411706b4fc4SDimitry Andric   // Check if this DBG_VALUE indicates a parameter's value changing.
1412706b4fc4SDimitry Andric   // If that is the case, we should stop tracking its entry value.
1413706b4fc4SDimitry Andric   auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
1414706b4fc4SDimitry Andric   if (Var->isParameter() && EntryValBackupID) {
1415344a3780SDimitry Andric     const VarLoc &EntryVL = VarLocIDs[EntryValBackupID->back()];
1416c0981da4SDimitry Andric     removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL, EntryValTransfers,
1417c0981da4SDimitry Andric                      RegSetInstrs);
1418706b4fc4SDimitry Andric   }
1419706b4fc4SDimitry Andric 
1420344a3780SDimitry Andric   if (all_of(MI.debug_operands(), [](const MachineOperand &MO) {
1421344a3780SDimitry Andric         return (MO.isReg() && MO.getReg()) || MO.isImm() || MO.isFPImm() ||
1422e3b55780SDimitry Andric                MO.isCImm() || MO.isTargetIndex();
1423344a3780SDimitry Andric       })) {
1424e6d15924SDimitry Andric     // Use normal VarLoc constructor for registers and immediates.
1425e3b55780SDimitry Andric     VarLoc VL(MI);
1426706b4fc4SDimitry Andric     // End all previous ranges of VL.Var.
1427706b4fc4SDimitry Andric     OpenRanges.erase(VL);
1428706b4fc4SDimitry Andric 
1429344a3780SDimitry Andric     LocIndices IDs = VarLocIDs.insert(VL);
1430706b4fc4SDimitry Andric     // Add the VarLoc to OpenRanges from this DBG_VALUE.
1431344a3780SDimitry Andric     OpenRanges.insert(IDs, VL);
1432344a3780SDimitry Andric   } else if (MI.memoperands().size() > 0) {
14331d5ae102SDimitry Andric     llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
1434e6d15924SDimitry Andric   } else {
1435cfca06d7SDimitry Andric     // This must be an undefined location. If it has an open range, erase it.
1436344a3780SDimitry Andric     assert(MI.isUndefDebugValue() &&
1437e6d15924SDimitry Andric            "Unexpected non-undef DBG_VALUE encountered");
1438e3b55780SDimitry Andric     VarLoc VL(MI);
1439cfca06d7SDimitry Andric     OpenRanges.erase(VL);
1440e6d15924SDimitry Andric   }
1441e6d15924SDimitry Andric }
1442e6d15924SDimitry Andric 
1443344a3780SDimitry Andric // This should be removed later, doesn't fit the new design.
collectAllVarLocs(SmallVectorImpl<VarLoc> & Collected,const VarLocSet & CollectFrom,const VarLocMap & VarLocIDs)1444344a3780SDimitry Andric void VarLocBasedLDV::collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
1445344a3780SDimitry Andric                                        const VarLocSet &CollectFrom,
1446344a3780SDimitry Andric                                        const VarLocMap &VarLocIDs) {
1447344a3780SDimitry Andric   // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all
1448344a3780SDimitry Andric   // possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which live
1449344a3780SDimitry Andric   // in Reg.
1450344a3780SDimitry Andric   uint64_t FirstIndex = LocIndex::rawIndexForReg(LocIndex::kUniversalLocation);
1451344a3780SDimitry Andric   uint64_t FirstInvalidIndex =
1452344a3780SDimitry Andric       LocIndex::rawIndexForReg(LocIndex::kUniversalLocation + 1);
1453344a3780SDimitry Andric   // Iterate through that half-open interval and collect all the set IDs.
1454344a3780SDimitry Andric   for (auto It = CollectFrom.find(FirstIndex), End = CollectFrom.end();
1455344a3780SDimitry Andric        It != End && *It < FirstInvalidIndex; ++It) {
1456344a3780SDimitry Andric     LocIndex RegIdx = LocIndex::fromRawInteger(*It);
1457344a3780SDimitry Andric     Collected.push_back(VarLocIDs[RegIdx]);
1458344a3780SDimitry Andric   }
1459344a3780SDimitry Andric }
1460344a3780SDimitry Andric 
1461706b4fc4SDimitry Andric /// Turn the entry value backup locations into primary locations.
emitEntryValues(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,InstToEntryLocMap & EntryValTransfers,VarLocsInRange & KillSet)1462b60736ecSDimitry Andric void VarLocBasedLDV::emitEntryValues(MachineInstr &MI,
1463e6d15924SDimitry Andric                                      OpenRangesSet &OpenRanges,
1464e6d15924SDimitry Andric                                      VarLocMap &VarLocIDs,
1465c0981da4SDimitry Andric                                      InstToEntryLocMap &EntryValTransfers,
1466344a3780SDimitry Andric                                      VarLocsInRange &KillSet) {
1467cfca06d7SDimitry Andric   // Do not insert entry value locations after a terminator.
1468cfca06d7SDimitry Andric   if (MI.isTerminator())
1469cfca06d7SDimitry Andric     return;
1470cfca06d7SDimitry Andric 
1471344a3780SDimitry Andric   for (uint32_t ID : KillSet) {
1472344a3780SDimitry Andric     // The KillSet IDs are indices for the universal location bucket.
1473344a3780SDimitry Andric     LocIndex Idx = LocIndex(LocIndex::kUniversalLocation, ID);
1474cfca06d7SDimitry Andric     const VarLoc &VL = VarLocIDs[Idx];
1475cfca06d7SDimitry Andric     if (!VL.Var.getVariable()->isParameter())
1476e6d15924SDimitry Andric       continue;
1477e6d15924SDimitry Andric 
1478cfca06d7SDimitry Andric     auto DebugVar = VL.Var;
1479e3b55780SDimitry Andric     std::optional<LocIndices> EntryValBackupIDs =
1480cfca06d7SDimitry Andric         OpenRanges.getEntryValueBackup(DebugVar);
1481e6d15924SDimitry Andric 
1482706b4fc4SDimitry Andric     // If the parameter has the entry value backup, it means we should
1483706b4fc4SDimitry Andric     // be able to use its entry value.
1484344a3780SDimitry Andric     if (!EntryValBackupIDs)
1485e6d15924SDimitry Andric       continue;
1486e6d15924SDimitry Andric 
1487344a3780SDimitry Andric     const VarLoc &EntryVL = VarLocIDs[EntryValBackupIDs->back()];
1488e3b55780SDimitry Andric     VarLoc EntryLoc = VarLoc::CreateEntryLoc(EntryVL.MI, EntryVL.Expr,
1489344a3780SDimitry Andric                                              EntryVL.Locs[0].Value.RegNo);
1490344a3780SDimitry Andric     LocIndices EntryValueIDs = VarLocIDs.insert(EntryLoc);
1491c0981da4SDimitry Andric     assert(EntryValueIDs.size() == 1 &&
1492c0981da4SDimitry Andric            "EntryValue loc should not be variadic");
1493c0981da4SDimitry Andric     EntryValTransfers.insert({&MI, EntryValueIDs.back()});
1494344a3780SDimitry Andric     OpenRanges.insert(EntryValueIDs, EntryLoc);
1495dd58ef01SDimitry Andric   }
1496dd58ef01SDimitry Andric }
1497dd58ef01SDimitry Andric 
1498eb11fae6SDimitry Andric /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
1499eb11fae6SDimitry Andric /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
1500eb11fae6SDimitry Andric /// new VarLoc. If \p NewReg is different than default zero value then the
1501eb11fae6SDimitry Andric /// new location will be register location created by the copy like instruction,
1502eb11fae6SDimitry Andric /// otherwise it is variable's location on the stack.
insertTransferDebugPair(MachineInstr & MI,OpenRangesSet & OpenRanges,TransferMap & Transfers,VarLocMap & VarLocIDs,LocIndex OldVarID,TransferKind Kind,const VarLoc::MachineLoc & OldLoc,Register NewReg)1503b60736ecSDimitry Andric void VarLocBasedLDV::insertTransferDebugPair(
1504eb11fae6SDimitry Andric     MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
1505cfca06d7SDimitry Andric     VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
1506344a3780SDimitry Andric     const VarLoc::MachineLoc &OldLoc, Register NewReg) {
1507344a3780SDimitry Andric   const VarLoc &OldVarLoc = VarLocIDs[OldVarID];
1508eb11fae6SDimitry Andric 
1509706b4fc4SDimitry Andric   auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
1510344a3780SDimitry Andric     LocIndices LocIds = VarLocIDs.insert(VL);
1511e6d15924SDimitry Andric 
1512e6d15924SDimitry Andric     // Close this variable's previous location range.
1513706b4fc4SDimitry Andric     OpenRanges.erase(VL);
1514e6d15924SDimitry Andric 
15151d5ae102SDimitry Andric     // Record the new location as an open range, and a postponed transfer
15161d5ae102SDimitry Andric     // inserting a DBG_VALUE for this location.
1517344a3780SDimitry Andric     OpenRanges.insert(LocIds, VL);
1518cfca06d7SDimitry Andric     assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator");
1519344a3780SDimitry Andric     TransferDebugPair MIP = {&MI, LocIds.back()};
1520eb11fae6SDimitry Andric     Transfers.push_back(MIP);
1521e6d15924SDimitry Andric   };
1522eb11fae6SDimitry Andric 
1523706b4fc4SDimitry Andric   // End all previous ranges of VL.Var.
1524706b4fc4SDimitry Andric   OpenRanges.erase(VarLocIDs[OldVarID]);
1525e6d15924SDimitry Andric   switch (Kind) {
1526e6d15924SDimitry Andric   case TransferKind::TransferCopy: {
1527e6d15924SDimitry Andric     assert(NewReg &&
1528e6d15924SDimitry Andric            "No register supplied when handling a copy of a debug value");
1529e6d15924SDimitry Andric     // Create a DBG_VALUE instruction to describe the Var in its new
1530e6d15924SDimitry Andric     // register location.
1531344a3780SDimitry Andric     VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
15321d5ae102SDimitry Andric     ProcessVarLoc(VL);
15331d5ae102SDimitry Andric     LLVM_DEBUG({
15341d5ae102SDimitry Andric       dbgs() << "Creating VarLoc for register copy:";
1535e3b55780SDimitry Andric       VL.dump(TRI, TII);
15361d5ae102SDimitry Andric     });
1537e6d15924SDimitry Andric     return;
1538e6d15924SDimitry Andric   }
1539e6d15924SDimitry Andric   case TransferKind::TransferSpill: {
1540e6d15924SDimitry Andric     // Create a DBG_VALUE instruction to describe the Var in its spilled
1541e6d15924SDimitry Andric     // location.
1542e6d15924SDimitry Andric     VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
1543344a3780SDimitry Andric     VarLoc VL = VarLoc::CreateSpillLoc(
1544344a3780SDimitry Andric         OldVarLoc, OldLoc, SpillLocation.SpillBase, SpillLocation.SpillOffset);
15451d5ae102SDimitry Andric     ProcessVarLoc(VL);
15461d5ae102SDimitry Andric     LLVM_DEBUG({
15471d5ae102SDimitry Andric       dbgs() << "Creating VarLoc for spill:";
1548e3b55780SDimitry Andric       VL.dump(TRI, TII);
15491d5ae102SDimitry Andric     });
1550e6d15924SDimitry Andric     return;
1551e6d15924SDimitry Andric   }
1552e6d15924SDimitry Andric   case TransferKind::TransferRestore: {
1553e6d15924SDimitry Andric     assert(NewReg &&
1554e6d15924SDimitry Andric            "No register supplied when handling a restore of a debug value");
15551d5ae102SDimitry Andric     // DebugInstr refers to the pre-spill location, therefore we can reuse
15561d5ae102SDimitry Andric     // its expression.
1557344a3780SDimitry Andric     VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
15581d5ae102SDimitry Andric     ProcessVarLoc(VL);
15591d5ae102SDimitry Andric     LLVM_DEBUG({
15601d5ae102SDimitry Andric       dbgs() << "Creating VarLoc for restore:";
1561e3b55780SDimitry Andric       VL.dump(TRI, TII);
15621d5ae102SDimitry Andric     });
1563e6d15924SDimitry Andric     return;
1564e6d15924SDimitry Andric   }
1565e6d15924SDimitry Andric   }
1566e6d15924SDimitry Andric   llvm_unreachable("Invalid transfer kind");
1567eb11fae6SDimitry Andric }
1568eb11fae6SDimitry Andric 
1569dd58ef01SDimitry Andric /// A definition of a register may mark the end of a range.
transferRegisterDef(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,InstToEntryLocMap & EntryValTransfers,RegDefToInstMap & RegSetInstrs)1570c0981da4SDimitry Andric void VarLocBasedLDV::transferRegisterDef(MachineInstr &MI,
1571c0981da4SDimitry Andric                                          OpenRangesSet &OpenRanges,
1572c0981da4SDimitry Andric                                          VarLocMap &VarLocIDs,
1573c0981da4SDimitry Andric                                          InstToEntryLocMap &EntryValTransfers,
1574c0981da4SDimitry Andric                                          RegDefToInstMap &RegSetInstrs) {
1575cfca06d7SDimitry Andric 
1576cfca06d7SDimitry Andric   // Meta Instructions do not affect the debug liveness of any register they
1577cfca06d7SDimitry Andric   // define.
1578cfca06d7SDimitry Andric   if (MI.isMetaInstruction())
1579cfca06d7SDimitry Andric     return;
1580cfca06d7SDimitry Andric 
1581044eb2f6SDimitry Andric   MachineFunction *MF = MI.getMF();
158201095a5dSDimitry Andric   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1583cfca06d7SDimitry Andric   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1584cfca06d7SDimitry Andric 
1585cfca06d7SDimitry Andric   // Find the regs killed by MI, and find regmasks of preserved regs.
1586cfca06d7SDimitry Andric   DefinedRegsSet DeadRegs;
1587cfca06d7SDimitry Andric   SmallVector<const uint32_t *, 4> RegMasks;
1588dd58ef01SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1589cfca06d7SDimitry Andric     // Determine whether the operand is a register def.
1590e3b55780SDimitry Andric     if (MO.isReg() && MO.isDef() && MO.getReg() && MO.getReg().isPhysical() &&
159171d5a254SDimitry Andric         !(MI.isCall() && MO.getReg() == SP)) {
1592dd58ef01SDimitry Andric       // Remove ranges of all aliased registers.
1593dd58ef01SDimitry Andric       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1594cfca06d7SDimitry Andric         // FIXME: Can we break out of this loop early if no insertion occurs?
1595cfca06d7SDimitry Andric         DeadRegs.insert(*RAI);
1596c0981da4SDimitry Andric       RegSetInstrs.erase(MO.getReg());
1597c0981da4SDimitry Andric       RegSetInstrs.insert({MO.getReg(), &MI});
159801095a5dSDimitry Andric     } else if (MO.isRegMask()) {
1599cfca06d7SDimitry Andric       RegMasks.push_back(MO.getRegMask());
1600cfca06d7SDimitry Andric     }
1601cfca06d7SDimitry Andric   }
1602cfca06d7SDimitry Andric 
1603cfca06d7SDimitry Andric   // Erase VarLocs which reside in one of the dead registers. For performance
1604cfca06d7SDimitry Andric   // reasons, it's critical to not iterate over the full set of open VarLocs.
1605cfca06d7SDimitry Andric   // Iterate over the set of dying/used regs instead.
1606cfca06d7SDimitry Andric   if (!RegMasks.empty()) {
1607344a3780SDimitry Andric     SmallVector<Register, 32> UsedRegs;
1608cfca06d7SDimitry Andric     getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
1609344a3780SDimitry Andric     for (Register Reg : UsedRegs) {
161001095a5dSDimitry Andric       // Remove ranges of all clobbered registers. Register masks don't usually
1611cfca06d7SDimitry Andric       // list SP as preserved. Assume that call instructions never clobber SP,
1612cfca06d7SDimitry Andric       // because some backends (e.g., AArch64) never list SP in the regmask.
1613cfca06d7SDimitry Andric       // While the debug info may be off for an instruction or two around
1614cfca06d7SDimitry Andric       // callee-cleanup calls, transferring the DEBUG_VALUE across the call is
1615cfca06d7SDimitry Andric       // still a better user experience.
1616cfca06d7SDimitry Andric       if (Reg == SP)
1617cfca06d7SDimitry Andric         continue;
1618cfca06d7SDimitry Andric       bool AnyRegMaskKillsReg =
1619cfca06d7SDimitry Andric           any_of(RegMasks, [Reg](const uint32_t *RegMask) {
1620cfca06d7SDimitry Andric             return MachineOperand::clobbersPhysReg(RegMask, Reg);
1621cfca06d7SDimitry Andric           });
1622cfca06d7SDimitry Andric       if (AnyRegMaskKillsReg)
1623cfca06d7SDimitry Andric         DeadRegs.insert(Reg);
1624c0981da4SDimitry Andric       if (AnyRegMaskKillsReg) {
1625c0981da4SDimitry Andric         RegSetInstrs.erase(Reg);
1626c0981da4SDimitry Andric         RegSetInstrs.insert({Reg, &MI});
1627c0981da4SDimitry Andric       }
1628dd58ef01SDimitry Andric     }
1629dd58ef01SDimitry Andric   }
1630cfca06d7SDimitry Andric 
1631cfca06d7SDimitry Andric   if (DeadRegs.empty())
1632cfca06d7SDimitry Andric     return;
1633cfca06d7SDimitry Andric 
1634344a3780SDimitry Andric   VarLocsInRange KillSet;
1635344a3780SDimitry Andric   collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs(), VarLocIDs);
1636344a3780SDimitry Andric   OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kUniversalLocation);
1637e6d15924SDimitry Andric 
1638b60736ecSDimitry Andric   if (TPC) {
1639e6d15924SDimitry Andric     auto &TM = TPC->getTM<TargetMachine>();
1640cfca06d7SDimitry Andric     if (TM.Options.ShouldEmitDebugEntryValues())
1641c0981da4SDimitry Andric       emitEntryValues(MI, OpenRanges, VarLocIDs, EntryValTransfers, KillSet);
1642e6d15924SDimitry Andric   }
164301095a5dSDimitry Andric }
1644dd58ef01SDimitry Andric 
transferWasmDef(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs)1645e3b55780SDimitry Andric void VarLocBasedLDV::transferWasmDef(MachineInstr &MI,
1646e3b55780SDimitry Andric                                      OpenRangesSet &OpenRanges,
1647e3b55780SDimitry Andric                                      VarLocMap &VarLocIDs) {
1648e3b55780SDimitry Andric   // If this is not a Wasm local.set or local.tee, which sets local values,
1649e3b55780SDimitry Andric   // return.
1650e3b55780SDimitry Andric   int Index;
1651e3b55780SDimitry Andric   int64_t Offset;
1652e3b55780SDimitry Andric   if (!TII->isExplicitTargetIndexDef(MI, Index, Offset))
1653e3b55780SDimitry Andric     return;
1654e3b55780SDimitry Andric 
1655e3b55780SDimitry Andric   // Find the target indices killed by MI, and delete those variable locations
1656e3b55780SDimitry Andric   // from the open range.
1657e3b55780SDimitry Andric   VarLocsInRange KillSet;
1658e3b55780SDimitry Andric   VarLoc::WasmLoc Loc{Index, Offset};
1659e3b55780SDimitry Andric   for (uint64_t ID : OpenRanges.getWasmVarLocs()) {
1660e3b55780SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1661e3b55780SDimitry Andric     const VarLoc &VL = VarLocIDs[Idx];
1662e3b55780SDimitry Andric     assert(VL.containsWasmLocs() && "Broken VarLocSet?");
1663e3b55780SDimitry Andric     if (VL.usesWasmLoc(Loc))
1664e3b55780SDimitry Andric       KillSet.insert(ID);
1665e3b55780SDimitry Andric   }
1666e3b55780SDimitry Andric   OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kWasmLocation);
1667e3b55780SDimitry Andric }
1668e3b55780SDimitry Andric 
isSpillInstruction(const MachineInstr & MI,MachineFunction * MF)1669b60736ecSDimitry Andric bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI,
16701d5ae102SDimitry Andric                                          MachineFunction *MF) {
167171d5a254SDimitry Andric   // TODO: Handle multiple stores folded into one.
167271d5a254SDimitry Andric   if (!MI.hasOneMemOperand())
167371d5a254SDimitry Andric     return false;
167471d5a254SDimitry Andric 
1675e6d15924SDimitry Andric   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1676e6d15924SDimitry Andric     return false; // This is not a spill instruction, since no valid size was
1677e6d15924SDimitry Andric                   // returned from either function.
167871d5a254SDimitry Andric 
16791d5ae102SDimitry Andric   return true;
16801d5ae102SDimitry Andric }
16811d5ae102SDimitry Andric 
isLocationSpill(const MachineInstr & MI,MachineFunction * MF,Register & Reg)1682b60736ecSDimitry Andric bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI,
1683cfca06d7SDimitry Andric                                       MachineFunction *MF, Register &Reg) {
16841d5ae102SDimitry Andric   if (!isSpillInstruction(MI, MF))
16851d5ae102SDimitry Andric     return false;
16861d5ae102SDimitry Andric 
1687cfca06d7SDimitry Andric   auto isKilledReg = [&](const MachineOperand MO, Register &Reg) {
1688eb11fae6SDimitry Andric     if (!MO.isReg() || !MO.isUse()) {
168971d5a254SDimitry Andric       Reg = 0;
1690eb11fae6SDimitry Andric       return false;
1691eb11fae6SDimitry Andric     }
169271d5a254SDimitry Andric     Reg = MO.getReg();
1693eb11fae6SDimitry Andric     return MO.isKill();
1694eb11fae6SDimitry Andric   };
1695eb11fae6SDimitry Andric 
1696eb11fae6SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1697eb11fae6SDimitry Andric     // In a spill instruction generated by the InlineSpiller the spilled
1698eb11fae6SDimitry Andric     // register has its kill flag set.
1699eb11fae6SDimitry Andric     if (isKilledReg(MO, Reg))
1700eb11fae6SDimitry Andric       return true;
1701eb11fae6SDimitry Andric     if (Reg != 0) {
1702eb11fae6SDimitry Andric       // Check whether next instruction kills the spilled register.
1703eb11fae6SDimitry Andric       // FIXME: Current solution does not cover search for killed register in
1704eb11fae6SDimitry Andric       // bundles and instructions further down the chain.
1705eb11fae6SDimitry Andric       auto NextI = std::next(MI.getIterator());
1706eb11fae6SDimitry Andric       // Skip next instruction that points to basic block end iterator.
1707eb11fae6SDimitry Andric       if (MI.getParent()->end() == NextI)
1708eb11fae6SDimitry Andric         continue;
1709cfca06d7SDimitry Andric       Register RegNext;
1710eb11fae6SDimitry Andric       for (const MachineOperand &MONext : NextI->operands()) {
1711eb11fae6SDimitry Andric         // Return true if we came across the register from the
1712eb11fae6SDimitry Andric         // previous spill instruction that is killed in NextI.
1713eb11fae6SDimitry Andric         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1714eb11fae6SDimitry Andric           return true;
171571d5a254SDimitry Andric       }
171671d5a254SDimitry Andric     }
1717eb11fae6SDimitry Andric   }
1718eb11fae6SDimitry Andric   // Return false if we didn't find spilled register.
1719eb11fae6SDimitry Andric   return false;
172071d5a254SDimitry Andric }
172171d5a254SDimitry Andric 
1722e3b55780SDimitry Andric std::optional<VarLocBasedLDV::VarLoc::SpillLoc>
isRestoreInstruction(const MachineInstr & MI,MachineFunction * MF,Register & Reg)1723b60736ecSDimitry Andric VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1724cfca06d7SDimitry Andric                                      MachineFunction *MF, Register &Reg) {
1725e6d15924SDimitry Andric   if (!MI.hasOneMemOperand())
1726e3b55780SDimitry Andric     return std::nullopt;
1727e6d15924SDimitry Andric 
1728e6d15924SDimitry Andric   // FIXME: Handle folded restore instructions with more than one memory
1729e6d15924SDimitry Andric   // operand.
1730e6d15924SDimitry Andric   if (MI.getRestoreSize(TII)) {
1731e6d15924SDimitry Andric     Reg = MI.getOperand(0).getReg();
1732e6d15924SDimitry Andric     return extractSpillBaseRegAndOffset(MI);
1733e6d15924SDimitry Andric   }
1734e3b55780SDimitry Andric   return std::nullopt;
1735e6d15924SDimitry Andric }
1736e6d15924SDimitry Andric 
173771d5a254SDimitry Andric /// A spilled register may indicate that we have to end the current range of
173871d5a254SDimitry Andric /// a variable and create a new one for the spill location.
1739e6d15924SDimitry Andric /// A restored register may indicate the reverse situation.
1740eb11fae6SDimitry Andric /// We don't want to insert any instructions in process(), so we just create
1741eb11fae6SDimitry Andric /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
174271d5a254SDimitry Andric /// It will be inserted into the BB when we're done iterating over the
174371d5a254SDimitry Andric /// instructions.
transferSpillOrRestoreInst(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers)1744b60736ecSDimitry Andric void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI,
174571d5a254SDimitry Andric                                                  OpenRangesSet &OpenRanges,
174671d5a254SDimitry Andric                                                  VarLocMap &VarLocIDs,
1747eb11fae6SDimitry Andric                                                  TransferMap &Transfers) {
1748044eb2f6SDimitry Andric   MachineFunction *MF = MI.getMF();
1749e6d15924SDimitry Andric   TransferKind TKind;
1750cfca06d7SDimitry Andric   Register Reg;
1751e3b55780SDimitry Andric   std::optional<VarLoc::SpillLoc> Loc;
175271d5a254SDimitry Andric 
1753e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1754e6d15924SDimitry Andric 
17551d5ae102SDimitry Andric   // First, if there are any DBG_VALUEs pointing at a spill slot that is
17561d5ae102SDimitry Andric   // written to, then close the variable location. The value in memory
17571d5ae102SDimitry Andric   // will have changed.
1758344a3780SDimitry Andric   VarLocsInRange KillSet;
17591d5ae102SDimitry Andric   if (isSpillInstruction(MI, MF)) {
17601d5ae102SDimitry Andric     Loc = extractSpillBaseRegAndOffset(MI);
1761cfca06d7SDimitry Andric     for (uint64_t ID : OpenRanges.getSpillVarLocs()) {
1762cfca06d7SDimitry Andric       LocIndex Idx = LocIndex::fromRawInteger(ID);
1763cfca06d7SDimitry Andric       const VarLoc &VL = VarLocIDs[Idx];
1764344a3780SDimitry Andric       assert(VL.containsSpillLocs() && "Broken VarLocSet?");
1765344a3780SDimitry Andric       if (VL.usesSpillLoc(*Loc)) {
17661d5ae102SDimitry Andric         // This location is overwritten by the current instruction -- terminate
17671d5ae102SDimitry Andric         // the open range, and insert an explicit DBG_VALUE $noreg.
17681d5ae102SDimitry Andric         //
17691d5ae102SDimitry Andric         // Doing this at a later stage would require re-interpreting all
17701d5ae102SDimitry Andric         // DBG_VALUes and DIExpressions to identify whether they point at
17711d5ae102SDimitry Andric         // memory, and then analysing all memory writes to see if they
17721d5ae102SDimitry Andric         // overwrite that memory, which is expensive.
17731d5ae102SDimitry Andric         //
17741d5ae102SDimitry Andric         // At this stage, we already know which DBG_VALUEs are for spills and
17751d5ae102SDimitry Andric         // where they are located; it's best to fix handle overwrites now.
1776344a3780SDimitry Andric         KillSet.insert(ID);
1777344a3780SDimitry Andric         unsigned SpillLocIdx = VL.getSpillLocIdx(*Loc);
1778344a3780SDimitry Andric         VarLoc::MachineLoc OldLoc = VL.Locs[SpillLocIdx];
1779344a3780SDimitry Andric         VarLoc UndefVL = VarLoc::CreateCopyLoc(VL, OldLoc, 0);
1780344a3780SDimitry Andric         LocIndices UndefLocIDs = VarLocIDs.insert(UndefVL);
1781344a3780SDimitry Andric         Transfers.push_back({&MI, UndefLocIDs.back()});
17821d5ae102SDimitry Andric       }
17831d5ae102SDimitry Andric     }
1784344a3780SDimitry Andric     OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kSpillLocation);
17851d5ae102SDimitry Andric   }
17861d5ae102SDimitry Andric 
17871d5ae102SDimitry Andric   // Try to recognise spill and restore instructions that may create a new
17881d5ae102SDimitry Andric   // variable location.
17891d5ae102SDimitry Andric   if (isLocationSpill(MI, MF, Reg)) {
1790e6d15924SDimitry Andric     TKind = TransferKind::TransferSpill;
1791e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1792e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1793e6d15924SDimitry Andric                       << "\n");
1794e6d15924SDimitry Andric   } else {
1795e6d15924SDimitry Andric     if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1796e6d15924SDimitry Andric       return;
1797e6d15924SDimitry Andric     TKind = TransferKind::TransferRestore;
1798e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1799e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1800e6d15924SDimitry Andric                       << "\n");
1801e6d15924SDimitry Andric   }
1802e6d15924SDimitry Andric   // Check if the register or spill location is the location of a debug value.
1803cfca06d7SDimitry Andric   auto TransferCandidates = OpenRanges.getEmptyVarLocRange();
1804cfca06d7SDimitry Andric   if (TKind == TransferKind::TransferSpill)
1805cfca06d7SDimitry Andric     TransferCandidates = OpenRanges.getRegisterVarLocs(Reg);
1806cfca06d7SDimitry Andric   else if (TKind == TransferKind::TransferRestore)
1807cfca06d7SDimitry Andric     TransferCandidates = OpenRanges.getSpillVarLocs();
1808cfca06d7SDimitry Andric   for (uint64_t ID : TransferCandidates) {
1809cfca06d7SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1810cfca06d7SDimitry Andric     const VarLoc &VL = VarLocIDs[Idx];
1811344a3780SDimitry Andric     unsigned LocIdx;
1812cfca06d7SDimitry Andric     if (TKind == TransferKind::TransferSpill) {
1813344a3780SDimitry Andric       assert(VL.usesReg(Reg) && "Broken VarLocSet?");
1814eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
1815cfca06d7SDimitry Andric                         << VL.Var.getVariable()->getName() << ")\n");
1816344a3780SDimitry Andric       LocIdx = VL.getRegIdx(Reg);
1817cfca06d7SDimitry Andric     } else {
1818344a3780SDimitry Andric       assert(TKind == TransferKind::TransferRestore && VL.containsSpillLocs() &&
1819344a3780SDimitry Andric              "Broken VarLocSet?");
1820344a3780SDimitry Andric       if (!VL.usesSpillLoc(*Loc))
1821cfca06d7SDimitry Andric         // The spill location is not the location of a debug value.
1822e6d15924SDimitry Andric         continue;
1823cfca06d7SDimitry Andric       LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
1824cfca06d7SDimitry Andric                         << VL.Var.getVariable()->getName() << ")\n");
1825344a3780SDimitry Andric       LocIdx = VL.getSpillLocIdx(*Loc);
1826cfca06d7SDimitry Andric     }
1827344a3780SDimitry Andric     VarLoc::MachineLoc MLoc = VL.Locs[LocIdx];
1828cfca06d7SDimitry Andric     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
1829344a3780SDimitry Andric                             MLoc, Reg);
1830cfca06d7SDimitry Andric     // FIXME: A comment should explain why it's correct to return early here,
1831cfca06d7SDimitry Andric     // if that is in fact correct.
1832eb11fae6SDimitry Andric     return;
1833eb11fae6SDimitry Andric   }
1834eb11fae6SDimitry Andric }
183571d5a254SDimitry Andric 
1836eb11fae6SDimitry Andric /// If \p MI is a register copy instruction, that copies a previously tracked
1837eb11fae6SDimitry Andric /// value from one register to another register that is callee saved, we
1838eb11fae6SDimitry Andric /// create new DBG_VALUE instruction  described with copy destination register.
transferRegisterCopy(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers)1839b60736ecSDimitry Andric void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI,
1840eb11fae6SDimitry Andric                                            OpenRangesSet &OpenRanges,
1841eb11fae6SDimitry Andric                                            VarLocMap &VarLocIDs,
1842eb11fae6SDimitry Andric                                            TransferMap &Transfers) {
1843312c0ed1SDimitry Andric   auto DestSrc = TII->isCopyLikeInstr(MI);
1844706b4fc4SDimitry Andric   if (!DestSrc)
1845eb11fae6SDimitry Andric     return;
184671d5a254SDimitry Andric 
1847706b4fc4SDimitry Andric   const MachineOperand *DestRegOp = DestSrc->Destination;
1848706b4fc4SDimitry Andric   const MachineOperand *SrcRegOp = DestSrc->Source;
1849706b4fc4SDimitry Andric 
1850706b4fc4SDimitry Andric   if (!DestRegOp->isDef())
1851706b4fc4SDimitry Andric     return;
1852706b4fc4SDimitry Andric 
1853cfca06d7SDimitry Andric   auto isCalleeSavedReg = [&](Register Reg) {
1854eb11fae6SDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1855eb11fae6SDimitry Andric       if (CalleeSavedRegs.test(*RAI))
1856eb11fae6SDimitry Andric         return true;
1857eb11fae6SDimitry Andric     return false;
1858eb11fae6SDimitry Andric   };
185971d5a254SDimitry Andric 
18601d5ae102SDimitry Andric   Register SrcReg = SrcRegOp->getReg();
18611d5ae102SDimitry Andric   Register DestReg = DestRegOp->getReg();
1862eb11fae6SDimitry Andric 
1863eb11fae6SDimitry Andric   // We want to recognize instructions where destination register is callee
1864eb11fae6SDimitry Andric   // saved register. If register that could be clobbered by the call is
1865eb11fae6SDimitry Andric   // included, there would be a great chance that it is going to be clobbered
1866eb11fae6SDimitry Andric   // soon. It is more likely that previous register location, which is callee
1867eb11fae6SDimitry Andric   // saved, is going to stay unclobbered longer, even if it is killed.
1868706b4fc4SDimitry Andric   if (!isCalleeSavedReg(DestReg))
1869706b4fc4SDimitry Andric     return;
1870706b4fc4SDimitry Andric 
1871706b4fc4SDimitry Andric   // Remember an entry value movement. If we encounter a new debug value of
1872706b4fc4SDimitry Andric   // a parameter describing only a moving of the value around, rather then
1873706b4fc4SDimitry Andric   // modifying it, we are still able to use the entry value if needed.
1874706b4fc4SDimitry Andric   if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1875cfca06d7SDimitry Andric     for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1876cfca06d7SDimitry Andric       LocIndex Idx = LocIndex::fromRawInteger(ID);
1877cfca06d7SDimitry Andric       const VarLoc &VL = VarLocIDs[Idx];
1878344a3780SDimitry Andric       if (VL.isEntryValueBackupReg(SrcReg)) {
1879706b4fc4SDimitry Andric         LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1880cfca06d7SDimitry Andric         VarLoc EntryValLocCopyBackup =
1881e3b55780SDimitry Andric             VarLoc::CreateEntryCopyBackupLoc(VL.MI, VL.Expr, DestReg);
1882706b4fc4SDimitry Andric         // Stop tracking the original entry value.
1883cfca06d7SDimitry Andric         OpenRanges.erase(VL);
1884706b4fc4SDimitry Andric 
1885706b4fc4SDimitry Andric         // Start tracking the entry value copy.
1886344a3780SDimitry Andric         LocIndices EntryValCopyLocIDs = VarLocIDs.insert(EntryValLocCopyBackup);
1887344a3780SDimitry Andric         OpenRanges.insert(EntryValCopyLocIDs, EntryValLocCopyBackup);
1888706b4fc4SDimitry Andric         break;
1889706b4fc4SDimitry Andric       }
1890706b4fc4SDimitry Andric     }
1891706b4fc4SDimitry Andric   }
1892706b4fc4SDimitry Andric 
1893706b4fc4SDimitry Andric   if (!SrcRegOp->isKill())
1894eb11fae6SDimitry Andric     return;
1895eb11fae6SDimitry Andric 
1896cfca06d7SDimitry Andric   for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) {
1897cfca06d7SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1898344a3780SDimitry Andric     assert(VarLocIDs[Idx].usesReg(SrcReg) && "Broken VarLocSet?");
1899344a3780SDimitry Andric     VarLoc::MachineLocValue Loc;
1900344a3780SDimitry Andric     Loc.RegNo = SrcReg;
1901344a3780SDimitry Andric     VarLoc::MachineLoc MLoc{VarLoc::MachineLocKind::RegisterKind, Loc};
1902cfca06d7SDimitry Andric     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
1903344a3780SDimitry Andric                             TransferKind::TransferCopy, MLoc, DestReg);
1904cfca06d7SDimitry Andric     // FIXME: A comment should explain why it's correct to return early here,
1905cfca06d7SDimitry Andric     // if that is in fact correct.
190671d5a254SDimitry Andric     return;
190771d5a254SDimitry Andric   }
190871d5a254SDimitry Andric }
190971d5a254SDimitry Andric 
1910dd58ef01SDimitry Andric /// Terminate all open ranges at the end of the current basic block.
transferTerminator(MachineBasicBlock * CurMBB,OpenRangesSet & OpenRanges,VarLocInMBB & OutLocs,const VarLocMap & VarLocIDs)1911b60736ecSDimitry Andric bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB,
191201095a5dSDimitry Andric                                          OpenRangesSet &OpenRanges,
191301095a5dSDimitry Andric                                          VarLocInMBB &OutLocs,
191401095a5dSDimitry Andric                                          const VarLocMap &VarLocIDs) {
1915050e163aSDimitry Andric   bool Changed = false;
1916344a3780SDimitry Andric   LLVM_DEBUG({
1917344a3780SDimitry Andric     VarVec VarLocs;
1918344a3780SDimitry Andric     OpenRanges.getUniqueVarLocs(VarLocs, VarLocIDs);
1919344a3780SDimitry Andric     for (VarLoc &VL : VarLocs) {
1920dd58ef01SDimitry Andric       // Copy OpenRanges to OutLocs, if not already present.
1921d8e91e46SDimitry Andric       dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ":  ";
1922e3b55780SDimitry Andric       VL.dump(TRI, TII);
1923344a3780SDimitry Andric     }
192401095a5dSDimitry Andric   });
1925cfca06d7SDimitry Andric   VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
19261d5ae102SDimitry Andric   Changed = VLS != OpenRanges.getVarLocs();
1927e6d15924SDimitry Andric   // New OutLocs set may be different due to spill, restore or register
1928e6d15924SDimitry Andric   // copy instruction processing.
1929e6d15924SDimitry Andric   if (Changed)
1930e6d15924SDimitry Andric     VLS = OpenRanges.getVarLocs();
1931dd58ef01SDimitry Andric   OpenRanges.clear();
1932050e163aSDimitry Andric   return Changed;
1933dd58ef01SDimitry Andric }
1934dd58ef01SDimitry Andric 
1935e6d15924SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
1936e6d15924SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
1937e6d15924SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1938e6d15924SDimitry Andric /// known-to-overlap fragments are present".
1939e6d15924SDimitry Andric /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1940e6d15924SDimitry Andric ///           fragment usage.
1941e6d15924SDimitry Andric /// \param SeenFragments Map from DILocalVariable to all fragments of that
1942e6d15924SDimitry Andric ///           Variable which are known to exist.
1943e6d15924SDimitry Andric /// \param OverlappingFragments The overlap map being constructed, from one
1944e6d15924SDimitry Andric ///           Var/Fragment pair to a vector of fragments known to overlap.
accumulateFragmentMap(MachineInstr & MI,VarToFragments & SeenFragments,OverlapMap & OverlappingFragments)1945b60736ecSDimitry Andric void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI,
1946e6d15924SDimitry Andric                                             VarToFragments &SeenFragments,
1947e6d15924SDimitry Andric                                             OverlapMap &OverlappingFragments) {
1948706b4fc4SDimitry Andric   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1949706b4fc4SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
1950706b4fc4SDimitry Andric   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1951e6d15924SDimitry Andric 
1952e6d15924SDimitry Andric   // If this is the first sighting of this variable, then we are guaranteed
1953e6d15924SDimitry Andric   // there are currently no overlapping fragments either. Initialize the set
1954e6d15924SDimitry Andric   // of seen fragments, record no overlaps for the current one, and return.
1955706b4fc4SDimitry Andric   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1956e6d15924SDimitry Andric   if (SeenIt == SeenFragments.end()) {
1957e6d15924SDimitry Andric     SmallSet<FragmentInfo, 4> OneFragment;
1958e6d15924SDimitry Andric     OneFragment.insert(ThisFragment);
1959706b4fc4SDimitry Andric     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1960e6d15924SDimitry Andric 
1961706b4fc4SDimitry Andric     OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1962e6d15924SDimitry Andric     return;
1963e6d15924SDimitry Andric   }
1964e6d15924SDimitry Andric 
1965e6d15924SDimitry Andric   // If this particular Variable/Fragment pair already exists in the overlap
1966e6d15924SDimitry Andric   // map, it has already been accounted for.
1967e6d15924SDimitry Andric   auto IsInOLapMap =
1968706b4fc4SDimitry Andric       OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1969e6d15924SDimitry Andric   if (!IsInOLapMap.second)
1970e6d15924SDimitry Andric     return;
1971e6d15924SDimitry Andric 
1972e6d15924SDimitry Andric   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1973e6d15924SDimitry Andric   auto &AllSeenFragments = SeenIt->second;
1974e6d15924SDimitry Andric 
1975e6d15924SDimitry Andric   // Otherwise, examine all other seen fragments for this variable, with "this"
1976e6d15924SDimitry Andric   // fragment being a previously unseen fragment. Record any pair of
1977e6d15924SDimitry Andric   // overlapping fragments.
19784b4fe385SDimitry Andric   for (const auto &ASeenFragment : AllSeenFragments) {
1979e6d15924SDimitry Andric     // Does this previously seen fragment overlap?
1980e6d15924SDimitry Andric     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1981e6d15924SDimitry Andric       // Yes: Mark the current fragment as being overlapped.
1982e6d15924SDimitry Andric       ThisFragmentsOverlaps.push_back(ASeenFragment);
1983e6d15924SDimitry Andric       // Mark the previously seen fragment as being overlapped by the current
1984e6d15924SDimitry Andric       // one.
1985e6d15924SDimitry Andric       auto ASeenFragmentsOverlaps =
1986706b4fc4SDimitry Andric           OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1987e6d15924SDimitry Andric       assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1988e6d15924SDimitry Andric              "Previously seen var fragment has no vector of overlaps");
1989e6d15924SDimitry Andric       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1990e6d15924SDimitry Andric     }
1991e6d15924SDimitry Andric   }
1992e6d15924SDimitry Andric 
1993e6d15924SDimitry Andric   AllSeenFragments.insert(ThisFragment);
1994e6d15924SDimitry Andric }
1995e6d15924SDimitry Andric 
1996706b4fc4SDimitry Andric /// This routine creates OpenRanges.
process(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers,InstToEntryLocMap & EntryValTransfers,RegDefToInstMap & RegSetInstrs)1997b60736ecSDimitry Andric void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1998c0981da4SDimitry Andric                              VarLocMap &VarLocIDs, TransferMap &Transfers,
1999c0981da4SDimitry Andric                              InstToEntryLocMap &EntryValTransfers,
2000c0981da4SDimitry Andric                              RegDefToInstMap &RegSetInstrs) {
2001c0981da4SDimitry Andric   if (!MI.isDebugInstr())
2002c0981da4SDimitry Andric     LastNonDbgMI = &MI;
2003c0981da4SDimitry Andric   transferDebugValue(MI, OpenRanges, VarLocIDs, EntryValTransfers,
2004c0981da4SDimitry Andric                      RegSetInstrs);
2005c0981da4SDimitry Andric   transferRegisterDef(MI, OpenRanges, VarLocIDs, EntryValTransfers,
2006c0981da4SDimitry Andric                       RegSetInstrs);
2007e3b55780SDimitry Andric   transferWasmDef(MI, OpenRanges, VarLocIDs);
2008eb11fae6SDimitry Andric   transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
2009e6d15924SDimitry Andric   transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
2010dd58ef01SDimitry Andric }
2011dd58ef01SDimitry Andric 
2012dd58ef01SDimitry Andric /// This routine joins the analysis results of all incoming edges in @MBB by
2013dd58ef01SDimitry Andric /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
2014dd58ef01SDimitry Andric /// source variable in all the predecessors of @MBB reside in the same location.
join(MachineBasicBlock & MBB,VarLocInMBB & OutLocs,VarLocInMBB & InLocs,const VarLocMap & VarLocIDs,SmallPtrSet<const MachineBasicBlock *,16> & Visited,SmallPtrSetImpl<const MachineBasicBlock * > & ArtificialBlocks)2015b60736ecSDimitry Andric bool VarLocBasedLDV::join(
2016d8e91e46SDimitry Andric     MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
2017d8e91e46SDimitry Andric     const VarLocMap &VarLocIDs,
2018d8e91e46SDimitry Andric     SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
2019cfca06d7SDimitry Andric     SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
2020d8e91e46SDimitry Andric   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2021dd58ef01SDimitry Andric 
2022cfca06d7SDimitry Andric   VarLocSet InLocsT(Alloc); // Temporary incoming locations.
2023dd58ef01SDimitry Andric 
202401095a5dSDimitry Andric   // For all predecessors of this MBB, find the set of VarLocs that
202501095a5dSDimitry Andric   // can be joined.
2026b915e9e0SDimitry Andric   int NumVisited = 0;
20274b4fe385SDimitry Andric   for (auto *p : MBB.predecessors()) {
20281d5ae102SDimitry Andric     // Ignore backedges if we have not visited the predecessor yet. As the
20291d5ae102SDimitry Andric     // predecessor hasn't yet had locations propagated into it, most locations
20301d5ae102SDimitry Andric     // will not yet be valid, so treat them as all being uninitialized and
20311d5ae102SDimitry Andric     // potentially valid. If a location guessed to be correct here is
20321d5ae102SDimitry Andric     // invalidated later, we will remove it when we revisit this block.
2033d8e91e46SDimitry Andric     if (!Visited.count(p)) {
2034d8e91e46SDimitry Andric       LLVM_DEBUG(dbgs() << "  ignoring unvisited pred MBB: " << p->getNumber()
2035d8e91e46SDimitry Andric                         << "\n");
2036b915e9e0SDimitry Andric       continue;
2037d8e91e46SDimitry Andric     }
2038dd58ef01SDimitry Andric     auto OL = OutLocs.find(p);
2039dd58ef01SDimitry Andric     // Join is null in case of empty OutLocs from any of the pred.
2040dd58ef01SDimitry Andric     if (OL == OutLocs.end())
2041050e163aSDimitry Andric       return false;
2042dd58ef01SDimitry Andric 
2043b915e9e0SDimitry Andric     // Just copy over the Out locs to incoming locs for the first visited
2044b915e9e0SDimitry Andric     // predecessor, and for all other predecessors join the Out locs.
2045145449b1SDimitry Andric     VarLocSet &OutLocVLS = *OL->second;
2046b915e9e0SDimitry Andric     if (!NumVisited)
2047cfca06d7SDimitry Andric       InLocsT = OutLocVLS;
2048b915e9e0SDimitry Andric     else
2049cfca06d7SDimitry Andric       InLocsT &= OutLocVLS;
2050d8e91e46SDimitry Andric 
2051d8e91e46SDimitry Andric     LLVM_DEBUG({
2052d8e91e46SDimitry Andric       if (!InLocsT.empty()) {
2053344a3780SDimitry Andric         VarVec VarLocs;
2054344a3780SDimitry Andric         collectAllVarLocs(VarLocs, InLocsT, VarLocIDs);
2055344a3780SDimitry Andric         for (const VarLoc &VL : VarLocs)
2056d8e91e46SDimitry Andric           dbgs() << "  gathered candidate incoming var: "
2057344a3780SDimitry Andric                  << VL.Var.getVariable()->getName() << "\n";
2058d8e91e46SDimitry Andric       }
2059d8e91e46SDimitry Andric     });
2060d8e91e46SDimitry Andric 
2061b915e9e0SDimitry Andric     NumVisited++;
2062dd58ef01SDimitry Andric   }
2063dd58ef01SDimitry Andric 
2064b915e9e0SDimitry Andric   // Filter out DBG_VALUES that are out of scope.
2065cfca06d7SDimitry Andric   VarLocSet KillSet(Alloc);
2066d8e91e46SDimitry Andric   bool IsArtificial = ArtificialBlocks.count(&MBB);
2067d8e91e46SDimitry Andric   if (!IsArtificial) {
2068cfca06d7SDimitry Andric     for (uint64_t ID : InLocsT) {
2069cfca06d7SDimitry Andric       LocIndex Idx = LocIndex::fromRawInteger(ID);
2070cfca06d7SDimitry Andric       if (!VarLocIDs[Idx].dominates(LS, MBB)) {
2071b915e9e0SDimitry Andric         KillSet.set(ID);
2072d8e91e46SDimitry Andric         LLVM_DEBUG({
2073cfca06d7SDimitry Andric           auto Name = VarLocIDs[Idx].Var.getVariable()->getName();
2074d8e91e46SDimitry Andric           dbgs() << "  killing " << Name << ", it doesn't dominate MBB\n";
2075d8e91e46SDimitry Andric         });
2076d8e91e46SDimitry Andric       }
2077d8e91e46SDimitry Andric     }
2078d8e91e46SDimitry Andric   }
2079b915e9e0SDimitry Andric   InLocsT.intersectWithComplement(KillSet);
2080b915e9e0SDimitry Andric 
2081b915e9e0SDimitry Andric   // As we are processing blocks in reverse post-order we
2082b915e9e0SDimitry Andric   // should have processed at least one predecessor, unless it
2083b915e9e0SDimitry Andric   // is the entry block which has no predecessor.
2084b915e9e0SDimitry Andric   assert((NumVisited || MBB.pred_empty()) &&
2085b915e9e0SDimitry Andric          "Should have processed at least one predecessor");
2086dd58ef01SDimitry Andric 
2087cfca06d7SDimitry Andric   VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
2088cfca06d7SDimitry Andric   bool Changed = false;
2089cfca06d7SDimitry Andric   if (ILS != InLocsT) {
2090cfca06d7SDimitry Andric     ILS = InLocsT;
20911d5ae102SDimitry Andric     Changed = true;
20921d5ae102SDimitry Andric   }
20931d5ae102SDimitry Andric 
2094050e163aSDimitry Andric   return Changed;
2095dd58ef01SDimitry Andric }
2096dd58ef01SDimitry Andric 
flushPendingLocs(VarLocInMBB & PendingInLocs,VarLocMap & VarLocIDs)2097b60736ecSDimitry Andric void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs,
20981d5ae102SDimitry Andric                                        VarLocMap &VarLocIDs) {
20991d5ae102SDimitry Andric   // PendingInLocs records all locations propagated into blocks, which have
21001d5ae102SDimitry Andric   // not had DBG_VALUE insts created. Go through and create those insts now.
21011d5ae102SDimitry Andric   for (auto &Iter : PendingInLocs) {
21021d5ae102SDimitry Andric     // Map is keyed on a constant pointer, unwrap it so we can insert insts.
21031d5ae102SDimitry Andric     auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
2104145449b1SDimitry Andric     VarLocSet &Pending = *Iter.second;
21051d5ae102SDimitry Andric 
2106344a3780SDimitry Andric     SmallVector<VarLoc, 32> VarLocs;
2107344a3780SDimitry Andric     collectAllVarLocs(VarLocs, Pending, VarLocIDs);
2108344a3780SDimitry Andric 
2109344a3780SDimitry Andric     for (VarLoc DiffIt : VarLocs) {
21101d5ae102SDimitry Andric       // The ID location is live-in to MBB -- work out what kind of machine
21111d5ae102SDimitry Andric       // location it is and create a DBG_VALUE.
2112706b4fc4SDimitry Andric       if (DiffIt.isEntryBackupLoc())
2113706b4fc4SDimitry Andric         continue;
21141d5ae102SDimitry Andric       MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
21151d5ae102SDimitry Andric       MBB.insert(MBB.instr_begin(), MI);
21161d5ae102SDimitry Andric 
21171d5ae102SDimitry Andric       (void)MI;
21181d5ae102SDimitry Andric       LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
21191d5ae102SDimitry Andric     }
21201d5ae102SDimitry Andric   }
21211d5ae102SDimitry Andric }
21221d5ae102SDimitry Andric 
isEntryValueCandidate(const MachineInstr & MI,const DefinedRegsSet & DefinedRegs) const2123b60736ecSDimitry Andric bool VarLocBasedLDV::isEntryValueCandidate(
2124706b4fc4SDimitry Andric     const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
2125706b4fc4SDimitry Andric   assert(MI.isDebugValue() && "This must be DBG_VALUE.");
2126706b4fc4SDimitry Andric 
2127706b4fc4SDimitry Andric   // TODO: Add support for local variables that are expressed in terms of
2128706b4fc4SDimitry Andric   // parameters entry values.
2129706b4fc4SDimitry Andric   // TODO: Add support for modified arguments that can be expressed
2130706b4fc4SDimitry Andric   // by using its entry value.
2131706b4fc4SDimitry Andric   auto *DIVar = MI.getDebugVariable();
2132706b4fc4SDimitry Andric   if (!DIVar->isParameter())
2133706b4fc4SDimitry Andric     return false;
2134706b4fc4SDimitry Andric 
2135706b4fc4SDimitry Andric   // Do not consider parameters that belong to an inlined function.
2136706b4fc4SDimitry Andric   if (MI.getDebugLoc()->getInlinedAt())
2137706b4fc4SDimitry Andric     return false;
2138706b4fc4SDimitry Andric 
2139706b4fc4SDimitry Andric   // Only consider parameters that are described using registers. Parameters
2140706b4fc4SDimitry Andric   // that are passed on the stack are not yet supported, so ignore debug
2141706b4fc4SDimitry Andric   // values that are described by the frame or stack pointer.
2142cfca06d7SDimitry Andric   if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI))
2143706b4fc4SDimitry Andric     return false;
2144706b4fc4SDimitry Andric 
2145706b4fc4SDimitry Andric   // If a parameter's value has been propagated from the caller, then the
2146706b4fc4SDimitry Andric   // parameter's DBG_VALUE may be described using a register defined by some
2147706b4fc4SDimitry Andric   // instruction in the entry block, in which case we shouldn't create an
2148706b4fc4SDimitry Andric   // entry value.
2149cfca06d7SDimitry Andric   if (DefinedRegs.count(MI.getDebugOperand(0).getReg()))
2150706b4fc4SDimitry Andric     return false;
2151706b4fc4SDimitry Andric 
2152706b4fc4SDimitry Andric   // TODO: Add support for parameters that have a pre-existing debug expressions
2153cfca06d7SDimitry Andric   // (e.g. fragments).
21547fa27ce4SDimitry Andric   // A simple deref expression is equivalent to an indirect debug value.
21557fa27ce4SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
21567fa27ce4SDimitry Andric   if (Expr->getNumElements() > 0 && !Expr->isDeref())
2157706b4fc4SDimitry Andric     return false;
2158706b4fc4SDimitry Andric 
2159706b4fc4SDimitry Andric   return true;
2160706b4fc4SDimitry Andric }
2161706b4fc4SDimitry Andric 
2162706b4fc4SDimitry Andric /// Collect all register defines (including aliases) for the given instruction.
collectRegDefs(const MachineInstr & MI,DefinedRegsSet & Regs,const TargetRegisterInfo * TRI)2163706b4fc4SDimitry Andric static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
2164706b4fc4SDimitry Andric                            const TargetRegisterInfo *TRI) {
21657fa27ce4SDimitry Andric   for (const MachineOperand &MO : MI.all_defs()) {
21667fa27ce4SDimitry Andric     if (MO.getReg() && MO.getReg().isPhysical()) {
2167e3b55780SDimitry Andric       Regs.insert(MO.getReg());
2168706b4fc4SDimitry Andric       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
2169706b4fc4SDimitry Andric         Regs.insert(*AI);
2170706b4fc4SDimitry Andric     }
2171e3b55780SDimitry Andric   }
2172e3b55780SDimitry Andric }
2173706b4fc4SDimitry Andric 
2174706b4fc4SDimitry Andric /// This routine records the entry values of function parameters. The values
2175706b4fc4SDimitry Andric /// could be used as backup values. If we loose the track of some unmodified
2176706b4fc4SDimitry Andric /// parameters, the backup values will be used as a primary locations.
recordEntryValue(const MachineInstr & MI,const DefinedRegsSet & DefinedRegs,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs)2177b60736ecSDimitry Andric void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI,
2178706b4fc4SDimitry Andric                                        const DefinedRegsSet &DefinedRegs,
2179706b4fc4SDimitry Andric                                        OpenRangesSet &OpenRanges,
2180706b4fc4SDimitry Andric                                        VarLocMap &VarLocIDs) {
2181b60736ecSDimitry Andric   if (TPC) {
2182706b4fc4SDimitry Andric     auto &TM = TPC->getTM<TargetMachine>();
2183cfca06d7SDimitry Andric     if (!TM.Options.ShouldEmitDebugEntryValues())
2184706b4fc4SDimitry Andric       return;
2185706b4fc4SDimitry Andric   }
2186706b4fc4SDimitry Andric 
2187706b4fc4SDimitry Andric   DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
2188706b4fc4SDimitry Andric                   MI.getDebugLoc()->getInlinedAt());
2189706b4fc4SDimitry Andric 
2190706b4fc4SDimitry Andric   if (!isEntryValueCandidate(MI, DefinedRegs) ||
2191706b4fc4SDimitry Andric       OpenRanges.getEntryValueBackup(V))
2192706b4fc4SDimitry Andric     return;
2193706b4fc4SDimitry Andric 
2194706b4fc4SDimitry Andric   LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
2195706b4fc4SDimitry Andric 
2196706b4fc4SDimitry Andric   // Create the entry value and use it as a backup location until it is
2197706b4fc4SDimitry Andric   // valid. It is valid until a parameter is not changed.
2198706b4fc4SDimitry Andric   DIExpression *NewExpr =
2199706b4fc4SDimitry Andric       DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
2200e3b55780SDimitry Andric   VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, NewExpr);
2201344a3780SDimitry Andric   LocIndices EntryValLocIDs = VarLocIDs.insert(EntryValLocAsBackup);
2202344a3780SDimitry Andric   OpenRanges.insert(EntryValLocIDs, EntryValLocAsBackup);
2203706b4fc4SDimitry Andric }
2204706b4fc4SDimitry Andric 
2205dd58ef01SDimitry Andric /// Calculate the liveness information for the given machine function and
2206dd58ef01SDimitry Andric /// extend ranges across basic blocks.
ExtendRanges(MachineFunction & MF,MachineDominatorTree * DomTree,TargetPassConfig * TPC,unsigned InputBBLimit,unsigned InputDbgValLimit)2207c0981da4SDimitry Andric bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF,
2208c0981da4SDimitry Andric                                   MachineDominatorTree *DomTree,
2209c0981da4SDimitry Andric                                   TargetPassConfig *TPC, unsigned InputBBLimit,
2210c0981da4SDimitry Andric                                   unsigned InputDbgValLimit) {
2211c0981da4SDimitry Andric   (void)DomTree;
2212e3b55780SDimitry Andric   LLVM_DEBUG(dbgs() << "\nDebug Range Extension: " << MF.getName() << "\n");
2213dd58ef01SDimitry Andric 
2214b60736ecSDimitry Andric   if (!MF.getFunction().getSubprogram())
2215b60736ecSDimitry Andric     // VarLocBaseLDV will already have removed all DBG_VALUEs.
2216b60736ecSDimitry Andric     return false;
2217b60736ecSDimitry Andric 
2218b60736ecSDimitry Andric   // Skip functions from NoDebug compilation units.
2219b60736ecSDimitry Andric   if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
2220b60736ecSDimitry Andric       DICompileUnit::NoDebug)
2221b60736ecSDimitry Andric     return false;
2222b60736ecSDimitry Andric 
2223b60736ecSDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
2224b60736ecSDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
2225b60736ecSDimitry Andric   TFI = MF.getSubtarget().getFrameLowering();
2226b60736ecSDimitry Andric   TFI->getCalleeSaves(MF, CalleeSavedRegs);
2227b60736ecSDimitry Andric   this->TPC = TPC;
2228b60736ecSDimitry Andric   LS.initialize(MF);
2229b60736ecSDimitry Andric 
2230dd58ef01SDimitry Andric   bool Changed = false;
2231050e163aSDimitry Andric   bool OLChanged = false;
2232050e163aSDimitry Andric   bool MBBJoined = false;
2233dd58ef01SDimitry Andric 
223401095a5dSDimitry Andric   VarLocMap VarLocIDs;         // Map VarLoc<>unique ID for use in bitvectors.
2235706b4fc4SDimitry Andric   OverlapMap OverlapFragments; // Map of overlapping variable fragments.
2236cfca06d7SDimitry Andric   OpenRangesSet OpenRanges(Alloc, OverlapFragments);
2237e6d15924SDimitry Andric                               // Ranges that are open until end of bb.
2238dd58ef01SDimitry Andric   VarLocInMBB OutLocs;        // Ranges that exist beyond bb.
2239dd58ef01SDimitry Andric   VarLocInMBB InLocs;         // Ranges that are incoming after joining.
2240706b4fc4SDimitry Andric   TransferMap Transfers;      // DBG_VALUEs associated with transfers (such as
2241706b4fc4SDimitry Andric                               // spills, copies and restores).
2242c0981da4SDimitry Andric   // Map responsible MI to attached Transfer emitted from Backup Entry Value.
2243c0981da4SDimitry Andric   InstToEntryLocMap EntryValTransfers;
2244c0981da4SDimitry Andric   // Map a Register to the last MI which clobbered it.
2245c0981da4SDimitry Andric   RegDefToInstMap RegSetInstrs;
2246dd58ef01SDimitry Andric 
2247e6d15924SDimitry Andric   VarToFragments SeenFragments;
2248e6d15924SDimitry Andric 
2249d8e91e46SDimitry Andric   // Blocks which are artificial, i.e. blocks which exclusively contain
2250d8e91e46SDimitry Andric   // instructions without locations, or with line 0 locations.
2251d8e91e46SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
2252d8e91e46SDimitry Andric 
2253050e163aSDimitry Andric   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
2254050e163aSDimitry Andric   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
2255050e163aSDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
225601095a5dSDimitry Andric                       std::greater<unsigned int>>
225701095a5dSDimitry Andric       Worklist;
2258050e163aSDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
225901095a5dSDimitry Andric                       std::greater<unsigned int>>
226001095a5dSDimitry Andric       Pending;
226101095a5dSDimitry Andric 
2262706b4fc4SDimitry Andric   // Set of register defines that are seen when traversing the entry block
2263706b4fc4SDimitry Andric   // looking for debug entry value candidates.
2264706b4fc4SDimitry Andric   DefinedRegsSet DefinedRegs;
2265e6d15924SDimitry Andric 
2266e6d15924SDimitry Andric   // Only in the case of entry MBB collect DBG_VALUEs representing
2267e6d15924SDimitry Andric   // function parameters in order to generate debug entry values for them.
2268706b4fc4SDimitry Andric   MachineBasicBlock &First_MBB = *(MF.begin());
2269706b4fc4SDimitry Andric   for (auto &MI : First_MBB) {
2270706b4fc4SDimitry Andric     collectRegDefs(MI, DefinedRegs, TRI);
2271706b4fc4SDimitry Andric     if (MI.isDebugValue())
2272706b4fc4SDimitry Andric       recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
2273706b4fc4SDimitry Andric   }
2274e6d15924SDimitry Andric 
22751d5ae102SDimitry Andric   // Initialize per-block structures and scan for fragment overlaps.
2276cfca06d7SDimitry Andric   for (auto &MBB : MF)
2277cfca06d7SDimitry Andric     for (auto &MI : MBB)
22781d5ae102SDimitry Andric       if (MI.isDebugValue())
22791d5ae102SDimitry Andric         accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
228001095a5dSDimitry Andric 
2281d8e91e46SDimitry Andric   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2282d8e91e46SDimitry Andric     if (const DebugLoc &DL = MI.getDebugLoc())
2283d8e91e46SDimitry Andric       return DL.getLine() != 0;
2284d8e91e46SDimitry Andric     return false;
2285d8e91e46SDimitry Andric   };
2286d8e91e46SDimitry Andric   for (auto &MBB : MF)
2287d8e91e46SDimitry Andric     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2288d8e91e46SDimitry Andric       ArtificialBlocks.insert(&MBB);
2289d8e91e46SDimitry Andric 
2290eb11fae6SDimitry Andric   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2291eb11fae6SDimitry Andric                               "OutLocs after initialization", dbgs()));
2292dd58ef01SDimitry Andric 
2293050e163aSDimitry Andric   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2294050e163aSDimitry Andric   unsigned int RPONumber = 0;
2295344a3780SDimitry Andric   for (MachineBasicBlock *MBB : RPOT) {
2296344a3780SDimitry Andric     OrderToBB[RPONumber] = MBB;
2297344a3780SDimitry Andric     BBToOrder[MBB] = RPONumber;
2298050e163aSDimitry Andric     Worklist.push(RPONumber);
2299050e163aSDimitry Andric     ++RPONumber;
2300050e163aSDimitry Andric   }
2301cfca06d7SDimitry Andric 
2302cfca06d7SDimitry Andric   if (RPONumber > InputBBLimit) {
2303cfca06d7SDimitry Andric     unsigned NumInputDbgValues = 0;
2304cfca06d7SDimitry Andric     for (auto &MBB : MF)
2305cfca06d7SDimitry Andric       for (auto &MI : MBB)
2306cfca06d7SDimitry Andric         if (MI.isDebugValue())
2307cfca06d7SDimitry Andric           ++NumInputDbgValues;
2308c0981da4SDimitry Andric     if (NumInputDbgValues > InputDbgValLimit) {
2309b60736ecSDimitry Andric       LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName()
2310cfca06d7SDimitry Andric                         << " has " << RPONumber << " basic blocks and "
2311cfca06d7SDimitry Andric                         << NumInputDbgValues
2312cfca06d7SDimitry Andric                         << " input DBG_VALUEs, exceeding limits.\n");
2313cfca06d7SDimitry Andric       return false;
2314cfca06d7SDimitry Andric     }
2315cfca06d7SDimitry Andric   }
2316cfca06d7SDimitry Andric 
2317050e163aSDimitry Andric   // This is a standard "union of predecessor outs" dataflow problem.
2318eb11fae6SDimitry Andric   // To solve it, we perform join() and process() using the two worklist method
2319050e163aSDimitry Andric   // until the ranges converge.
2320050e163aSDimitry Andric   // Ranges have converged when both worklists are empty.
2321b915e9e0SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2322050e163aSDimitry Andric   while (!Worklist.empty() || !Pending.empty()) {
2323050e163aSDimitry Andric     // We track what is on the pending worklist to avoid inserting the same
2324050e163aSDimitry Andric     // thing twice.  We could avoid this with a custom priority queue, but this
2325050e163aSDimitry Andric     // is probably not worth it.
2326050e163aSDimitry Andric     SmallPtrSet<MachineBasicBlock *, 16> OnPending;
2327eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Processing Worklist\n");
2328050e163aSDimitry Andric     while (!Worklist.empty()) {
2329050e163aSDimitry Andric       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2330050e163aSDimitry Andric       Worklist.pop();
23311d5ae102SDimitry Andric       MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
2332cfca06d7SDimitry Andric                        ArtificialBlocks);
23331d5ae102SDimitry Andric       MBBJoined |= Visited.insert(MBB).second;
2334dd58ef01SDimitry Andric       if (MBBJoined) {
2335050e163aSDimitry Andric         MBBJoined = false;
2336dd58ef01SDimitry Andric         Changed = true;
233771d5a254SDimitry Andric         // Now that we have started to extend ranges across BBs we need to
2338706b4fc4SDimitry Andric         // examine spill, copy and restore instructions to see whether they
2339706b4fc4SDimitry Andric         // operate with registers that correspond to user variables.
23401d5ae102SDimitry Andric         // First load any pending inlocs.
2341cfca06d7SDimitry Andric         OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs);
2342c0981da4SDimitry Andric         LastNonDbgMI = nullptr;
2343c0981da4SDimitry Andric         RegSetInstrs.clear();
2344dd58ef01SDimitry Andric         for (auto &MI : *MBB)
2345c0981da4SDimitry Andric           process(MI, OpenRanges, VarLocIDs, Transfers, EntryValTransfers,
2346c0981da4SDimitry Andric                   RegSetInstrs);
23471d5ae102SDimitry Andric         OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
234801095a5dSDimitry Andric 
2349eb11fae6SDimitry Andric         LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
235001095a5dSDimitry Andric                                     "OutLocs after propagating", dbgs()));
2351eb11fae6SDimitry Andric         LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
235201095a5dSDimitry Andric                                     "InLocs after propagating", dbgs()));
2353dd58ef01SDimitry Andric 
2354dd58ef01SDimitry Andric         if (OLChanged) {
2355dd58ef01SDimitry Andric           OLChanged = false;
23564b4fe385SDimitry Andric           for (auto *s : MBB->successors())
235701095a5dSDimitry Andric             if (OnPending.insert(s).second) {
2358050e163aSDimitry Andric               Pending.push(BBToOrder[s]);
2359dd58ef01SDimitry Andric             }
2360dd58ef01SDimitry Andric         }
2361dd58ef01SDimitry Andric       }
2362050e163aSDimitry Andric     }
2363050e163aSDimitry Andric     Worklist.swap(Pending);
2364050e163aSDimitry Andric     // At this point, pending must be empty, since it was just the empty
2365050e163aSDimitry Andric     // worklist
2366050e163aSDimitry Andric     assert(Pending.empty() && "Pending should be empty");
2367050e163aSDimitry Andric   }
2368050e163aSDimitry Andric 
23691d5ae102SDimitry Andric   // Add any DBG_VALUE instructions created by location transfers.
23701d5ae102SDimitry Andric   for (auto &TR : Transfers) {
2371cfca06d7SDimitry Andric     assert(!TR.TransferInst->isTerminator() &&
2372cfca06d7SDimitry Andric            "Cannot insert DBG_VALUE after terminator");
23731d5ae102SDimitry Andric     MachineBasicBlock *MBB = TR.TransferInst->getParent();
23741d5ae102SDimitry Andric     const VarLoc &VL = VarLocIDs[TR.LocationID];
23751d5ae102SDimitry Andric     MachineInstr *MI = VL.BuildDbgValue(MF);
23761d5ae102SDimitry Andric     MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
23771d5ae102SDimitry Andric   }
23781d5ae102SDimitry Andric   Transfers.clear();
23791d5ae102SDimitry Andric 
2380c0981da4SDimitry Andric   // Add DBG_VALUEs created using Backup Entry Value location.
2381c0981da4SDimitry Andric   for (auto &TR : EntryValTransfers) {
2382c0981da4SDimitry Andric     MachineInstr *TRInst = const_cast<MachineInstr *>(TR.first);
2383c0981da4SDimitry Andric     assert(!TRInst->isTerminator() &&
2384c0981da4SDimitry Andric            "Cannot insert DBG_VALUE after terminator");
2385c0981da4SDimitry Andric     MachineBasicBlock *MBB = TRInst->getParent();
2386c0981da4SDimitry Andric     const VarLoc &VL = VarLocIDs[TR.second];
2387c0981da4SDimitry Andric     MachineInstr *MI = VL.BuildDbgValue(MF);
2388c0981da4SDimitry Andric     MBB->insertAfterBundle(TRInst->getIterator(), MI);
2389c0981da4SDimitry Andric   }
2390c0981da4SDimitry Andric   EntryValTransfers.clear();
2391c0981da4SDimitry Andric 
23921d5ae102SDimitry Andric   // Deferred inlocs will not have had any DBG_VALUE insts created; do
23931d5ae102SDimitry Andric   // that now.
2394cfca06d7SDimitry Andric   flushPendingLocs(InLocs, VarLocIDs);
23951d5ae102SDimitry Andric 
2396eb11fae6SDimitry Andric   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
2397eb11fae6SDimitry Andric   LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
2398dd58ef01SDimitry Andric   return Changed;
2399dd58ef01SDimitry Andric }
2400dd58ef01SDimitry Andric 
2401b60736ecSDimitry Andric LDVImpl *
makeVarLocBasedLiveDebugValues()2402b60736ecSDimitry Andric llvm::makeVarLocBasedLiveDebugValues()
2403b60736ecSDimitry Andric {
2404b60736ecSDimitry Andric   return new VarLocBasedLDV();
2405dd58ef01SDimitry Andric }
2406