xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.h (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1349cc55cSDimitry Andric //===- InstrRefBasedImpl.h - Tracking Debug Value MIs ---------------------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric 
9349cc55cSDimitry Andric #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
10349cc55cSDimitry Andric #define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
11349cc55cSDimitry Andric 
12349cc55cSDimitry Andric #include "llvm/ADT/DenseMap.h"
1381ad6265SDimitry Andric #include "llvm/ADT/IndexedMap.h"
14349cc55cSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
15349cc55cSDimitry Andric #include "llvm/ADT/SmallVector.h"
16349cc55cSDimitry Andric #include "llvm/ADT/UniqueVector.h"
17349cc55cSDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
18349cc55cSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
19349cc55cSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
2081ad6265SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
21349cc55cSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
22bdd1243dSDimitry Andric #include <optional>
23349cc55cSDimitry Andric 
24349cc55cSDimitry Andric #include "LiveDebugValues.h"
25349cc55cSDimitry Andric 
26349cc55cSDimitry Andric class TransferTracker;
27349cc55cSDimitry Andric 
28349cc55cSDimitry Andric // Forward dec of unit test class, so that we can peer into the LDV object.
29349cc55cSDimitry Andric class InstrRefLDVTest;
30349cc55cSDimitry Andric 
31349cc55cSDimitry Andric namespace LiveDebugValues {
32349cc55cSDimitry Andric 
33349cc55cSDimitry Andric class MLocTracker;
34bdd1243dSDimitry Andric class DbgOpIDMap;
35349cc55cSDimitry Andric 
36349cc55cSDimitry Andric using namespace llvm;
37349cc55cSDimitry Andric 
38349cc55cSDimitry Andric /// Handle-class for a particular "location". This value-type uniquely
39349cc55cSDimitry Andric /// symbolises a register or stack location, allowing manipulation of locations
40349cc55cSDimitry Andric /// without concern for where that location is. Practically, this allows us to
41349cc55cSDimitry Andric /// treat the state of the machine at a particular point as an array of values,
42349cc55cSDimitry Andric /// rather than a map of values.
43349cc55cSDimitry Andric class LocIdx {
44349cc55cSDimitry Andric   unsigned Location;
45349cc55cSDimitry Andric 
46349cc55cSDimitry Andric   // Default constructor is private, initializing to an illegal location number.
47349cc55cSDimitry Andric   // Use only for "not an entry" elements in IndexedMaps.
48349cc55cSDimitry Andric   LocIdx() : Location(UINT_MAX) {}
49349cc55cSDimitry Andric 
50349cc55cSDimitry Andric public:
51349cc55cSDimitry Andric #define NUM_LOC_BITS 24
52349cc55cSDimitry Andric   LocIdx(unsigned L) : Location(L) {
53349cc55cSDimitry Andric     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
54349cc55cSDimitry Andric   }
55349cc55cSDimitry Andric 
56349cc55cSDimitry Andric   static LocIdx MakeIllegalLoc() { return LocIdx(); }
57349cc55cSDimitry Andric   static LocIdx MakeTombstoneLoc() {
58349cc55cSDimitry Andric     LocIdx L = LocIdx();
59349cc55cSDimitry Andric     --L.Location;
60349cc55cSDimitry Andric     return L;
61349cc55cSDimitry Andric   }
62349cc55cSDimitry Andric 
63349cc55cSDimitry Andric   bool isIllegal() const { return Location == UINT_MAX; }
64349cc55cSDimitry Andric 
65349cc55cSDimitry Andric   uint64_t asU64() const { return Location; }
66349cc55cSDimitry Andric 
67349cc55cSDimitry Andric   bool operator==(unsigned L) const { return Location == L; }
68349cc55cSDimitry Andric 
69349cc55cSDimitry Andric   bool operator==(const LocIdx &L) const { return Location == L.Location; }
70349cc55cSDimitry Andric 
71349cc55cSDimitry Andric   bool operator!=(unsigned L) const { return !(*this == L); }
72349cc55cSDimitry Andric 
73349cc55cSDimitry Andric   bool operator!=(const LocIdx &L) const { return !(*this == L); }
74349cc55cSDimitry Andric 
75349cc55cSDimitry Andric   bool operator<(const LocIdx &Other) const {
76349cc55cSDimitry Andric     return Location < Other.Location;
77349cc55cSDimitry Andric   }
78349cc55cSDimitry Andric };
79349cc55cSDimitry Andric 
80349cc55cSDimitry Andric // The location at which a spilled value resides. It consists of a register and
81349cc55cSDimitry Andric // an offset.
82349cc55cSDimitry Andric struct SpillLoc {
83349cc55cSDimitry Andric   unsigned SpillBase;
84349cc55cSDimitry Andric   StackOffset SpillOffset;
85349cc55cSDimitry Andric   bool operator==(const SpillLoc &Other) const {
86349cc55cSDimitry Andric     return std::make_pair(SpillBase, SpillOffset) ==
87349cc55cSDimitry Andric            std::make_pair(Other.SpillBase, Other.SpillOffset);
88349cc55cSDimitry Andric   }
89349cc55cSDimitry Andric   bool operator<(const SpillLoc &Other) const {
90349cc55cSDimitry Andric     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
91349cc55cSDimitry Andric                            SpillOffset.getScalable()) <
92349cc55cSDimitry Andric            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
93349cc55cSDimitry Andric                            Other.SpillOffset.getScalable());
94349cc55cSDimitry Andric   }
95349cc55cSDimitry Andric };
96349cc55cSDimitry Andric 
97349cc55cSDimitry Andric /// Unique identifier for a value defined by an instruction, as a value type.
98349cc55cSDimitry Andric /// Casts back and forth to a uint64_t. Probably replacable with something less
99349cc55cSDimitry Andric /// bit-constrained. Each value identifies the instruction and machine location
100349cc55cSDimitry Andric /// where the value is defined, although there may be no corresponding machine
101349cc55cSDimitry Andric /// operand for it (ex: regmasks clobbering values). The instructions are
102349cc55cSDimitry Andric /// one-based, and definitions that are PHIs have instruction number zero.
103349cc55cSDimitry Andric ///
104349cc55cSDimitry Andric /// The obvious limits of a 1M block function or 1M instruction blocks are
105349cc55cSDimitry Andric /// problematic; but by that point we should probably have bailed out of
106349cc55cSDimitry Andric /// trying to analyse the function.
107349cc55cSDimitry Andric class ValueIDNum {
108349cc55cSDimitry Andric   union {
109349cc55cSDimitry Andric     struct {
110349cc55cSDimitry Andric       uint64_t BlockNo : 20; /// The block where the def happens.
111349cc55cSDimitry Andric       uint64_t InstNo : 20;  /// The Instruction where the def happens.
112349cc55cSDimitry Andric                              /// One based, is distance from start of block.
113349cc55cSDimitry Andric       uint64_t LocNo
114349cc55cSDimitry Andric           : NUM_LOC_BITS; /// The machine location where the def happens.
115349cc55cSDimitry Andric     } s;
116349cc55cSDimitry Andric     uint64_t Value;
117349cc55cSDimitry Andric   } u;
118349cc55cSDimitry Andric 
119349cc55cSDimitry Andric   static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
120349cc55cSDimitry Andric 
121349cc55cSDimitry Andric public:
122349cc55cSDimitry Andric   // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
123349cc55cSDimitry Andric   // of values to work.
124349cc55cSDimitry Andric   ValueIDNum() { u.Value = EmptyValue.asU64(); }
125349cc55cSDimitry Andric 
126349cc55cSDimitry Andric   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
127349cc55cSDimitry Andric     u.s = {Block, Inst, Loc};
128349cc55cSDimitry Andric   }
129349cc55cSDimitry Andric 
130349cc55cSDimitry Andric   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
131349cc55cSDimitry Andric     u.s = {Block, Inst, Loc.asU64()};
132349cc55cSDimitry Andric   }
133349cc55cSDimitry Andric 
134349cc55cSDimitry Andric   uint64_t getBlock() const { return u.s.BlockNo; }
135349cc55cSDimitry Andric   uint64_t getInst() const { return u.s.InstNo; }
136349cc55cSDimitry Andric   uint64_t getLoc() const { return u.s.LocNo; }
137349cc55cSDimitry Andric   bool isPHI() const { return u.s.InstNo == 0; }
138349cc55cSDimitry Andric 
139349cc55cSDimitry Andric   uint64_t asU64() const { return u.Value; }
140349cc55cSDimitry Andric 
141349cc55cSDimitry Andric   static ValueIDNum fromU64(uint64_t v) {
142349cc55cSDimitry Andric     ValueIDNum Val;
143349cc55cSDimitry Andric     Val.u.Value = v;
144349cc55cSDimitry Andric     return Val;
145349cc55cSDimitry Andric   }
146349cc55cSDimitry Andric 
147349cc55cSDimitry Andric   bool operator<(const ValueIDNum &Other) const {
148349cc55cSDimitry Andric     return asU64() < Other.asU64();
149349cc55cSDimitry Andric   }
150349cc55cSDimitry Andric 
151349cc55cSDimitry Andric   bool operator==(const ValueIDNum &Other) const {
152349cc55cSDimitry Andric     return u.Value == Other.u.Value;
153349cc55cSDimitry Andric   }
154349cc55cSDimitry Andric 
155349cc55cSDimitry Andric   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
156349cc55cSDimitry Andric 
157349cc55cSDimitry Andric   std::string asString(const std::string &mlocname) const {
158349cc55cSDimitry Andric     return Twine("Value{bb: ")
159349cc55cSDimitry Andric         .concat(Twine(u.s.BlockNo)
160349cc55cSDimitry Andric                     .concat(Twine(", inst: ")
161349cc55cSDimitry Andric                                 .concat((u.s.InstNo ? Twine(u.s.InstNo)
162349cc55cSDimitry Andric                                                     : Twine("live-in"))
163349cc55cSDimitry Andric                                             .concat(Twine(", loc: ").concat(
164349cc55cSDimitry Andric                                                 Twine(mlocname)))
165349cc55cSDimitry Andric                                             .concat(Twine("}")))))
166349cc55cSDimitry Andric         .str();
167349cc55cSDimitry Andric   }
168349cc55cSDimitry Andric 
169349cc55cSDimitry Andric   static ValueIDNum EmptyValue;
170349cc55cSDimitry Andric   static ValueIDNum TombstoneValue;
171349cc55cSDimitry Andric };
172349cc55cSDimitry Andric 
173bdd1243dSDimitry Andric } // End namespace LiveDebugValues
174bdd1243dSDimitry Andric 
175bdd1243dSDimitry Andric namespace llvm {
176bdd1243dSDimitry Andric using namespace LiveDebugValues;
177bdd1243dSDimitry Andric 
178bdd1243dSDimitry Andric template <> struct DenseMapInfo<LocIdx> {
179bdd1243dSDimitry Andric   static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); }
180bdd1243dSDimitry Andric   static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); }
181bdd1243dSDimitry Andric 
182bdd1243dSDimitry Andric   static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
183bdd1243dSDimitry Andric 
184bdd1243dSDimitry Andric   static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
185bdd1243dSDimitry Andric };
186bdd1243dSDimitry Andric 
187bdd1243dSDimitry Andric template <> struct DenseMapInfo<ValueIDNum> {
188bdd1243dSDimitry Andric   static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; }
189bdd1243dSDimitry Andric   static inline ValueIDNum getTombstoneKey() {
190bdd1243dSDimitry Andric     return ValueIDNum::TombstoneValue;
191bdd1243dSDimitry Andric   }
192bdd1243dSDimitry Andric 
193bdd1243dSDimitry Andric   static unsigned getHashValue(const ValueIDNum &Val) {
194bdd1243dSDimitry Andric     return hash_value(Val.asU64());
195bdd1243dSDimitry Andric   }
196bdd1243dSDimitry Andric 
197bdd1243dSDimitry Andric   static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
198bdd1243dSDimitry Andric     return A == B;
199bdd1243dSDimitry Andric   }
200bdd1243dSDimitry Andric };
201bdd1243dSDimitry Andric 
202bdd1243dSDimitry Andric } // end namespace llvm
203bdd1243dSDimitry Andric 
204bdd1243dSDimitry Andric namespace LiveDebugValues {
205bdd1243dSDimitry Andric using namespace llvm;
206bdd1243dSDimitry Andric 
20781ad6265SDimitry Andric /// Type for a table of values in a block.
20881ad6265SDimitry Andric using ValueTable = std::unique_ptr<ValueIDNum[]>;
20981ad6265SDimitry Andric 
21081ad6265SDimitry Andric /// Type for a table-of-table-of-values, i.e., the collection of either
21181ad6265SDimitry Andric /// live-in or live-out values for each block in the function.
21281ad6265SDimitry Andric using FuncValueTable = std::unique_ptr<ValueTable[]>;
21381ad6265SDimitry Andric 
214349cc55cSDimitry Andric /// Thin wrapper around an integer -- designed to give more type safety to
215349cc55cSDimitry Andric /// spill location numbers.
216349cc55cSDimitry Andric class SpillLocationNo {
217349cc55cSDimitry Andric public:
218349cc55cSDimitry Andric   explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
219349cc55cSDimitry Andric   unsigned SpillNo;
220349cc55cSDimitry Andric   unsigned id() const { return SpillNo; }
221349cc55cSDimitry Andric 
222349cc55cSDimitry Andric   bool operator<(const SpillLocationNo &Other) const {
223349cc55cSDimitry Andric     return SpillNo < Other.SpillNo;
224349cc55cSDimitry Andric   }
225349cc55cSDimitry Andric 
226349cc55cSDimitry Andric   bool operator==(const SpillLocationNo &Other) const {
227349cc55cSDimitry Andric     return SpillNo == Other.SpillNo;
228349cc55cSDimitry Andric   }
229349cc55cSDimitry Andric   bool operator!=(const SpillLocationNo &Other) const {
230349cc55cSDimitry Andric     return !(*this == Other);
231349cc55cSDimitry Andric   }
232349cc55cSDimitry Andric };
233349cc55cSDimitry Andric 
234349cc55cSDimitry Andric /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
23581ad6265SDimitry Andric /// the value, and Boolean of whether or not it's indirect.
236349cc55cSDimitry Andric class DbgValueProperties {
237349cc55cSDimitry Andric public:
238bdd1243dSDimitry Andric   DbgValueProperties(const DIExpression *DIExpr, bool Indirect, bool IsVariadic)
239bdd1243dSDimitry Andric       : DIExpr(DIExpr), Indirect(Indirect), IsVariadic(IsVariadic) {}
240349cc55cSDimitry Andric 
241349cc55cSDimitry Andric   /// Extract properties from an existing DBG_VALUE instruction.
242349cc55cSDimitry Andric   DbgValueProperties(const MachineInstr &MI) {
243349cc55cSDimitry Andric     assert(MI.isDebugValue());
244bdd1243dSDimitry Andric     assert(MI.getDebugExpression()->getNumLocationOperands() == 0 ||
245bdd1243dSDimitry Andric            MI.isDebugValueList() || MI.isUndefDebugValue());
246bdd1243dSDimitry Andric     IsVariadic = MI.isDebugValueList();
247349cc55cSDimitry Andric     DIExpr = MI.getDebugExpression();
248bdd1243dSDimitry Andric     Indirect = MI.isDebugOffsetImm();
249bdd1243dSDimitry Andric   }
250bdd1243dSDimitry Andric 
251bdd1243dSDimitry Andric   bool isJoinable(const DbgValueProperties &Other) const {
252bdd1243dSDimitry Andric     return DIExpression::isEqualExpression(DIExpr, Indirect, Other.DIExpr,
253bdd1243dSDimitry Andric                                            Other.Indirect);
254349cc55cSDimitry Andric   }
255349cc55cSDimitry Andric 
256349cc55cSDimitry Andric   bool operator==(const DbgValueProperties &Other) const {
257bdd1243dSDimitry Andric     return std::tie(DIExpr, Indirect, IsVariadic) ==
258bdd1243dSDimitry Andric            std::tie(Other.DIExpr, Other.Indirect, Other.IsVariadic);
259349cc55cSDimitry Andric   }
260349cc55cSDimitry Andric 
261349cc55cSDimitry Andric   bool operator!=(const DbgValueProperties &Other) const {
262349cc55cSDimitry Andric     return !(*this == Other);
263349cc55cSDimitry Andric   }
264349cc55cSDimitry Andric 
265bdd1243dSDimitry Andric   unsigned getLocationOpCount() const {
266bdd1243dSDimitry Andric     return IsVariadic ? DIExpr->getNumLocationOperands() : 1;
267bdd1243dSDimitry Andric   }
268bdd1243dSDimitry Andric 
269349cc55cSDimitry Andric   const DIExpression *DIExpr;
270349cc55cSDimitry Andric   bool Indirect;
271bdd1243dSDimitry Andric   bool IsVariadic;
272349cc55cSDimitry Andric };
273349cc55cSDimitry Andric 
274bdd1243dSDimitry Andric /// TODO: Might pack better if we changed this to a Struct of Arrays, since
275bdd1243dSDimitry Andric /// MachineOperand is width 32, making this struct width 33. We could also
276bdd1243dSDimitry Andric /// potentially avoid storing the whole MachineOperand (sizeof=32), instead
277bdd1243dSDimitry Andric /// choosing to store just the contents portion (sizeof=8) and a Kind enum,
278bdd1243dSDimitry Andric /// since we already know it is some type of immediate value.
279bdd1243dSDimitry Andric /// Stores a single debug operand, which can either be a MachineOperand for
280bdd1243dSDimitry Andric /// directly storing immediate values, or a ValueIDNum representing some value
281bdd1243dSDimitry Andric /// computed at some point in the program. IsConst is used as a discriminator.
282bdd1243dSDimitry Andric struct DbgOp {
283bdd1243dSDimitry Andric   union {
284bdd1243dSDimitry Andric     ValueIDNum ID;
285bdd1243dSDimitry Andric     MachineOperand MO;
286bdd1243dSDimitry Andric   };
287bdd1243dSDimitry Andric   bool IsConst;
288bdd1243dSDimitry Andric 
289bdd1243dSDimitry Andric   DbgOp() : ID(ValueIDNum::EmptyValue), IsConst(false) {}
290bdd1243dSDimitry Andric   DbgOp(ValueIDNum ID) : ID(ID), IsConst(false) {}
291bdd1243dSDimitry Andric   DbgOp(MachineOperand MO) : MO(MO), IsConst(true) {}
292bdd1243dSDimitry Andric 
293bdd1243dSDimitry Andric   bool isUndef() const { return !IsConst && ID == ValueIDNum::EmptyValue; }
294bdd1243dSDimitry Andric 
295bdd1243dSDimitry Andric #ifndef NDEBUG
296bdd1243dSDimitry Andric   void dump(const MLocTracker *MTrack) const;
297bdd1243dSDimitry Andric #endif
298bdd1243dSDimitry Andric };
299bdd1243dSDimitry Andric 
300bdd1243dSDimitry Andric /// A DbgOp whose ID (if any) has resolved to an actual location, LocIdx. Used
301bdd1243dSDimitry Andric /// when working with concrete debug values, i.e. when joining MLocs and VLocs
302bdd1243dSDimitry Andric /// in the TransferTracker or emitting DBG_VALUE/DBG_VALUE_LIST instructions in
303bdd1243dSDimitry Andric /// the MLocTracker.
304bdd1243dSDimitry Andric struct ResolvedDbgOp {
305bdd1243dSDimitry Andric   union {
306bdd1243dSDimitry Andric     LocIdx Loc;
307bdd1243dSDimitry Andric     MachineOperand MO;
308bdd1243dSDimitry Andric   };
309bdd1243dSDimitry Andric   bool IsConst;
310bdd1243dSDimitry Andric 
311bdd1243dSDimitry Andric   ResolvedDbgOp(LocIdx Loc) : Loc(Loc), IsConst(false) {}
312bdd1243dSDimitry Andric   ResolvedDbgOp(MachineOperand MO) : MO(MO), IsConst(true) {}
313bdd1243dSDimitry Andric 
314bdd1243dSDimitry Andric   bool operator==(const ResolvedDbgOp &Other) const {
315bdd1243dSDimitry Andric     if (IsConst != Other.IsConst)
316bdd1243dSDimitry Andric       return false;
317bdd1243dSDimitry Andric     if (IsConst)
318bdd1243dSDimitry Andric       return MO.isIdenticalTo(Other.MO);
319bdd1243dSDimitry Andric     return Loc == Other.Loc;
320bdd1243dSDimitry Andric   }
321bdd1243dSDimitry Andric 
322bdd1243dSDimitry Andric #ifndef NDEBUG
323bdd1243dSDimitry Andric   void dump(const MLocTracker *MTrack) const;
324bdd1243dSDimitry Andric #endif
325bdd1243dSDimitry Andric };
326bdd1243dSDimitry Andric 
327bdd1243dSDimitry Andric /// An ID used in the DbgOpIDMap (below) to lookup a stored DbgOp. This is used
328bdd1243dSDimitry Andric /// in place of actual DbgOps inside of a DbgValue to reduce its size, as
329bdd1243dSDimitry Andric /// DbgValue is very frequently used and passed around, and the actual DbgOp is
330bdd1243dSDimitry Andric /// over 8x larger than this class, due to storing a MachineOperand. This ID
331bdd1243dSDimitry Andric /// should be equal for all equal DbgOps, and also encodes whether the mapped
332bdd1243dSDimitry Andric /// DbgOp is a constant, meaning that for simple equality or const-ness checks
333bdd1243dSDimitry Andric /// it is not necessary to lookup this ID.
334bdd1243dSDimitry Andric struct DbgOpID {
335bdd1243dSDimitry Andric   struct IsConstIndexPair {
336bdd1243dSDimitry Andric     uint32_t IsConst : 1;
337bdd1243dSDimitry Andric     uint32_t Index : 31;
338bdd1243dSDimitry Andric   };
339bdd1243dSDimitry Andric 
340bdd1243dSDimitry Andric   union {
341bdd1243dSDimitry Andric     struct IsConstIndexPair ID;
342bdd1243dSDimitry Andric     uint32_t RawID;
343bdd1243dSDimitry Andric   };
344bdd1243dSDimitry Andric 
345bdd1243dSDimitry Andric   DbgOpID() : RawID(UndefID.RawID) {
346bdd1243dSDimitry Andric     static_assert(sizeof(DbgOpID) == 4, "DbgOpID should fit within 4 bytes.");
347bdd1243dSDimitry Andric   }
348bdd1243dSDimitry Andric   DbgOpID(uint32_t RawID) : RawID(RawID) {}
349bdd1243dSDimitry Andric   DbgOpID(bool IsConst, uint32_t Index) : ID({IsConst, Index}) {}
350bdd1243dSDimitry Andric 
351bdd1243dSDimitry Andric   static DbgOpID UndefID;
352bdd1243dSDimitry Andric 
353bdd1243dSDimitry Andric   bool operator==(const DbgOpID &Other) const { return RawID == Other.RawID; }
354bdd1243dSDimitry Andric   bool operator!=(const DbgOpID &Other) const { return !(*this == Other); }
355bdd1243dSDimitry Andric 
356bdd1243dSDimitry Andric   uint32_t asU32() const { return RawID; }
357bdd1243dSDimitry Andric 
358bdd1243dSDimitry Andric   bool isUndef() const { return *this == UndefID; }
359bdd1243dSDimitry Andric   bool isConst() const { return ID.IsConst && !isUndef(); }
360bdd1243dSDimitry Andric   uint32_t getIndex() const { return ID.Index; }
361bdd1243dSDimitry Andric 
362bdd1243dSDimitry Andric #ifndef NDEBUG
363bdd1243dSDimitry Andric   void dump(const MLocTracker *MTrack, const DbgOpIDMap *OpStore) const;
364bdd1243dSDimitry Andric #endif
365bdd1243dSDimitry Andric };
366bdd1243dSDimitry Andric 
367bdd1243dSDimitry Andric /// Class storing the complete set of values that are observed by DbgValues
368bdd1243dSDimitry Andric /// within the current function. Allows 2-way lookup, with `find` returning the
369bdd1243dSDimitry Andric /// Op for a given ID and `insert` returning the ID for a given Op (creating one
370bdd1243dSDimitry Andric /// if none exists).
371bdd1243dSDimitry Andric class DbgOpIDMap {
372bdd1243dSDimitry Andric 
373bdd1243dSDimitry Andric   SmallVector<ValueIDNum, 0> ValueOps;
374bdd1243dSDimitry Andric   SmallVector<MachineOperand, 0> ConstOps;
375bdd1243dSDimitry Andric 
376bdd1243dSDimitry Andric   DenseMap<ValueIDNum, DbgOpID> ValueOpToID;
377bdd1243dSDimitry Andric   DenseMap<MachineOperand, DbgOpID> ConstOpToID;
378bdd1243dSDimitry Andric 
379bdd1243dSDimitry Andric public:
380bdd1243dSDimitry Andric   /// If \p Op does not already exist in this map, it is inserted and the
381bdd1243dSDimitry Andric   /// corresponding DbgOpID is returned. If Op already exists in this map, then
382bdd1243dSDimitry Andric   /// no change is made and the existing ID for Op is returned.
383bdd1243dSDimitry Andric   /// Calling this with the undef DbgOp will always return DbgOpID::UndefID.
384bdd1243dSDimitry Andric   DbgOpID insert(DbgOp Op) {
385bdd1243dSDimitry Andric     if (Op.isUndef())
386bdd1243dSDimitry Andric       return DbgOpID::UndefID;
387bdd1243dSDimitry Andric     if (Op.IsConst)
388bdd1243dSDimitry Andric       return insertConstOp(Op.MO);
389bdd1243dSDimitry Andric     return insertValueOp(Op.ID);
390bdd1243dSDimitry Andric   }
391bdd1243dSDimitry Andric   /// Returns the DbgOp associated with \p ID. Should only be used for IDs
392bdd1243dSDimitry Andric   /// returned from calling `insert` from this map or DbgOpID::UndefID.
393bdd1243dSDimitry Andric   DbgOp find(DbgOpID ID) const {
394bdd1243dSDimitry Andric     if (ID == DbgOpID::UndefID)
395bdd1243dSDimitry Andric       return DbgOp();
396bdd1243dSDimitry Andric     if (ID.isConst())
397bdd1243dSDimitry Andric       return DbgOp(ConstOps[ID.getIndex()]);
398bdd1243dSDimitry Andric     return DbgOp(ValueOps[ID.getIndex()]);
399bdd1243dSDimitry Andric   }
400bdd1243dSDimitry Andric 
401bdd1243dSDimitry Andric   void clear() {
402bdd1243dSDimitry Andric     ValueOps.clear();
403bdd1243dSDimitry Andric     ConstOps.clear();
404bdd1243dSDimitry Andric     ValueOpToID.clear();
405bdd1243dSDimitry Andric     ConstOpToID.clear();
406bdd1243dSDimitry Andric   }
407bdd1243dSDimitry Andric 
408bdd1243dSDimitry Andric private:
409bdd1243dSDimitry Andric   DbgOpID insertConstOp(MachineOperand &MO) {
410bdd1243dSDimitry Andric     auto ExistingIt = ConstOpToID.find(MO);
411bdd1243dSDimitry Andric     if (ExistingIt != ConstOpToID.end())
412bdd1243dSDimitry Andric       return ExistingIt->second;
413bdd1243dSDimitry Andric     DbgOpID ID(true, ConstOps.size());
414bdd1243dSDimitry Andric     ConstOpToID.insert(std::make_pair(MO, ID));
415bdd1243dSDimitry Andric     ConstOps.push_back(MO);
416bdd1243dSDimitry Andric     return ID;
417bdd1243dSDimitry Andric   }
418bdd1243dSDimitry Andric   DbgOpID insertValueOp(ValueIDNum VID) {
419bdd1243dSDimitry Andric     auto ExistingIt = ValueOpToID.find(VID);
420bdd1243dSDimitry Andric     if (ExistingIt != ValueOpToID.end())
421bdd1243dSDimitry Andric       return ExistingIt->second;
422bdd1243dSDimitry Andric     DbgOpID ID(false, ValueOps.size());
423bdd1243dSDimitry Andric     ValueOpToID.insert(std::make_pair(VID, ID));
424bdd1243dSDimitry Andric     ValueOps.push_back(VID);
425bdd1243dSDimitry Andric     return ID;
426bdd1243dSDimitry Andric   }
427bdd1243dSDimitry Andric };
428bdd1243dSDimitry Andric 
429bdd1243dSDimitry Andric // We set the maximum number of operands that we will handle to keep DbgValue
430bdd1243dSDimitry Andric // within a reasonable size (64 bytes), as we store and pass a lot of them
431bdd1243dSDimitry Andric // around.
432bdd1243dSDimitry Andric #define MAX_DBG_OPS 8
433bdd1243dSDimitry Andric 
434bdd1243dSDimitry Andric /// Class recording the (high level) _value_ of a variable. Identifies the value
435bdd1243dSDimitry Andric /// of the variable as a list of ValueIDNums and constant MachineOperands, or as
436bdd1243dSDimitry Andric /// an empty list for undef debug values or VPHI values which we have not found
437bdd1243dSDimitry Andric /// valid locations for.
438349cc55cSDimitry Andric /// This class also stores meta-information about how the value is qualified.
439349cc55cSDimitry Andric /// Used to reason about variable values when performing the second
440349cc55cSDimitry Andric /// (DebugVariable specific) dataflow analysis.
441349cc55cSDimitry Andric class DbgValue {
442bdd1243dSDimitry Andric private:
443bdd1243dSDimitry Andric   /// If Kind is Def or VPHI, the set of IDs corresponding to the DbgOps that
444bdd1243dSDimitry Andric   /// are used. VPHIs set every ID to EmptyID when we have not found a valid
445bdd1243dSDimitry Andric   /// machine-value for every operand, and sets them to the corresponding
446bdd1243dSDimitry Andric   /// machine-values when we have found all of them.
447bdd1243dSDimitry Andric   DbgOpID DbgOps[MAX_DBG_OPS];
448bdd1243dSDimitry Andric   unsigned OpCount;
449bdd1243dSDimitry Andric 
450349cc55cSDimitry Andric public:
451349cc55cSDimitry Andric   /// For a NoVal or VPHI DbgValue, which block it was generated in.
452349cc55cSDimitry Andric   int BlockNo;
453349cc55cSDimitry Andric 
454349cc55cSDimitry Andric   /// Qualifiers for the ValueIDNum above.
455349cc55cSDimitry Andric   DbgValueProperties Properties;
456349cc55cSDimitry Andric 
457349cc55cSDimitry Andric   typedef enum {
458349cc55cSDimitry Andric     Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
459bdd1243dSDimitry Andric     Def,   // This value is defined by some combination of constants,
460bdd1243dSDimitry Andric            // instructions, or PHI values.
461349cc55cSDimitry Andric     VPHI,  // Incoming values to BlockNo differ, those values must be joined by
462349cc55cSDimitry Andric            // a PHI in this block.
463349cc55cSDimitry Andric     NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
464349cc55cSDimitry Andric            // before dominating blocks values are propagated in.
465349cc55cSDimitry Andric   } KindT;
466349cc55cSDimitry Andric   /// Discriminator for whether this is a constant or an in-program value.
467349cc55cSDimitry Andric   KindT Kind;
468349cc55cSDimitry Andric 
469bdd1243dSDimitry Andric   DbgValue(ArrayRef<DbgOpID> DbgOps, const DbgValueProperties &Prop)
470bdd1243dSDimitry Andric       : OpCount(DbgOps.size()), BlockNo(0), Properties(Prop), Kind(Def) {
471bdd1243dSDimitry Andric     static_assert(sizeof(DbgValue) <= 64,
472bdd1243dSDimitry Andric                   "DbgValue should fit within 64 bytes.");
473bdd1243dSDimitry Andric     assert(DbgOps.size() == Prop.getLocationOpCount());
474bdd1243dSDimitry Andric     if (DbgOps.size() > MAX_DBG_OPS ||
475bdd1243dSDimitry Andric         any_of(DbgOps, [](DbgOpID ID) { return ID.isUndef(); })) {
476bdd1243dSDimitry Andric       Kind = Undef;
477bdd1243dSDimitry Andric       OpCount = 0;
478bdd1243dSDimitry Andric #define DEBUG_TYPE "LiveDebugValues"
479bdd1243dSDimitry Andric       if (DbgOps.size() > MAX_DBG_OPS) {
480bdd1243dSDimitry Andric         LLVM_DEBUG(dbgs() << "Found DbgValue with more than maximum allowed "
481bdd1243dSDimitry Andric                              "operands.\n");
482bdd1243dSDimitry Andric       }
483bdd1243dSDimitry Andric #undef DEBUG_TYPE
484bdd1243dSDimitry Andric     } else {
485bdd1243dSDimitry Andric       for (unsigned Idx = 0; Idx < DbgOps.size(); ++Idx)
486bdd1243dSDimitry Andric         this->DbgOps[Idx] = DbgOps[Idx];
487bdd1243dSDimitry Andric     }
488349cc55cSDimitry Andric   }
489349cc55cSDimitry Andric 
490349cc55cSDimitry Andric   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
491bdd1243dSDimitry Andric       : OpCount(0), BlockNo(BlockNo), Properties(Prop), Kind(Kind) {
492349cc55cSDimitry Andric     assert(Kind == NoVal || Kind == VPHI);
493349cc55cSDimitry Andric   }
494349cc55cSDimitry Andric 
495349cc55cSDimitry Andric   DbgValue(const DbgValueProperties &Prop, KindT Kind)
496bdd1243dSDimitry Andric       : OpCount(0), BlockNo(0), Properties(Prop), Kind(Kind) {
497349cc55cSDimitry Andric     assert(Kind == Undef &&
498349cc55cSDimitry Andric            "Empty DbgValue constructor must pass in Undef kind");
499349cc55cSDimitry Andric   }
500349cc55cSDimitry Andric 
501349cc55cSDimitry Andric #ifndef NDEBUG
502bdd1243dSDimitry Andric   void dump(const MLocTracker *MTrack = nullptr,
503bdd1243dSDimitry Andric             const DbgOpIDMap *OpStore = nullptr) const;
504349cc55cSDimitry Andric #endif
505349cc55cSDimitry Andric 
506349cc55cSDimitry Andric   bool operator==(const DbgValue &Other) const {
507349cc55cSDimitry Andric     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
508349cc55cSDimitry Andric       return false;
509bdd1243dSDimitry Andric     else if (Kind == Def && !equal(getDbgOpIDs(), Other.getDbgOpIDs()))
510349cc55cSDimitry Andric       return false;
511349cc55cSDimitry Andric     else if (Kind == NoVal && BlockNo != Other.BlockNo)
512349cc55cSDimitry Andric       return false;
513349cc55cSDimitry Andric     else if (Kind == VPHI && BlockNo != Other.BlockNo)
514349cc55cSDimitry Andric       return false;
515bdd1243dSDimitry Andric     else if (Kind == VPHI && !equal(getDbgOpIDs(), Other.getDbgOpIDs()))
516349cc55cSDimitry Andric       return false;
517349cc55cSDimitry Andric 
518349cc55cSDimitry Andric     return true;
519349cc55cSDimitry Andric   }
520349cc55cSDimitry Andric 
521349cc55cSDimitry Andric   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
522bdd1243dSDimitry Andric 
523bdd1243dSDimitry Andric   // Returns an array of all the machine values used to calculate this variable
524bdd1243dSDimitry Andric   // value, or an empty list for an Undef or unjoined VPHI.
525bdd1243dSDimitry Andric   ArrayRef<DbgOpID> getDbgOpIDs() const { return {DbgOps, OpCount}; }
526bdd1243dSDimitry Andric 
527bdd1243dSDimitry Andric   // Returns either DbgOps[Index] if this DbgValue has Debug Operands, or
528bdd1243dSDimitry Andric   // the ID for ValueIDNum::EmptyValue otherwise (i.e. if this is an Undef,
529bdd1243dSDimitry Andric   // NoVal, or an unjoined VPHI).
530bdd1243dSDimitry Andric   DbgOpID getDbgOpID(unsigned Index) const {
531bdd1243dSDimitry Andric     if (!OpCount)
532bdd1243dSDimitry Andric       return DbgOpID::UndefID;
533bdd1243dSDimitry Andric     assert(Index < OpCount);
534bdd1243dSDimitry Andric     return DbgOps[Index];
535bdd1243dSDimitry Andric   }
536bdd1243dSDimitry Andric   // Replaces this DbgValue's existing DbgOpIDs (if any) with the contents of
537bdd1243dSDimitry Andric   // \p NewIDs. The number of DbgOpIDs passed must be equal to the number of
538bdd1243dSDimitry Andric   // arguments expected by this DbgValue's properties (the return value of
539bdd1243dSDimitry Andric   // `getLocationOpCount()`).
540bdd1243dSDimitry Andric   void setDbgOpIDs(ArrayRef<DbgOpID> NewIDs) {
541bdd1243dSDimitry Andric     // We can go from no ops to some ops, but not from some ops to no ops.
542bdd1243dSDimitry Andric     assert(NewIDs.size() == getLocationOpCount() &&
543bdd1243dSDimitry Andric            "Incorrect number of Debug Operands for this DbgValue.");
544bdd1243dSDimitry Andric     OpCount = NewIDs.size();
545bdd1243dSDimitry Andric     for (unsigned Idx = 0; Idx < NewIDs.size(); ++Idx)
546bdd1243dSDimitry Andric       DbgOps[Idx] = NewIDs[Idx];
547bdd1243dSDimitry Andric   }
548bdd1243dSDimitry Andric 
549bdd1243dSDimitry Andric   // The number of debug operands expected by this DbgValue's expression.
550bdd1243dSDimitry Andric   // getDbgOpIDs() should return an array of this length, unless this is an
551bdd1243dSDimitry Andric   // Undef or an unjoined VPHI.
552bdd1243dSDimitry Andric   unsigned getLocationOpCount() const {
553bdd1243dSDimitry Andric     return Properties.getLocationOpCount();
554bdd1243dSDimitry Andric   }
555bdd1243dSDimitry Andric 
556bdd1243dSDimitry Andric   // Returns true if this or Other are unjoined PHIs, which do not have defined
557bdd1243dSDimitry Andric   // Loc Ops, or if the `n`th Loc Op for this has a different constness to the
558bdd1243dSDimitry Andric   // `n`th Loc Op for Other.
559bdd1243dSDimitry Andric   bool hasJoinableLocOps(const DbgValue &Other) const {
560bdd1243dSDimitry Andric     if (isUnjoinedPHI() || Other.isUnjoinedPHI())
561bdd1243dSDimitry Andric       return true;
562bdd1243dSDimitry Andric     for (unsigned Idx = 0; Idx < getLocationOpCount(); ++Idx) {
563bdd1243dSDimitry Andric       if (getDbgOpID(Idx).isConst() != Other.getDbgOpID(Idx).isConst())
564bdd1243dSDimitry Andric         return false;
565bdd1243dSDimitry Andric     }
566bdd1243dSDimitry Andric     return true;
567bdd1243dSDimitry Andric   }
568bdd1243dSDimitry Andric 
569bdd1243dSDimitry Andric   bool isUnjoinedPHI() const { return Kind == VPHI && OpCount == 0; }
570bdd1243dSDimitry Andric 
571bdd1243dSDimitry Andric   bool hasIdenticalValidLocOps(const DbgValue &Other) const {
572bdd1243dSDimitry Andric     if (!OpCount)
573bdd1243dSDimitry Andric       return false;
574bdd1243dSDimitry Andric     return equal(getDbgOpIDs(), Other.getDbgOpIDs());
575bdd1243dSDimitry Andric   }
576349cc55cSDimitry Andric };
577349cc55cSDimitry Andric 
578349cc55cSDimitry Andric class LocIdxToIndexFunctor {
579349cc55cSDimitry Andric public:
580349cc55cSDimitry Andric   using argument_type = LocIdx;
581349cc55cSDimitry Andric   unsigned operator()(const LocIdx &L) const { return L.asU64(); }
582349cc55cSDimitry Andric };
583349cc55cSDimitry Andric 
584349cc55cSDimitry Andric /// Tracker for what values are in machine locations. Listens to the Things
585349cc55cSDimitry Andric /// being Done by various instructions, and maintains a table of what machine
586349cc55cSDimitry Andric /// locations have what values (as defined by a ValueIDNum).
587349cc55cSDimitry Andric ///
588349cc55cSDimitry Andric /// There are potentially a much larger number of machine locations on the
589349cc55cSDimitry Andric /// target machine than the actual working-set size of the function. On x86 for
590349cc55cSDimitry Andric /// example, we're extremely unlikely to want to track values through control
591349cc55cSDimitry Andric /// or debug registers. To avoid doing so, MLocTracker has several layers of
592349cc55cSDimitry Andric /// indirection going on, described below, to avoid unnecessarily tracking
593349cc55cSDimitry Andric /// any location.
594349cc55cSDimitry Andric ///
595349cc55cSDimitry Andric /// Here's a sort of diagram of the indexes, read from the bottom up:
596349cc55cSDimitry Andric ///
597349cc55cSDimitry Andric ///           Size on stack   Offset on stack
598349cc55cSDimitry Andric ///                 \              /
599349cc55cSDimitry Andric ///          Stack Idx (Where in slot is this?)
600349cc55cSDimitry Andric ///                         /
601349cc55cSDimitry Andric ///                        /
602349cc55cSDimitry Andric /// Slot Num (%stack.0)   /
603349cc55cSDimitry Andric /// FrameIdx => SpillNum /
604349cc55cSDimitry Andric ///              \      /
605349cc55cSDimitry Andric ///           SpillID (int)              Register number (int)
606349cc55cSDimitry Andric ///                      \                  /
607349cc55cSDimitry Andric ///                      LocationID => LocIdx
608349cc55cSDimitry Andric ///                                |
609349cc55cSDimitry Andric ///                       LocIdx => ValueIDNum
610349cc55cSDimitry Andric ///
611349cc55cSDimitry Andric /// The aim here is that the LocIdx => ValueIDNum vector is just an array of
612349cc55cSDimitry Andric /// values in numbered locations, so that later analyses can ignore whether the
613349cc55cSDimitry Andric /// location is a register or otherwise. To map a register / spill location to
614349cc55cSDimitry Andric /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
615349cc55cSDimitry Andric /// build a LocationID for a stack slot, you need to combine identifiers for
616349cc55cSDimitry Andric /// which stack slot it is and where within that slot is being described.
617349cc55cSDimitry Andric ///
618349cc55cSDimitry Andric /// Register mask operands cause trouble by technically defining every register;
619349cc55cSDimitry Andric /// various hacks are used to avoid tracking registers that are never read and
620349cc55cSDimitry Andric /// only written by regmasks.
621349cc55cSDimitry Andric class MLocTracker {
622349cc55cSDimitry Andric public:
623349cc55cSDimitry Andric   MachineFunction &MF;
624349cc55cSDimitry Andric   const TargetInstrInfo &TII;
625349cc55cSDimitry Andric   const TargetRegisterInfo &TRI;
626349cc55cSDimitry Andric   const TargetLowering &TLI;
627349cc55cSDimitry Andric 
628349cc55cSDimitry Andric   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
629349cc55cSDimitry Andric   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
630349cc55cSDimitry Andric 
631349cc55cSDimitry Andric   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
632349cc55cSDimitry Andric   /// packed, entries only exist for locations that are being tracked.
633349cc55cSDimitry Andric   LocToValueType LocIdxToIDNum;
634349cc55cSDimitry Andric 
635349cc55cSDimitry Andric   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
636349cc55cSDimitry Andric   /// LocIdx key / number for that location. There are always at least as many
637349cc55cSDimitry Andric   /// as the number of registers on the target -- if the value in the register
638349cc55cSDimitry Andric   /// is not being tracked, then the LocIdx value will be zero. New entries are
639349cc55cSDimitry Andric   /// appended if a new spill slot begins being tracked.
640349cc55cSDimitry Andric   /// This, and the corresponding reverse map persist for the analysis of the
641349cc55cSDimitry Andric   /// whole function, and is necessarying for decoding various vectors of
642349cc55cSDimitry Andric   /// values.
643349cc55cSDimitry Andric   std::vector<LocIdx> LocIDToLocIdx;
644349cc55cSDimitry Andric 
645349cc55cSDimitry Andric   /// Inverse map of LocIDToLocIdx.
646349cc55cSDimitry Andric   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
647349cc55cSDimitry Andric 
648349cc55cSDimitry Andric   /// When clobbering register masks, we chose to not believe the machine model
649349cc55cSDimitry Andric   /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
650349cc55cSDimitry Andric   /// keep a set of them here.
651349cc55cSDimitry Andric   SmallSet<Register, 8> SPAliases;
652349cc55cSDimitry Andric 
653349cc55cSDimitry Andric   /// Unique-ification of spill. Used to number them -- their LocID number is
654349cc55cSDimitry Andric   /// the index in SpillLocs minus one plus NumRegs.
655349cc55cSDimitry Andric   UniqueVector<SpillLoc> SpillLocs;
656349cc55cSDimitry Andric 
657349cc55cSDimitry Andric   // If we discover a new machine location, assign it an mphi with this
658349cc55cSDimitry Andric   // block number.
659*06c3fb27SDimitry Andric   unsigned CurBB = -1;
660349cc55cSDimitry Andric 
661349cc55cSDimitry Andric   /// Cached local copy of the number of registers the target has.
662349cc55cSDimitry Andric   unsigned NumRegs;
663349cc55cSDimitry Andric 
664349cc55cSDimitry Andric   /// Number of slot indexes the target has -- distinct segments of a stack
665349cc55cSDimitry Andric   /// slot that can take on the value of a subregister, when a super-register
666349cc55cSDimitry Andric   /// is written to the stack.
667349cc55cSDimitry Andric   unsigned NumSlotIdxes;
668349cc55cSDimitry Andric 
669349cc55cSDimitry Andric   /// Collection of register mask operands that have been observed. Second part
670349cc55cSDimitry Andric   /// of pair indicates the instruction that they happened in. Used to
671349cc55cSDimitry Andric   /// reconstruct where defs happened if we start tracking a location later
672349cc55cSDimitry Andric   /// on.
673349cc55cSDimitry Andric   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
674349cc55cSDimitry Andric 
675349cc55cSDimitry Andric   /// Pair for describing a position within a stack slot -- first the size in
676349cc55cSDimitry Andric   /// bits, then the offset.
677349cc55cSDimitry Andric   typedef std::pair<unsigned short, unsigned short> StackSlotPos;
678349cc55cSDimitry Andric 
679349cc55cSDimitry Andric   /// Map from a size/offset pair describing a position in a stack slot, to a
680349cc55cSDimitry Andric   /// numeric identifier for that position. Allows easier identification of
681349cc55cSDimitry Andric   /// individual positions.
682349cc55cSDimitry Andric   DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
683349cc55cSDimitry Andric 
684349cc55cSDimitry Andric   /// Inverse of StackSlotIdxes.
685349cc55cSDimitry Andric   DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
686349cc55cSDimitry Andric 
687349cc55cSDimitry Andric   /// Iterator for locations and the values they contain. Dereferencing
688349cc55cSDimitry Andric   /// produces a struct/pair containing the LocIdx key for this location,
689349cc55cSDimitry Andric   /// and a reference to the value currently stored. Simplifies the process
690349cc55cSDimitry Andric   /// of seeking a particular location.
691349cc55cSDimitry Andric   class MLocIterator {
692349cc55cSDimitry Andric     LocToValueType &ValueMap;
693349cc55cSDimitry Andric     LocIdx Idx;
694349cc55cSDimitry Andric 
695349cc55cSDimitry Andric   public:
696349cc55cSDimitry Andric     class value_type {
697349cc55cSDimitry Andric     public:
698349cc55cSDimitry Andric       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
699349cc55cSDimitry Andric       const LocIdx Idx;  /// Read-only index of this location.
700349cc55cSDimitry Andric       ValueIDNum &Value; /// Reference to the stored value at this location.
701349cc55cSDimitry Andric     };
702349cc55cSDimitry Andric 
703349cc55cSDimitry Andric     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
704349cc55cSDimitry Andric         : ValueMap(ValueMap), Idx(Idx) {}
705349cc55cSDimitry Andric 
706349cc55cSDimitry Andric     bool operator==(const MLocIterator &Other) const {
707349cc55cSDimitry Andric       assert(&ValueMap == &Other.ValueMap);
708349cc55cSDimitry Andric       return Idx == Other.Idx;
709349cc55cSDimitry Andric     }
710349cc55cSDimitry Andric 
711349cc55cSDimitry Andric     bool operator!=(const MLocIterator &Other) const {
712349cc55cSDimitry Andric       return !(*this == Other);
713349cc55cSDimitry Andric     }
714349cc55cSDimitry Andric 
715349cc55cSDimitry Andric     void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
716349cc55cSDimitry Andric 
717349cc55cSDimitry Andric     value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
718349cc55cSDimitry Andric   };
719349cc55cSDimitry Andric 
720349cc55cSDimitry Andric   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
721349cc55cSDimitry Andric               const TargetRegisterInfo &TRI, const TargetLowering &TLI);
722349cc55cSDimitry Andric 
723349cc55cSDimitry Andric   /// Produce location ID number for a Register. Provides some small amount of
724349cc55cSDimitry Andric   /// type safety.
725349cc55cSDimitry Andric   /// \param Reg The register we're looking up.
726349cc55cSDimitry Andric   unsigned getLocID(Register Reg) { return Reg.id(); }
727349cc55cSDimitry Andric 
728349cc55cSDimitry Andric   /// Produce location ID number for a spill position.
729349cc55cSDimitry Andric   /// \param Spill The number of the spill we're fetching the location for.
730349cc55cSDimitry Andric   /// \param SpillSubReg Subregister within the spill we're addressing.
731349cc55cSDimitry Andric   unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
732349cc55cSDimitry Andric     unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg);
733349cc55cSDimitry Andric     unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg);
734349cc55cSDimitry Andric     return getLocID(Spill, {Size, Offs});
735349cc55cSDimitry Andric   }
736349cc55cSDimitry Andric 
737349cc55cSDimitry Andric   /// Produce location ID number for a spill position.
738349cc55cSDimitry Andric   /// \param Spill The number of the spill we're fetching the location for.
739349cc55cSDimitry Andric   /// \apram SpillIdx size/offset within the spill slot to be addressed.
740349cc55cSDimitry Andric   unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
741349cc55cSDimitry Andric     unsigned SlotNo = Spill.id() - 1;
742349cc55cSDimitry Andric     SlotNo *= NumSlotIdxes;
743*06c3fb27SDimitry Andric     assert(StackSlotIdxes.contains(Idx));
744349cc55cSDimitry Andric     SlotNo += StackSlotIdxes[Idx];
745349cc55cSDimitry Andric     SlotNo += NumRegs;
746349cc55cSDimitry Andric     return SlotNo;
747349cc55cSDimitry Andric   }
748349cc55cSDimitry Andric 
749349cc55cSDimitry Andric   /// Given a spill number, and a slot within the spill, calculate the ID number
750349cc55cSDimitry Andric   /// for that location.
751349cc55cSDimitry Andric   unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
752349cc55cSDimitry Andric     unsigned SlotNo = Spill.id() - 1;
753349cc55cSDimitry Andric     SlotNo *= NumSlotIdxes;
754349cc55cSDimitry Andric     SlotNo += Idx;
755349cc55cSDimitry Andric     SlotNo += NumRegs;
756349cc55cSDimitry Andric     return SlotNo;
757349cc55cSDimitry Andric   }
758349cc55cSDimitry Andric 
759349cc55cSDimitry Andric   /// Return the spill number that a location ID corresponds to.
760349cc55cSDimitry Andric   SpillLocationNo locIDToSpill(unsigned ID) const {
761349cc55cSDimitry Andric     assert(ID >= NumRegs);
762349cc55cSDimitry Andric     ID -= NumRegs;
763349cc55cSDimitry Andric     // Truncate away the index part, leaving only the spill number.
764349cc55cSDimitry Andric     ID /= NumSlotIdxes;
765349cc55cSDimitry Andric     return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
766349cc55cSDimitry Andric   }
767349cc55cSDimitry Andric 
768349cc55cSDimitry Andric   /// Returns the spill-slot size/offs that a location ID corresponds to.
769349cc55cSDimitry Andric   StackSlotPos locIDToSpillIdx(unsigned ID) const {
770349cc55cSDimitry Andric     assert(ID >= NumRegs);
771349cc55cSDimitry Andric     ID -= NumRegs;
772349cc55cSDimitry Andric     unsigned Idx = ID % NumSlotIdxes;
773349cc55cSDimitry Andric     return StackIdxesToPos.find(Idx)->second;
774349cc55cSDimitry Andric   }
775349cc55cSDimitry Andric 
77604eeddc0SDimitry Andric   unsigned getNumLocs() const { return LocIdxToIDNum.size(); }
777349cc55cSDimitry Andric 
778349cc55cSDimitry Andric   /// Reset all locations to contain a PHI value at the designated block. Used
779349cc55cSDimitry Andric   /// sometimes for actual PHI values, othertimes to indicate the block entry
780349cc55cSDimitry Andric   /// value (before any more information is known).
781349cc55cSDimitry Andric   void setMPhis(unsigned NewCurBB) {
782349cc55cSDimitry Andric     CurBB = NewCurBB;
783349cc55cSDimitry Andric     for (auto Location : locations())
784349cc55cSDimitry Andric       Location.Value = {CurBB, 0, Location.Idx};
785349cc55cSDimitry Andric   }
786349cc55cSDimitry Andric 
787349cc55cSDimitry Andric   /// Load values for each location from array of ValueIDNums. Take current
788349cc55cSDimitry Andric   /// bbnum just in case we read a value from a hitherto untouched register.
78981ad6265SDimitry Andric   void loadFromArray(ValueTable &Locs, unsigned NewCurBB) {
790349cc55cSDimitry Andric     CurBB = NewCurBB;
791349cc55cSDimitry Andric     // Iterate over all tracked locations, and load each locations live-in
792349cc55cSDimitry Andric     // value into our local index.
793349cc55cSDimitry Andric     for (auto Location : locations())
794349cc55cSDimitry Andric       Location.Value = Locs[Location.Idx.asU64()];
795349cc55cSDimitry Andric   }
796349cc55cSDimitry Andric 
797349cc55cSDimitry Andric   /// Wipe any un-necessary location records after traversing a block.
79804eeddc0SDimitry Andric   void reset() {
799349cc55cSDimitry Andric     // We could reset all the location values too; however either loadFromArray
800349cc55cSDimitry Andric     // or setMPhis should be called before this object is re-used. Just
801349cc55cSDimitry Andric     // clear Masks, they're definitely not needed.
802349cc55cSDimitry Andric     Masks.clear();
803349cc55cSDimitry Andric   }
804349cc55cSDimitry Andric 
805349cc55cSDimitry Andric   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
806349cc55cSDimitry Andric   /// the information in this pass uninterpretable.
80704eeddc0SDimitry Andric   void clear() {
808349cc55cSDimitry Andric     reset();
809349cc55cSDimitry Andric     LocIDToLocIdx.clear();
810349cc55cSDimitry Andric     LocIdxToLocID.clear();
811349cc55cSDimitry Andric     LocIdxToIDNum.clear();
812349cc55cSDimitry Andric     // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
813349cc55cSDimitry Andric     // 0
814349cc55cSDimitry Andric     SpillLocs = decltype(SpillLocs)();
815349cc55cSDimitry Andric     StackSlotIdxes.clear();
816349cc55cSDimitry Andric     StackIdxesToPos.clear();
817349cc55cSDimitry Andric 
818349cc55cSDimitry Andric     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
819349cc55cSDimitry Andric   }
820349cc55cSDimitry Andric 
821349cc55cSDimitry Andric   /// Set a locaiton to a certain value.
822349cc55cSDimitry Andric   void setMLoc(LocIdx L, ValueIDNum Num) {
823349cc55cSDimitry Andric     assert(L.asU64() < LocIdxToIDNum.size());
824349cc55cSDimitry Andric     LocIdxToIDNum[L] = Num;
825349cc55cSDimitry Andric   }
826349cc55cSDimitry Andric 
827349cc55cSDimitry Andric   /// Read the value of a particular location
828349cc55cSDimitry Andric   ValueIDNum readMLoc(LocIdx L) {
829349cc55cSDimitry Andric     assert(L.asU64() < LocIdxToIDNum.size());
830349cc55cSDimitry Andric     return LocIdxToIDNum[L];
831349cc55cSDimitry Andric   }
832349cc55cSDimitry Andric 
833349cc55cSDimitry Andric   /// Create a LocIdx for an untracked register ID. Initialize it to either an
834349cc55cSDimitry Andric   /// mphi value representing a live-in, or a recent register mask clobber.
835349cc55cSDimitry Andric   LocIdx trackRegister(unsigned ID);
836349cc55cSDimitry Andric 
837349cc55cSDimitry Andric   LocIdx lookupOrTrackRegister(unsigned ID) {
838349cc55cSDimitry Andric     LocIdx &Index = LocIDToLocIdx[ID];
839349cc55cSDimitry Andric     if (Index.isIllegal())
840349cc55cSDimitry Andric       Index = trackRegister(ID);
841349cc55cSDimitry Andric     return Index;
842349cc55cSDimitry Andric   }
843349cc55cSDimitry Andric 
844349cc55cSDimitry Andric   /// Is register R currently tracked by MLocTracker?
845349cc55cSDimitry Andric   bool isRegisterTracked(Register R) {
846349cc55cSDimitry Andric     LocIdx &Index = LocIDToLocIdx[R];
847349cc55cSDimitry Andric     return !Index.isIllegal();
848349cc55cSDimitry Andric   }
849349cc55cSDimitry Andric 
850349cc55cSDimitry Andric   /// Record a definition of the specified register at the given block / inst.
851349cc55cSDimitry Andric   /// This doesn't take a ValueIDNum, because the definition and its location
852349cc55cSDimitry Andric   /// are synonymous.
853349cc55cSDimitry Andric   void defReg(Register R, unsigned BB, unsigned Inst) {
854349cc55cSDimitry Andric     unsigned ID = getLocID(R);
855349cc55cSDimitry Andric     LocIdx Idx = lookupOrTrackRegister(ID);
856349cc55cSDimitry Andric     ValueIDNum ValueID = {BB, Inst, Idx};
857349cc55cSDimitry Andric     LocIdxToIDNum[Idx] = ValueID;
858349cc55cSDimitry Andric   }
859349cc55cSDimitry Andric 
860349cc55cSDimitry Andric   /// Set a register to a value number. To be used if the value number is
861349cc55cSDimitry Andric   /// known in advance.
862349cc55cSDimitry Andric   void setReg(Register R, ValueIDNum ValueID) {
863349cc55cSDimitry Andric     unsigned ID = getLocID(R);
864349cc55cSDimitry Andric     LocIdx Idx = lookupOrTrackRegister(ID);
865349cc55cSDimitry Andric     LocIdxToIDNum[Idx] = ValueID;
866349cc55cSDimitry Andric   }
867349cc55cSDimitry Andric 
868349cc55cSDimitry Andric   ValueIDNum readReg(Register R) {
869349cc55cSDimitry Andric     unsigned ID = getLocID(R);
870349cc55cSDimitry Andric     LocIdx Idx = lookupOrTrackRegister(ID);
871349cc55cSDimitry Andric     return LocIdxToIDNum[Idx];
872349cc55cSDimitry Andric   }
873349cc55cSDimitry Andric 
874349cc55cSDimitry Andric   /// Reset a register value to zero / empty. Needed to replicate the
875349cc55cSDimitry Andric   /// VarLoc implementation where a copy to/from a register effectively
876349cc55cSDimitry Andric   /// clears the contents of the source register. (Values can only have one
877349cc55cSDimitry Andric   ///  machine location in VarLocBasedImpl).
878349cc55cSDimitry Andric   void wipeRegister(Register R) {
879349cc55cSDimitry Andric     unsigned ID = getLocID(R);
880349cc55cSDimitry Andric     LocIdx Idx = LocIDToLocIdx[ID];
881349cc55cSDimitry Andric     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
882349cc55cSDimitry Andric   }
883349cc55cSDimitry Andric 
884349cc55cSDimitry Andric   /// Determine the LocIdx of an existing register.
885349cc55cSDimitry Andric   LocIdx getRegMLoc(Register R) {
886349cc55cSDimitry Andric     unsigned ID = getLocID(R);
887349cc55cSDimitry Andric     assert(ID < LocIDToLocIdx.size());
888349cc55cSDimitry Andric     assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap.
889349cc55cSDimitry Andric     return LocIDToLocIdx[ID];
890349cc55cSDimitry Andric   }
891349cc55cSDimitry Andric 
892349cc55cSDimitry Andric   /// Record a RegMask operand being executed. Defs any register we currently
893349cc55cSDimitry Andric   /// track, stores a pointer to the mask in case we have to account for it
894349cc55cSDimitry Andric   /// later.
895349cc55cSDimitry Andric   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
896349cc55cSDimitry Andric 
897349cc55cSDimitry Andric   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
898bdd1243dSDimitry Andric   /// Returns std::nullopt when in scenarios where a spill slot could be
899bdd1243dSDimitry Andric   /// tracked, but we would likely run into resource limitations.
900bdd1243dSDimitry Andric   std::optional<SpillLocationNo> getOrTrackSpillLoc(SpillLoc L);
901349cc55cSDimitry Andric 
902349cc55cSDimitry Andric   // Get LocIdx of a spill ID.
903349cc55cSDimitry Andric   LocIdx getSpillMLoc(unsigned SpillID) {
904349cc55cSDimitry Andric     assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap.
905349cc55cSDimitry Andric     return LocIDToLocIdx[SpillID];
906349cc55cSDimitry Andric   }
907349cc55cSDimitry Andric 
908349cc55cSDimitry Andric   /// Return true if Idx is a spill machine location.
909349cc55cSDimitry Andric   bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
910349cc55cSDimitry Andric 
91181ad6265SDimitry Andric   /// How large is this location (aka, how wide is a value defined there?).
91281ad6265SDimitry Andric   unsigned getLocSizeInBits(LocIdx L) const {
91381ad6265SDimitry Andric     unsigned ID = LocIdxToLocID[L];
91481ad6265SDimitry Andric     if (!isSpill(L)) {
91581ad6265SDimitry Andric       return TRI.getRegSizeInBits(Register(ID), MF.getRegInfo());
91681ad6265SDimitry Andric     } else {
91781ad6265SDimitry Andric       // The slot location on the stack is uninteresting, we care about the
91881ad6265SDimitry Andric       // position of the value within the slot (which comes with a size).
91981ad6265SDimitry Andric       StackSlotPos Pos = locIDToSpillIdx(ID);
92081ad6265SDimitry Andric       return Pos.first;
92181ad6265SDimitry Andric     }
92281ad6265SDimitry Andric   }
92381ad6265SDimitry Andric 
924349cc55cSDimitry Andric   MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
925349cc55cSDimitry Andric 
926349cc55cSDimitry Andric   MLocIterator end() {
927349cc55cSDimitry Andric     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
928349cc55cSDimitry Andric   }
929349cc55cSDimitry Andric 
930349cc55cSDimitry Andric   /// Return a range over all locations currently tracked.
931349cc55cSDimitry Andric   iterator_range<MLocIterator> locations() {
932349cc55cSDimitry Andric     return llvm::make_range(begin(), end());
933349cc55cSDimitry Andric   }
934349cc55cSDimitry Andric 
935349cc55cSDimitry Andric   std::string LocIdxToName(LocIdx Idx) const;
936349cc55cSDimitry Andric 
937349cc55cSDimitry Andric   std::string IDAsString(const ValueIDNum &Num) const;
938349cc55cSDimitry Andric 
939349cc55cSDimitry Andric #ifndef NDEBUG
940349cc55cSDimitry Andric   LLVM_DUMP_METHOD void dump();
941349cc55cSDimitry Andric 
942349cc55cSDimitry Andric   LLVM_DUMP_METHOD void dump_mloc_map();
943349cc55cSDimitry Andric #endif
944349cc55cSDimitry Andric 
945bdd1243dSDimitry Andric   /// Create a DBG_VALUE based on debug operands \p DbgOps. Qualify it with the
946349cc55cSDimitry Andric   /// information in \pProperties, for variable Var. Don't insert it anywhere,
947349cc55cSDimitry Andric   /// just return the builder for it.
948bdd1243dSDimitry Andric   MachineInstrBuilder emitLoc(const SmallVectorImpl<ResolvedDbgOp> &DbgOps,
949bdd1243dSDimitry Andric                               const DebugVariable &Var,
950349cc55cSDimitry Andric                               const DbgValueProperties &Properties);
951349cc55cSDimitry Andric };
952349cc55cSDimitry Andric 
9534824e7fdSDimitry Andric /// Types for recording sets of variable fragments that overlap. For a given
9544824e7fdSDimitry Andric /// local variable, we record all other fragments of that variable that could
9554824e7fdSDimitry Andric /// overlap it, to reduce search time.
9564824e7fdSDimitry Andric using FragmentOfVar =
9574824e7fdSDimitry Andric     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
9584824e7fdSDimitry Andric using OverlapMap =
9594824e7fdSDimitry Andric     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
9604824e7fdSDimitry Andric 
961349cc55cSDimitry Andric /// Collection of DBG_VALUEs observed when traversing a block. Records each
962349cc55cSDimitry Andric /// variable and the value the DBG_VALUE refers to. Requires the machine value
963349cc55cSDimitry Andric /// location dataflow algorithm to have run already, so that values can be
964349cc55cSDimitry Andric /// identified.
965349cc55cSDimitry Andric class VLocTracker {
966349cc55cSDimitry Andric public:
967349cc55cSDimitry Andric   /// Map DebugVariable to the latest Value it's defined to have.
968349cc55cSDimitry Andric   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
969349cc55cSDimitry Andric   /// the order in this container.
970349cc55cSDimitry Andric   /// We only retain the last DbgValue in each block for each variable, to
971349cc55cSDimitry Andric   /// determine the blocks live-out variable value. The Vars container forms the
972349cc55cSDimitry Andric   /// transfer function for this block, as part of the dataflow analysis. The
973349cc55cSDimitry Andric   /// movement of values between locations inside of a block is handled at a
974349cc55cSDimitry Andric   /// much later stage, in the TransferTracker class.
975349cc55cSDimitry Andric   MapVector<DebugVariable, DbgValue> Vars;
976d56accc7SDimitry Andric   SmallDenseMap<DebugVariable, const DILocation *, 8> Scopes;
977349cc55cSDimitry Andric   MachineBasicBlock *MBB = nullptr;
9784824e7fdSDimitry Andric   const OverlapMap &OverlappingFragments;
9794824e7fdSDimitry Andric   DbgValueProperties EmptyProperties;
980349cc55cSDimitry Andric 
981349cc55cSDimitry Andric public:
9824824e7fdSDimitry Andric   VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr)
983bdd1243dSDimitry Andric       : OverlappingFragments(O), EmptyProperties(EmptyExpr, false, false) {}
984349cc55cSDimitry Andric 
985349cc55cSDimitry Andric   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
986bdd1243dSDimitry Andric               const SmallVectorImpl<DbgOpID> &DebugOps) {
987bdd1243dSDimitry Andric     assert(MI.isDebugValueLike());
988349cc55cSDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
989349cc55cSDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
990bdd1243dSDimitry Andric     DbgValue Rec = (DebugOps.size() > 0)
991bdd1243dSDimitry Andric                        ? DbgValue(DebugOps, Properties)
992349cc55cSDimitry Andric                        : DbgValue(Properties, DbgValue::Undef);
993349cc55cSDimitry Andric 
994349cc55cSDimitry Andric     // Attempt insertion; overwrite if it's already mapped.
995349cc55cSDimitry Andric     auto Result = Vars.insert(std::make_pair(Var, Rec));
996349cc55cSDimitry Andric     if (!Result.second)
997349cc55cSDimitry Andric       Result.first->second = Rec;
998349cc55cSDimitry Andric     Scopes[Var] = MI.getDebugLoc().get();
9994824e7fdSDimitry Andric 
10004824e7fdSDimitry Andric     considerOverlaps(Var, MI.getDebugLoc().get());
1001349cc55cSDimitry Andric   }
1002349cc55cSDimitry Andric 
10034824e7fdSDimitry Andric   void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
10044824e7fdSDimitry Andric     auto Overlaps = OverlappingFragments.find(
10054824e7fdSDimitry Andric         {Var.getVariable(), Var.getFragmentOrDefault()});
10064824e7fdSDimitry Andric     if (Overlaps == OverlappingFragments.end())
10074824e7fdSDimitry Andric       return;
10084824e7fdSDimitry Andric 
10094824e7fdSDimitry Andric     // Otherwise: terminate any overlapped variable locations.
10104824e7fdSDimitry Andric     for (auto FragmentInfo : Overlaps->second) {
10114824e7fdSDimitry Andric       // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
10124824e7fdSDimitry Andric       // that it overlaps with everything, however its cannonical representation
10134824e7fdSDimitry Andric       // in a DebugVariable is as "None".
1014bdd1243dSDimitry Andric       std::optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
10154824e7fdSDimitry Andric       if (DebugVariable::isDefaultFragment(FragmentInfo))
1016bdd1243dSDimitry Andric         OptFragmentInfo = std::nullopt;
10174824e7fdSDimitry Andric 
10184824e7fdSDimitry Andric       DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
10194824e7fdSDimitry Andric                                Var.getInlinedAt());
10204824e7fdSDimitry Andric       DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
10214824e7fdSDimitry Andric 
10224824e7fdSDimitry Andric       // Attempt insertion; overwrite if it's already mapped.
10234824e7fdSDimitry Andric       auto Result = Vars.insert(std::make_pair(Overlapped, Rec));
10244824e7fdSDimitry Andric       if (!Result.second)
10254824e7fdSDimitry Andric         Result.first->second = Rec;
10264824e7fdSDimitry Andric       Scopes[Overlapped] = Loc;
10274824e7fdSDimitry Andric     }
1028349cc55cSDimitry Andric   }
1029d56accc7SDimitry Andric 
1030d56accc7SDimitry Andric   void clear() {
1031d56accc7SDimitry Andric     Vars.clear();
1032d56accc7SDimitry Andric     Scopes.clear();
1033d56accc7SDimitry Andric   }
1034349cc55cSDimitry Andric };
1035349cc55cSDimitry Andric 
1036349cc55cSDimitry Andric // XXX XXX docs
1037349cc55cSDimitry Andric class InstrRefBasedLDV : public LDVImpl {
1038349cc55cSDimitry Andric public:
1039349cc55cSDimitry Andric   friend class ::InstrRefLDVTest;
1040349cc55cSDimitry Andric 
1041349cc55cSDimitry Andric   using FragmentInfo = DIExpression::FragmentInfo;
1042bdd1243dSDimitry Andric   using OptFragmentInfo = std::optional<DIExpression::FragmentInfo>;
1043349cc55cSDimitry Andric 
1044349cc55cSDimitry Andric   // Helper while building OverlapMap, a map of all fragments seen for a given
1045349cc55cSDimitry Andric   // DILocalVariable.
1046349cc55cSDimitry Andric   using VarToFragments =
1047349cc55cSDimitry Andric       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
1048349cc55cSDimitry Andric 
1049349cc55cSDimitry Andric   /// Machine location/value transfer function, a mapping of which locations
1050349cc55cSDimitry Andric   /// are assigned which new values.
1051349cc55cSDimitry Andric   using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
1052349cc55cSDimitry Andric 
1053349cc55cSDimitry Andric   /// Live in/out structure for the variable values: a per-block map of
1054349cc55cSDimitry Andric   /// variables to their values.
1055349cc55cSDimitry Andric   using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>;
1056349cc55cSDimitry Andric 
1057349cc55cSDimitry Andric   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
1058349cc55cSDimitry Andric 
1059349cc55cSDimitry Andric   /// Type for a live-in value: the predecessor block, and its value.
1060349cc55cSDimitry Andric   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
1061349cc55cSDimitry Andric 
1062349cc55cSDimitry Andric   /// Vector (per block) of a collection (inner smallvector) of live-ins.
1063349cc55cSDimitry Andric   /// Used as the result type for the variable value dataflow problem.
1064349cc55cSDimitry Andric   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
1065349cc55cSDimitry Andric 
10661fd87a68SDimitry Andric   /// Mapping from lexical scopes to a DILocation in that scope.
10671fd87a68SDimitry Andric   using ScopeToDILocT = DenseMap<const LexicalScope *, const DILocation *>;
10681fd87a68SDimitry Andric 
10691fd87a68SDimitry Andric   /// Mapping from lexical scopes to variables in that scope.
10701fd87a68SDimitry Andric   using ScopeToVarsT = DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>>;
10711fd87a68SDimitry Andric 
10721fd87a68SDimitry Andric   /// Mapping from lexical scopes to blocks where variables in that scope are
10731fd87a68SDimitry Andric   /// assigned. Such blocks aren't necessarily "in" the lexical scope, it's
10741fd87a68SDimitry Andric   /// just a block where an assignment happens.
10751fd87a68SDimitry Andric   using ScopeToAssignBlocksT = DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>;
10761fd87a68SDimitry Andric 
1077349cc55cSDimitry Andric private:
1078349cc55cSDimitry Andric   MachineDominatorTree *DomTree;
1079349cc55cSDimitry Andric   const TargetRegisterInfo *TRI;
1080349cc55cSDimitry Andric   const MachineRegisterInfo *MRI;
1081349cc55cSDimitry Andric   const TargetInstrInfo *TII;
1082349cc55cSDimitry Andric   const TargetFrameLowering *TFI;
1083349cc55cSDimitry Andric   const MachineFrameInfo *MFI;
1084349cc55cSDimitry Andric   BitVector CalleeSavedRegs;
1085349cc55cSDimitry Andric   LexicalScopes LS;
1086349cc55cSDimitry Andric   TargetPassConfig *TPC;
1087349cc55cSDimitry Andric 
1088349cc55cSDimitry Andric   // An empty DIExpression. Used default / placeholder DbgValueProperties
1089349cc55cSDimitry Andric   // objects, as we can't have null expressions.
1090349cc55cSDimitry Andric   const DIExpression *EmptyExpr;
1091349cc55cSDimitry Andric 
1092349cc55cSDimitry Andric   /// Object to track machine locations as we step through a block. Could
1093349cc55cSDimitry Andric   /// probably be a field rather than a pointer, as it's always used.
1094349cc55cSDimitry Andric   MLocTracker *MTracker = nullptr;
1095349cc55cSDimitry Andric 
1096349cc55cSDimitry Andric   /// Number of the current block LiveDebugValues is stepping through.
1097*06c3fb27SDimitry Andric   unsigned CurBB = -1;
1098349cc55cSDimitry Andric 
1099349cc55cSDimitry Andric   /// Number of the current instruction LiveDebugValues is evaluating.
1100349cc55cSDimitry Andric   unsigned CurInst;
1101349cc55cSDimitry Andric 
1102349cc55cSDimitry Andric   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
1103349cc55cSDimitry Andric   /// steps through a block. Reads the values at each location from the
1104349cc55cSDimitry Andric   /// MLocTracker object.
1105349cc55cSDimitry Andric   VLocTracker *VTracker = nullptr;
1106349cc55cSDimitry Andric 
1107349cc55cSDimitry Andric   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
1108349cc55cSDimitry Andric   /// between locations during stepping, creates new DBG_VALUEs when values move
1109349cc55cSDimitry Andric   /// location.
1110349cc55cSDimitry Andric   TransferTracker *TTracker = nullptr;
1111349cc55cSDimitry Andric 
1112349cc55cSDimitry Andric   /// Blocks which are artificial, i.e. blocks which exclusively contain
1113349cc55cSDimitry Andric   /// instructions without DebugLocs, or with line 0 locations.
11141fd87a68SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 16> ArtificialBlocks;
1115349cc55cSDimitry Andric 
1116349cc55cSDimitry Andric   // Mapping of blocks to and from their RPOT order.
1117349cc55cSDimitry Andric   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1118349cc55cSDimitry Andric   DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
1119349cc55cSDimitry Andric   DenseMap<unsigned, unsigned> BBNumToRPO;
1120349cc55cSDimitry Andric 
1121349cc55cSDimitry Andric   /// Pair of MachineInstr, and its 1-based offset into the containing block.
1122349cc55cSDimitry Andric   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
1123349cc55cSDimitry Andric   /// Map from debug instruction number to the MachineInstr labelled with that
1124349cc55cSDimitry Andric   /// number, and its location within the function. Used to transform
1125349cc55cSDimitry Andric   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
1126349cc55cSDimitry Andric   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
1127349cc55cSDimitry Andric 
1128349cc55cSDimitry Andric   /// Record of where we observed a DBG_PHI instruction.
1129349cc55cSDimitry Andric   class DebugPHIRecord {
1130349cc55cSDimitry Andric   public:
113181ad6265SDimitry Andric     /// Instruction number of this DBG_PHI.
113281ad6265SDimitry Andric     uint64_t InstrNum;
113381ad6265SDimitry Andric     /// Block where DBG_PHI occurred.
113481ad6265SDimitry Andric     MachineBasicBlock *MBB;
1135bdd1243dSDimitry Andric     /// The value number read by the DBG_PHI -- or std::nullopt if it didn't
1136bdd1243dSDimitry Andric     /// refer to a value.
1137bdd1243dSDimitry Andric     std::optional<ValueIDNum> ValueRead;
1138bdd1243dSDimitry Andric     /// Register/Stack location the DBG_PHI reads -- or std::nullopt if it
1139bdd1243dSDimitry Andric     /// referred to something unexpected.
1140bdd1243dSDimitry Andric     std::optional<LocIdx> ReadLoc;
1141349cc55cSDimitry Andric 
1142349cc55cSDimitry Andric     operator unsigned() const { return InstrNum; }
1143349cc55cSDimitry Andric   };
1144349cc55cSDimitry Andric 
1145349cc55cSDimitry Andric   /// Map from instruction numbers defined by DBG_PHIs to a record of what that
1146349cc55cSDimitry Andric   /// DBG_PHI read and where. Populated and edited during the machine value
1147349cc55cSDimitry Andric   /// location problem -- we use LLVMs SSA Updater to fix changes by
1148349cc55cSDimitry Andric   /// optimizations that destroy PHI instructions.
1149349cc55cSDimitry Andric   SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
1150349cc55cSDimitry Andric 
1151349cc55cSDimitry Andric   // Map of overlapping variable fragments.
1152349cc55cSDimitry Andric   OverlapMap OverlapFragments;
1153349cc55cSDimitry Andric   VarToFragments SeenFragments;
1154349cc55cSDimitry Andric 
1155d56accc7SDimitry Andric   /// Mapping of DBG_INSTR_REF instructions to their values, for those
1156d56accc7SDimitry Andric   /// DBG_INSTR_REFs that call resolveDbgPHIs. These variable references solve
1157d56accc7SDimitry Andric   /// a mini SSA problem caused by DBG_PHIs being cloned, this collection caches
1158d56accc7SDimitry Andric   /// the result.
1159bdd1243dSDimitry Andric   DenseMap<std::pair<MachineInstr *, unsigned>, std::optional<ValueIDNum>>
1160bdd1243dSDimitry Andric       SeenDbgPHIs;
1161bdd1243dSDimitry Andric 
1162bdd1243dSDimitry Andric   DbgOpIDMap DbgOpStore;
1163d56accc7SDimitry Andric 
11644824e7fdSDimitry Andric   /// True if we need to examine call instructions for stack clobbers. We
11654824e7fdSDimitry Andric   /// normally assume that they don't clobber SP, but stack probes on Windows
11664824e7fdSDimitry Andric   /// do.
11674824e7fdSDimitry Andric   bool AdjustsStackInCalls = false;
11684824e7fdSDimitry Andric 
11694824e7fdSDimitry Andric   /// If AdjustsStackInCalls is true, this holds the name of the target's stack
11704824e7fdSDimitry Andric   /// probe function, which is the function we expect will alter the stack
11714824e7fdSDimitry Andric   /// pointer.
11724824e7fdSDimitry Andric   StringRef StackProbeSymbolName;
11734824e7fdSDimitry Andric 
1174349cc55cSDimitry Andric   /// Tests whether this instruction is a spill to a stack slot.
1175bdd1243dSDimitry Andric   std::optional<SpillLocationNo> isSpillInstruction(const MachineInstr &MI,
1176d56accc7SDimitry Andric                                                     MachineFunction *MF);
1177349cc55cSDimitry Andric 
1178349cc55cSDimitry Andric   /// Decide if @MI is a spill instruction and return true if it is. We use 2
1179349cc55cSDimitry Andric   /// criteria to make this decision:
1180349cc55cSDimitry Andric   /// - Is this instruction a store to a spill slot?
1181349cc55cSDimitry Andric   /// - Is there a register operand that is both used and killed?
1182349cc55cSDimitry Andric   /// TODO: Store optimization can fold spills into other stores (including
1183349cc55cSDimitry Andric   /// other spills). We do not handle this yet (more than one memory operand).
1184349cc55cSDimitry Andric   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1185349cc55cSDimitry Andric                        unsigned &Reg);
1186349cc55cSDimitry Andric 
1187349cc55cSDimitry Andric   /// If a given instruction is identified as a spill, return the spill slot
1188349cc55cSDimitry Andric   /// and set \p Reg to the spilled register.
1189bdd1243dSDimitry Andric   std::optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
1190bdd1243dSDimitry Andric                                                       MachineFunction *MF,
1191bdd1243dSDimitry Andric                                                       unsigned &Reg);
1192349cc55cSDimitry Andric 
1193349cc55cSDimitry Andric   /// Given a spill instruction, extract the spill slot information, ensure it's
1194349cc55cSDimitry Andric   /// tracked, and return the spill number.
1195bdd1243dSDimitry Andric   std::optional<SpillLocationNo>
1196d56accc7SDimitry Andric   extractSpillBaseRegAndOffset(const MachineInstr &MI);
1197349cc55cSDimitry Andric 
1198bdd1243dSDimitry Andric   /// For an instruction reference given by \p InstNo and \p OpNo in instruction
1199bdd1243dSDimitry Andric   /// \p MI returns the Value pointed to by that instruction reference if any
1200*06c3fb27SDimitry Andric   /// exists, otherwise returns std::nullopt.
1201bdd1243dSDimitry Andric   std::optional<ValueIDNum> getValueForInstrRef(unsigned InstNo, unsigned OpNo,
1202bdd1243dSDimitry Andric                                                 MachineInstr &MI,
1203bdd1243dSDimitry Andric                                                 const ValueTable *MLiveOuts,
1204bdd1243dSDimitry Andric                                                 const ValueTable *MLiveIns);
1205bdd1243dSDimitry Andric 
1206349cc55cSDimitry Andric   /// Observe a single instruction while stepping through a block.
120781ad6265SDimitry Andric   void process(MachineInstr &MI, const ValueTable *MLiveOuts,
120881ad6265SDimitry Andric                const ValueTable *MLiveIns);
1209349cc55cSDimitry Andric 
1210349cc55cSDimitry Andric   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
1211349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
1212349cc55cSDimitry Andric   bool transferDebugValue(const MachineInstr &MI);
1213349cc55cSDimitry Andric 
1214349cc55cSDimitry Andric   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
1215349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
121681ad6265SDimitry Andric   bool transferDebugInstrRef(MachineInstr &MI, const ValueTable *MLiveOuts,
121781ad6265SDimitry Andric                              const ValueTable *MLiveIns);
1218349cc55cSDimitry Andric 
1219349cc55cSDimitry Andric   /// Stores value-information about where this PHI occurred, and what
1220349cc55cSDimitry Andric   /// instruction number is associated with it.
1221349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
1222349cc55cSDimitry Andric   bool transferDebugPHI(MachineInstr &MI);
1223349cc55cSDimitry Andric 
1224349cc55cSDimitry Andric   /// Examines whether \p MI is copy instruction, and notifies trackers.
1225349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
1226349cc55cSDimitry Andric   bool transferRegisterCopy(MachineInstr &MI);
1227349cc55cSDimitry Andric 
1228349cc55cSDimitry Andric   /// Examines whether \p MI is stack spill or restore  instruction, and
1229349cc55cSDimitry Andric   /// notifies trackers. \returns true if MI was recognized and processed.
1230349cc55cSDimitry Andric   bool transferSpillOrRestoreInst(MachineInstr &MI);
1231349cc55cSDimitry Andric 
1232349cc55cSDimitry Andric   /// Examines \p MI for any registers that it defines, and notifies trackers.
1233349cc55cSDimitry Andric   void transferRegisterDef(MachineInstr &MI);
1234349cc55cSDimitry Andric 
1235349cc55cSDimitry Andric   /// Copy one location to the other, accounting for movement of subregisters
1236349cc55cSDimitry Andric   /// too.
1237349cc55cSDimitry Andric   void performCopy(Register Src, Register Dst);
1238349cc55cSDimitry Andric 
1239349cc55cSDimitry Andric   void accumulateFragmentMap(MachineInstr &MI);
1240349cc55cSDimitry Andric 
1241349cc55cSDimitry Andric   /// Determine the machine value number referred to by (potentially several)
1242349cc55cSDimitry Andric   /// DBG_PHI instructions. Block duplication and tail folding can duplicate
1243349cc55cSDimitry Andric   /// DBG_PHIs, shifting the position where values in registers merge, and
1244349cc55cSDimitry Andric   /// forming another mini-ssa problem to solve.
1245349cc55cSDimitry Andric   /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
1246349cc55cSDimitry Andric   /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
1247bdd1243dSDimitry Andric   /// \returns The machine value number at position Here, or std::nullopt.
1248bdd1243dSDimitry Andric   std::optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
124981ad6265SDimitry Andric                                            const ValueTable *MLiveOuts,
125081ad6265SDimitry Andric                                            const ValueTable *MLiveIns,
1251bdd1243dSDimitry Andric                                            MachineInstr &Here,
1252bdd1243dSDimitry Andric                                            uint64_t InstrNum);
1253349cc55cSDimitry Andric 
1254bdd1243dSDimitry Andric   std::optional<ValueIDNum> resolveDbgPHIsImpl(MachineFunction &MF,
125581ad6265SDimitry Andric                                                const ValueTable *MLiveOuts,
125681ad6265SDimitry Andric                                                const ValueTable *MLiveIns,
1257d56accc7SDimitry Andric                                                MachineInstr &Here,
1258d56accc7SDimitry Andric                                                uint64_t InstrNum);
1259d56accc7SDimitry Andric 
1260349cc55cSDimitry Andric   /// Step through the function, recording register definitions and movements
1261349cc55cSDimitry Andric   /// in an MLocTracker. Convert the observations into a per-block transfer
1262349cc55cSDimitry Andric   /// function in \p MLocTransfer, suitable for using with the machine value
1263349cc55cSDimitry Andric   /// location dataflow problem.
1264349cc55cSDimitry Andric   void
1265349cc55cSDimitry Andric   produceMLocTransferFunction(MachineFunction &MF,
1266349cc55cSDimitry Andric                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1267349cc55cSDimitry Andric                               unsigned MaxNumBlocks);
1268349cc55cSDimitry Andric 
1269349cc55cSDimitry Andric   /// Solve the machine value location dataflow problem. Takes as input the
1270349cc55cSDimitry Andric   /// transfer functions in \p MLocTransfer. Writes the output live-in and
1271349cc55cSDimitry Andric   /// live-out arrays to the (initialized to zero) multidimensional arrays in
1272349cc55cSDimitry Andric   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1273349cc55cSDimitry Andric   /// number, the inner by LocIdx.
127481ad6265SDimitry Andric   void buildMLocValueMap(MachineFunction &MF, FuncValueTable &MInLocs,
127581ad6265SDimitry Andric                          FuncValueTable &MOutLocs,
1276349cc55cSDimitry Andric                          SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1277349cc55cSDimitry Andric 
1278349cc55cSDimitry Andric   /// Examine the stack indexes (i.e. offsets within the stack) to find the
1279349cc55cSDimitry Andric   /// basic units of interference -- like reg units, but for the stack.
1280349cc55cSDimitry Andric   void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
1281349cc55cSDimitry Andric 
1282349cc55cSDimitry Andric   /// Install PHI values into the live-in array for each block, according to
1283349cc55cSDimitry Andric   /// the IDF of each register.
1284349cc55cSDimitry Andric   void placeMLocPHIs(MachineFunction &MF,
1285349cc55cSDimitry Andric                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
128681ad6265SDimitry Andric                      FuncValueTable &MInLocs,
1287349cc55cSDimitry Andric                      SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1288349cc55cSDimitry Andric 
12891fd87a68SDimitry Andric   /// Propagate variable values to blocks in the common case where there's
12901fd87a68SDimitry Andric   /// only one value assigned to the variable. This function has better
12911fd87a68SDimitry Andric   /// performance as it doesn't have to find the dominance frontier between
12921fd87a68SDimitry Andric   /// different assignments.
12931fd87a68SDimitry Andric   void placePHIsForSingleVarDefinition(
12941fd87a68SDimitry Andric           const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
12951fd87a68SDimitry Andric           MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
12961fd87a68SDimitry Andric           const DebugVariable &Var, LiveInsT &Output);
12971fd87a68SDimitry Andric 
1298349cc55cSDimitry Andric   /// Calculate the iterated-dominance-frontier for a set of defs, using the
1299349cc55cSDimitry Andric   /// existing LLVM facilities for this. Works for a single "value" or
1300349cc55cSDimitry Andric   /// machine/variable location.
1301349cc55cSDimitry Andric   /// \p AllBlocks Set of blocks where we might consume the value.
1302349cc55cSDimitry Andric   /// \p DefBlocks Set of blocks where the value/location is defined.
1303349cc55cSDimitry Andric   /// \p PHIBlocks Output set of blocks where PHIs must be placed.
1304349cc55cSDimitry Andric   void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1305349cc55cSDimitry Andric                          const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
1306349cc55cSDimitry Andric                          SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
1307349cc55cSDimitry Andric 
1308349cc55cSDimitry Andric   /// Perform a control flow join (lattice value meet) of the values in machine
1309349cc55cSDimitry Andric   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1310349cc55cSDimitry Andric   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1311349cc55cSDimitry Andric   /// from \p InLocs, and assigning the newly computed live ins back into
1312349cc55cSDimitry Andric   /// \p InLocs. \returns two bools -- the first indicates whether a change
1313349cc55cSDimitry Andric   /// was made, the second whether a lattice downgrade occurred. If the latter
1314349cc55cSDimitry Andric   /// is true, revisiting this block is necessary.
1315349cc55cSDimitry Andric   bool mlocJoin(MachineBasicBlock &MBB,
1316349cc55cSDimitry Andric                 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
131781ad6265SDimitry Andric                 FuncValueTable &OutLocs, ValueTable &InLocs);
1318349cc55cSDimitry Andric 
13191fd87a68SDimitry Andric   /// Produce a set of blocks that are in the current lexical scope. This means
13201fd87a68SDimitry Andric   /// those blocks that contain instructions "in" the scope, blocks where
13211fd87a68SDimitry Andric   /// assignments to variables in scope occur, and artificial blocks that are
13221fd87a68SDimitry Andric   /// successors to any of the earlier blocks. See https://llvm.org/PR48091 for
13231fd87a68SDimitry Andric   /// more commentry on what "in scope" means.
13241fd87a68SDimitry Andric   /// \p DILoc A location in the scope that we're fetching blocks for.
13251fd87a68SDimitry Andric   /// \p Output Set to put in-scope-blocks into.
13261fd87a68SDimitry Andric   /// \p AssignBlocks Blocks known to contain assignments of variables in scope.
13271fd87a68SDimitry Andric   void
13281fd87a68SDimitry Andric   getBlocksForScope(const DILocation *DILoc,
13291fd87a68SDimitry Andric                     SmallPtrSetImpl<const MachineBasicBlock *> &Output,
13301fd87a68SDimitry Andric                     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks);
13311fd87a68SDimitry Andric 
1332349cc55cSDimitry Andric   /// Solve the variable value dataflow problem, for a single lexical scope.
1333349cc55cSDimitry Andric   /// Uses the algorithm from the file comment to resolve control flow joins
1334349cc55cSDimitry Andric   /// using PHI placement and value propagation. Reads the locations of machine
1335349cc55cSDimitry Andric   /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
1336349cc55cSDimitry Andric   /// and reads the variable values transfer function from \p AllTheVlocs.
1337349cc55cSDimitry Andric   /// Live-in and Live-out variable values are stored locally, with the live-ins
1338349cc55cSDimitry Andric   /// permanently stored to \p Output once a fixedpoint is reached.
1339349cc55cSDimitry Andric   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1340349cc55cSDimitry Andric   /// that we should be tracking.
1341349cc55cSDimitry Andric   /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
1342349cc55cSDimitry Andric   /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
1343349cc55cSDimitry Andric   /// locations through.
1344349cc55cSDimitry Andric   void buildVLocValueMap(const DILocation *DILoc,
1345349cc55cSDimitry Andric                          const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1346349cc55cSDimitry Andric                          SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
134781ad6265SDimitry Andric                          LiveInsT &Output, FuncValueTable &MOutLocs,
134881ad6265SDimitry Andric                          FuncValueTable &MInLocs,
1349349cc55cSDimitry Andric                          SmallVectorImpl<VLocTracker> &AllTheVLocs);
1350349cc55cSDimitry Andric 
1351349cc55cSDimitry Andric   /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
1352349cc55cSDimitry Andric   /// live-in values coming from predecessors live-outs, and replaces any PHIs
1353349cc55cSDimitry Andric   /// already present in this blocks live-ins with a live-through value if the
1354349cc55cSDimitry Andric   /// PHI isn't needed.
1355349cc55cSDimitry Andric   /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
1356349cc55cSDimitry Andric   /// \returns true if any live-ins change value, either from value propagation
1357349cc55cSDimitry Andric   ///          or PHI elimination.
1358349cc55cSDimitry Andric   bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
1359349cc55cSDimitry Andric                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1360349cc55cSDimitry Andric                 DbgValue &LiveIn);
1361349cc55cSDimitry Andric 
1362bdd1243dSDimitry Andric   /// For the given block and live-outs feeding into it, try to find
1363bdd1243dSDimitry Andric   /// machine locations for each debug operand where all the values feeding
1364bdd1243dSDimitry Andric   /// into that operand join together.
1365bdd1243dSDimitry Andric   /// \returns true if a joined location was found for every value that needed
1366bdd1243dSDimitry Andric   ///          to be joined.
1367bdd1243dSDimitry Andric   bool
1368bdd1243dSDimitry Andric   pickVPHILoc(SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
136981ad6265SDimitry Andric               const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
1370349cc55cSDimitry Andric               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1371349cc55cSDimitry Andric 
1372bdd1243dSDimitry Andric   std::optional<ValueIDNum> pickOperandPHILoc(
1373bdd1243dSDimitry Andric       unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
1374bdd1243dSDimitry Andric       FuncValueTable &MOutLocs,
1375bdd1243dSDimitry Andric       const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1376bdd1243dSDimitry Andric 
13771fd87a68SDimitry Andric   /// Take collections of DBG_VALUE instructions stored in TTracker, and
13781fd87a68SDimitry Andric   /// install them into their output blocks. Preserves a stable order of
13791fd87a68SDimitry Andric   /// DBG_VALUEs produced (which would otherwise cause nondeterminism) through
13801fd87a68SDimitry Andric   /// the AllVarsNumbering order.
13811fd87a68SDimitry Andric   bool emitTransfers(DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
13821fd87a68SDimitry Andric 
1383349cc55cSDimitry Andric   /// Boilerplate computation of some initial sets, artifical blocks and
1384349cc55cSDimitry Andric   /// RPOT block ordering.
1385349cc55cSDimitry Andric   void initialSetup(MachineFunction &MF);
1386349cc55cSDimitry Andric 
1387d56accc7SDimitry Andric   /// Produce a map of the last lexical scope that uses a block, using the
1388d56accc7SDimitry Andric   /// scopes DFSOut number. Mapping is block-number to DFSOut.
1389d56accc7SDimitry Andric   /// \p EjectionMap Pre-allocated vector in which to install the built ma.
1390d56accc7SDimitry Andric   /// \p ScopeToDILocation Mapping of LexicalScopes to their DILocations.
1391d56accc7SDimitry Andric   /// \p AssignBlocks Map of blocks where assignments happen for a scope.
1392d56accc7SDimitry Andric   void makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> &EjectionMap,
1393d56accc7SDimitry Andric                                  const ScopeToDILocT &ScopeToDILocation,
1394d56accc7SDimitry Andric                                  ScopeToAssignBlocksT &AssignBlocks);
1395d56accc7SDimitry Andric 
1396d56accc7SDimitry Andric   /// When determining per-block variable values and emitting to DBG_VALUEs,
1397d56accc7SDimitry Andric   /// this function explores by lexical scope depth. Doing so means that per
1398d56accc7SDimitry Andric   /// block information can be fully computed before exploration finishes,
1399d56accc7SDimitry Andric   /// allowing us to emit it and free data structures earlier than otherwise.
1400d56accc7SDimitry Andric   /// It's also good for locality.
1401d56accc7SDimitry Andric   bool depthFirstVLocAndEmit(
1402d56accc7SDimitry Andric       unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
1403d56accc7SDimitry Andric       const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToBlocks,
140481ad6265SDimitry Andric       LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
1405d56accc7SDimitry Andric       SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
1406d56accc7SDimitry Andric       DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
1407d56accc7SDimitry Andric       const TargetPassConfig &TPC);
1408d56accc7SDimitry Andric 
1409349cc55cSDimitry Andric   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1410349cc55cSDimitry Andric                     TargetPassConfig *TPC, unsigned InputBBLimit,
1411349cc55cSDimitry Andric                     unsigned InputDbgValLimit) override;
1412349cc55cSDimitry Andric 
1413349cc55cSDimitry Andric public:
1414349cc55cSDimitry Andric   /// Default construct and initialize the pass.
1415349cc55cSDimitry Andric   InstrRefBasedLDV();
1416349cc55cSDimitry Andric 
1417349cc55cSDimitry Andric   LLVM_DUMP_METHOD
1418349cc55cSDimitry Andric   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1419349cc55cSDimitry Andric 
1420349cc55cSDimitry Andric   bool isCalleeSaved(LocIdx L) const;
1421bdd1243dSDimitry Andric   bool isCalleeSavedReg(Register R) const;
1422349cc55cSDimitry Andric 
1423349cc55cSDimitry Andric   bool hasFoldedStackStore(const MachineInstr &MI) {
1424349cc55cSDimitry Andric     // Instruction must have a memory operand that's a stack slot, and isn't
1425349cc55cSDimitry Andric     // aliased, meaning it's a spill from regalloc instead of a variable.
1426349cc55cSDimitry Andric     // If it's aliased, we can't guarantee its value.
1427349cc55cSDimitry Andric     if (!MI.hasOneMemOperand())
1428349cc55cSDimitry Andric       return false;
1429349cc55cSDimitry Andric     auto *MemOperand = *MI.memoperands_begin();
1430349cc55cSDimitry Andric     return MemOperand->isStore() &&
1431349cc55cSDimitry Andric            MemOperand->getPseudoValue() &&
1432349cc55cSDimitry Andric            MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
1433349cc55cSDimitry Andric            && !MemOperand->getPseudoValue()->isAliased(MFI);
1434349cc55cSDimitry Andric   }
1435349cc55cSDimitry Andric 
1436bdd1243dSDimitry Andric   std::optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
1437349cc55cSDimitry Andric };
1438349cc55cSDimitry Andric 
1439349cc55cSDimitry Andric } // namespace LiveDebugValues
1440349cc55cSDimitry Andric 
1441349cc55cSDimitry Andric #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
1442