xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1e8d8bef9SDimitry Andric //===- VarLocBasedImpl.cpp - Tracking Debug Value MIs with VarLoc class----===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric ///
9e8d8bef9SDimitry Andric /// \file VarLocBasedImpl.cpp
10e8d8bef9SDimitry Andric ///
11e8d8bef9SDimitry Andric /// LiveDebugValues is an optimistic "available expressions" dataflow
12e8d8bef9SDimitry Andric /// algorithm. The set of expressions is the set of machine locations
13e8d8bef9SDimitry Andric /// (registers, spill slots, constants) that a variable fragment might be
14e8d8bef9SDimitry Andric /// located, qualified by a DIExpression and indirect-ness flag, while each
15e8d8bef9SDimitry Andric /// variable is identified by a DebugVariable object. The availability of an
16e8d8bef9SDimitry Andric /// expression begins when a DBG_VALUE instruction specifies the location of a
17e8d8bef9SDimitry Andric /// DebugVariable, and continues until that location is clobbered or
18e8d8bef9SDimitry Andric /// re-specified by a different DBG_VALUE for the same DebugVariable.
19e8d8bef9SDimitry Andric ///
20e8d8bef9SDimitry Andric /// The output of LiveDebugValues is additional DBG_VALUE instructions,
21e8d8bef9SDimitry Andric /// placed to extend variable locations as far they're available. This file
22e8d8bef9SDimitry Andric /// and the VarLocBasedLDV class is an implementation that explicitly tracks
23e8d8bef9SDimitry Andric /// locations, using the VarLoc class.
24e8d8bef9SDimitry Andric ///
25e8d8bef9SDimitry Andric /// The canonical "available expressions" problem doesn't have expression
26e8d8bef9SDimitry Andric /// clobbering, instead when a variable is re-assigned, any expressions using
27e8d8bef9SDimitry Andric /// that variable get invalidated. LiveDebugValues can map onto "available
28e8d8bef9SDimitry Andric /// expressions" by having every register represented by a variable, which is
29e8d8bef9SDimitry Andric /// used in an expression that becomes available at a DBG_VALUE instruction.
30e8d8bef9SDimitry Andric /// When the register is clobbered, its variable is effectively reassigned, and
31e8d8bef9SDimitry Andric /// expressions computed from it become unavailable. A similar construct is
32e8d8bef9SDimitry Andric /// needed when a DebugVariable has its location re-specified, to invalidate
33e8d8bef9SDimitry Andric /// all other locations for that DebugVariable.
34e8d8bef9SDimitry Andric ///
35e8d8bef9SDimitry Andric /// Using the dataflow analysis to compute the available expressions, we create
36e8d8bef9SDimitry Andric /// a DBG_VALUE at the beginning of each block where the expression is
37e8d8bef9SDimitry Andric /// live-in. This propagates variable locations into every basic block where
38e8d8bef9SDimitry Andric /// the location can be determined, rather than only having DBG_VALUEs in blocks
39e8d8bef9SDimitry Andric /// where locations are specified due to an assignment or some optimization.
40e8d8bef9SDimitry Andric /// Movements of values between registers and spill slots are annotated with
41e8d8bef9SDimitry Andric /// DBG_VALUEs too to track variable values bewteen locations. All this allows
42e8d8bef9SDimitry Andric /// DbgEntityHistoryCalculator to focus on only the locations within individual
43e8d8bef9SDimitry Andric /// blocks, facilitating testing and improving modularity.
44e8d8bef9SDimitry Andric ///
45e8d8bef9SDimitry Andric /// We follow an optimisic dataflow approach, with this lattice:
46e8d8bef9SDimitry Andric ///
47e8d8bef9SDimitry Andric /// \verbatim
48e8d8bef9SDimitry Andric ///                    ┬ "Unknown"
49e8d8bef9SDimitry Andric ///                          |
50e8d8bef9SDimitry Andric ///                          v
51e8d8bef9SDimitry Andric ///                         True
52e8d8bef9SDimitry Andric ///                          |
53e8d8bef9SDimitry Andric ///                          v
54e8d8bef9SDimitry Andric ///                      ⊥ False
55e8d8bef9SDimitry Andric /// \endverbatim With "True" signifying that the expression is available (and
56e8d8bef9SDimitry Andric /// thus a DebugVariable's location is the corresponding register), while
57e8d8bef9SDimitry Andric /// "False" signifies that the expression is unavailable. "Unknown"s never
58e8d8bef9SDimitry Andric /// survive to the end of the analysis (see below).
59e8d8bef9SDimitry Andric ///
60e8d8bef9SDimitry Andric /// Formally, all DebugVariable locations that are live-out of a block are
61e8d8bef9SDimitry Andric /// initialized to \top.  A blocks live-in values take the meet of the lattice
62e8d8bef9SDimitry Andric /// value for every predecessors live-outs, except for the entry block, where
63e8d8bef9SDimitry Andric /// all live-ins are \bot. The usual dataflow propagation occurs: the transfer
64e8d8bef9SDimitry Andric /// function for a block assigns an expression for a DebugVariable to be "True"
65e8d8bef9SDimitry Andric /// if a DBG_VALUE in the block specifies it; "False" if the location is
66e8d8bef9SDimitry Andric /// clobbered; or the live-in value if it is unaffected by the block. We
67e8d8bef9SDimitry Andric /// visit each block in reverse post order until a fixedpoint is reached. The
68e8d8bef9SDimitry Andric /// solution produced is maximal.
69e8d8bef9SDimitry Andric ///
70e8d8bef9SDimitry Andric /// Intuitively, we start by assuming that every expression / variable location
71e8d8bef9SDimitry Andric /// is at least "True", and then propagate "False" from the entry block and any
72e8d8bef9SDimitry Andric /// clobbers until there are no more changes to make. This gives us an accurate
73e8d8bef9SDimitry Andric /// solution because all incorrect locations will have a "False" propagated into
74e8d8bef9SDimitry Andric /// them. It also gives us a solution that copes well with loops by assuming
75e8d8bef9SDimitry Andric /// that variable locations are live-through every loop, and then removing those
76e8d8bef9SDimitry Andric /// that are not through dataflow.
77e8d8bef9SDimitry Andric ///
78e8d8bef9SDimitry Andric /// Within LiveDebugValues: each variable location is represented by a
79fe6060f1SDimitry Andric /// VarLoc object that identifies the source variable, the set of
80fe6060f1SDimitry Andric /// machine-locations that currently describe it (a single location for
81fe6060f1SDimitry Andric /// DBG_VALUE or multiple for DBG_VALUE_LIST), and the DBG_VALUE inst that
82fe6060f1SDimitry Andric /// specifies the location. Each VarLoc is indexed in the (function-scope) \p
83fe6060f1SDimitry Andric /// VarLocMap, giving each VarLoc a set of unique indexes, each of which
84fe6060f1SDimitry Andric /// corresponds to one of the VarLoc's machine-locations and can be used to
85fe6060f1SDimitry Andric /// lookup the VarLoc in the VarLocMap. Rather than operate directly on machine
86fe6060f1SDimitry Andric /// locations, the dataflow analysis in this pass identifies locations by their
87fe6060f1SDimitry Andric /// indices in the VarLocMap, meaning all the variable locations in a block can
88fe6060f1SDimitry Andric /// be described by a sparse vector of VarLocMap indicies.
89e8d8bef9SDimitry Andric ///
90e8d8bef9SDimitry Andric /// All the storage for the dataflow analysis is local to the ExtendRanges
91e8d8bef9SDimitry Andric /// method and passed down to helper methods. "OutLocs" and "InLocs" record the
92e8d8bef9SDimitry Andric /// in and out lattice values for each block. "OpenRanges" maintains a list of
93e8d8bef9SDimitry Andric /// variable locations and, with the "process" method, evaluates the transfer
94fe6060f1SDimitry Andric /// function of each block. "flushPendingLocs" installs debug value instructions
95fe6060f1SDimitry Andric /// for each live-in location at the start of blocks, while "Transfers" records
96e8d8bef9SDimitry Andric /// transfers of values between machine-locations.
97e8d8bef9SDimitry Andric ///
98e8d8bef9SDimitry Andric /// We avoid explicitly representing the "Unknown" (\top) lattice value in the
99e8d8bef9SDimitry Andric /// implementation. Instead, unvisited blocks implicitly have all lattice
100e8d8bef9SDimitry Andric /// values set as "Unknown". After being visited, there will be path back to
101e8d8bef9SDimitry Andric /// the entry block where the lattice value is "False", and as the transfer
102e8d8bef9SDimitry Andric /// function cannot make new "Unknown" locations, there are no scenarios where
103e8d8bef9SDimitry Andric /// a block can have an "Unknown" location after being visited. Similarly, we
104e8d8bef9SDimitry Andric /// don't enumerate all possible variable locations before exploring the
105e8d8bef9SDimitry Andric /// function: when a new location is discovered, all blocks previously explored
106e8d8bef9SDimitry Andric /// were implicitly "False" but unrecorded, and become explicitly "False" when
107e8d8bef9SDimitry Andric /// a new VarLoc is created with its bit not set in predecessor InLocs or
108e8d8bef9SDimitry Andric /// OutLocs.
109e8d8bef9SDimitry Andric ///
110e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
111e8d8bef9SDimitry Andric 
112e8d8bef9SDimitry Andric #include "LiveDebugValues.h"
113e8d8bef9SDimitry Andric 
114e8d8bef9SDimitry Andric #include "llvm/ADT/CoalescingBitVector.h"
115e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h"
116e8d8bef9SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
117e8d8bef9SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
118e8d8bef9SDimitry Andric #include "llvm/ADT/SmallSet.h"
119e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h"
120e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
121*81ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
122e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
123e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
124e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
125e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
126e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
127e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
128e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
129e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
130e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
131e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
132e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
133e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
134e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
135e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
136e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
137e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
138e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h"
139e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
140e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
141e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h"
142e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
143e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h"
144e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h"
145e8d8bef9SDimitry Andric #include "llvm/Target/TargetMachine.h"
146e8d8bef9SDimitry Andric #include <algorithm>
147e8d8bef9SDimitry Andric #include <cassert>
148e8d8bef9SDimitry Andric #include <cstdint>
149e8d8bef9SDimitry Andric #include <functional>
150349cc55cSDimitry Andric #include <map>
151e8d8bef9SDimitry Andric #include <queue>
152e8d8bef9SDimitry Andric #include <tuple>
153e8d8bef9SDimitry Andric #include <utility>
154e8d8bef9SDimitry Andric #include <vector>
155e8d8bef9SDimitry Andric 
156e8d8bef9SDimitry Andric using namespace llvm;
157e8d8bef9SDimitry Andric 
158e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues"
159e8d8bef9SDimitry Andric 
160e8d8bef9SDimitry Andric STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
161e8d8bef9SDimitry Andric 
162e8d8bef9SDimitry Andric /// If \p Op is a stack or frame register return true, otherwise return false.
163e8d8bef9SDimitry Andric /// This is used to avoid basing the debug entry values on the registers, since
164e8d8bef9SDimitry Andric /// we do not support it at the moment.
165e8d8bef9SDimitry Andric static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
166e8d8bef9SDimitry Andric                                   const MachineInstr &MI,
167e8d8bef9SDimitry Andric                                   const TargetRegisterInfo *TRI) {
168e8d8bef9SDimitry Andric   if (!Op.isReg())
169e8d8bef9SDimitry Andric     return false;
170e8d8bef9SDimitry Andric 
171e8d8bef9SDimitry Andric   const MachineFunction *MF = MI.getParent()->getParent();
172e8d8bef9SDimitry Andric   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
173e8d8bef9SDimitry Andric   Register SP = TLI->getStackPointerRegisterToSaveRestore();
174e8d8bef9SDimitry Andric   Register FP = TRI->getFrameRegister(*MF);
175e8d8bef9SDimitry Andric   Register Reg = Op.getReg();
176e8d8bef9SDimitry Andric 
177e8d8bef9SDimitry Andric   return Reg && Reg != SP && Reg != FP;
178e8d8bef9SDimitry Andric }
179e8d8bef9SDimitry Andric 
180e8d8bef9SDimitry Andric namespace {
181e8d8bef9SDimitry Andric 
182e8d8bef9SDimitry Andric // Max out the number of statically allocated elements in DefinedRegsSet, as
183e8d8bef9SDimitry Andric // this prevents fallback to std::set::count() operations.
184e8d8bef9SDimitry Andric using DefinedRegsSet = SmallSet<Register, 32>;
185e8d8bef9SDimitry Andric 
186fe6060f1SDimitry Andric // The IDs in this set correspond to MachineLocs in VarLocs, as well as VarLocs
187fe6060f1SDimitry Andric // that represent Entry Values; every VarLoc in the set will also appear
188fe6060f1SDimitry Andric // exactly once at Location=0.
189fe6060f1SDimitry Andric // As a result, each VarLoc may appear more than once in this "set", but each
190fe6060f1SDimitry Andric // range corresponding to a Reg, SpillLoc, or EntryValue type will still be a
191fe6060f1SDimitry Andric // "true" set (i.e. each VarLoc may appear only once), and the range Location=0
192fe6060f1SDimitry Andric // is the set of all VarLocs.
193e8d8bef9SDimitry Andric using VarLocSet = CoalescingBitVector<uint64_t>;
194e8d8bef9SDimitry Andric 
195e8d8bef9SDimitry Andric /// A type-checked pair of {Register Location (or 0), Index}, used to index
196e8d8bef9SDimitry Andric /// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int
197e8d8bef9SDimitry Andric /// for insertion into a \ref VarLocSet, and efficiently converted back. The
198e8d8bef9SDimitry Andric /// type-checker helps ensure that the conversions aren't lossy.
199e8d8bef9SDimitry Andric ///
200e8d8bef9SDimitry Andric /// Why encode a location /into/ the VarLocMap index? This makes it possible
201e8d8bef9SDimitry Andric /// to find the open VarLocs killed by a register def very quickly. This is a
202e8d8bef9SDimitry Andric /// performance-critical operation for LiveDebugValues.
203e8d8bef9SDimitry Andric struct LocIndex {
204e8d8bef9SDimitry Andric   using u32_location_t = uint32_t;
205e8d8bef9SDimitry Andric   using u32_index_t = uint32_t;
206e8d8bef9SDimitry Andric 
207e8d8bef9SDimitry Andric   u32_location_t Location; // Physical registers live in the range [1;2^30) (see
208e8d8bef9SDimitry Andric                            // \ref MCRegister), so we have plenty of range left
209e8d8bef9SDimitry Andric                            // here to encode non-register locations.
210e8d8bef9SDimitry Andric   u32_index_t Index;
211e8d8bef9SDimitry Andric 
212fe6060f1SDimitry Andric   /// The location that has an entry for every VarLoc in the map.
213fe6060f1SDimitry Andric   static constexpr u32_location_t kUniversalLocation = 0;
214fe6060f1SDimitry Andric 
215fe6060f1SDimitry Andric   /// The first location that is reserved for VarLocs with locations of kind
216fe6060f1SDimitry Andric   /// RegisterKind.
217fe6060f1SDimitry Andric   static constexpr u32_location_t kFirstRegLocation = 1;
218fe6060f1SDimitry Andric 
219fe6060f1SDimitry Andric   /// The first location greater than 0 that is not reserved for VarLocs with
220fe6060f1SDimitry Andric   /// locations of kind RegisterKind.
221e8d8bef9SDimitry Andric   static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30;
222e8d8bef9SDimitry Andric 
223fe6060f1SDimitry Andric   /// A special location reserved for VarLocs with locations of kind
224fe6060f1SDimitry Andric   /// SpillLocKind.
225e8d8bef9SDimitry Andric   static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation;
226e8d8bef9SDimitry Andric 
227e8d8bef9SDimitry Andric   /// A special location reserved for VarLocs of kind EntryValueBackupKind and
228e8d8bef9SDimitry Andric   /// EntryValueCopyBackupKind.
229e8d8bef9SDimitry Andric   static constexpr u32_location_t kEntryValueBackupLocation =
230e8d8bef9SDimitry Andric       kFirstInvalidRegLocation + 1;
231e8d8bef9SDimitry Andric 
232e8d8bef9SDimitry Andric   LocIndex(u32_location_t Location, u32_index_t Index)
233e8d8bef9SDimitry Andric       : Location(Location), Index(Index) {}
234e8d8bef9SDimitry Andric 
235e8d8bef9SDimitry Andric   uint64_t getAsRawInteger() const {
236e8d8bef9SDimitry Andric     return (static_cast<uint64_t>(Location) << 32) | Index;
237e8d8bef9SDimitry Andric   }
238e8d8bef9SDimitry Andric 
239e8d8bef9SDimitry Andric   template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
240e8d8bef9SDimitry Andric     static_assert(std::is_unsigned<IntT>::value &&
241e8d8bef9SDimitry Andric                       sizeof(ID) == sizeof(uint64_t),
242e8d8bef9SDimitry Andric                   "Cannot convert raw integer to LocIndex");
243e8d8bef9SDimitry Andric     return {static_cast<u32_location_t>(ID >> 32),
244e8d8bef9SDimitry Andric             static_cast<u32_index_t>(ID)};
245e8d8bef9SDimitry Andric   }
246e8d8bef9SDimitry Andric 
247e8d8bef9SDimitry Andric   /// Get the start of the interval reserved for VarLocs of kind RegisterKind
248e8d8bef9SDimitry Andric   /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1.
249fe6060f1SDimitry Andric   static uint64_t rawIndexForReg(Register Reg) {
250e8d8bef9SDimitry Andric     return LocIndex(Reg, 0).getAsRawInteger();
251e8d8bef9SDimitry Andric   }
252e8d8bef9SDimitry Andric 
253e8d8bef9SDimitry Andric   /// Return a range covering all set indices in the interval reserved for
254e8d8bef9SDimitry Andric   /// \p Location in \p Set.
255e8d8bef9SDimitry Andric   static auto indexRangeForLocation(const VarLocSet &Set,
256e8d8bef9SDimitry Andric                                     u32_location_t Location) {
257e8d8bef9SDimitry Andric     uint64_t Start = LocIndex(Location, 0).getAsRawInteger();
258e8d8bef9SDimitry Andric     uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger();
259e8d8bef9SDimitry Andric     return Set.half_open_range(Start, End);
260e8d8bef9SDimitry Andric   }
261e8d8bef9SDimitry Andric };
262e8d8bef9SDimitry Andric 
263fe6060f1SDimitry Andric // Simple Set for storing all the VarLoc Indices at a Location bucket.
264fe6060f1SDimitry Andric using VarLocsInRange = SmallSet<LocIndex::u32_index_t, 32>;
265fe6060f1SDimitry Andric // Vector of all `LocIndex`s for a given VarLoc; the same Location should not
266fe6060f1SDimitry Andric // appear in any two of these, as each VarLoc appears at most once in any
267fe6060f1SDimitry Andric // Location bucket.
268fe6060f1SDimitry Andric using LocIndices = SmallVector<LocIndex, 2>;
269fe6060f1SDimitry Andric 
270e8d8bef9SDimitry Andric class VarLocBasedLDV : public LDVImpl {
271e8d8bef9SDimitry Andric private:
272e8d8bef9SDimitry Andric   const TargetRegisterInfo *TRI;
273e8d8bef9SDimitry Andric   const TargetInstrInfo *TII;
274e8d8bef9SDimitry Andric   const TargetFrameLowering *TFI;
275e8d8bef9SDimitry Andric   TargetPassConfig *TPC;
276e8d8bef9SDimitry Andric   BitVector CalleeSavedRegs;
277e8d8bef9SDimitry Andric   LexicalScopes LS;
278e8d8bef9SDimitry Andric   VarLocSet::Allocator Alloc;
279e8d8bef9SDimitry Andric 
280349cc55cSDimitry Andric   const MachineInstr *LastNonDbgMI;
281349cc55cSDimitry Andric 
282e8d8bef9SDimitry Andric   enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
283e8d8bef9SDimitry Andric 
284e8d8bef9SDimitry Andric   using FragmentInfo = DIExpression::FragmentInfo;
285e8d8bef9SDimitry Andric   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
286e8d8bef9SDimitry Andric 
287e8d8bef9SDimitry Andric   /// A pair of debug variable and value location.
288e8d8bef9SDimitry Andric   struct VarLoc {
289e8d8bef9SDimitry Andric     // The location at which a spilled variable resides. It consists of a
290e8d8bef9SDimitry Andric     // register and an offset.
291e8d8bef9SDimitry Andric     struct SpillLoc {
292e8d8bef9SDimitry Andric       unsigned SpillBase;
293e8d8bef9SDimitry Andric       StackOffset SpillOffset;
294e8d8bef9SDimitry Andric       bool operator==(const SpillLoc &Other) const {
295e8d8bef9SDimitry Andric         return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
296e8d8bef9SDimitry Andric       }
297e8d8bef9SDimitry Andric       bool operator!=(const SpillLoc &Other) const {
298e8d8bef9SDimitry Andric         return !(*this == Other);
299e8d8bef9SDimitry Andric       }
300e8d8bef9SDimitry Andric     };
301e8d8bef9SDimitry Andric 
302e8d8bef9SDimitry Andric     /// Identity of the variable at this location.
303e8d8bef9SDimitry Andric     const DebugVariable Var;
304e8d8bef9SDimitry Andric 
305e8d8bef9SDimitry Andric     /// The expression applied to this location.
306e8d8bef9SDimitry Andric     const DIExpression *Expr;
307e8d8bef9SDimitry Andric 
308e8d8bef9SDimitry Andric     /// DBG_VALUE to clone var/expr information from if this location
309e8d8bef9SDimitry Andric     /// is moved.
310e8d8bef9SDimitry Andric     const MachineInstr &MI;
311e8d8bef9SDimitry Andric 
312fe6060f1SDimitry Andric     enum class MachineLocKind {
313e8d8bef9SDimitry Andric       InvalidKind = 0,
314e8d8bef9SDimitry Andric       RegisterKind,
315e8d8bef9SDimitry Andric       SpillLocKind,
316fe6060f1SDimitry Andric       ImmediateKind
317fe6060f1SDimitry Andric     };
318fe6060f1SDimitry Andric 
319fe6060f1SDimitry Andric     enum class EntryValueLocKind {
320fe6060f1SDimitry Andric       NonEntryValueKind = 0,
321e8d8bef9SDimitry Andric       EntryValueKind,
322e8d8bef9SDimitry Andric       EntryValueBackupKind,
323e8d8bef9SDimitry Andric       EntryValueCopyBackupKind
3241fd87a68SDimitry Andric     } EVKind = EntryValueLocKind::NonEntryValueKind;
325e8d8bef9SDimitry Andric 
326e8d8bef9SDimitry Andric     /// The value location. Stored separately to avoid repeatedly
327e8d8bef9SDimitry Andric     /// extracting it from MI.
328fe6060f1SDimitry Andric     union MachineLocValue {
329e8d8bef9SDimitry Andric       uint64_t RegNo;
330e8d8bef9SDimitry Andric       SpillLoc SpillLocation;
331e8d8bef9SDimitry Andric       uint64_t Hash;
332e8d8bef9SDimitry Andric       int64_t Immediate;
333e8d8bef9SDimitry Andric       const ConstantFP *FPImm;
334e8d8bef9SDimitry Andric       const ConstantInt *CImm;
335fe6060f1SDimitry Andric       MachineLocValue() : Hash(0) {}
336fe6060f1SDimitry Andric     };
337fe6060f1SDimitry Andric 
338fe6060f1SDimitry Andric     /// A single machine location; its Kind is either a register, spill
339fe6060f1SDimitry Andric     /// location, or immediate value.
340fe6060f1SDimitry Andric     /// If the VarLoc is not a NonEntryValueKind, then it will use only a
341fe6060f1SDimitry Andric     /// single MachineLoc of RegisterKind.
342fe6060f1SDimitry Andric     struct MachineLoc {
343fe6060f1SDimitry Andric       MachineLocKind Kind;
344fe6060f1SDimitry Andric       MachineLocValue Value;
345fe6060f1SDimitry Andric       bool operator==(const MachineLoc &Other) const {
346fe6060f1SDimitry Andric         if (Kind != Other.Kind)
347fe6060f1SDimitry Andric           return false;
348fe6060f1SDimitry Andric         switch (Kind) {
349fe6060f1SDimitry Andric         case MachineLocKind::SpillLocKind:
350fe6060f1SDimitry Andric           return Value.SpillLocation == Other.Value.SpillLocation;
351fe6060f1SDimitry Andric         case MachineLocKind::RegisterKind:
352fe6060f1SDimitry Andric         case MachineLocKind::ImmediateKind:
353fe6060f1SDimitry Andric           return Value.Hash == Other.Value.Hash;
354fe6060f1SDimitry Andric         default:
355fe6060f1SDimitry Andric           llvm_unreachable("Invalid kind");
356fe6060f1SDimitry Andric         }
357fe6060f1SDimitry Andric       }
358fe6060f1SDimitry Andric       bool operator<(const MachineLoc &Other) const {
359fe6060f1SDimitry Andric         switch (Kind) {
360fe6060f1SDimitry Andric         case MachineLocKind::SpillLocKind:
361fe6060f1SDimitry Andric           return std::make_tuple(
362fe6060f1SDimitry Andric                      Kind, Value.SpillLocation.SpillBase,
363fe6060f1SDimitry Andric                      Value.SpillLocation.SpillOffset.getFixed(),
364fe6060f1SDimitry Andric                      Value.SpillLocation.SpillOffset.getScalable()) <
365fe6060f1SDimitry Andric                  std::make_tuple(
366fe6060f1SDimitry Andric                      Other.Kind, Other.Value.SpillLocation.SpillBase,
367fe6060f1SDimitry Andric                      Other.Value.SpillLocation.SpillOffset.getFixed(),
368fe6060f1SDimitry Andric                      Other.Value.SpillLocation.SpillOffset.getScalable());
369fe6060f1SDimitry Andric         case MachineLocKind::RegisterKind:
370fe6060f1SDimitry Andric         case MachineLocKind::ImmediateKind:
371fe6060f1SDimitry Andric           return std::tie(Kind, Value.Hash) <
372fe6060f1SDimitry Andric                  std::tie(Other.Kind, Other.Value.Hash);
373fe6060f1SDimitry Andric         default:
374fe6060f1SDimitry Andric           llvm_unreachable("Invalid kind");
375fe6060f1SDimitry Andric         }
376fe6060f1SDimitry Andric       }
377fe6060f1SDimitry Andric     };
378fe6060f1SDimitry Andric 
379fe6060f1SDimitry Andric     /// The set of machine locations used to determine the variable's value, in
380fe6060f1SDimitry Andric     /// conjunction with Expr. Initially populated with MI's debug operands,
381fe6060f1SDimitry Andric     /// but may be transformed independently afterwards.
382fe6060f1SDimitry Andric     SmallVector<MachineLoc, 8> Locs;
383fe6060f1SDimitry Andric     /// Used to map the index of each location in Locs back to the index of its
384fe6060f1SDimitry Andric     /// original debug operand in MI. Used when multiple location operands are
385fe6060f1SDimitry Andric     /// coalesced and the original MI's operands need to be accessed while
386fe6060f1SDimitry Andric     /// emitting a debug value.
387fe6060f1SDimitry Andric     SmallVector<unsigned, 8> OrigLocMap;
388e8d8bef9SDimitry Andric 
389e8d8bef9SDimitry Andric     VarLoc(const MachineInstr &MI, LexicalScopes &LS)
390e8d8bef9SDimitry Andric         : Var(MI.getDebugVariable(), MI.getDebugExpression(),
391e8d8bef9SDimitry Andric               MI.getDebugLoc()->getInlinedAt()),
3921fd87a68SDimitry Andric           Expr(MI.getDebugExpression()), MI(MI) {
393e8d8bef9SDimitry Andric       assert(MI.isDebugValue() && "not a DBG_VALUE");
394fe6060f1SDimitry Andric       assert((MI.isDebugValueList() || MI.getNumOperands() == 4) &&
395fe6060f1SDimitry Andric              "malformed DBG_VALUE");
396fe6060f1SDimitry Andric       for (const MachineOperand &Op : MI.debug_operands()) {
397fe6060f1SDimitry Andric         MachineLoc ML = GetLocForOp(Op);
398fe6060f1SDimitry Andric         auto It = find(Locs, ML);
399fe6060f1SDimitry Andric         if (It == Locs.end()) {
400fe6060f1SDimitry Andric           Locs.push_back(ML);
401fe6060f1SDimitry Andric           OrigLocMap.push_back(MI.getDebugOperandIndex(&Op));
402fe6060f1SDimitry Andric         } else {
403fe6060f1SDimitry Andric           // ML duplicates an element in Locs; replace references to Op
404fe6060f1SDimitry Andric           // with references to the duplicating element.
405fe6060f1SDimitry Andric           unsigned OpIdx = Locs.size();
406fe6060f1SDimitry Andric           unsigned DuplicatingIdx = std::distance(Locs.begin(), It);
407fe6060f1SDimitry Andric           Expr = DIExpression::replaceArg(Expr, OpIdx, DuplicatingIdx);
408fe6060f1SDimitry Andric         }
409e8d8bef9SDimitry Andric       }
410e8d8bef9SDimitry Andric 
411fe6060f1SDimitry Andric       // We create the debug entry values from the factory functions rather
412fe6060f1SDimitry Andric       // than from this ctor.
413fe6060f1SDimitry Andric       assert(EVKind != EntryValueLocKind::EntryValueKind &&
414fe6060f1SDimitry Andric              !isEntryBackupLoc());
415fe6060f1SDimitry Andric     }
416fe6060f1SDimitry Andric 
417fe6060f1SDimitry Andric     static MachineLoc GetLocForOp(const MachineOperand &Op) {
418fe6060f1SDimitry Andric       MachineLocKind Kind;
419fe6060f1SDimitry Andric       MachineLocValue Loc;
420fe6060f1SDimitry Andric       if (Op.isReg()) {
421fe6060f1SDimitry Andric         Kind = MachineLocKind::RegisterKind;
422fe6060f1SDimitry Andric         Loc.RegNo = Op.getReg();
423fe6060f1SDimitry Andric       } else if (Op.isImm()) {
424fe6060f1SDimitry Andric         Kind = MachineLocKind::ImmediateKind;
425fe6060f1SDimitry Andric         Loc.Immediate = Op.getImm();
426fe6060f1SDimitry Andric       } else if (Op.isFPImm()) {
427fe6060f1SDimitry Andric         Kind = MachineLocKind::ImmediateKind;
428fe6060f1SDimitry Andric         Loc.FPImm = Op.getFPImm();
429fe6060f1SDimitry Andric       } else if (Op.isCImm()) {
430fe6060f1SDimitry Andric         Kind = MachineLocKind::ImmediateKind;
431fe6060f1SDimitry Andric         Loc.CImm = Op.getCImm();
432fe6060f1SDimitry Andric       } else
433fe6060f1SDimitry Andric         llvm_unreachable("Invalid Op kind for MachineLoc.");
434fe6060f1SDimitry Andric       return {Kind, Loc};
435e8d8bef9SDimitry Andric     }
436e8d8bef9SDimitry Andric 
437e8d8bef9SDimitry Andric     /// Take the variable and machine-location in DBG_VALUE MI, and build an
438e8d8bef9SDimitry Andric     /// entry location using the given expression.
439e8d8bef9SDimitry Andric     static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
440e8d8bef9SDimitry Andric                                  const DIExpression *EntryExpr, Register Reg) {
441e8d8bef9SDimitry Andric       VarLoc VL(MI, LS);
442fe6060f1SDimitry Andric       assert(VL.Locs.size() == 1 &&
443fe6060f1SDimitry Andric              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
444fe6060f1SDimitry Andric       VL.EVKind = EntryValueLocKind::EntryValueKind;
445e8d8bef9SDimitry Andric       VL.Expr = EntryExpr;
446fe6060f1SDimitry Andric       VL.Locs[0].Value.RegNo = Reg;
447e8d8bef9SDimitry Andric       return VL;
448e8d8bef9SDimitry Andric     }
449e8d8bef9SDimitry Andric 
450e8d8bef9SDimitry Andric     /// Take the variable and machine-location from the DBG_VALUE (from the
451e8d8bef9SDimitry Andric     /// function entry), and build an entry value backup location. The backup
452e8d8bef9SDimitry Andric     /// location will turn into the normal location if the backup is valid at
453e8d8bef9SDimitry Andric     /// the time of the primary location clobbering.
454e8d8bef9SDimitry Andric     static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
455e8d8bef9SDimitry Andric                                        LexicalScopes &LS,
456e8d8bef9SDimitry Andric                                        const DIExpression *EntryExpr) {
457e8d8bef9SDimitry Andric       VarLoc VL(MI, LS);
458fe6060f1SDimitry Andric       assert(VL.Locs.size() == 1 &&
459fe6060f1SDimitry Andric              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
460fe6060f1SDimitry Andric       VL.EVKind = EntryValueLocKind::EntryValueBackupKind;
461e8d8bef9SDimitry Andric       VL.Expr = EntryExpr;
462e8d8bef9SDimitry Andric       return VL;
463e8d8bef9SDimitry Andric     }
464e8d8bef9SDimitry Andric 
465e8d8bef9SDimitry Andric     /// Take the variable and machine-location from the DBG_VALUE (from the
466e8d8bef9SDimitry Andric     /// function entry), and build a copy of an entry value backup location by
467e8d8bef9SDimitry Andric     /// setting the register location to NewReg.
468e8d8bef9SDimitry Andric     static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
469e8d8bef9SDimitry Andric                                            LexicalScopes &LS,
470e8d8bef9SDimitry Andric                                            const DIExpression *EntryExpr,
471e8d8bef9SDimitry Andric                                            Register NewReg) {
472e8d8bef9SDimitry Andric       VarLoc VL(MI, LS);
473fe6060f1SDimitry Andric       assert(VL.Locs.size() == 1 &&
474fe6060f1SDimitry Andric              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
475fe6060f1SDimitry Andric       VL.EVKind = EntryValueLocKind::EntryValueCopyBackupKind;
476e8d8bef9SDimitry Andric       VL.Expr = EntryExpr;
477fe6060f1SDimitry Andric       VL.Locs[0].Value.RegNo = NewReg;
478e8d8bef9SDimitry Andric       return VL;
479e8d8bef9SDimitry Andric     }
480e8d8bef9SDimitry Andric 
481e8d8bef9SDimitry Andric     /// Copy the register location in DBG_VALUE MI, updating the register to
482e8d8bef9SDimitry Andric     /// be NewReg.
483fe6060f1SDimitry Andric     static VarLoc CreateCopyLoc(const VarLoc &OldVL, const MachineLoc &OldML,
484e8d8bef9SDimitry Andric                                 Register NewReg) {
485fe6060f1SDimitry Andric       VarLoc VL = OldVL;
4860eae32dcSDimitry Andric       for (MachineLoc &ML : VL.Locs)
4870eae32dcSDimitry Andric         if (ML == OldML) {
4880eae32dcSDimitry Andric           ML.Kind = MachineLocKind::RegisterKind;
4890eae32dcSDimitry Andric           ML.Value.RegNo = NewReg;
490e8d8bef9SDimitry Andric           return VL;
491e8d8bef9SDimitry Andric         }
492fe6060f1SDimitry Andric       llvm_unreachable("Should have found OldML in new VarLoc.");
493fe6060f1SDimitry Andric     }
494e8d8bef9SDimitry Andric 
495fe6060f1SDimitry Andric     /// Take the variable described by DBG_VALUE* MI, and create a VarLoc
496e8d8bef9SDimitry Andric     /// locating it in the specified spill location.
497fe6060f1SDimitry Andric     static VarLoc CreateSpillLoc(const VarLoc &OldVL, const MachineLoc &OldML,
498fe6060f1SDimitry Andric                                  unsigned SpillBase, StackOffset SpillOffset) {
499fe6060f1SDimitry Andric       VarLoc VL = OldVL;
5000eae32dcSDimitry Andric       for (MachineLoc &ML : VL.Locs)
5010eae32dcSDimitry Andric         if (ML == OldML) {
5020eae32dcSDimitry Andric           ML.Kind = MachineLocKind::SpillLocKind;
5030eae32dcSDimitry Andric           ML.Value.SpillLocation = {SpillBase, SpillOffset};
504e8d8bef9SDimitry Andric           return VL;
505e8d8bef9SDimitry Andric         }
506fe6060f1SDimitry Andric       llvm_unreachable("Should have found OldML in new VarLoc.");
507fe6060f1SDimitry Andric     }
508e8d8bef9SDimitry Andric 
509e8d8bef9SDimitry Andric     /// Create a DBG_VALUE representing this VarLoc in the given function.
510e8d8bef9SDimitry Andric     /// Copies variable-specific information such as DILocalVariable and
511e8d8bef9SDimitry Andric     /// inlining information from the original DBG_VALUE instruction, which may
512e8d8bef9SDimitry Andric     /// have been several transfers ago.
513e8d8bef9SDimitry Andric     MachineInstr *BuildDbgValue(MachineFunction &MF) const {
514fe6060f1SDimitry Andric       assert(!isEntryBackupLoc() &&
515fe6060f1SDimitry Andric              "Tried to produce DBG_VALUE for backup VarLoc");
516e8d8bef9SDimitry Andric       const DebugLoc &DbgLoc = MI.getDebugLoc();
517e8d8bef9SDimitry Andric       bool Indirect = MI.isIndirectDebugValue();
518e8d8bef9SDimitry Andric       const auto &IID = MI.getDesc();
519e8d8bef9SDimitry Andric       const DILocalVariable *Var = MI.getDebugVariable();
520e8d8bef9SDimitry Andric       NumInserted++;
521e8d8bef9SDimitry Andric 
522fe6060f1SDimitry Andric       const DIExpression *DIExpr = Expr;
523fe6060f1SDimitry Andric       SmallVector<MachineOperand, 8> MOs;
524fe6060f1SDimitry Andric       for (unsigned I = 0, E = Locs.size(); I < E; ++I) {
525fe6060f1SDimitry Andric         MachineLocKind LocKind = Locs[I].Kind;
526fe6060f1SDimitry Andric         MachineLocValue Loc = Locs[I].Value;
527fe6060f1SDimitry Andric         const MachineOperand &Orig = MI.getDebugOperand(OrigLocMap[I]);
528fe6060f1SDimitry Andric         switch (LocKind) {
529fe6060f1SDimitry Andric         case MachineLocKind::RegisterKind:
530e8d8bef9SDimitry Andric           // An entry value is a register location -- but with an updated
531fe6060f1SDimitry Andric           // expression. The register location of such DBG_VALUE is always the
532fe6060f1SDimitry Andric           // one from the entry DBG_VALUE, it does not matter if the entry value
533fe6060f1SDimitry Andric           // was copied in to another register due to some optimizations.
534fe6060f1SDimitry Andric           // Non-entry value register locations are like the source
535fe6060f1SDimitry Andric           // DBG_VALUE, but with the register number from this VarLoc.
536fe6060f1SDimitry Andric           MOs.push_back(MachineOperand::CreateReg(
537fe6060f1SDimitry Andric               EVKind == EntryValueLocKind::EntryValueKind ? Orig.getReg()
538fe6060f1SDimitry Andric                                                           : Register(Loc.RegNo),
539fe6060f1SDimitry Andric               false));
540fe6060f1SDimitry Andric           break;
541fe6060f1SDimitry Andric         case MachineLocKind::SpillLocKind: {
542e8d8bef9SDimitry Andric           // Spills are indirect DBG_VALUEs, with a base register and offset.
543e8d8bef9SDimitry Andric           // Use the original DBG_VALUEs expression to build the spilt location
544e8d8bef9SDimitry Andric           // on top of. FIXME: spill locations created before this pass runs
545e8d8bef9SDimitry Andric           // are not recognized, and not handled here.
546e8d8bef9SDimitry Andric           unsigned Base = Loc.SpillLocation.SpillBase;
547fe6060f1SDimitry Andric           auto *TRI = MF.getSubtarget().getRegisterInfo();
548fe6060f1SDimitry Andric           if (MI.isNonListDebugValue()) {
549349cc55cSDimitry Andric             auto Deref = Indirect ? DIExpression::DerefAfter : 0;
550349cc55cSDimitry Andric             DIExpr = TRI->prependOffsetExpression(
551349cc55cSDimitry Andric                 DIExpr, DIExpression::ApplyOffset | Deref,
552fe6060f1SDimitry Andric                 Loc.SpillLocation.SpillOffset);
553fe6060f1SDimitry Andric             Indirect = true;
554fe6060f1SDimitry Andric           } else {
555fe6060f1SDimitry Andric             SmallVector<uint64_t, 4> Ops;
556fe6060f1SDimitry Andric             TRI->getOffsetOpcodes(Loc.SpillLocation.SpillOffset, Ops);
557fe6060f1SDimitry Andric             Ops.push_back(dwarf::DW_OP_deref);
558fe6060f1SDimitry Andric             DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, I);
559e8d8bef9SDimitry Andric           }
560fe6060f1SDimitry Andric           MOs.push_back(MachineOperand::CreateReg(Base, false));
561fe6060f1SDimitry Andric           break;
562e8d8bef9SDimitry Andric         }
563fe6060f1SDimitry Andric         case MachineLocKind::ImmediateKind: {
564fe6060f1SDimitry Andric           MOs.push_back(Orig);
565fe6060f1SDimitry Andric           break;
566e8d8bef9SDimitry Andric         }
567fe6060f1SDimitry Andric         case MachineLocKind::InvalidKind:
568fe6060f1SDimitry Andric           llvm_unreachable("Tried to produce DBG_VALUE for invalid VarLoc");
569fe6060f1SDimitry Andric         }
570fe6060f1SDimitry Andric       }
571fe6060f1SDimitry Andric       return BuildMI(MF, DbgLoc, IID, Indirect, MOs, Var, DIExpr);
572e8d8bef9SDimitry Andric     }
573e8d8bef9SDimitry Andric 
574e8d8bef9SDimitry Andric     /// Is the Loc field a constant or constant object?
575fe6060f1SDimitry Andric     bool isConstant(MachineLocKind Kind) const {
576fe6060f1SDimitry Andric       return Kind == MachineLocKind::ImmediateKind;
577fe6060f1SDimitry Andric     }
578e8d8bef9SDimitry Andric 
579e8d8bef9SDimitry Andric     /// Check if the Loc field is an entry backup location.
580e8d8bef9SDimitry Andric     bool isEntryBackupLoc() const {
581fe6060f1SDimitry Andric       return EVKind == EntryValueLocKind::EntryValueBackupKind ||
582fe6060f1SDimitry Andric              EVKind == EntryValueLocKind::EntryValueCopyBackupKind;
583e8d8bef9SDimitry Andric     }
584e8d8bef9SDimitry Andric 
585fe6060f1SDimitry Andric     /// If this variable is described by register \p Reg holding the entry
586fe6060f1SDimitry Andric     /// value, return true.
587fe6060f1SDimitry Andric     bool isEntryValueBackupReg(Register Reg) const {
588fe6060f1SDimitry Andric       return EVKind == EntryValueLocKind::EntryValueBackupKind && usesReg(Reg);
589e8d8bef9SDimitry Andric     }
590e8d8bef9SDimitry Andric 
591fe6060f1SDimitry Andric     /// If this variable is described by register \p Reg holding a copy of the
592fe6060f1SDimitry Andric     /// entry value, return true.
593fe6060f1SDimitry Andric     bool isEntryValueCopyBackupReg(Register Reg) const {
594fe6060f1SDimitry Andric       return EVKind == EntryValueLocKind::EntryValueCopyBackupKind &&
595fe6060f1SDimitry Andric              usesReg(Reg);
596e8d8bef9SDimitry Andric     }
597e8d8bef9SDimitry Andric 
598fe6060f1SDimitry Andric     /// If this variable is described in whole or part by \p Reg, return true.
599fe6060f1SDimitry Andric     bool usesReg(Register Reg) const {
600fe6060f1SDimitry Andric       MachineLoc RegML;
601fe6060f1SDimitry Andric       RegML.Kind = MachineLocKind::RegisterKind;
602fe6060f1SDimitry Andric       RegML.Value.RegNo = Reg;
603fe6060f1SDimitry Andric       return is_contained(Locs, RegML);
604fe6060f1SDimitry Andric     }
605fe6060f1SDimitry Andric 
606fe6060f1SDimitry Andric     /// If this variable is described in whole or part by \p Reg, return true.
607fe6060f1SDimitry Andric     unsigned getRegIdx(Register Reg) const {
608fe6060f1SDimitry Andric       for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
609fe6060f1SDimitry Andric         if (Locs[Idx].Kind == MachineLocKind::RegisterKind &&
610349cc55cSDimitry Andric             Register{static_cast<unsigned>(Locs[Idx].Value.RegNo)} == Reg)
611fe6060f1SDimitry Andric           return Idx;
612fe6060f1SDimitry Andric       llvm_unreachable("Could not find given Reg in Locs");
613fe6060f1SDimitry Andric     }
614fe6060f1SDimitry Andric 
615fe6060f1SDimitry Andric     /// If this variable is described in whole or part by 1 or more registers,
616fe6060f1SDimitry Andric     /// add each of them to \p Regs and return true.
617fe6060f1SDimitry Andric     bool getDescribingRegs(SmallVectorImpl<uint32_t> &Regs) const {
618fe6060f1SDimitry Andric       bool AnyRegs = false;
619349cc55cSDimitry Andric       for (const auto &Loc : Locs)
620fe6060f1SDimitry Andric         if (Loc.Kind == MachineLocKind::RegisterKind) {
621fe6060f1SDimitry Andric           Regs.push_back(Loc.Value.RegNo);
622fe6060f1SDimitry Andric           AnyRegs = true;
623fe6060f1SDimitry Andric         }
624fe6060f1SDimitry Andric       return AnyRegs;
625fe6060f1SDimitry Andric     }
626fe6060f1SDimitry Andric 
627fe6060f1SDimitry Andric     bool containsSpillLocs() const {
628fe6060f1SDimitry Andric       return any_of(Locs, [](VarLoc::MachineLoc ML) {
629fe6060f1SDimitry Andric         return ML.Kind == VarLoc::MachineLocKind::SpillLocKind;
630fe6060f1SDimitry Andric       });
631fe6060f1SDimitry Andric     }
632fe6060f1SDimitry Andric 
633fe6060f1SDimitry Andric     /// If this variable is described in whole or part by \p SpillLocation,
634fe6060f1SDimitry Andric     /// return true.
635fe6060f1SDimitry Andric     bool usesSpillLoc(SpillLoc SpillLocation) const {
636fe6060f1SDimitry Andric       MachineLoc SpillML;
637fe6060f1SDimitry Andric       SpillML.Kind = MachineLocKind::SpillLocKind;
638fe6060f1SDimitry Andric       SpillML.Value.SpillLocation = SpillLocation;
639fe6060f1SDimitry Andric       return is_contained(Locs, SpillML);
640fe6060f1SDimitry Andric     }
641fe6060f1SDimitry Andric 
642fe6060f1SDimitry Andric     /// If this variable is described in whole or part by \p SpillLocation,
643fe6060f1SDimitry Andric     /// return the index .
644fe6060f1SDimitry Andric     unsigned getSpillLocIdx(SpillLoc SpillLocation) const {
645fe6060f1SDimitry Andric       for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
646fe6060f1SDimitry Andric         if (Locs[Idx].Kind == MachineLocKind::SpillLocKind &&
647fe6060f1SDimitry Andric             Locs[Idx].Value.SpillLocation == SpillLocation)
648fe6060f1SDimitry Andric           return Idx;
649fe6060f1SDimitry Andric       llvm_unreachable("Could not find given SpillLoc in Locs");
650e8d8bef9SDimitry Andric     }
651e8d8bef9SDimitry Andric 
652e8d8bef9SDimitry Andric     /// Determine whether the lexical scope of this value's debug location
653e8d8bef9SDimitry Andric     /// dominates MBB.
654e8d8bef9SDimitry Andric     bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const {
655e8d8bef9SDimitry Andric       return LS.dominates(MI.getDebugLoc().get(), &MBB);
656e8d8bef9SDimitry Andric     }
657e8d8bef9SDimitry Andric 
658e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
659e8d8bef9SDimitry Andric     // TRI can be null.
660e8d8bef9SDimitry Andric     void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
661e8d8bef9SDimitry Andric       Out << "VarLoc(";
662fe6060f1SDimitry Andric       for (const MachineLoc &MLoc : Locs) {
663fe6060f1SDimitry Andric         if (Locs.begin() != &MLoc)
664fe6060f1SDimitry Andric           Out << ", ";
665fe6060f1SDimitry Andric         switch (MLoc.Kind) {
666fe6060f1SDimitry Andric         case MachineLocKind::RegisterKind:
667fe6060f1SDimitry Andric           Out << printReg(MLoc.Value.RegNo, TRI);
668e8d8bef9SDimitry Andric           break;
669fe6060f1SDimitry Andric         case MachineLocKind::SpillLocKind:
670fe6060f1SDimitry Andric           Out << printReg(MLoc.Value.SpillLocation.SpillBase, TRI);
671fe6060f1SDimitry Andric           Out << "[" << MLoc.Value.SpillLocation.SpillOffset.getFixed() << " + "
672fe6060f1SDimitry Andric               << MLoc.Value.SpillLocation.SpillOffset.getScalable()
673fe6060f1SDimitry Andric               << "x vscale"
674e8d8bef9SDimitry Andric               << "]";
675e8d8bef9SDimitry Andric           break;
676fe6060f1SDimitry Andric         case MachineLocKind::ImmediateKind:
677fe6060f1SDimitry Andric           Out << MLoc.Value.Immediate;
678e8d8bef9SDimitry Andric           break;
679fe6060f1SDimitry Andric         case MachineLocKind::InvalidKind:
680e8d8bef9SDimitry Andric           llvm_unreachable("Invalid VarLoc in dump method");
681e8d8bef9SDimitry Andric         }
682fe6060f1SDimitry Andric       }
683e8d8bef9SDimitry Andric 
684e8d8bef9SDimitry Andric       Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", ";
685e8d8bef9SDimitry Andric       if (Var.getInlinedAt())
686e8d8bef9SDimitry Andric         Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
687e8d8bef9SDimitry Andric       else
688e8d8bef9SDimitry Andric         Out << "(null))";
689e8d8bef9SDimitry Andric 
690e8d8bef9SDimitry Andric       if (isEntryBackupLoc())
691e8d8bef9SDimitry Andric         Out << " (backup loc)\n";
692e8d8bef9SDimitry Andric       else
693e8d8bef9SDimitry Andric         Out << "\n";
694e8d8bef9SDimitry Andric     }
695e8d8bef9SDimitry Andric #endif
696e8d8bef9SDimitry Andric 
697e8d8bef9SDimitry Andric     bool operator==(const VarLoc &Other) const {
698fe6060f1SDimitry Andric       return std::tie(EVKind, Var, Expr, Locs) ==
699fe6060f1SDimitry Andric              std::tie(Other.EVKind, Other.Var, Other.Expr, Other.Locs);
700e8d8bef9SDimitry Andric     }
701e8d8bef9SDimitry Andric 
702e8d8bef9SDimitry Andric     /// This operator guarantees that VarLocs are sorted by Variable first.
703e8d8bef9SDimitry Andric     bool operator<(const VarLoc &Other) const {
704fe6060f1SDimitry Andric       return std::tie(Var, EVKind, Locs, Expr) <
705fe6060f1SDimitry Andric              std::tie(Other.Var, Other.EVKind, Other.Locs, Other.Expr);
706e8d8bef9SDimitry Andric     }
707e8d8bef9SDimitry Andric   };
708e8d8bef9SDimitry Andric 
709fe6060f1SDimitry Andric #ifndef NDEBUG
710fe6060f1SDimitry Andric   using VarVec = SmallVector<VarLoc, 32>;
711fe6060f1SDimitry Andric #endif
712fe6060f1SDimitry Andric 
713e8d8bef9SDimitry Andric   /// VarLocMap is used for two things:
714fe6060f1SDimitry Andric   /// 1) Assigning LocIndices to a VarLoc. The LocIndices can be used to
715e8d8bef9SDimitry Andric   ///    virtually insert a VarLoc into a VarLocSet.
716e8d8bef9SDimitry Andric   /// 2) Given a LocIndex, look up the unique associated VarLoc.
717e8d8bef9SDimitry Andric   class VarLocMap {
718e8d8bef9SDimitry Andric     /// Map a VarLoc to an index within the vector reserved for its location
719e8d8bef9SDimitry Andric     /// within Loc2Vars.
720fe6060f1SDimitry Andric     std::map<VarLoc, LocIndices> Var2Indices;
721e8d8bef9SDimitry Andric 
722e8d8bef9SDimitry Andric     /// Map a location to a vector which holds VarLocs which live in that
723e8d8bef9SDimitry Andric     /// location.
724e8d8bef9SDimitry Andric     SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars;
725e8d8bef9SDimitry Andric 
726fe6060f1SDimitry Andric   public:
727fe6060f1SDimitry Andric     /// Retrieve LocIndices for \p VL.
728fe6060f1SDimitry Andric     LocIndices insert(const VarLoc &VL) {
729fe6060f1SDimitry Andric       LocIndices &Indices = Var2Indices[VL];
730fe6060f1SDimitry Andric       // If Indices is not empty, VL is already in the map.
731fe6060f1SDimitry Andric       if (!Indices.empty())
732fe6060f1SDimitry Andric         return Indices;
733fe6060f1SDimitry Andric       SmallVector<LocIndex::u32_location_t, 4> Locations;
734fe6060f1SDimitry Andric       // LocIndices are determined by EVKind and MLs; each Register has a
735fe6060f1SDimitry Andric       // unique location, while all SpillLocs use a single bucket, and any EV
736fe6060f1SDimitry Andric       // VarLocs use only the Backup bucket or none at all (except the
737fe6060f1SDimitry Andric       // compulsory entry at the universal location index). LocIndices will
738fe6060f1SDimitry Andric       // always have an index at the universal location index as the last index.
739fe6060f1SDimitry Andric       if (VL.EVKind == VarLoc::EntryValueLocKind::NonEntryValueKind) {
740fe6060f1SDimitry Andric         VL.getDescribingRegs(Locations);
741fe6060f1SDimitry Andric         assert(all_of(Locations,
742fe6060f1SDimitry Andric                       [](auto RegNo) {
743fe6060f1SDimitry Andric                         return RegNo < LocIndex::kFirstInvalidRegLocation;
744fe6060f1SDimitry Andric                       }) &&
745e8d8bef9SDimitry Andric                "Physreg out of range?");
746fe6060f1SDimitry Andric         if (VL.containsSpillLocs()) {
747fe6060f1SDimitry Andric           LocIndex::u32_location_t Loc = LocIndex::kSpillLocation;
748fe6060f1SDimitry Andric           Locations.push_back(Loc);
749e8d8bef9SDimitry Andric         }
750fe6060f1SDimitry Andric       } else if (VL.EVKind != VarLoc::EntryValueLocKind::EntryValueKind) {
751fe6060f1SDimitry Andric         LocIndex::u32_location_t Loc = LocIndex::kEntryValueBackupLocation;
752fe6060f1SDimitry Andric         Locations.push_back(Loc);
753fe6060f1SDimitry Andric       }
754fe6060f1SDimitry Andric       Locations.push_back(LocIndex::kUniversalLocation);
755fe6060f1SDimitry Andric       for (LocIndex::u32_location_t Location : Locations) {
756fe6060f1SDimitry Andric         auto &Vars = Loc2Vars[Location];
757fe6060f1SDimitry Andric         Indices.push_back(
758fe6060f1SDimitry Andric             {Location, static_cast<LocIndex::u32_index_t>(Vars.size())});
759fe6060f1SDimitry Andric         Vars.push_back(VL);
760fe6060f1SDimitry Andric       }
761fe6060f1SDimitry Andric       return Indices;
762e8d8bef9SDimitry Andric     }
763e8d8bef9SDimitry Andric 
764fe6060f1SDimitry Andric     LocIndices getAllIndices(const VarLoc &VL) const {
765fe6060f1SDimitry Andric       auto IndIt = Var2Indices.find(VL);
766fe6060f1SDimitry Andric       assert(IndIt != Var2Indices.end() && "VarLoc not tracked");
767fe6060f1SDimitry Andric       return IndIt->second;
768e8d8bef9SDimitry Andric     }
769e8d8bef9SDimitry Andric 
770e8d8bef9SDimitry Andric     /// Retrieve the unique VarLoc associated with \p ID.
771e8d8bef9SDimitry Andric     const VarLoc &operator[](LocIndex ID) const {
772e8d8bef9SDimitry Andric       auto LocIt = Loc2Vars.find(ID.Location);
773e8d8bef9SDimitry Andric       assert(LocIt != Loc2Vars.end() && "Location not tracked");
774e8d8bef9SDimitry Andric       return LocIt->second[ID.Index];
775e8d8bef9SDimitry Andric     }
776e8d8bef9SDimitry Andric   };
777e8d8bef9SDimitry Andric 
778e8d8bef9SDimitry Andric   using VarLocInMBB =
779e8d8bef9SDimitry Andric       SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>;
780e8d8bef9SDimitry Andric   struct TransferDebugPair {
781e8d8bef9SDimitry Andric     MachineInstr *TransferInst; ///< Instruction where this transfer occurs.
782e8d8bef9SDimitry Andric     LocIndex LocationID;        ///< Location number for the transfer dest.
783e8d8bef9SDimitry Andric   };
784e8d8bef9SDimitry Andric   using TransferMap = SmallVector<TransferDebugPair, 4>;
785349cc55cSDimitry Andric   // Types for recording Entry Var Locations emitted by a single MachineInstr,
786349cc55cSDimitry Andric   // as well as recording MachineInstr which last defined a register.
787349cc55cSDimitry Andric   using InstToEntryLocMap = std::multimap<const MachineInstr *, LocIndex>;
788349cc55cSDimitry Andric   using RegDefToInstMap = DenseMap<Register, MachineInstr *>;
789e8d8bef9SDimitry Andric 
790e8d8bef9SDimitry Andric   // Types for recording sets of variable fragments that overlap. For a given
791e8d8bef9SDimitry Andric   // local variable, we record all other fragments of that variable that could
792e8d8bef9SDimitry Andric   // overlap it, to reduce search time.
793e8d8bef9SDimitry Andric   using FragmentOfVar =
794e8d8bef9SDimitry Andric       std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
795e8d8bef9SDimitry Andric   using OverlapMap =
796e8d8bef9SDimitry Andric       DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
797e8d8bef9SDimitry Andric 
798e8d8bef9SDimitry Andric   // Helper while building OverlapMap, a map of all fragments seen for a given
799e8d8bef9SDimitry Andric   // DILocalVariable.
800e8d8bef9SDimitry Andric   using VarToFragments =
801e8d8bef9SDimitry Andric       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
802e8d8bef9SDimitry Andric 
803fe6060f1SDimitry Andric   /// Collects all VarLocs from \p CollectFrom. Each unique VarLoc is added
804fe6060f1SDimitry Andric   /// to \p Collected once, in order of insertion into \p VarLocIDs.
805fe6060f1SDimitry Andric   static void collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
806fe6060f1SDimitry Andric                                 const VarLocSet &CollectFrom,
807fe6060f1SDimitry Andric                                 const VarLocMap &VarLocIDs);
808fe6060f1SDimitry Andric 
809fe6060f1SDimitry Andric   /// Get the registers which are used by VarLocs of kind RegisterKind tracked
810fe6060f1SDimitry Andric   /// by \p CollectFrom.
811fe6060f1SDimitry Andric   void getUsedRegs(const VarLocSet &CollectFrom,
812fe6060f1SDimitry Andric                    SmallVectorImpl<Register> &UsedRegs) const;
813fe6060f1SDimitry Andric 
814e8d8bef9SDimitry Andric   /// This holds the working set of currently open ranges. For fast
815e8d8bef9SDimitry Andric   /// access, this is done both as a set of VarLocIDs, and a map of
816e8d8bef9SDimitry Andric   /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
817e8d8bef9SDimitry Andric   /// previous open ranges for the same variable. In addition, we keep
818e8d8bef9SDimitry Andric   /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
819e8d8bef9SDimitry Andric   /// methods act differently depending on whether a VarLoc is primary
820e8d8bef9SDimitry Andric   /// location or backup one. In the case the VarLoc is backup location
821e8d8bef9SDimitry Andric   /// we will erase/insert from the EntryValuesBackupVars map, otherwise
822e8d8bef9SDimitry Andric   /// we perform the operation on the Vars.
823e8d8bef9SDimitry Andric   class OpenRangesSet {
824fe6060f1SDimitry Andric     VarLocSet::Allocator &Alloc;
825e8d8bef9SDimitry Andric     VarLocSet VarLocs;
826e8d8bef9SDimitry Andric     // Map the DebugVariable to recent primary location ID.
827fe6060f1SDimitry Andric     SmallDenseMap<DebugVariable, LocIndices, 8> Vars;
828e8d8bef9SDimitry Andric     // Map the DebugVariable to recent backup location ID.
829fe6060f1SDimitry Andric     SmallDenseMap<DebugVariable, LocIndices, 8> EntryValuesBackupVars;
830e8d8bef9SDimitry Andric     OverlapMap &OverlappingFragments;
831e8d8bef9SDimitry Andric 
832e8d8bef9SDimitry Andric   public:
833e8d8bef9SDimitry Andric     OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
834fe6060f1SDimitry Andric         : Alloc(Alloc), VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
835e8d8bef9SDimitry Andric 
836e8d8bef9SDimitry Andric     const VarLocSet &getVarLocs() const { return VarLocs; }
837e8d8bef9SDimitry Andric 
838fe6060f1SDimitry Andric     // Fetches all VarLocs in \p VarLocIDs and inserts them into \p Collected.
839fe6060f1SDimitry Andric     // This method is needed to get every VarLoc once, as each VarLoc may have
840fe6060f1SDimitry Andric     // multiple indices in a VarLocMap (corresponding to each applicable
841fe6060f1SDimitry Andric     // location), but all VarLocs appear exactly once at the universal location
842fe6060f1SDimitry Andric     // index.
843fe6060f1SDimitry Andric     void getUniqueVarLocs(SmallVectorImpl<VarLoc> &Collected,
844fe6060f1SDimitry Andric                           const VarLocMap &VarLocIDs) const {
845fe6060f1SDimitry Andric       collectAllVarLocs(Collected, VarLocs, VarLocIDs);
846fe6060f1SDimitry Andric     }
847fe6060f1SDimitry Andric 
848e8d8bef9SDimitry Andric     /// Terminate all open ranges for VL.Var by removing it from the set.
849e8d8bef9SDimitry Andric     void erase(const VarLoc &VL);
850e8d8bef9SDimitry Andric 
851fe6060f1SDimitry Andric     /// Terminate all open ranges listed as indices in \c KillSet with
852fe6060f1SDimitry Andric     /// \c Location by removing them from the set.
853fe6060f1SDimitry Andric     void erase(const VarLocsInRange &KillSet, const VarLocMap &VarLocIDs,
854fe6060f1SDimitry Andric                LocIndex::u32_location_t Location);
855e8d8bef9SDimitry Andric 
856e8d8bef9SDimitry Andric     /// Insert a new range into the set.
857fe6060f1SDimitry Andric     void insert(LocIndices VarLocIDs, const VarLoc &VL);
858e8d8bef9SDimitry Andric 
859e8d8bef9SDimitry Andric     /// Insert a set of ranges.
860fe6060f1SDimitry Andric     void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map);
861e8d8bef9SDimitry Andric 
862fe6060f1SDimitry Andric     llvm::Optional<LocIndices> getEntryValueBackup(DebugVariable Var);
863e8d8bef9SDimitry Andric 
864e8d8bef9SDimitry Andric     /// Empty the set.
865e8d8bef9SDimitry Andric     void clear() {
866e8d8bef9SDimitry Andric       VarLocs.clear();
867e8d8bef9SDimitry Andric       Vars.clear();
868e8d8bef9SDimitry Andric       EntryValuesBackupVars.clear();
869e8d8bef9SDimitry Andric     }
870e8d8bef9SDimitry Andric 
871e8d8bef9SDimitry Andric     /// Return whether the set is empty or not.
872e8d8bef9SDimitry Andric     bool empty() const {
873e8d8bef9SDimitry Andric       assert(Vars.empty() == EntryValuesBackupVars.empty() &&
874e8d8bef9SDimitry Andric              Vars.empty() == VarLocs.empty() &&
875e8d8bef9SDimitry Andric              "open ranges are inconsistent");
876e8d8bef9SDimitry Andric       return VarLocs.empty();
877e8d8bef9SDimitry Andric     }
878e8d8bef9SDimitry Andric 
879e8d8bef9SDimitry Andric     /// Get an empty range of VarLoc IDs.
880e8d8bef9SDimitry Andric     auto getEmptyVarLocRange() const {
881e8d8bef9SDimitry Andric       return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(),
882e8d8bef9SDimitry Andric                                                        getVarLocs().end());
883e8d8bef9SDimitry Andric     }
884e8d8bef9SDimitry Andric 
885fe6060f1SDimitry Andric     /// Get all set IDs for VarLocs with MLs of kind RegisterKind in \p Reg.
886e8d8bef9SDimitry Andric     auto getRegisterVarLocs(Register Reg) const {
887e8d8bef9SDimitry Andric       return LocIndex::indexRangeForLocation(getVarLocs(), Reg);
888e8d8bef9SDimitry Andric     }
889e8d8bef9SDimitry Andric 
890fe6060f1SDimitry Andric     /// Get all set IDs for VarLocs with MLs of kind SpillLocKind.
891e8d8bef9SDimitry Andric     auto getSpillVarLocs() const {
892e8d8bef9SDimitry Andric       return LocIndex::indexRangeForLocation(getVarLocs(),
893e8d8bef9SDimitry Andric                                              LocIndex::kSpillLocation);
894e8d8bef9SDimitry Andric     }
895e8d8bef9SDimitry Andric 
896fe6060f1SDimitry Andric     /// Get all set IDs for VarLocs of EVKind EntryValueBackupKind or
897e8d8bef9SDimitry Andric     /// EntryValueCopyBackupKind.
898e8d8bef9SDimitry Andric     auto getEntryValueBackupVarLocs() const {
899e8d8bef9SDimitry Andric       return LocIndex::indexRangeForLocation(
900e8d8bef9SDimitry Andric           getVarLocs(), LocIndex::kEntryValueBackupLocation);
901e8d8bef9SDimitry Andric     }
902e8d8bef9SDimitry Andric   };
903e8d8bef9SDimitry Andric 
904fe6060f1SDimitry Andric   /// Collect all VarLoc IDs from \p CollectFrom for VarLocs with MLs of kind
905fe6060f1SDimitry Andric   /// RegisterKind which are located in any reg in \p Regs. The IDs for each
906fe6060f1SDimitry Andric   /// VarLoc correspond to entries in the universal location bucket, which every
907fe6060f1SDimitry Andric   /// VarLoc has exactly 1 entry for. Insert collected IDs into \p Collected.
908fe6060f1SDimitry Andric   static void collectIDsForRegs(VarLocsInRange &Collected,
909fe6060f1SDimitry Andric                                 const DefinedRegsSet &Regs,
910fe6060f1SDimitry Andric                                 const VarLocSet &CollectFrom,
911fe6060f1SDimitry Andric                                 const VarLocMap &VarLocIDs);
912e8d8bef9SDimitry Andric 
913e8d8bef9SDimitry Andric   VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
914e8d8bef9SDimitry Andric     std::unique_ptr<VarLocSet> &VLS = Locs[MBB];
915e8d8bef9SDimitry Andric     if (!VLS)
916e8d8bef9SDimitry Andric       VLS = std::make_unique<VarLocSet>(Alloc);
917*81ad6265SDimitry Andric     return *VLS;
918e8d8bef9SDimitry Andric   }
919e8d8bef9SDimitry Andric 
920e8d8bef9SDimitry Andric   const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
921e8d8bef9SDimitry Andric                                    const VarLocInMBB &Locs) const {
922e8d8bef9SDimitry Andric     auto It = Locs.find(MBB);
923e8d8bef9SDimitry Andric     assert(It != Locs.end() && "MBB not in map");
924*81ad6265SDimitry Andric     return *It->second;
925e8d8bef9SDimitry Andric   }
926e8d8bef9SDimitry Andric 
927e8d8bef9SDimitry Andric   /// Tests whether this instruction is a spill to a stack location.
928e8d8bef9SDimitry Andric   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
929e8d8bef9SDimitry Andric 
930e8d8bef9SDimitry Andric   /// Decide if @MI is a spill instruction and return true if it is. We use 2
931e8d8bef9SDimitry Andric   /// criteria to make this decision:
932e8d8bef9SDimitry Andric   /// - Is this instruction a store to a spill slot?
933e8d8bef9SDimitry Andric   /// - Is there a register operand that is both used and killed?
934e8d8bef9SDimitry Andric   /// TODO: Store optimization can fold spills into other stores (including
935e8d8bef9SDimitry Andric   /// other spills). We do not handle this yet (more than one memory operand).
936e8d8bef9SDimitry Andric   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
937e8d8bef9SDimitry Andric                        Register &Reg);
938e8d8bef9SDimitry Andric 
939e8d8bef9SDimitry Andric   /// Returns true if the given machine instruction is a debug value which we
940e8d8bef9SDimitry Andric   /// can emit entry values for.
941e8d8bef9SDimitry Andric   ///
942e8d8bef9SDimitry Andric   /// Currently, we generate debug entry values only for parameters that are
943e8d8bef9SDimitry Andric   /// unmodified throughout the function and located in a register.
944e8d8bef9SDimitry Andric   bool isEntryValueCandidate(const MachineInstr &MI,
945e8d8bef9SDimitry Andric                              const DefinedRegsSet &Regs) const;
946e8d8bef9SDimitry Andric 
947e8d8bef9SDimitry Andric   /// If a given instruction is identified as a spill, return the spill location
948e8d8bef9SDimitry Andric   /// and set \p Reg to the spilled register.
949e8d8bef9SDimitry Andric   Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
950e8d8bef9SDimitry Andric                                                   MachineFunction *MF,
951e8d8bef9SDimitry Andric                                                   Register &Reg);
952e8d8bef9SDimitry Andric   /// Given a spill instruction, extract the register and offset used to
953e8d8bef9SDimitry Andric   /// address the spill location in a target independent way.
954e8d8bef9SDimitry Andric   VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
955e8d8bef9SDimitry Andric   void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
956e8d8bef9SDimitry Andric                                TransferMap &Transfers, VarLocMap &VarLocIDs,
957e8d8bef9SDimitry Andric                                LocIndex OldVarID, TransferKind Kind,
958fe6060f1SDimitry Andric                                const VarLoc::MachineLoc &OldLoc,
959e8d8bef9SDimitry Andric                                Register NewReg = Register());
960e8d8bef9SDimitry Andric 
961e8d8bef9SDimitry Andric   void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
962349cc55cSDimitry Andric                           VarLocMap &VarLocIDs,
963349cc55cSDimitry Andric                           InstToEntryLocMap &EntryValTransfers,
964349cc55cSDimitry Andric                           RegDefToInstMap &RegSetInstrs);
965e8d8bef9SDimitry Andric   void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
966e8d8bef9SDimitry Andric                                   VarLocMap &VarLocIDs, TransferMap &Transfers);
967349cc55cSDimitry Andric   void cleanupEntryValueTransfers(const MachineInstr *MI,
968349cc55cSDimitry Andric                                   OpenRangesSet &OpenRanges,
969349cc55cSDimitry Andric                                   VarLocMap &VarLocIDs, const VarLoc &EntryVL,
970349cc55cSDimitry Andric                                   InstToEntryLocMap &EntryValTransfers);
971349cc55cSDimitry Andric   void removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
972349cc55cSDimitry Andric                         VarLocMap &VarLocIDs, const VarLoc &EntryVL,
973349cc55cSDimitry Andric                         InstToEntryLocMap &EntryValTransfers,
974349cc55cSDimitry Andric                         RegDefToInstMap &RegSetInstrs);
975e8d8bef9SDimitry Andric   void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
976349cc55cSDimitry Andric                        VarLocMap &VarLocIDs,
977349cc55cSDimitry Andric                        InstToEntryLocMap &EntryValTransfers,
978fe6060f1SDimitry Andric                        VarLocsInRange &KillSet);
979e8d8bef9SDimitry Andric   void recordEntryValue(const MachineInstr &MI,
980e8d8bef9SDimitry Andric                         const DefinedRegsSet &DefinedRegs,
981e8d8bef9SDimitry Andric                         OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
982e8d8bef9SDimitry Andric   void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
983e8d8bef9SDimitry Andric                             VarLocMap &VarLocIDs, TransferMap &Transfers);
984e8d8bef9SDimitry Andric   void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
985349cc55cSDimitry Andric                            VarLocMap &VarLocIDs,
986349cc55cSDimitry Andric                            InstToEntryLocMap &EntryValTransfers,
987349cc55cSDimitry Andric                            RegDefToInstMap &RegSetInstrs);
988e8d8bef9SDimitry Andric   bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
989e8d8bef9SDimitry Andric                           VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
990e8d8bef9SDimitry Andric 
991e8d8bef9SDimitry Andric   void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
992349cc55cSDimitry Andric                VarLocMap &VarLocIDs, TransferMap &Transfers,
993349cc55cSDimitry Andric                InstToEntryLocMap &EntryValTransfers,
994349cc55cSDimitry Andric                RegDefToInstMap &RegSetInstrs);
995e8d8bef9SDimitry Andric 
996e8d8bef9SDimitry Andric   void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
997e8d8bef9SDimitry Andric                              OverlapMap &OLapMap);
998e8d8bef9SDimitry Andric 
999e8d8bef9SDimitry Andric   bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1000e8d8bef9SDimitry Andric             const VarLocMap &VarLocIDs,
1001e8d8bef9SDimitry Andric             SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1002e8d8bef9SDimitry Andric             SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
1003e8d8bef9SDimitry Andric 
1004e8d8bef9SDimitry Andric   /// Create DBG_VALUE insts for inlocs that have been propagated but
1005e8d8bef9SDimitry Andric   /// had their instruction creation deferred.
1006e8d8bef9SDimitry Andric   void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
1007e8d8bef9SDimitry Andric 
1008349cc55cSDimitry Andric   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1009349cc55cSDimitry Andric                     TargetPassConfig *TPC, unsigned InputBBLimit,
1010349cc55cSDimitry Andric                     unsigned InputDbgValLimit) override;
1011e8d8bef9SDimitry Andric 
1012e8d8bef9SDimitry Andric public:
1013e8d8bef9SDimitry Andric   /// Default construct and initialize the pass.
1014e8d8bef9SDimitry Andric   VarLocBasedLDV();
1015e8d8bef9SDimitry Andric 
1016e8d8bef9SDimitry Andric   ~VarLocBasedLDV();
1017e8d8bef9SDimitry Andric 
1018e8d8bef9SDimitry Andric   /// Print to ostream with a message.
1019e8d8bef9SDimitry Andric   void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
1020e8d8bef9SDimitry Andric                         const VarLocMap &VarLocIDs, const char *msg,
1021e8d8bef9SDimitry Andric                         raw_ostream &Out) const;
1022e8d8bef9SDimitry Andric };
1023e8d8bef9SDimitry Andric 
1024e8d8bef9SDimitry Andric } // end anonymous namespace
1025e8d8bef9SDimitry Andric 
1026e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1027e8d8bef9SDimitry Andric //            Implementation
1028e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1029e8d8bef9SDimitry Andric 
1030*81ad6265SDimitry Andric VarLocBasedLDV::VarLocBasedLDV() = default;
1031e8d8bef9SDimitry Andric 
1032*81ad6265SDimitry Andric VarLocBasedLDV::~VarLocBasedLDV() = default;
1033e8d8bef9SDimitry Andric 
1034e8d8bef9SDimitry Andric /// Erase a variable from the set of open ranges, and additionally erase any
1035e8d8bef9SDimitry Andric /// fragments that may overlap it. If the VarLoc is a backup location, erase
1036e8d8bef9SDimitry Andric /// the variable from the EntryValuesBackupVars set, indicating we should stop
1037e8d8bef9SDimitry Andric /// tracking its backup entry location. Otherwise, if the VarLoc is primary
1038e8d8bef9SDimitry Andric /// location, erase the variable from the Vars set.
1039e8d8bef9SDimitry Andric void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) {
1040e8d8bef9SDimitry Andric   // Erasure helper.
1041e8d8bef9SDimitry Andric   auto DoErase = [VL, this](DebugVariable VarToErase) {
1042e8d8bef9SDimitry Andric     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1043e8d8bef9SDimitry Andric     auto It = EraseFrom->find(VarToErase);
1044e8d8bef9SDimitry Andric     if (It != EraseFrom->end()) {
1045fe6060f1SDimitry Andric       LocIndices IDs = It->second;
1046fe6060f1SDimitry Andric       for (LocIndex ID : IDs)
1047e8d8bef9SDimitry Andric         VarLocs.reset(ID.getAsRawInteger());
1048e8d8bef9SDimitry Andric       EraseFrom->erase(It);
1049e8d8bef9SDimitry Andric     }
1050e8d8bef9SDimitry Andric   };
1051e8d8bef9SDimitry Andric 
1052e8d8bef9SDimitry Andric   DebugVariable Var = VL.Var;
1053e8d8bef9SDimitry Andric 
1054e8d8bef9SDimitry Andric   // Erase the variable/fragment that ends here.
1055e8d8bef9SDimitry Andric   DoErase(Var);
1056e8d8bef9SDimitry Andric 
1057e8d8bef9SDimitry Andric   // Extract the fragment. Interpret an empty fragment as one that covers all
1058e8d8bef9SDimitry Andric   // possible bits.
1059e8d8bef9SDimitry Andric   FragmentInfo ThisFragment = Var.getFragmentOrDefault();
1060e8d8bef9SDimitry Andric 
1061e8d8bef9SDimitry Andric   // There may be fragments that overlap the designated fragment. Look them up
1062e8d8bef9SDimitry Andric   // in the pre-computed overlap map, and erase them too.
1063e8d8bef9SDimitry Andric   auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
1064e8d8bef9SDimitry Andric   if (MapIt != OverlappingFragments.end()) {
1065e8d8bef9SDimitry Andric     for (auto Fragment : MapIt->second) {
1066e8d8bef9SDimitry Andric       VarLocBasedLDV::OptFragmentInfo FragmentHolder;
1067e8d8bef9SDimitry Andric       if (!DebugVariable::isDefaultFragment(Fragment))
1068e8d8bef9SDimitry Andric         FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment);
1069e8d8bef9SDimitry Andric       DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
1070e8d8bef9SDimitry Andric     }
1071e8d8bef9SDimitry Andric   }
1072e8d8bef9SDimitry Andric }
1073e8d8bef9SDimitry Andric 
1074fe6060f1SDimitry Andric void VarLocBasedLDV::OpenRangesSet::erase(const VarLocsInRange &KillSet,
1075fe6060f1SDimitry Andric                                           const VarLocMap &VarLocIDs,
1076fe6060f1SDimitry Andric                                           LocIndex::u32_location_t Location) {
1077fe6060f1SDimitry Andric   VarLocSet RemoveSet(Alloc);
1078fe6060f1SDimitry Andric   for (LocIndex::u32_index_t ID : KillSet) {
1079fe6060f1SDimitry Andric     const VarLoc &VL = VarLocIDs[LocIndex(Location, ID)];
1080fe6060f1SDimitry Andric     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1081fe6060f1SDimitry Andric     EraseFrom->erase(VL.Var);
1082fe6060f1SDimitry Andric     LocIndices VLI = VarLocIDs.getAllIndices(VL);
1083fe6060f1SDimitry Andric     for (LocIndex ID : VLI)
1084fe6060f1SDimitry Andric       RemoveSet.set(ID.getAsRawInteger());
1085fe6060f1SDimitry Andric   }
1086fe6060f1SDimitry Andric   VarLocs.intersectWithComplement(RemoveSet);
1087fe6060f1SDimitry Andric }
1088fe6060f1SDimitry Andric 
1089fe6060f1SDimitry Andric void VarLocBasedLDV::OpenRangesSet::insertFromLocSet(const VarLocSet &ToLoad,
1090fe6060f1SDimitry Andric                                                      const VarLocMap &Map) {
1091fe6060f1SDimitry Andric   VarLocsInRange UniqueVarLocIDs;
1092fe6060f1SDimitry Andric   DefinedRegsSet Regs;
1093fe6060f1SDimitry Andric   Regs.insert(LocIndex::kUniversalLocation);
1094fe6060f1SDimitry Andric   collectIDsForRegs(UniqueVarLocIDs, Regs, ToLoad, Map);
1095fe6060f1SDimitry Andric   for (uint64_t ID : UniqueVarLocIDs) {
1096fe6060f1SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1097fe6060f1SDimitry Andric     const VarLoc &VarL = Map[Idx];
1098fe6060f1SDimitry Andric     const LocIndices Indices = Map.getAllIndices(VarL);
1099fe6060f1SDimitry Andric     insert(Indices, VarL);
1100e8d8bef9SDimitry Andric   }
1101e8d8bef9SDimitry Andric }
1102e8d8bef9SDimitry Andric 
1103fe6060f1SDimitry Andric void VarLocBasedLDV::OpenRangesSet::insert(LocIndices VarLocIDs,
1104e8d8bef9SDimitry Andric                                            const VarLoc &VL) {
1105e8d8bef9SDimitry Andric   auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1106fe6060f1SDimitry Andric   for (LocIndex ID : VarLocIDs)
1107fe6060f1SDimitry Andric     VarLocs.set(ID.getAsRawInteger());
1108fe6060f1SDimitry Andric   InsertInto->insert({VL.Var, VarLocIDs});
1109e8d8bef9SDimitry Andric }
1110e8d8bef9SDimitry Andric 
1111e8d8bef9SDimitry Andric /// Return the Loc ID of an entry value backup location, if it exists for the
1112e8d8bef9SDimitry Andric /// variable.
1113fe6060f1SDimitry Andric llvm::Optional<LocIndices>
1114e8d8bef9SDimitry Andric VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
1115e8d8bef9SDimitry Andric   auto It = EntryValuesBackupVars.find(Var);
1116e8d8bef9SDimitry Andric   if (It != EntryValuesBackupVars.end())
1117e8d8bef9SDimitry Andric     return It->second;
1118e8d8bef9SDimitry Andric 
1119e8d8bef9SDimitry Andric   return llvm::None;
1120e8d8bef9SDimitry Andric }
1121e8d8bef9SDimitry Andric 
1122fe6060f1SDimitry Andric void VarLocBasedLDV::collectIDsForRegs(VarLocsInRange &Collected,
1123e8d8bef9SDimitry Andric                                        const DefinedRegsSet &Regs,
1124fe6060f1SDimitry Andric                                        const VarLocSet &CollectFrom,
1125fe6060f1SDimitry Andric                                        const VarLocMap &VarLocIDs) {
1126e8d8bef9SDimitry Andric   assert(!Regs.empty() && "Nothing to collect");
1127fe6060f1SDimitry Andric   SmallVector<Register, 32> SortedRegs;
1128fe6060f1SDimitry Andric   append_range(SortedRegs, Regs);
1129e8d8bef9SDimitry Andric   array_pod_sort(SortedRegs.begin(), SortedRegs.end());
1130e8d8bef9SDimitry Andric   auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front()));
1131e8d8bef9SDimitry Andric   auto End = CollectFrom.end();
1132fe6060f1SDimitry Andric   for (Register Reg : SortedRegs) {
1133fe6060f1SDimitry Andric     // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains
1134fe6060f1SDimitry Andric     // all possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which
1135fe6060f1SDimitry Andric     // live in Reg.
1136e8d8bef9SDimitry Andric     uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
1137e8d8bef9SDimitry Andric     uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
1138e8d8bef9SDimitry Andric     It.advanceToLowerBound(FirstIndexForReg);
1139e8d8bef9SDimitry Andric 
1140e8d8bef9SDimitry Andric     // Iterate through that half-open interval and collect all the set IDs.
1141fe6060f1SDimitry Andric     for (; It != End && *It < FirstInvalidIndex; ++It) {
1142fe6060f1SDimitry Andric       LocIndex ItIdx = LocIndex::fromRawInteger(*It);
1143fe6060f1SDimitry Andric       const VarLoc &VL = VarLocIDs[ItIdx];
1144fe6060f1SDimitry Andric       LocIndices LI = VarLocIDs.getAllIndices(VL);
1145fe6060f1SDimitry Andric       // For now, the back index is always the universal location index.
1146fe6060f1SDimitry Andric       assert(LI.back().Location == LocIndex::kUniversalLocation &&
1147fe6060f1SDimitry Andric              "Unexpected order of LocIndices for VarLoc; was it inserted into "
1148fe6060f1SDimitry Andric              "the VarLocMap correctly?");
1149fe6060f1SDimitry Andric       Collected.insert(LI.back().Index);
1150fe6060f1SDimitry Andric     }
1151e8d8bef9SDimitry Andric 
1152e8d8bef9SDimitry Andric     if (It == End)
1153e8d8bef9SDimitry Andric       return;
1154e8d8bef9SDimitry Andric   }
1155e8d8bef9SDimitry Andric }
1156e8d8bef9SDimitry Andric 
1157e8d8bef9SDimitry Andric void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom,
1158fe6060f1SDimitry Andric                                  SmallVectorImpl<Register> &UsedRegs) const {
1159e8d8bef9SDimitry Andric   // All register-based VarLocs are assigned indices greater than or equal to
1160e8d8bef9SDimitry Andric   // FirstRegIndex.
1161fe6060f1SDimitry Andric   uint64_t FirstRegIndex =
1162fe6060f1SDimitry Andric       LocIndex::rawIndexForReg(LocIndex::kFirstRegLocation);
1163e8d8bef9SDimitry Andric   uint64_t FirstInvalidIndex =
1164e8d8bef9SDimitry Andric       LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation);
1165e8d8bef9SDimitry Andric   for (auto It = CollectFrom.find(FirstRegIndex),
1166e8d8bef9SDimitry Andric             End = CollectFrom.find(FirstInvalidIndex);
1167e8d8bef9SDimitry Andric        It != End;) {
1168e8d8bef9SDimitry Andric     // We found a VarLoc ID for a VarLoc that lives in a register. Figure out
1169e8d8bef9SDimitry Andric     // which register and add it to UsedRegs.
1170e8d8bef9SDimitry Andric     uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
1171e8d8bef9SDimitry Andric     assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
1172e8d8bef9SDimitry Andric            "Duplicate used reg");
1173e8d8bef9SDimitry Andric     UsedRegs.push_back(FoundReg);
1174e8d8bef9SDimitry Andric 
1175e8d8bef9SDimitry Andric     // Skip to the next /set/ register. Note that this finds a lower bound, so
1176e8d8bef9SDimitry Andric     // even if there aren't any VarLocs living in `FoundReg+1`, we're still
1177e8d8bef9SDimitry Andric     // guaranteed to move on to the next register (or to end()).
1178e8d8bef9SDimitry Andric     uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
1179e8d8bef9SDimitry Andric     It.advanceToLowerBound(NextRegIndex);
1180e8d8bef9SDimitry Andric   }
1181e8d8bef9SDimitry Andric }
1182e8d8bef9SDimitry Andric 
1183e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1184e8d8bef9SDimitry Andric //            Debug Range Extension Implementation
1185e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1186e8d8bef9SDimitry Andric 
1187e8d8bef9SDimitry Andric #ifndef NDEBUG
1188e8d8bef9SDimitry Andric void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF,
1189e8d8bef9SDimitry Andric                                        const VarLocInMBB &V,
1190e8d8bef9SDimitry Andric                                        const VarLocMap &VarLocIDs,
1191e8d8bef9SDimitry Andric                                        const char *msg,
1192e8d8bef9SDimitry Andric                                        raw_ostream &Out) const {
1193e8d8bef9SDimitry Andric   Out << '\n' << msg << '\n';
1194e8d8bef9SDimitry Andric   for (const MachineBasicBlock &BB : MF) {
1195e8d8bef9SDimitry Andric     if (!V.count(&BB))
1196e8d8bef9SDimitry Andric       continue;
1197e8d8bef9SDimitry Andric     const VarLocSet &L = getVarLocsInMBB(&BB, V);
1198e8d8bef9SDimitry Andric     if (L.empty())
1199e8d8bef9SDimitry Andric       continue;
1200fe6060f1SDimitry Andric     SmallVector<VarLoc, 32> VarLocs;
1201fe6060f1SDimitry Andric     collectAllVarLocs(VarLocs, L, VarLocIDs);
1202e8d8bef9SDimitry Andric     Out << "MBB: " << BB.getNumber() << ":\n";
1203fe6060f1SDimitry Andric     for (const VarLoc &VL : VarLocs) {
1204e8d8bef9SDimitry Andric       Out << " Var: " << VL.Var.getVariable()->getName();
1205e8d8bef9SDimitry Andric       Out << " MI: ";
1206e8d8bef9SDimitry Andric       VL.dump(TRI, Out);
1207e8d8bef9SDimitry Andric     }
1208e8d8bef9SDimitry Andric   }
1209e8d8bef9SDimitry Andric   Out << "\n";
1210e8d8bef9SDimitry Andric }
1211e8d8bef9SDimitry Andric #endif
1212e8d8bef9SDimitry Andric 
1213e8d8bef9SDimitry Andric VarLocBasedLDV::VarLoc::SpillLoc
1214e8d8bef9SDimitry Andric VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1215e8d8bef9SDimitry Andric   assert(MI.hasOneMemOperand() &&
1216e8d8bef9SDimitry Andric          "Spill instruction does not have exactly one memory operand?");
1217e8d8bef9SDimitry Andric   auto MMOI = MI.memoperands_begin();
1218e8d8bef9SDimitry Andric   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1219e8d8bef9SDimitry Andric   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1220e8d8bef9SDimitry Andric          "Inconsistent memory operand in spill instruction");
1221e8d8bef9SDimitry Andric   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1222e8d8bef9SDimitry Andric   const MachineBasicBlock *MBB = MI.getParent();
1223e8d8bef9SDimitry Andric   Register Reg;
1224e8d8bef9SDimitry Andric   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1225e8d8bef9SDimitry Andric   return {Reg, Offset};
1226e8d8bef9SDimitry Andric }
1227e8d8bef9SDimitry Andric 
1228349cc55cSDimitry Andric /// Do cleanup of \p EntryValTransfers created by \p TRInst, by removing the
1229349cc55cSDimitry Andric /// Transfer, which uses the to-be-deleted \p EntryVL.
1230349cc55cSDimitry Andric void VarLocBasedLDV::cleanupEntryValueTransfers(
1231349cc55cSDimitry Andric     const MachineInstr *TRInst, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
1232349cc55cSDimitry Andric     const VarLoc &EntryVL, InstToEntryLocMap &EntryValTransfers) {
1233349cc55cSDimitry Andric   if (EntryValTransfers.empty() || TRInst == nullptr)
1234349cc55cSDimitry Andric     return;
1235349cc55cSDimitry Andric 
1236349cc55cSDimitry Andric   auto TransRange = EntryValTransfers.equal_range(TRInst);
1237349cc55cSDimitry Andric   for (auto TDPair : llvm::make_range(TransRange.first, TransRange.second)) {
1238349cc55cSDimitry Andric     const VarLoc &EmittedEV = VarLocIDs[TDPair.second];
1239349cc55cSDimitry Andric     if (std::tie(EntryVL.Var, EntryVL.Locs[0].Value.RegNo, EntryVL.Expr) ==
1240349cc55cSDimitry Andric         std::tie(EmittedEV.Var, EmittedEV.Locs[0].Value.RegNo,
1241349cc55cSDimitry Andric                  EmittedEV.Expr)) {
1242349cc55cSDimitry Andric       OpenRanges.erase(EmittedEV);
1243349cc55cSDimitry Andric       EntryValTransfers.erase(TRInst);
1244349cc55cSDimitry Andric       break;
1245349cc55cSDimitry Andric     }
1246349cc55cSDimitry Andric   }
1247349cc55cSDimitry Andric }
1248349cc55cSDimitry Andric 
1249e8d8bef9SDimitry Andric /// Try to salvage the debug entry value if we encounter a new debug value
1250e8d8bef9SDimitry Andric /// describing the same parameter, otherwise stop tracking the value. Return
1251349cc55cSDimitry Andric /// true if we should stop tracking the entry value and do the cleanup of
1252349cc55cSDimitry Andric /// emitted Entry Value Transfers, otherwise return false.
1253349cc55cSDimitry Andric void VarLocBasedLDV::removeEntryValue(const MachineInstr &MI,
1254e8d8bef9SDimitry Andric                                       OpenRangesSet &OpenRanges,
1255e8d8bef9SDimitry Andric                                       VarLocMap &VarLocIDs,
1256349cc55cSDimitry Andric                                       const VarLoc &EntryVL,
1257349cc55cSDimitry Andric                                       InstToEntryLocMap &EntryValTransfers,
1258349cc55cSDimitry Andric                                       RegDefToInstMap &RegSetInstrs) {
1259e8d8bef9SDimitry Andric   // Skip the DBG_VALUE which is the debug entry value itself.
1260349cc55cSDimitry Andric   if (&MI == &EntryVL.MI)
1261349cc55cSDimitry Andric     return;
1262e8d8bef9SDimitry Andric 
1263e8d8bef9SDimitry Andric   // If the parameter's location is not register location, we can not track
1264349cc55cSDimitry Andric   // the entry value any more. It doesn't have the TransferInst which defines
1265349cc55cSDimitry Andric   // register, so no Entry Value Transfers have been emitted already.
1266349cc55cSDimitry Andric   if (!MI.getDebugOperand(0).isReg())
1267349cc55cSDimitry Andric     return;
1268e8d8bef9SDimitry Andric 
1269349cc55cSDimitry Andric   // Try to get non-debug instruction responsible for the DBG_VALUE.
1270349cc55cSDimitry Andric   const MachineInstr *TransferInst = nullptr;
1271e8d8bef9SDimitry Andric   Register Reg = MI.getDebugOperand(0).getReg();
1272349cc55cSDimitry Andric   if (Reg.isValid() && RegSetInstrs.find(Reg) != RegSetInstrs.end())
1273349cc55cSDimitry Andric     TransferInst = RegSetInstrs.find(Reg)->second;
1274fe6060f1SDimitry Andric 
1275349cc55cSDimitry Andric   // Case of the parameter's DBG_VALUE at the start of entry MBB.
1276349cc55cSDimitry Andric   if (!TransferInst && !LastNonDbgMI && MI.getParent()->isEntryBlock())
1277349cc55cSDimitry Andric     return;
1278349cc55cSDimitry Andric 
1279349cc55cSDimitry Andric   // If the debug expression from the DBG_VALUE is not empty, we can assume the
1280349cc55cSDimitry Andric   // parameter's value has changed indicating that we should stop tracking its
1281349cc55cSDimitry Andric   // entry value as well.
1282349cc55cSDimitry Andric   if (MI.getDebugExpression()->getNumElements() == 0 && TransferInst) {
1283349cc55cSDimitry Andric     // If the DBG_VALUE comes from a copy instruction that copies the entry
1284349cc55cSDimitry Andric     // value, it means the parameter's value has not changed and we should be
1285349cc55cSDimitry Andric     // able to use its entry value.
1286e8d8bef9SDimitry Andric     // TODO: Try to keep tracking of an entry value if we encounter a propagated
1287e8d8bef9SDimitry Andric     // DBG_VALUE describing the copy of the entry value. (Propagated entry value
1288e8d8bef9SDimitry Andric     // does not indicate the parameter modification.)
1289349cc55cSDimitry Andric     auto DestSrc = TII->isCopyInstr(*TransferInst);
1290349cc55cSDimitry Andric     if (DestSrc) {
1291349cc55cSDimitry Andric       const MachineOperand *SrcRegOp, *DestRegOp;
1292e8d8bef9SDimitry Andric       SrcRegOp = DestSrc->Source;
1293e8d8bef9SDimitry Andric       DestRegOp = DestSrc->Destination;
1294349cc55cSDimitry Andric       if (Reg == DestRegOp->getReg()) {
1295e8d8bef9SDimitry Andric         for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1296e8d8bef9SDimitry Andric           const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
1297fe6060f1SDimitry Andric           if (VL.isEntryValueCopyBackupReg(Reg) &&
1298fe6060f1SDimitry Andric               // Entry Values should not be variadic.
1299e8d8bef9SDimitry Andric               VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg())
1300349cc55cSDimitry Andric             return;
1301349cc55cSDimitry Andric         }
1302349cc55cSDimitry Andric       }
1303e8d8bef9SDimitry Andric     }
1304e8d8bef9SDimitry Andric   }
1305e8d8bef9SDimitry Andric 
1306349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
1307349cc55cSDimitry Andric              MI.print(dbgs(), /*IsStandalone*/ false,
1308349cc55cSDimitry Andric                       /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
1309349cc55cSDimitry Andric                       /*AddNewLine*/ true, TII));
1310349cc55cSDimitry Andric   cleanupEntryValueTransfers(TransferInst, OpenRanges, VarLocIDs, EntryVL,
1311349cc55cSDimitry Andric                              EntryValTransfers);
1312349cc55cSDimitry Andric   OpenRanges.erase(EntryVL);
1313e8d8bef9SDimitry Andric }
1314e8d8bef9SDimitry Andric 
1315e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI
1316e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr.
1317e8d8bef9SDimitry Andric void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI,
1318e8d8bef9SDimitry Andric                                         OpenRangesSet &OpenRanges,
1319349cc55cSDimitry Andric                                         VarLocMap &VarLocIDs,
1320349cc55cSDimitry Andric                                         InstToEntryLocMap &EntryValTransfers,
1321349cc55cSDimitry Andric                                         RegDefToInstMap &RegSetInstrs) {
1322e8d8bef9SDimitry Andric   if (!MI.isDebugValue())
1323e8d8bef9SDimitry Andric     return;
1324e8d8bef9SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
1325e8d8bef9SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
1326e8d8bef9SDimitry Andric   const DILocation *DebugLoc = MI.getDebugLoc();
1327e8d8bef9SDimitry Andric   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1328e8d8bef9SDimitry Andric   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1329e8d8bef9SDimitry Andric          "Expected inlined-at fields to agree");
1330e8d8bef9SDimitry Andric 
1331e8d8bef9SDimitry Andric   DebugVariable V(Var, Expr, InlinedAt);
1332e8d8bef9SDimitry Andric 
1333e8d8bef9SDimitry Andric   // Check if this DBG_VALUE indicates a parameter's value changing.
1334e8d8bef9SDimitry Andric   // If that is the case, we should stop tracking its entry value.
1335e8d8bef9SDimitry Andric   auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
1336e8d8bef9SDimitry Andric   if (Var->isParameter() && EntryValBackupID) {
1337fe6060f1SDimitry Andric     const VarLoc &EntryVL = VarLocIDs[EntryValBackupID->back()];
1338349cc55cSDimitry Andric     removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL, EntryValTransfers,
1339349cc55cSDimitry Andric                      RegSetInstrs);
1340e8d8bef9SDimitry Andric   }
1341e8d8bef9SDimitry Andric 
1342fe6060f1SDimitry Andric   if (all_of(MI.debug_operands(), [](const MachineOperand &MO) {
1343fe6060f1SDimitry Andric         return (MO.isReg() && MO.getReg()) || MO.isImm() || MO.isFPImm() ||
1344fe6060f1SDimitry Andric                MO.isCImm();
1345fe6060f1SDimitry Andric       })) {
1346e8d8bef9SDimitry Andric     // Use normal VarLoc constructor for registers and immediates.
1347e8d8bef9SDimitry Andric     VarLoc VL(MI, LS);
1348e8d8bef9SDimitry Andric     // End all previous ranges of VL.Var.
1349e8d8bef9SDimitry Andric     OpenRanges.erase(VL);
1350e8d8bef9SDimitry Andric 
1351fe6060f1SDimitry Andric     LocIndices IDs = VarLocIDs.insert(VL);
1352e8d8bef9SDimitry Andric     // Add the VarLoc to OpenRanges from this DBG_VALUE.
1353fe6060f1SDimitry Andric     OpenRanges.insert(IDs, VL);
1354fe6060f1SDimitry Andric   } else if (MI.memoperands().size() > 0) {
1355e8d8bef9SDimitry Andric     llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
1356e8d8bef9SDimitry Andric   } else {
1357e8d8bef9SDimitry Andric     // This must be an undefined location. If it has an open range, erase it.
1358fe6060f1SDimitry Andric     assert(MI.isUndefDebugValue() &&
1359e8d8bef9SDimitry Andric            "Unexpected non-undef DBG_VALUE encountered");
1360e8d8bef9SDimitry Andric     VarLoc VL(MI, LS);
1361e8d8bef9SDimitry Andric     OpenRanges.erase(VL);
1362e8d8bef9SDimitry Andric   }
1363e8d8bef9SDimitry Andric }
1364e8d8bef9SDimitry Andric 
1365fe6060f1SDimitry Andric // This should be removed later, doesn't fit the new design.
1366fe6060f1SDimitry Andric void VarLocBasedLDV::collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
1367fe6060f1SDimitry Andric                                        const VarLocSet &CollectFrom,
1368fe6060f1SDimitry Andric                                        const VarLocMap &VarLocIDs) {
1369fe6060f1SDimitry Andric   // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all
1370fe6060f1SDimitry Andric   // possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which live
1371fe6060f1SDimitry Andric   // in Reg.
1372fe6060f1SDimitry Andric   uint64_t FirstIndex = LocIndex::rawIndexForReg(LocIndex::kUniversalLocation);
1373fe6060f1SDimitry Andric   uint64_t FirstInvalidIndex =
1374fe6060f1SDimitry Andric       LocIndex::rawIndexForReg(LocIndex::kUniversalLocation + 1);
1375fe6060f1SDimitry Andric   // Iterate through that half-open interval and collect all the set IDs.
1376fe6060f1SDimitry Andric   for (auto It = CollectFrom.find(FirstIndex), End = CollectFrom.end();
1377fe6060f1SDimitry Andric        It != End && *It < FirstInvalidIndex; ++It) {
1378fe6060f1SDimitry Andric     LocIndex RegIdx = LocIndex::fromRawInteger(*It);
1379fe6060f1SDimitry Andric     Collected.push_back(VarLocIDs[RegIdx]);
1380fe6060f1SDimitry Andric   }
1381fe6060f1SDimitry Andric }
1382fe6060f1SDimitry Andric 
1383e8d8bef9SDimitry Andric /// Turn the entry value backup locations into primary locations.
1384e8d8bef9SDimitry Andric void VarLocBasedLDV::emitEntryValues(MachineInstr &MI,
1385e8d8bef9SDimitry Andric                                      OpenRangesSet &OpenRanges,
1386e8d8bef9SDimitry Andric                                      VarLocMap &VarLocIDs,
1387349cc55cSDimitry Andric                                      InstToEntryLocMap &EntryValTransfers,
1388fe6060f1SDimitry Andric                                      VarLocsInRange &KillSet) {
1389e8d8bef9SDimitry Andric   // Do not insert entry value locations after a terminator.
1390e8d8bef9SDimitry Andric   if (MI.isTerminator())
1391e8d8bef9SDimitry Andric     return;
1392e8d8bef9SDimitry Andric 
1393fe6060f1SDimitry Andric   for (uint32_t ID : KillSet) {
1394fe6060f1SDimitry Andric     // The KillSet IDs are indices for the universal location bucket.
1395fe6060f1SDimitry Andric     LocIndex Idx = LocIndex(LocIndex::kUniversalLocation, ID);
1396e8d8bef9SDimitry Andric     const VarLoc &VL = VarLocIDs[Idx];
1397e8d8bef9SDimitry Andric     if (!VL.Var.getVariable()->isParameter())
1398e8d8bef9SDimitry Andric       continue;
1399e8d8bef9SDimitry Andric 
1400e8d8bef9SDimitry Andric     auto DebugVar = VL.Var;
1401fe6060f1SDimitry Andric     Optional<LocIndices> EntryValBackupIDs =
1402e8d8bef9SDimitry Andric         OpenRanges.getEntryValueBackup(DebugVar);
1403e8d8bef9SDimitry Andric 
1404e8d8bef9SDimitry Andric     // If the parameter has the entry value backup, it means we should
1405e8d8bef9SDimitry Andric     // be able to use its entry value.
1406fe6060f1SDimitry Andric     if (!EntryValBackupIDs)
1407e8d8bef9SDimitry Andric       continue;
1408e8d8bef9SDimitry Andric 
1409fe6060f1SDimitry Andric     const VarLoc &EntryVL = VarLocIDs[EntryValBackupIDs->back()];
1410fe6060f1SDimitry Andric     VarLoc EntryLoc = VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr,
1411fe6060f1SDimitry Andric                                              EntryVL.Locs[0].Value.RegNo);
1412fe6060f1SDimitry Andric     LocIndices EntryValueIDs = VarLocIDs.insert(EntryLoc);
1413349cc55cSDimitry Andric     assert(EntryValueIDs.size() == 1 &&
1414349cc55cSDimitry Andric            "EntryValue loc should not be variadic");
1415349cc55cSDimitry Andric     EntryValTransfers.insert({&MI, EntryValueIDs.back()});
1416fe6060f1SDimitry Andric     OpenRanges.insert(EntryValueIDs, EntryLoc);
1417e8d8bef9SDimitry Andric   }
1418e8d8bef9SDimitry Andric }
1419e8d8bef9SDimitry Andric 
1420e8d8bef9SDimitry Andric /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
1421e8d8bef9SDimitry Andric /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
1422e8d8bef9SDimitry Andric /// new VarLoc. If \p NewReg is different than default zero value then the
1423e8d8bef9SDimitry Andric /// new location will be register location created by the copy like instruction,
1424e8d8bef9SDimitry Andric /// otherwise it is variable's location on the stack.
1425e8d8bef9SDimitry Andric void VarLocBasedLDV::insertTransferDebugPair(
1426e8d8bef9SDimitry Andric     MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
1427e8d8bef9SDimitry Andric     VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
1428fe6060f1SDimitry Andric     const VarLoc::MachineLoc &OldLoc, Register NewReg) {
1429fe6060f1SDimitry Andric   const VarLoc &OldVarLoc = VarLocIDs[OldVarID];
1430e8d8bef9SDimitry Andric 
1431e8d8bef9SDimitry Andric   auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
1432fe6060f1SDimitry Andric     LocIndices LocIds = VarLocIDs.insert(VL);
1433e8d8bef9SDimitry Andric 
1434e8d8bef9SDimitry Andric     // Close this variable's previous location range.
1435e8d8bef9SDimitry Andric     OpenRanges.erase(VL);
1436e8d8bef9SDimitry Andric 
1437e8d8bef9SDimitry Andric     // Record the new location as an open range, and a postponed transfer
1438e8d8bef9SDimitry Andric     // inserting a DBG_VALUE for this location.
1439fe6060f1SDimitry Andric     OpenRanges.insert(LocIds, VL);
1440e8d8bef9SDimitry Andric     assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator");
1441fe6060f1SDimitry Andric     TransferDebugPair MIP = {&MI, LocIds.back()};
1442e8d8bef9SDimitry Andric     Transfers.push_back(MIP);
1443e8d8bef9SDimitry Andric   };
1444e8d8bef9SDimitry Andric 
1445e8d8bef9SDimitry Andric   // End all previous ranges of VL.Var.
1446e8d8bef9SDimitry Andric   OpenRanges.erase(VarLocIDs[OldVarID]);
1447e8d8bef9SDimitry Andric   switch (Kind) {
1448e8d8bef9SDimitry Andric   case TransferKind::TransferCopy: {
1449e8d8bef9SDimitry Andric     assert(NewReg &&
1450e8d8bef9SDimitry Andric            "No register supplied when handling a copy of a debug value");
1451e8d8bef9SDimitry Andric     // Create a DBG_VALUE instruction to describe the Var in its new
1452e8d8bef9SDimitry Andric     // register location.
1453fe6060f1SDimitry Andric     VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
1454e8d8bef9SDimitry Andric     ProcessVarLoc(VL);
1455e8d8bef9SDimitry Andric     LLVM_DEBUG({
1456e8d8bef9SDimitry Andric       dbgs() << "Creating VarLoc for register copy:";
1457e8d8bef9SDimitry Andric       VL.dump(TRI);
1458e8d8bef9SDimitry Andric     });
1459e8d8bef9SDimitry Andric     return;
1460e8d8bef9SDimitry Andric   }
1461e8d8bef9SDimitry Andric   case TransferKind::TransferSpill: {
1462e8d8bef9SDimitry Andric     // Create a DBG_VALUE instruction to describe the Var in its spilled
1463e8d8bef9SDimitry Andric     // location.
1464e8d8bef9SDimitry Andric     VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
1465fe6060f1SDimitry Andric     VarLoc VL = VarLoc::CreateSpillLoc(
1466fe6060f1SDimitry Andric         OldVarLoc, OldLoc, SpillLocation.SpillBase, SpillLocation.SpillOffset);
1467e8d8bef9SDimitry Andric     ProcessVarLoc(VL);
1468e8d8bef9SDimitry Andric     LLVM_DEBUG({
1469e8d8bef9SDimitry Andric       dbgs() << "Creating VarLoc for spill:";
1470e8d8bef9SDimitry Andric       VL.dump(TRI);
1471e8d8bef9SDimitry Andric     });
1472e8d8bef9SDimitry Andric     return;
1473e8d8bef9SDimitry Andric   }
1474e8d8bef9SDimitry Andric   case TransferKind::TransferRestore: {
1475e8d8bef9SDimitry Andric     assert(NewReg &&
1476e8d8bef9SDimitry Andric            "No register supplied when handling a restore of a debug value");
1477e8d8bef9SDimitry Andric     // DebugInstr refers to the pre-spill location, therefore we can reuse
1478e8d8bef9SDimitry Andric     // its expression.
1479fe6060f1SDimitry Andric     VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
1480e8d8bef9SDimitry Andric     ProcessVarLoc(VL);
1481e8d8bef9SDimitry Andric     LLVM_DEBUG({
1482e8d8bef9SDimitry Andric       dbgs() << "Creating VarLoc for restore:";
1483e8d8bef9SDimitry Andric       VL.dump(TRI);
1484e8d8bef9SDimitry Andric     });
1485e8d8bef9SDimitry Andric     return;
1486e8d8bef9SDimitry Andric   }
1487e8d8bef9SDimitry Andric   }
1488e8d8bef9SDimitry Andric   llvm_unreachable("Invalid transfer kind");
1489e8d8bef9SDimitry Andric }
1490e8d8bef9SDimitry Andric 
1491e8d8bef9SDimitry Andric /// A definition of a register may mark the end of a range.
1492349cc55cSDimitry Andric void VarLocBasedLDV::transferRegisterDef(MachineInstr &MI,
1493349cc55cSDimitry Andric                                          OpenRangesSet &OpenRanges,
1494349cc55cSDimitry Andric                                          VarLocMap &VarLocIDs,
1495349cc55cSDimitry Andric                                          InstToEntryLocMap &EntryValTransfers,
1496349cc55cSDimitry Andric                                          RegDefToInstMap &RegSetInstrs) {
1497e8d8bef9SDimitry Andric 
1498e8d8bef9SDimitry Andric   // Meta Instructions do not affect the debug liveness of any register they
1499e8d8bef9SDimitry Andric   // define.
1500e8d8bef9SDimitry Andric   if (MI.isMetaInstruction())
1501e8d8bef9SDimitry Andric     return;
1502e8d8bef9SDimitry Andric 
1503e8d8bef9SDimitry Andric   MachineFunction *MF = MI.getMF();
1504e8d8bef9SDimitry Andric   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1505e8d8bef9SDimitry Andric   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1506e8d8bef9SDimitry Andric 
1507e8d8bef9SDimitry Andric   // Find the regs killed by MI, and find regmasks of preserved regs.
1508e8d8bef9SDimitry Andric   DefinedRegsSet DeadRegs;
1509e8d8bef9SDimitry Andric   SmallVector<const uint32_t *, 4> RegMasks;
1510e8d8bef9SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1511e8d8bef9SDimitry Andric     // Determine whether the operand is a register def.
1512e8d8bef9SDimitry Andric     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1513e8d8bef9SDimitry Andric         Register::isPhysicalRegister(MO.getReg()) &&
1514e8d8bef9SDimitry Andric         !(MI.isCall() && MO.getReg() == SP)) {
1515e8d8bef9SDimitry Andric       // Remove ranges of all aliased registers.
1516e8d8bef9SDimitry Andric       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1517e8d8bef9SDimitry Andric         // FIXME: Can we break out of this loop early if no insertion occurs?
1518e8d8bef9SDimitry Andric         DeadRegs.insert(*RAI);
1519349cc55cSDimitry Andric       RegSetInstrs.erase(MO.getReg());
1520349cc55cSDimitry Andric       RegSetInstrs.insert({MO.getReg(), &MI});
1521e8d8bef9SDimitry Andric     } else if (MO.isRegMask()) {
1522e8d8bef9SDimitry Andric       RegMasks.push_back(MO.getRegMask());
1523e8d8bef9SDimitry Andric     }
1524e8d8bef9SDimitry Andric   }
1525e8d8bef9SDimitry Andric 
1526e8d8bef9SDimitry Andric   // Erase VarLocs which reside in one of the dead registers. For performance
1527e8d8bef9SDimitry Andric   // reasons, it's critical to not iterate over the full set of open VarLocs.
1528e8d8bef9SDimitry Andric   // Iterate over the set of dying/used regs instead.
1529e8d8bef9SDimitry Andric   if (!RegMasks.empty()) {
1530fe6060f1SDimitry Andric     SmallVector<Register, 32> UsedRegs;
1531e8d8bef9SDimitry Andric     getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
1532fe6060f1SDimitry Andric     for (Register Reg : UsedRegs) {
1533e8d8bef9SDimitry Andric       // Remove ranges of all clobbered registers. Register masks don't usually
1534e8d8bef9SDimitry Andric       // list SP as preserved. Assume that call instructions never clobber SP,
1535e8d8bef9SDimitry Andric       // because some backends (e.g., AArch64) never list SP in the regmask.
1536e8d8bef9SDimitry Andric       // While the debug info may be off for an instruction or two around
1537e8d8bef9SDimitry Andric       // callee-cleanup calls, transferring the DEBUG_VALUE across the call is
1538e8d8bef9SDimitry Andric       // still a better user experience.
1539e8d8bef9SDimitry Andric       if (Reg == SP)
1540e8d8bef9SDimitry Andric         continue;
1541e8d8bef9SDimitry Andric       bool AnyRegMaskKillsReg =
1542e8d8bef9SDimitry Andric           any_of(RegMasks, [Reg](const uint32_t *RegMask) {
1543e8d8bef9SDimitry Andric             return MachineOperand::clobbersPhysReg(RegMask, Reg);
1544e8d8bef9SDimitry Andric           });
1545e8d8bef9SDimitry Andric       if (AnyRegMaskKillsReg)
1546e8d8bef9SDimitry Andric         DeadRegs.insert(Reg);
1547349cc55cSDimitry Andric       if (AnyRegMaskKillsReg) {
1548349cc55cSDimitry Andric         RegSetInstrs.erase(Reg);
1549349cc55cSDimitry Andric         RegSetInstrs.insert({Reg, &MI});
1550349cc55cSDimitry Andric       }
1551e8d8bef9SDimitry Andric     }
1552e8d8bef9SDimitry Andric   }
1553e8d8bef9SDimitry Andric 
1554e8d8bef9SDimitry Andric   if (DeadRegs.empty())
1555e8d8bef9SDimitry Andric     return;
1556e8d8bef9SDimitry Andric 
1557fe6060f1SDimitry Andric   VarLocsInRange KillSet;
1558fe6060f1SDimitry Andric   collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs(), VarLocIDs);
1559fe6060f1SDimitry Andric   OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kUniversalLocation);
1560e8d8bef9SDimitry Andric 
1561e8d8bef9SDimitry Andric   if (TPC) {
1562e8d8bef9SDimitry Andric     auto &TM = TPC->getTM<TargetMachine>();
1563e8d8bef9SDimitry Andric     if (TM.Options.ShouldEmitDebugEntryValues())
1564349cc55cSDimitry Andric       emitEntryValues(MI, OpenRanges, VarLocIDs, EntryValTransfers, KillSet);
1565e8d8bef9SDimitry Andric   }
1566e8d8bef9SDimitry Andric }
1567e8d8bef9SDimitry Andric 
1568e8d8bef9SDimitry Andric bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI,
1569e8d8bef9SDimitry Andric                                          MachineFunction *MF) {
1570e8d8bef9SDimitry Andric   // TODO: Handle multiple stores folded into one.
1571e8d8bef9SDimitry Andric   if (!MI.hasOneMemOperand())
1572e8d8bef9SDimitry Andric     return false;
1573e8d8bef9SDimitry Andric 
1574e8d8bef9SDimitry Andric   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1575e8d8bef9SDimitry Andric     return false; // This is not a spill instruction, since no valid size was
1576e8d8bef9SDimitry Andric                   // returned from either function.
1577e8d8bef9SDimitry Andric 
1578e8d8bef9SDimitry Andric   return true;
1579e8d8bef9SDimitry Andric }
1580e8d8bef9SDimitry Andric 
1581e8d8bef9SDimitry Andric bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI,
1582e8d8bef9SDimitry Andric                                       MachineFunction *MF, Register &Reg) {
1583e8d8bef9SDimitry Andric   if (!isSpillInstruction(MI, MF))
1584e8d8bef9SDimitry Andric     return false;
1585e8d8bef9SDimitry Andric 
1586e8d8bef9SDimitry Andric   auto isKilledReg = [&](const MachineOperand MO, Register &Reg) {
1587e8d8bef9SDimitry Andric     if (!MO.isReg() || !MO.isUse()) {
1588e8d8bef9SDimitry Andric       Reg = 0;
1589e8d8bef9SDimitry Andric       return false;
1590e8d8bef9SDimitry Andric     }
1591e8d8bef9SDimitry Andric     Reg = MO.getReg();
1592e8d8bef9SDimitry Andric     return MO.isKill();
1593e8d8bef9SDimitry Andric   };
1594e8d8bef9SDimitry Andric 
1595e8d8bef9SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1596e8d8bef9SDimitry Andric     // In a spill instruction generated by the InlineSpiller the spilled
1597e8d8bef9SDimitry Andric     // register has its kill flag set.
1598e8d8bef9SDimitry Andric     if (isKilledReg(MO, Reg))
1599e8d8bef9SDimitry Andric       return true;
1600e8d8bef9SDimitry Andric     if (Reg != 0) {
1601e8d8bef9SDimitry Andric       // Check whether next instruction kills the spilled register.
1602e8d8bef9SDimitry Andric       // FIXME: Current solution does not cover search for killed register in
1603e8d8bef9SDimitry Andric       // bundles and instructions further down the chain.
1604e8d8bef9SDimitry Andric       auto NextI = std::next(MI.getIterator());
1605e8d8bef9SDimitry Andric       // Skip next instruction that points to basic block end iterator.
1606e8d8bef9SDimitry Andric       if (MI.getParent()->end() == NextI)
1607e8d8bef9SDimitry Andric         continue;
1608e8d8bef9SDimitry Andric       Register RegNext;
1609e8d8bef9SDimitry Andric       for (const MachineOperand &MONext : NextI->operands()) {
1610e8d8bef9SDimitry Andric         // Return true if we came across the register from the
1611e8d8bef9SDimitry Andric         // previous spill instruction that is killed in NextI.
1612e8d8bef9SDimitry Andric         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1613e8d8bef9SDimitry Andric           return true;
1614e8d8bef9SDimitry Andric       }
1615e8d8bef9SDimitry Andric     }
1616e8d8bef9SDimitry Andric   }
1617e8d8bef9SDimitry Andric   // Return false if we didn't find spilled register.
1618e8d8bef9SDimitry Andric   return false;
1619e8d8bef9SDimitry Andric }
1620e8d8bef9SDimitry Andric 
1621e8d8bef9SDimitry Andric Optional<VarLocBasedLDV::VarLoc::SpillLoc>
1622e8d8bef9SDimitry Andric VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1623e8d8bef9SDimitry Andric                                       MachineFunction *MF, Register &Reg) {
1624e8d8bef9SDimitry Andric   if (!MI.hasOneMemOperand())
1625e8d8bef9SDimitry Andric     return None;
1626e8d8bef9SDimitry Andric 
1627e8d8bef9SDimitry Andric   // FIXME: Handle folded restore instructions with more than one memory
1628e8d8bef9SDimitry Andric   // operand.
1629e8d8bef9SDimitry Andric   if (MI.getRestoreSize(TII)) {
1630e8d8bef9SDimitry Andric     Reg = MI.getOperand(0).getReg();
1631e8d8bef9SDimitry Andric     return extractSpillBaseRegAndOffset(MI);
1632e8d8bef9SDimitry Andric   }
1633e8d8bef9SDimitry Andric   return None;
1634e8d8bef9SDimitry Andric }
1635e8d8bef9SDimitry Andric 
1636e8d8bef9SDimitry Andric /// A spilled register may indicate that we have to end the current range of
1637e8d8bef9SDimitry Andric /// a variable and create a new one for the spill location.
1638e8d8bef9SDimitry Andric /// A restored register may indicate the reverse situation.
1639e8d8bef9SDimitry Andric /// We don't want to insert any instructions in process(), so we just create
1640e8d8bef9SDimitry Andric /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
1641e8d8bef9SDimitry Andric /// It will be inserted into the BB when we're done iterating over the
1642e8d8bef9SDimitry Andric /// instructions.
1643e8d8bef9SDimitry Andric void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI,
1644e8d8bef9SDimitry Andric                                                  OpenRangesSet &OpenRanges,
1645e8d8bef9SDimitry Andric                                                  VarLocMap &VarLocIDs,
1646e8d8bef9SDimitry Andric                                                  TransferMap &Transfers) {
1647e8d8bef9SDimitry Andric   MachineFunction *MF = MI.getMF();
1648e8d8bef9SDimitry Andric   TransferKind TKind;
1649e8d8bef9SDimitry Andric   Register Reg;
1650e8d8bef9SDimitry Andric   Optional<VarLoc::SpillLoc> Loc;
1651e8d8bef9SDimitry Andric 
1652e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1653e8d8bef9SDimitry Andric 
1654e8d8bef9SDimitry Andric   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1655e8d8bef9SDimitry Andric   // written to, then close the variable location. The value in memory
1656e8d8bef9SDimitry Andric   // will have changed.
1657fe6060f1SDimitry Andric   VarLocsInRange KillSet;
1658e8d8bef9SDimitry Andric   if (isSpillInstruction(MI, MF)) {
1659e8d8bef9SDimitry Andric     Loc = extractSpillBaseRegAndOffset(MI);
1660e8d8bef9SDimitry Andric     for (uint64_t ID : OpenRanges.getSpillVarLocs()) {
1661e8d8bef9SDimitry Andric       LocIndex Idx = LocIndex::fromRawInteger(ID);
1662e8d8bef9SDimitry Andric       const VarLoc &VL = VarLocIDs[Idx];
1663fe6060f1SDimitry Andric       assert(VL.containsSpillLocs() && "Broken VarLocSet?");
1664fe6060f1SDimitry Andric       if (VL.usesSpillLoc(*Loc)) {
1665e8d8bef9SDimitry Andric         // This location is overwritten by the current instruction -- terminate
1666e8d8bef9SDimitry Andric         // the open range, and insert an explicit DBG_VALUE $noreg.
1667e8d8bef9SDimitry Andric         //
1668e8d8bef9SDimitry Andric         // Doing this at a later stage would require re-interpreting all
1669e8d8bef9SDimitry Andric         // DBG_VALUes and DIExpressions to identify whether they point at
1670e8d8bef9SDimitry Andric         // memory, and then analysing all memory writes to see if they
1671e8d8bef9SDimitry Andric         // overwrite that memory, which is expensive.
1672e8d8bef9SDimitry Andric         //
1673e8d8bef9SDimitry Andric         // At this stage, we already know which DBG_VALUEs are for spills and
1674e8d8bef9SDimitry Andric         // where they are located; it's best to fix handle overwrites now.
1675fe6060f1SDimitry Andric         KillSet.insert(ID);
1676fe6060f1SDimitry Andric         unsigned SpillLocIdx = VL.getSpillLocIdx(*Loc);
1677fe6060f1SDimitry Andric         VarLoc::MachineLoc OldLoc = VL.Locs[SpillLocIdx];
1678fe6060f1SDimitry Andric         VarLoc UndefVL = VarLoc::CreateCopyLoc(VL, OldLoc, 0);
1679fe6060f1SDimitry Andric         LocIndices UndefLocIDs = VarLocIDs.insert(UndefVL);
1680fe6060f1SDimitry Andric         Transfers.push_back({&MI, UndefLocIDs.back()});
1681e8d8bef9SDimitry Andric       }
1682e8d8bef9SDimitry Andric     }
1683fe6060f1SDimitry Andric     OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kSpillLocation);
1684e8d8bef9SDimitry Andric   }
1685e8d8bef9SDimitry Andric 
1686e8d8bef9SDimitry Andric   // Try to recognise spill and restore instructions that may create a new
1687e8d8bef9SDimitry Andric   // variable location.
1688e8d8bef9SDimitry Andric   if (isLocationSpill(MI, MF, Reg)) {
1689e8d8bef9SDimitry Andric     TKind = TransferKind::TransferSpill;
1690e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1691e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1692e8d8bef9SDimitry Andric                       << "\n");
1693e8d8bef9SDimitry Andric   } else {
1694e8d8bef9SDimitry Andric     if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1695e8d8bef9SDimitry Andric       return;
1696e8d8bef9SDimitry Andric     TKind = TransferKind::TransferRestore;
1697e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1698e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1699e8d8bef9SDimitry Andric                       << "\n");
1700e8d8bef9SDimitry Andric   }
1701e8d8bef9SDimitry Andric   // Check if the register or spill location is the location of a debug value.
1702e8d8bef9SDimitry Andric   auto TransferCandidates = OpenRanges.getEmptyVarLocRange();
1703e8d8bef9SDimitry Andric   if (TKind == TransferKind::TransferSpill)
1704e8d8bef9SDimitry Andric     TransferCandidates = OpenRanges.getRegisterVarLocs(Reg);
1705e8d8bef9SDimitry Andric   else if (TKind == TransferKind::TransferRestore)
1706e8d8bef9SDimitry Andric     TransferCandidates = OpenRanges.getSpillVarLocs();
1707e8d8bef9SDimitry Andric   for (uint64_t ID : TransferCandidates) {
1708e8d8bef9SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1709e8d8bef9SDimitry Andric     const VarLoc &VL = VarLocIDs[Idx];
1710fe6060f1SDimitry Andric     unsigned LocIdx;
1711e8d8bef9SDimitry Andric     if (TKind == TransferKind::TransferSpill) {
1712fe6060f1SDimitry Andric       assert(VL.usesReg(Reg) && "Broken VarLocSet?");
1713e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
1714e8d8bef9SDimitry Andric                         << VL.Var.getVariable()->getName() << ")\n");
1715fe6060f1SDimitry Andric       LocIdx = VL.getRegIdx(Reg);
1716e8d8bef9SDimitry Andric     } else {
1717fe6060f1SDimitry Andric       assert(TKind == TransferKind::TransferRestore && VL.containsSpillLocs() &&
1718fe6060f1SDimitry Andric              "Broken VarLocSet?");
1719fe6060f1SDimitry Andric       if (!VL.usesSpillLoc(*Loc))
1720e8d8bef9SDimitry Andric         // The spill location is not the location of a debug value.
1721e8d8bef9SDimitry Andric         continue;
1722e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
1723e8d8bef9SDimitry Andric                         << VL.Var.getVariable()->getName() << ")\n");
1724fe6060f1SDimitry Andric       LocIdx = VL.getSpillLocIdx(*Loc);
1725e8d8bef9SDimitry Andric     }
1726fe6060f1SDimitry Andric     VarLoc::MachineLoc MLoc = VL.Locs[LocIdx];
1727e8d8bef9SDimitry Andric     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
1728fe6060f1SDimitry Andric                             MLoc, Reg);
1729e8d8bef9SDimitry Andric     // FIXME: A comment should explain why it's correct to return early here,
1730e8d8bef9SDimitry Andric     // if that is in fact correct.
1731e8d8bef9SDimitry Andric     return;
1732e8d8bef9SDimitry Andric   }
1733e8d8bef9SDimitry Andric }
1734e8d8bef9SDimitry Andric 
1735e8d8bef9SDimitry Andric /// If \p MI is a register copy instruction, that copies a previously tracked
1736e8d8bef9SDimitry Andric /// value from one register to another register that is callee saved, we
1737e8d8bef9SDimitry Andric /// create new DBG_VALUE instruction  described with copy destination register.
1738e8d8bef9SDimitry Andric void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI,
1739e8d8bef9SDimitry Andric                                            OpenRangesSet &OpenRanges,
1740e8d8bef9SDimitry Andric                                            VarLocMap &VarLocIDs,
1741e8d8bef9SDimitry Andric                                            TransferMap &Transfers) {
1742e8d8bef9SDimitry Andric   auto DestSrc = TII->isCopyInstr(MI);
1743e8d8bef9SDimitry Andric   if (!DestSrc)
1744e8d8bef9SDimitry Andric     return;
1745e8d8bef9SDimitry Andric 
1746e8d8bef9SDimitry Andric   const MachineOperand *DestRegOp = DestSrc->Destination;
1747e8d8bef9SDimitry Andric   const MachineOperand *SrcRegOp = DestSrc->Source;
1748e8d8bef9SDimitry Andric 
1749e8d8bef9SDimitry Andric   if (!DestRegOp->isDef())
1750e8d8bef9SDimitry Andric     return;
1751e8d8bef9SDimitry Andric 
1752e8d8bef9SDimitry Andric   auto isCalleeSavedReg = [&](Register Reg) {
1753e8d8bef9SDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1754e8d8bef9SDimitry Andric       if (CalleeSavedRegs.test(*RAI))
1755e8d8bef9SDimitry Andric         return true;
1756e8d8bef9SDimitry Andric     return false;
1757e8d8bef9SDimitry Andric   };
1758e8d8bef9SDimitry Andric 
1759e8d8bef9SDimitry Andric   Register SrcReg = SrcRegOp->getReg();
1760e8d8bef9SDimitry Andric   Register DestReg = DestRegOp->getReg();
1761e8d8bef9SDimitry Andric 
1762e8d8bef9SDimitry Andric   // We want to recognize instructions where destination register is callee
1763e8d8bef9SDimitry Andric   // saved register. If register that could be clobbered by the call is
1764e8d8bef9SDimitry Andric   // included, there would be a great chance that it is going to be clobbered
1765e8d8bef9SDimitry Andric   // soon. It is more likely that previous register location, which is callee
1766e8d8bef9SDimitry Andric   // saved, is going to stay unclobbered longer, even if it is killed.
1767e8d8bef9SDimitry Andric   if (!isCalleeSavedReg(DestReg))
1768e8d8bef9SDimitry Andric     return;
1769e8d8bef9SDimitry Andric 
1770e8d8bef9SDimitry Andric   // Remember an entry value movement. If we encounter a new debug value of
1771e8d8bef9SDimitry Andric   // a parameter describing only a moving of the value around, rather then
1772e8d8bef9SDimitry Andric   // modifying it, we are still able to use the entry value if needed.
1773e8d8bef9SDimitry Andric   if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1774e8d8bef9SDimitry Andric     for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1775e8d8bef9SDimitry Andric       LocIndex Idx = LocIndex::fromRawInteger(ID);
1776e8d8bef9SDimitry Andric       const VarLoc &VL = VarLocIDs[Idx];
1777fe6060f1SDimitry Andric       if (VL.isEntryValueBackupReg(SrcReg)) {
1778e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1779e8d8bef9SDimitry Andric         VarLoc EntryValLocCopyBackup =
1780e8d8bef9SDimitry Andric             VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg);
1781e8d8bef9SDimitry Andric         // Stop tracking the original entry value.
1782e8d8bef9SDimitry Andric         OpenRanges.erase(VL);
1783e8d8bef9SDimitry Andric 
1784e8d8bef9SDimitry Andric         // Start tracking the entry value copy.
1785fe6060f1SDimitry Andric         LocIndices EntryValCopyLocIDs = VarLocIDs.insert(EntryValLocCopyBackup);
1786fe6060f1SDimitry Andric         OpenRanges.insert(EntryValCopyLocIDs, EntryValLocCopyBackup);
1787e8d8bef9SDimitry Andric         break;
1788e8d8bef9SDimitry Andric       }
1789e8d8bef9SDimitry Andric     }
1790e8d8bef9SDimitry Andric   }
1791e8d8bef9SDimitry Andric 
1792e8d8bef9SDimitry Andric   if (!SrcRegOp->isKill())
1793e8d8bef9SDimitry Andric     return;
1794e8d8bef9SDimitry Andric 
1795e8d8bef9SDimitry Andric   for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) {
1796e8d8bef9SDimitry Andric     LocIndex Idx = LocIndex::fromRawInteger(ID);
1797fe6060f1SDimitry Andric     assert(VarLocIDs[Idx].usesReg(SrcReg) && "Broken VarLocSet?");
1798fe6060f1SDimitry Andric     VarLoc::MachineLocValue Loc;
1799fe6060f1SDimitry Andric     Loc.RegNo = SrcReg;
1800fe6060f1SDimitry Andric     VarLoc::MachineLoc MLoc{VarLoc::MachineLocKind::RegisterKind, Loc};
1801e8d8bef9SDimitry Andric     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
1802fe6060f1SDimitry Andric                             TransferKind::TransferCopy, MLoc, DestReg);
1803e8d8bef9SDimitry Andric     // FIXME: A comment should explain why it's correct to return early here,
1804e8d8bef9SDimitry Andric     // if that is in fact correct.
1805e8d8bef9SDimitry Andric     return;
1806e8d8bef9SDimitry Andric   }
1807e8d8bef9SDimitry Andric }
1808e8d8bef9SDimitry Andric 
1809e8d8bef9SDimitry Andric /// Terminate all open ranges at the end of the current basic block.
1810e8d8bef9SDimitry Andric bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB,
1811e8d8bef9SDimitry Andric                                          OpenRangesSet &OpenRanges,
1812e8d8bef9SDimitry Andric                                          VarLocInMBB &OutLocs,
1813e8d8bef9SDimitry Andric                                          const VarLocMap &VarLocIDs) {
1814e8d8bef9SDimitry Andric   bool Changed = false;
1815fe6060f1SDimitry Andric   LLVM_DEBUG({
1816fe6060f1SDimitry Andric     VarVec VarLocs;
1817fe6060f1SDimitry Andric     OpenRanges.getUniqueVarLocs(VarLocs, VarLocIDs);
1818fe6060f1SDimitry Andric     for (VarLoc &VL : VarLocs) {
1819e8d8bef9SDimitry Andric       // Copy OpenRanges to OutLocs, if not already present.
1820e8d8bef9SDimitry Andric       dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ":  ";
1821fe6060f1SDimitry Andric       VL.dump(TRI);
1822fe6060f1SDimitry Andric     }
1823e8d8bef9SDimitry Andric   });
1824e8d8bef9SDimitry Andric   VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
1825e8d8bef9SDimitry Andric   Changed = VLS != OpenRanges.getVarLocs();
1826e8d8bef9SDimitry Andric   // New OutLocs set may be different due to spill, restore or register
1827e8d8bef9SDimitry Andric   // copy instruction processing.
1828e8d8bef9SDimitry Andric   if (Changed)
1829e8d8bef9SDimitry Andric     VLS = OpenRanges.getVarLocs();
1830e8d8bef9SDimitry Andric   OpenRanges.clear();
1831e8d8bef9SDimitry Andric   return Changed;
1832e8d8bef9SDimitry Andric }
1833e8d8bef9SDimitry Andric 
1834e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
1835e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
1836e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1837e8d8bef9SDimitry Andric /// known-to-overlap fragments are present".
1838e8d8bef9SDimitry Andric /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1839e8d8bef9SDimitry Andric ///           fragment usage.
1840e8d8bef9SDimitry Andric /// \param SeenFragments Map from DILocalVariable to all fragments of that
1841e8d8bef9SDimitry Andric ///           Variable which are known to exist.
1842e8d8bef9SDimitry Andric /// \param OverlappingFragments The overlap map being constructed, from one
1843e8d8bef9SDimitry Andric ///           Var/Fragment pair to a vector of fragments known to overlap.
1844e8d8bef9SDimitry Andric void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI,
1845e8d8bef9SDimitry Andric                                             VarToFragments &SeenFragments,
1846e8d8bef9SDimitry Andric                                             OverlapMap &OverlappingFragments) {
1847e8d8bef9SDimitry Andric   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1848e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
1849e8d8bef9SDimitry Andric   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1850e8d8bef9SDimitry Andric 
1851e8d8bef9SDimitry Andric   // If this is the first sighting of this variable, then we are guaranteed
1852e8d8bef9SDimitry Andric   // there are currently no overlapping fragments either. Initialize the set
1853e8d8bef9SDimitry Andric   // of seen fragments, record no overlaps for the current one, and return.
1854e8d8bef9SDimitry Andric   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1855e8d8bef9SDimitry Andric   if (SeenIt == SeenFragments.end()) {
1856e8d8bef9SDimitry Andric     SmallSet<FragmentInfo, 4> OneFragment;
1857e8d8bef9SDimitry Andric     OneFragment.insert(ThisFragment);
1858e8d8bef9SDimitry Andric     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1859e8d8bef9SDimitry Andric 
1860e8d8bef9SDimitry Andric     OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1861e8d8bef9SDimitry Andric     return;
1862e8d8bef9SDimitry Andric   }
1863e8d8bef9SDimitry Andric 
1864e8d8bef9SDimitry Andric   // If this particular Variable/Fragment pair already exists in the overlap
1865e8d8bef9SDimitry Andric   // map, it has already been accounted for.
1866e8d8bef9SDimitry Andric   auto IsInOLapMap =
1867e8d8bef9SDimitry Andric       OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1868e8d8bef9SDimitry Andric   if (!IsInOLapMap.second)
1869e8d8bef9SDimitry Andric     return;
1870e8d8bef9SDimitry Andric 
1871e8d8bef9SDimitry Andric   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1872e8d8bef9SDimitry Andric   auto &AllSeenFragments = SeenIt->second;
1873e8d8bef9SDimitry Andric 
1874e8d8bef9SDimitry Andric   // Otherwise, examine all other seen fragments for this variable, with "this"
1875e8d8bef9SDimitry Andric   // fragment being a previously unseen fragment. Record any pair of
1876e8d8bef9SDimitry Andric   // overlapping fragments.
1877e8d8bef9SDimitry Andric   for (auto &ASeenFragment : AllSeenFragments) {
1878e8d8bef9SDimitry Andric     // Does this previously seen fragment overlap?
1879e8d8bef9SDimitry Andric     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1880e8d8bef9SDimitry Andric       // Yes: Mark the current fragment as being overlapped.
1881e8d8bef9SDimitry Andric       ThisFragmentsOverlaps.push_back(ASeenFragment);
1882e8d8bef9SDimitry Andric       // Mark the previously seen fragment as being overlapped by the current
1883e8d8bef9SDimitry Andric       // one.
1884e8d8bef9SDimitry Andric       auto ASeenFragmentsOverlaps =
1885e8d8bef9SDimitry Andric           OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1886e8d8bef9SDimitry Andric       assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1887e8d8bef9SDimitry Andric              "Previously seen var fragment has no vector of overlaps");
1888e8d8bef9SDimitry Andric       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1889e8d8bef9SDimitry Andric     }
1890e8d8bef9SDimitry Andric   }
1891e8d8bef9SDimitry Andric 
1892e8d8bef9SDimitry Andric   AllSeenFragments.insert(ThisFragment);
1893e8d8bef9SDimitry Andric }
1894e8d8bef9SDimitry Andric 
1895e8d8bef9SDimitry Andric /// This routine creates OpenRanges.
1896e8d8bef9SDimitry Andric void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1897349cc55cSDimitry Andric                              VarLocMap &VarLocIDs, TransferMap &Transfers,
1898349cc55cSDimitry Andric                              InstToEntryLocMap &EntryValTransfers,
1899349cc55cSDimitry Andric                              RegDefToInstMap &RegSetInstrs) {
1900349cc55cSDimitry Andric   if (!MI.isDebugInstr())
1901349cc55cSDimitry Andric     LastNonDbgMI = &MI;
1902349cc55cSDimitry Andric   transferDebugValue(MI, OpenRanges, VarLocIDs, EntryValTransfers,
1903349cc55cSDimitry Andric                      RegSetInstrs);
1904349cc55cSDimitry Andric   transferRegisterDef(MI, OpenRanges, VarLocIDs, EntryValTransfers,
1905349cc55cSDimitry Andric                       RegSetInstrs);
1906e8d8bef9SDimitry Andric   transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1907e8d8bef9SDimitry Andric   transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
1908e8d8bef9SDimitry Andric }
1909e8d8bef9SDimitry Andric 
1910e8d8bef9SDimitry Andric /// This routine joins the analysis results of all incoming edges in @MBB by
1911e8d8bef9SDimitry Andric /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1912e8d8bef9SDimitry Andric /// source variable in all the predecessors of @MBB reside in the same location.
1913e8d8bef9SDimitry Andric bool VarLocBasedLDV::join(
1914e8d8bef9SDimitry Andric     MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1915e8d8bef9SDimitry Andric     const VarLocMap &VarLocIDs,
1916e8d8bef9SDimitry Andric     SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1917e8d8bef9SDimitry Andric     SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
1918e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1919e8d8bef9SDimitry Andric 
1920e8d8bef9SDimitry Andric   VarLocSet InLocsT(Alloc); // Temporary incoming locations.
1921e8d8bef9SDimitry Andric 
1922e8d8bef9SDimitry Andric   // For all predecessors of this MBB, find the set of VarLocs that
1923e8d8bef9SDimitry Andric   // can be joined.
1924e8d8bef9SDimitry Andric   int NumVisited = 0;
1925e8d8bef9SDimitry Andric   for (auto p : MBB.predecessors()) {
1926e8d8bef9SDimitry Andric     // Ignore backedges if we have not visited the predecessor yet. As the
1927e8d8bef9SDimitry Andric     // predecessor hasn't yet had locations propagated into it, most locations
1928e8d8bef9SDimitry Andric     // will not yet be valid, so treat them as all being uninitialized and
1929e8d8bef9SDimitry Andric     // potentially valid. If a location guessed to be correct here is
1930e8d8bef9SDimitry Andric     // invalidated later, we will remove it when we revisit this block.
1931e8d8bef9SDimitry Andric     if (!Visited.count(p)) {
1932e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "  ignoring unvisited pred MBB: " << p->getNumber()
1933e8d8bef9SDimitry Andric                         << "\n");
1934e8d8bef9SDimitry Andric       continue;
1935e8d8bef9SDimitry Andric     }
1936e8d8bef9SDimitry Andric     auto OL = OutLocs.find(p);
1937e8d8bef9SDimitry Andric     // Join is null in case of empty OutLocs from any of the pred.
1938e8d8bef9SDimitry Andric     if (OL == OutLocs.end())
1939e8d8bef9SDimitry Andric       return false;
1940e8d8bef9SDimitry Andric 
1941e8d8bef9SDimitry Andric     // Just copy over the Out locs to incoming locs for the first visited
1942e8d8bef9SDimitry Andric     // predecessor, and for all other predecessors join the Out locs.
1943*81ad6265SDimitry Andric     VarLocSet &OutLocVLS = *OL->second;
1944e8d8bef9SDimitry Andric     if (!NumVisited)
1945e8d8bef9SDimitry Andric       InLocsT = OutLocVLS;
1946e8d8bef9SDimitry Andric     else
1947e8d8bef9SDimitry Andric       InLocsT &= OutLocVLS;
1948e8d8bef9SDimitry Andric 
1949e8d8bef9SDimitry Andric     LLVM_DEBUG({
1950e8d8bef9SDimitry Andric       if (!InLocsT.empty()) {
1951fe6060f1SDimitry Andric         VarVec VarLocs;
1952fe6060f1SDimitry Andric         collectAllVarLocs(VarLocs, InLocsT, VarLocIDs);
1953fe6060f1SDimitry Andric         for (const VarLoc &VL : VarLocs)
1954e8d8bef9SDimitry Andric           dbgs() << "  gathered candidate incoming var: "
1955fe6060f1SDimitry Andric                  << VL.Var.getVariable()->getName() << "\n";
1956e8d8bef9SDimitry Andric       }
1957e8d8bef9SDimitry Andric     });
1958e8d8bef9SDimitry Andric 
1959e8d8bef9SDimitry Andric     NumVisited++;
1960e8d8bef9SDimitry Andric   }
1961e8d8bef9SDimitry Andric 
1962e8d8bef9SDimitry Andric   // Filter out DBG_VALUES that are out of scope.
1963e8d8bef9SDimitry Andric   VarLocSet KillSet(Alloc);
1964e8d8bef9SDimitry Andric   bool IsArtificial = ArtificialBlocks.count(&MBB);
1965e8d8bef9SDimitry Andric   if (!IsArtificial) {
1966e8d8bef9SDimitry Andric     for (uint64_t ID : InLocsT) {
1967e8d8bef9SDimitry Andric       LocIndex Idx = LocIndex::fromRawInteger(ID);
1968e8d8bef9SDimitry Andric       if (!VarLocIDs[Idx].dominates(LS, MBB)) {
1969e8d8bef9SDimitry Andric         KillSet.set(ID);
1970e8d8bef9SDimitry Andric         LLVM_DEBUG({
1971e8d8bef9SDimitry Andric           auto Name = VarLocIDs[Idx].Var.getVariable()->getName();
1972e8d8bef9SDimitry Andric           dbgs() << "  killing " << Name << ", it doesn't dominate MBB\n";
1973e8d8bef9SDimitry Andric         });
1974e8d8bef9SDimitry Andric       }
1975e8d8bef9SDimitry Andric     }
1976e8d8bef9SDimitry Andric   }
1977e8d8bef9SDimitry Andric   InLocsT.intersectWithComplement(KillSet);
1978e8d8bef9SDimitry Andric 
1979e8d8bef9SDimitry Andric   // As we are processing blocks in reverse post-order we
1980e8d8bef9SDimitry Andric   // should have processed at least one predecessor, unless it
1981e8d8bef9SDimitry Andric   // is the entry block which has no predecessor.
1982e8d8bef9SDimitry Andric   assert((NumVisited || MBB.pred_empty()) &&
1983e8d8bef9SDimitry Andric          "Should have processed at least one predecessor");
1984e8d8bef9SDimitry Andric 
1985e8d8bef9SDimitry Andric   VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
1986e8d8bef9SDimitry Andric   bool Changed = false;
1987e8d8bef9SDimitry Andric   if (ILS != InLocsT) {
1988e8d8bef9SDimitry Andric     ILS = InLocsT;
1989e8d8bef9SDimitry Andric     Changed = true;
1990e8d8bef9SDimitry Andric   }
1991e8d8bef9SDimitry Andric 
1992e8d8bef9SDimitry Andric   return Changed;
1993e8d8bef9SDimitry Andric }
1994e8d8bef9SDimitry Andric 
1995e8d8bef9SDimitry Andric void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs,
1996e8d8bef9SDimitry Andric                                        VarLocMap &VarLocIDs) {
1997e8d8bef9SDimitry Andric   // PendingInLocs records all locations propagated into blocks, which have
1998e8d8bef9SDimitry Andric   // not had DBG_VALUE insts created. Go through and create those insts now.
1999e8d8bef9SDimitry Andric   for (auto &Iter : PendingInLocs) {
2000e8d8bef9SDimitry Andric     // Map is keyed on a constant pointer, unwrap it so we can insert insts.
2001e8d8bef9SDimitry Andric     auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
2002*81ad6265SDimitry Andric     VarLocSet &Pending = *Iter.second;
2003e8d8bef9SDimitry Andric 
2004fe6060f1SDimitry Andric     SmallVector<VarLoc, 32> VarLocs;
2005fe6060f1SDimitry Andric     collectAllVarLocs(VarLocs, Pending, VarLocIDs);
2006fe6060f1SDimitry Andric 
2007fe6060f1SDimitry Andric     for (VarLoc DiffIt : VarLocs) {
2008e8d8bef9SDimitry Andric       // The ID location is live-in to MBB -- work out what kind of machine
2009e8d8bef9SDimitry Andric       // location it is and create a DBG_VALUE.
2010e8d8bef9SDimitry Andric       if (DiffIt.isEntryBackupLoc())
2011e8d8bef9SDimitry Andric         continue;
2012e8d8bef9SDimitry Andric       MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
2013e8d8bef9SDimitry Andric       MBB.insert(MBB.instr_begin(), MI);
2014e8d8bef9SDimitry Andric 
2015e8d8bef9SDimitry Andric       (void)MI;
2016e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
2017e8d8bef9SDimitry Andric     }
2018e8d8bef9SDimitry Andric   }
2019e8d8bef9SDimitry Andric }
2020e8d8bef9SDimitry Andric 
2021e8d8bef9SDimitry Andric bool VarLocBasedLDV::isEntryValueCandidate(
2022e8d8bef9SDimitry Andric     const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
2023e8d8bef9SDimitry Andric   assert(MI.isDebugValue() && "This must be DBG_VALUE.");
2024e8d8bef9SDimitry Andric 
2025e8d8bef9SDimitry Andric   // TODO: Add support for local variables that are expressed in terms of
2026e8d8bef9SDimitry Andric   // parameters entry values.
2027e8d8bef9SDimitry Andric   // TODO: Add support for modified arguments that can be expressed
2028e8d8bef9SDimitry Andric   // by using its entry value.
2029e8d8bef9SDimitry Andric   auto *DIVar = MI.getDebugVariable();
2030e8d8bef9SDimitry Andric   if (!DIVar->isParameter())
2031e8d8bef9SDimitry Andric     return false;
2032e8d8bef9SDimitry Andric 
2033e8d8bef9SDimitry Andric   // Do not consider parameters that belong to an inlined function.
2034e8d8bef9SDimitry Andric   if (MI.getDebugLoc()->getInlinedAt())
2035e8d8bef9SDimitry Andric     return false;
2036e8d8bef9SDimitry Andric 
2037e8d8bef9SDimitry Andric   // Only consider parameters that are described using registers. Parameters
2038e8d8bef9SDimitry Andric   // that are passed on the stack are not yet supported, so ignore debug
2039e8d8bef9SDimitry Andric   // values that are described by the frame or stack pointer.
2040e8d8bef9SDimitry Andric   if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI))
2041e8d8bef9SDimitry Andric     return false;
2042e8d8bef9SDimitry Andric 
2043e8d8bef9SDimitry Andric   // If a parameter's value has been propagated from the caller, then the
2044e8d8bef9SDimitry Andric   // parameter's DBG_VALUE may be described using a register defined by some
2045e8d8bef9SDimitry Andric   // instruction in the entry block, in which case we shouldn't create an
2046e8d8bef9SDimitry Andric   // entry value.
2047e8d8bef9SDimitry Andric   if (DefinedRegs.count(MI.getDebugOperand(0).getReg()))
2048e8d8bef9SDimitry Andric     return false;
2049e8d8bef9SDimitry Andric 
2050e8d8bef9SDimitry Andric   // TODO: Add support for parameters that have a pre-existing debug expressions
2051e8d8bef9SDimitry Andric   // (e.g. fragments).
2052e8d8bef9SDimitry Andric   if (MI.getDebugExpression()->getNumElements() > 0)
2053e8d8bef9SDimitry Andric     return false;
2054e8d8bef9SDimitry Andric 
2055e8d8bef9SDimitry Andric   return true;
2056e8d8bef9SDimitry Andric }
2057e8d8bef9SDimitry Andric 
2058e8d8bef9SDimitry Andric /// Collect all register defines (including aliases) for the given instruction.
2059e8d8bef9SDimitry Andric static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
2060e8d8bef9SDimitry Andric                            const TargetRegisterInfo *TRI) {
2061e8d8bef9SDimitry Andric   for (const MachineOperand &MO : MI.operands())
2062e8d8bef9SDimitry Andric     if (MO.isReg() && MO.isDef() && MO.getReg())
2063e8d8bef9SDimitry Andric       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
2064e8d8bef9SDimitry Andric         Regs.insert(*AI);
2065e8d8bef9SDimitry Andric }
2066e8d8bef9SDimitry Andric 
2067e8d8bef9SDimitry Andric /// This routine records the entry values of function parameters. The values
2068e8d8bef9SDimitry Andric /// could be used as backup values. If we loose the track of some unmodified
2069e8d8bef9SDimitry Andric /// parameters, the backup values will be used as a primary locations.
2070e8d8bef9SDimitry Andric void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI,
2071e8d8bef9SDimitry Andric                                        const DefinedRegsSet &DefinedRegs,
2072e8d8bef9SDimitry Andric                                        OpenRangesSet &OpenRanges,
2073e8d8bef9SDimitry Andric                                        VarLocMap &VarLocIDs) {
2074e8d8bef9SDimitry Andric   if (TPC) {
2075e8d8bef9SDimitry Andric     auto &TM = TPC->getTM<TargetMachine>();
2076e8d8bef9SDimitry Andric     if (!TM.Options.ShouldEmitDebugEntryValues())
2077e8d8bef9SDimitry Andric       return;
2078e8d8bef9SDimitry Andric   }
2079e8d8bef9SDimitry Andric 
2080e8d8bef9SDimitry Andric   DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
2081e8d8bef9SDimitry Andric                   MI.getDebugLoc()->getInlinedAt());
2082e8d8bef9SDimitry Andric 
2083e8d8bef9SDimitry Andric   if (!isEntryValueCandidate(MI, DefinedRegs) ||
2084e8d8bef9SDimitry Andric       OpenRanges.getEntryValueBackup(V))
2085e8d8bef9SDimitry Andric     return;
2086e8d8bef9SDimitry Andric 
2087e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
2088e8d8bef9SDimitry Andric 
2089e8d8bef9SDimitry Andric   // Create the entry value and use it as a backup location until it is
2090e8d8bef9SDimitry Andric   // valid. It is valid until a parameter is not changed.
2091e8d8bef9SDimitry Andric   DIExpression *NewExpr =
2092e8d8bef9SDimitry Andric       DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
2093e8d8bef9SDimitry Andric   VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
2094fe6060f1SDimitry Andric   LocIndices EntryValLocIDs = VarLocIDs.insert(EntryValLocAsBackup);
2095fe6060f1SDimitry Andric   OpenRanges.insert(EntryValLocIDs, EntryValLocAsBackup);
2096e8d8bef9SDimitry Andric }
2097e8d8bef9SDimitry Andric 
2098e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and
2099e8d8bef9SDimitry Andric /// extend ranges across basic blocks.
2100349cc55cSDimitry Andric bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF,
2101349cc55cSDimitry Andric                                   MachineDominatorTree *DomTree,
2102349cc55cSDimitry Andric                                   TargetPassConfig *TPC, unsigned InputBBLimit,
2103349cc55cSDimitry Andric                                   unsigned InputDbgValLimit) {
2104349cc55cSDimitry Andric   (void)DomTree;
2105e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
2106e8d8bef9SDimitry Andric 
2107e8d8bef9SDimitry Andric   if (!MF.getFunction().getSubprogram())
2108e8d8bef9SDimitry Andric     // VarLocBaseLDV will already have removed all DBG_VALUEs.
2109e8d8bef9SDimitry Andric     return false;
2110e8d8bef9SDimitry Andric 
2111e8d8bef9SDimitry Andric   // Skip functions from NoDebug compilation units.
2112e8d8bef9SDimitry Andric   if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
2113e8d8bef9SDimitry Andric       DICompileUnit::NoDebug)
2114e8d8bef9SDimitry Andric     return false;
2115e8d8bef9SDimitry Andric 
2116e8d8bef9SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
2117e8d8bef9SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
2118e8d8bef9SDimitry Andric   TFI = MF.getSubtarget().getFrameLowering();
2119e8d8bef9SDimitry Andric   TFI->getCalleeSaves(MF, CalleeSavedRegs);
2120e8d8bef9SDimitry Andric   this->TPC = TPC;
2121e8d8bef9SDimitry Andric   LS.initialize(MF);
2122e8d8bef9SDimitry Andric 
2123e8d8bef9SDimitry Andric   bool Changed = false;
2124e8d8bef9SDimitry Andric   bool OLChanged = false;
2125e8d8bef9SDimitry Andric   bool MBBJoined = false;
2126e8d8bef9SDimitry Andric 
2127e8d8bef9SDimitry Andric   VarLocMap VarLocIDs;         // Map VarLoc<>unique ID for use in bitvectors.
2128e8d8bef9SDimitry Andric   OverlapMap OverlapFragments; // Map of overlapping variable fragments.
2129e8d8bef9SDimitry Andric   OpenRangesSet OpenRanges(Alloc, OverlapFragments);
2130e8d8bef9SDimitry Andric                               // Ranges that are open until end of bb.
2131e8d8bef9SDimitry Andric   VarLocInMBB OutLocs;        // Ranges that exist beyond bb.
2132e8d8bef9SDimitry Andric   VarLocInMBB InLocs;         // Ranges that are incoming after joining.
2133e8d8bef9SDimitry Andric   TransferMap Transfers;      // DBG_VALUEs associated with transfers (such as
2134e8d8bef9SDimitry Andric                               // spills, copies and restores).
2135349cc55cSDimitry Andric   // Map responsible MI to attached Transfer emitted from Backup Entry Value.
2136349cc55cSDimitry Andric   InstToEntryLocMap EntryValTransfers;
2137349cc55cSDimitry Andric   // Map a Register to the last MI which clobbered it.
2138349cc55cSDimitry Andric   RegDefToInstMap RegSetInstrs;
2139e8d8bef9SDimitry Andric 
2140e8d8bef9SDimitry Andric   VarToFragments SeenFragments;
2141e8d8bef9SDimitry Andric 
2142e8d8bef9SDimitry Andric   // Blocks which are artificial, i.e. blocks which exclusively contain
2143e8d8bef9SDimitry Andric   // instructions without locations, or with line 0 locations.
2144e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
2145e8d8bef9SDimitry Andric 
2146e8d8bef9SDimitry Andric   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
2147e8d8bef9SDimitry Andric   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
2148e8d8bef9SDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
2149e8d8bef9SDimitry Andric                       std::greater<unsigned int>>
2150e8d8bef9SDimitry Andric       Worklist;
2151e8d8bef9SDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
2152e8d8bef9SDimitry Andric                       std::greater<unsigned int>>
2153e8d8bef9SDimitry Andric       Pending;
2154e8d8bef9SDimitry Andric 
2155e8d8bef9SDimitry Andric   // Set of register defines that are seen when traversing the entry block
2156e8d8bef9SDimitry Andric   // looking for debug entry value candidates.
2157e8d8bef9SDimitry Andric   DefinedRegsSet DefinedRegs;
2158e8d8bef9SDimitry Andric 
2159e8d8bef9SDimitry Andric   // Only in the case of entry MBB collect DBG_VALUEs representing
2160e8d8bef9SDimitry Andric   // function parameters in order to generate debug entry values for them.
2161e8d8bef9SDimitry Andric   MachineBasicBlock &First_MBB = *(MF.begin());
2162e8d8bef9SDimitry Andric   for (auto &MI : First_MBB) {
2163e8d8bef9SDimitry Andric     collectRegDefs(MI, DefinedRegs, TRI);
2164e8d8bef9SDimitry Andric     if (MI.isDebugValue())
2165e8d8bef9SDimitry Andric       recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
2166e8d8bef9SDimitry Andric   }
2167e8d8bef9SDimitry Andric 
2168e8d8bef9SDimitry Andric   // Initialize per-block structures and scan for fragment overlaps.
2169e8d8bef9SDimitry Andric   for (auto &MBB : MF)
2170e8d8bef9SDimitry Andric     for (auto &MI : MBB)
2171e8d8bef9SDimitry Andric       if (MI.isDebugValue())
2172e8d8bef9SDimitry Andric         accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
2173e8d8bef9SDimitry Andric 
2174e8d8bef9SDimitry Andric   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2175e8d8bef9SDimitry Andric     if (const DebugLoc &DL = MI.getDebugLoc())
2176e8d8bef9SDimitry Andric       return DL.getLine() != 0;
2177e8d8bef9SDimitry Andric     return false;
2178e8d8bef9SDimitry Andric   };
2179e8d8bef9SDimitry Andric   for (auto &MBB : MF)
2180e8d8bef9SDimitry Andric     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2181e8d8bef9SDimitry Andric       ArtificialBlocks.insert(&MBB);
2182e8d8bef9SDimitry Andric 
2183e8d8bef9SDimitry Andric   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2184e8d8bef9SDimitry Andric                               "OutLocs after initialization", dbgs()));
2185e8d8bef9SDimitry Andric 
2186e8d8bef9SDimitry Andric   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2187e8d8bef9SDimitry Andric   unsigned int RPONumber = 0;
2188fe6060f1SDimitry Andric   for (MachineBasicBlock *MBB : RPOT) {
2189fe6060f1SDimitry Andric     OrderToBB[RPONumber] = MBB;
2190fe6060f1SDimitry Andric     BBToOrder[MBB] = RPONumber;
2191e8d8bef9SDimitry Andric     Worklist.push(RPONumber);
2192e8d8bef9SDimitry Andric     ++RPONumber;
2193e8d8bef9SDimitry Andric   }
2194e8d8bef9SDimitry Andric 
2195e8d8bef9SDimitry Andric   if (RPONumber > InputBBLimit) {
2196e8d8bef9SDimitry Andric     unsigned NumInputDbgValues = 0;
2197e8d8bef9SDimitry Andric     for (auto &MBB : MF)
2198e8d8bef9SDimitry Andric       for (auto &MI : MBB)
2199e8d8bef9SDimitry Andric         if (MI.isDebugValue())
2200e8d8bef9SDimitry Andric           ++NumInputDbgValues;
2201349cc55cSDimitry Andric     if (NumInputDbgValues > InputDbgValLimit) {
2202e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName()
2203e8d8bef9SDimitry Andric                         << " has " << RPONumber << " basic blocks and "
2204e8d8bef9SDimitry Andric                         << NumInputDbgValues
2205e8d8bef9SDimitry Andric                         << " input DBG_VALUEs, exceeding limits.\n");
2206e8d8bef9SDimitry Andric       return false;
2207e8d8bef9SDimitry Andric     }
2208e8d8bef9SDimitry Andric   }
2209e8d8bef9SDimitry Andric 
2210e8d8bef9SDimitry Andric   // This is a standard "union of predecessor outs" dataflow problem.
2211e8d8bef9SDimitry Andric   // To solve it, we perform join() and process() using the two worklist method
2212e8d8bef9SDimitry Andric   // until the ranges converge.
2213e8d8bef9SDimitry Andric   // Ranges have converged when both worklists are empty.
2214e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2215e8d8bef9SDimitry Andric   while (!Worklist.empty() || !Pending.empty()) {
2216e8d8bef9SDimitry Andric     // We track what is on the pending worklist to avoid inserting the same
2217e8d8bef9SDimitry Andric     // thing twice.  We could avoid this with a custom priority queue, but this
2218e8d8bef9SDimitry Andric     // is probably not worth it.
2219e8d8bef9SDimitry Andric     SmallPtrSet<MachineBasicBlock *, 16> OnPending;
2220e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Processing Worklist\n");
2221e8d8bef9SDimitry Andric     while (!Worklist.empty()) {
2222e8d8bef9SDimitry Andric       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2223e8d8bef9SDimitry Andric       Worklist.pop();
2224e8d8bef9SDimitry Andric       MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
2225e8d8bef9SDimitry Andric                        ArtificialBlocks);
2226e8d8bef9SDimitry Andric       MBBJoined |= Visited.insert(MBB).second;
2227e8d8bef9SDimitry Andric       if (MBBJoined) {
2228e8d8bef9SDimitry Andric         MBBJoined = false;
2229e8d8bef9SDimitry Andric         Changed = true;
2230e8d8bef9SDimitry Andric         // Now that we have started to extend ranges across BBs we need to
2231e8d8bef9SDimitry Andric         // examine spill, copy and restore instructions to see whether they
2232e8d8bef9SDimitry Andric         // operate with registers that correspond to user variables.
2233e8d8bef9SDimitry Andric         // First load any pending inlocs.
2234e8d8bef9SDimitry Andric         OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs);
2235349cc55cSDimitry Andric         LastNonDbgMI = nullptr;
2236349cc55cSDimitry Andric         RegSetInstrs.clear();
2237e8d8bef9SDimitry Andric         for (auto &MI : *MBB)
2238349cc55cSDimitry Andric           process(MI, OpenRanges, VarLocIDs, Transfers, EntryValTransfers,
2239349cc55cSDimitry Andric                   RegSetInstrs);
2240e8d8bef9SDimitry Andric         OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
2241e8d8bef9SDimitry Andric 
2242e8d8bef9SDimitry Andric         LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2243e8d8bef9SDimitry Andric                                     "OutLocs after propagating", dbgs()));
2244e8d8bef9SDimitry Andric         LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
2245e8d8bef9SDimitry Andric                                     "InLocs after propagating", dbgs()));
2246e8d8bef9SDimitry Andric 
2247e8d8bef9SDimitry Andric         if (OLChanged) {
2248e8d8bef9SDimitry Andric           OLChanged = false;
2249e8d8bef9SDimitry Andric           for (auto s : MBB->successors())
2250e8d8bef9SDimitry Andric             if (OnPending.insert(s).second) {
2251e8d8bef9SDimitry Andric               Pending.push(BBToOrder[s]);
2252e8d8bef9SDimitry Andric             }
2253e8d8bef9SDimitry Andric         }
2254e8d8bef9SDimitry Andric       }
2255e8d8bef9SDimitry Andric     }
2256e8d8bef9SDimitry Andric     Worklist.swap(Pending);
2257e8d8bef9SDimitry Andric     // At this point, pending must be empty, since it was just the empty
2258e8d8bef9SDimitry Andric     // worklist
2259e8d8bef9SDimitry Andric     assert(Pending.empty() && "Pending should be empty");
2260e8d8bef9SDimitry Andric   }
2261e8d8bef9SDimitry Andric 
2262e8d8bef9SDimitry Andric   // Add any DBG_VALUE instructions created by location transfers.
2263e8d8bef9SDimitry Andric   for (auto &TR : Transfers) {
2264e8d8bef9SDimitry Andric     assert(!TR.TransferInst->isTerminator() &&
2265e8d8bef9SDimitry Andric            "Cannot insert DBG_VALUE after terminator");
2266e8d8bef9SDimitry Andric     MachineBasicBlock *MBB = TR.TransferInst->getParent();
2267e8d8bef9SDimitry Andric     const VarLoc &VL = VarLocIDs[TR.LocationID];
2268e8d8bef9SDimitry Andric     MachineInstr *MI = VL.BuildDbgValue(MF);
2269e8d8bef9SDimitry Andric     MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
2270e8d8bef9SDimitry Andric   }
2271e8d8bef9SDimitry Andric   Transfers.clear();
2272e8d8bef9SDimitry Andric 
2273349cc55cSDimitry Andric   // Add DBG_VALUEs created using Backup Entry Value location.
2274349cc55cSDimitry Andric   for (auto &TR : EntryValTransfers) {
2275349cc55cSDimitry Andric     MachineInstr *TRInst = const_cast<MachineInstr *>(TR.first);
2276349cc55cSDimitry Andric     assert(!TRInst->isTerminator() &&
2277349cc55cSDimitry Andric            "Cannot insert DBG_VALUE after terminator");
2278349cc55cSDimitry Andric     MachineBasicBlock *MBB = TRInst->getParent();
2279349cc55cSDimitry Andric     const VarLoc &VL = VarLocIDs[TR.second];
2280349cc55cSDimitry Andric     MachineInstr *MI = VL.BuildDbgValue(MF);
2281349cc55cSDimitry Andric     MBB->insertAfterBundle(TRInst->getIterator(), MI);
2282349cc55cSDimitry Andric   }
2283349cc55cSDimitry Andric   EntryValTransfers.clear();
2284349cc55cSDimitry Andric 
2285e8d8bef9SDimitry Andric   // Deferred inlocs will not have had any DBG_VALUE insts created; do
2286e8d8bef9SDimitry Andric   // that now.
2287e8d8bef9SDimitry Andric   flushPendingLocs(InLocs, VarLocIDs);
2288e8d8bef9SDimitry Andric 
2289e8d8bef9SDimitry Andric   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
2290e8d8bef9SDimitry Andric   LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
2291e8d8bef9SDimitry Andric   return Changed;
2292e8d8bef9SDimitry Andric }
2293e8d8bef9SDimitry Andric 
2294e8d8bef9SDimitry Andric LDVImpl *
2295e8d8bef9SDimitry Andric llvm::makeVarLocBasedLiveDebugValues()
2296e8d8bef9SDimitry Andric {
2297e8d8bef9SDimitry Andric   return new VarLocBasedLDV();
2298e8d8bef9SDimitry Andric }
2299