1838b4a53SJeremy Morse //===- InstrRefBasedImpl.h - Tracking Debug Value MIs ---------------------===//
2838b4a53SJeremy Morse //
3838b4a53SJeremy Morse // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4838b4a53SJeremy Morse // See https://llvm.org/LICENSE.txt for license information.
5838b4a53SJeremy Morse // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6838b4a53SJeremy Morse //
7838b4a53SJeremy Morse //===----------------------------------------------------------------------===//
8838b4a53SJeremy Morse 
9838b4a53SJeremy Morse #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
10838b4a53SJeremy Morse #define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
11838b4a53SJeremy Morse 
12838b4a53SJeremy Morse #include "llvm/ADT/DenseMap.h"
13838b4a53SJeremy Morse #include "llvm/ADT/SmallPtrSet.h"
14838b4a53SJeremy Morse #include "llvm/ADT/SmallVector.h"
15838b4a53SJeremy Morse #include "llvm/ADT/UniqueVector.h"
16838b4a53SJeremy Morse #include "llvm/CodeGen/LexicalScopes.h"
17838b4a53SJeremy Morse #include "llvm/CodeGen/MachineBasicBlock.h"
18838b4a53SJeremy Morse #include "llvm/CodeGen/MachineFrameInfo.h"
19838b4a53SJeremy Morse #include "llvm/CodeGen/MachineFunction.h"
20838b4a53SJeremy Morse #include "llvm/CodeGen/MachineInstr.h"
21838b4a53SJeremy Morse #include "llvm/CodeGen/TargetFrameLowering.h"
22838b4a53SJeremy Morse #include "llvm/CodeGen/TargetInstrInfo.h"
23838b4a53SJeremy Morse #include "llvm/CodeGen/TargetPassConfig.h"
24838b4a53SJeremy Morse #include "llvm/IR/DebugInfoMetadata.h"
25838b4a53SJeremy Morse 
26838b4a53SJeremy Morse #include "LiveDebugValues.h"
27838b4a53SJeremy Morse 
28838b4a53SJeremy Morse class TransferTracker;
29838b4a53SJeremy Morse 
30838b4a53SJeremy Morse // Forward dec of unit test class, so that we can peer into the LDV object.
31838b4a53SJeremy Morse class InstrRefLDVTest;
32838b4a53SJeremy Morse 
33838b4a53SJeremy Morse namespace LiveDebugValues {
34838b4a53SJeremy Morse 
35838b4a53SJeremy Morse class MLocTracker;
36838b4a53SJeremy Morse 
37838b4a53SJeremy Morse using namespace llvm;
38838b4a53SJeremy Morse 
39838b4a53SJeremy Morse /// Handle-class for a particular "location". This value-type uniquely
40838b4a53SJeremy Morse /// symbolises a register or stack location, allowing manipulation of locations
41838b4a53SJeremy Morse /// without concern for where that location is. Practically, this allows us to
42838b4a53SJeremy Morse /// treat the state of the machine at a particular point as an array of values,
43838b4a53SJeremy Morse /// rather than a map of values.
44838b4a53SJeremy Morse class LocIdx {
45838b4a53SJeremy Morse   unsigned Location;
46838b4a53SJeremy Morse 
47838b4a53SJeremy Morse   // Default constructor is private, initializing to an illegal location number.
48838b4a53SJeremy Morse   // Use only for "not an entry" elements in IndexedMaps.
49838b4a53SJeremy Morse   LocIdx() : Location(UINT_MAX) {}
50838b4a53SJeremy Morse 
51838b4a53SJeremy Morse public:
52838b4a53SJeremy Morse #define NUM_LOC_BITS 24
53838b4a53SJeremy Morse   LocIdx(unsigned L) : Location(L) {
54838b4a53SJeremy Morse     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
55838b4a53SJeremy Morse   }
56838b4a53SJeremy Morse 
57838b4a53SJeremy Morse   static LocIdx MakeIllegalLoc() { return LocIdx(); }
58838b4a53SJeremy Morse 
59838b4a53SJeremy Morse   bool isIllegal() const { return Location == UINT_MAX; }
60838b4a53SJeremy Morse 
61838b4a53SJeremy Morse   uint64_t asU64() const { return Location; }
62838b4a53SJeremy Morse 
63838b4a53SJeremy Morse   bool operator==(unsigned L) const { return Location == L; }
64838b4a53SJeremy Morse 
65838b4a53SJeremy Morse   bool operator==(const LocIdx &L) const { return Location == L.Location; }
66838b4a53SJeremy Morse 
67838b4a53SJeremy Morse   bool operator!=(unsigned L) const { return !(*this == L); }
68838b4a53SJeremy Morse 
69838b4a53SJeremy Morse   bool operator!=(const LocIdx &L) const { return !(*this == L); }
70838b4a53SJeremy Morse 
71838b4a53SJeremy Morse   bool operator<(const LocIdx &Other) const {
72838b4a53SJeremy Morse     return Location < Other.Location;
73838b4a53SJeremy Morse   }
74838b4a53SJeremy Morse };
75838b4a53SJeremy Morse 
76838b4a53SJeremy Morse // The location at which a spilled value resides. It consists of a register and
77838b4a53SJeremy Morse // an offset.
78838b4a53SJeremy Morse struct SpillLoc {
79838b4a53SJeremy Morse   unsigned SpillBase;
80838b4a53SJeremy Morse   StackOffset SpillOffset;
81838b4a53SJeremy Morse   bool operator==(const SpillLoc &Other) const {
82838b4a53SJeremy Morse     return std::make_pair(SpillBase, SpillOffset) ==
83838b4a53SJeremy Morse            std::make_pair(Other.SpillBase, Other.SpillOffset);
84838b4a53SJeremy Morse   }
85838b4a53SJeremy Morse   bool operator<(const SpillLoc &Other) const {
86838b4a53SJeremy Morse     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
87838b4a53SJeremy Morse                            SpillOffset.getScalable()) <
88838b4a53SJeremy Morse            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
89838b4a53SJeremy Morse                            Other.SpillOffset.getScalable());
90838b4a53SJeremy Morse   }
91838b4a53SJeremy Morse };
92838b4a53SJeremy Morse 
93838b4a53SJeremy Morse /// Unique identifier for a value defined by an instruction, as a value type.
94838b4a53SJeremy Morse /// Casts back and forth to a uint64_t. Probably replacable with something less
95838b4a53SJeremy Morse /// bit-constrained. Each value identifies the instruction and machine location
96838b4a53SJeremy Morse /// where the value is defined, although there may be no corresponding machine
97838b4a53SJeremy Morse /// operand for it (ex: regmasks clobbering values). The instructions are
98838b4a53SJeremy Morse /// one-based, and definitions that are PHIs have instruction number zero.
99838b4a53SJeremy Morse ///
100838b4a53SJeremy Morse /// The obvious limits of a 1M block function or 1M instruction blocks are
101838b4a53SJeremy Morse /// problematic; but by that point we should probably have bailed out of
102838b4a53SJeremy Morse /// trying to analyse the function.
103838b4a53SJeremy Morse class ValueIDNum {
104838b4a53SJeremy Morse   uint64_t BlockNo : 20;         /// The block where the def happens.
105838b4a53SJeremy Morse   uint64_t InstNo : 20;          /// The Instruction where the def happens.
106838b4a53SJeremy Morse                                  /// One based, is distance from start of block.
107838b4a53SJeremy Morse   uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens.
108838b4a53SJeremy Morse 
109838b4a53SJeremy Morse public:
110838b4a53SJeremy Morse   // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
111838b4a53SJeremy Morse   // of values to work.
112838b4a53SJeremy Morse   ValueIDNum() : BlockNo(0xFFFFF), InstNo(0xFFFFF), LocNo(0xFFFFFF) {}
113838b4a53SJeremy Morse 
114838b4a53SJeremy Morse   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc)
115838b4a53SJeremy Morse       : BlockNo(Block), InstNo(Inst), LocNo(Loc) {}
116838b4a53SJeremy Morse 
117838b4a53SJeremy Morse   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc)
118838b4a53SJeremy Morse       : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) {}
119838b4a53SJeremy Morse 
120838b4a53SJeremy Morse   uint64_t getBlock() const { return BlockNo; }
121838b4a53SJeremy Morse   uint64_t getInst() const { return InstNo; }
122838b4a53SJeremy Morse   uint64_t getLoc() const { return LocNo; }
123838b4a53SJeremy Morse   bool isPHI() const { return InstNo == 0; }
124838b4a53SJeremy Morse 
125838b4a53SJeremy Morse   uint64_t asU64() const {
126838b4a53SJeremy Morse     uint64_t TmpBlock = BlockNo;
127838b4a53SJeremy Morse     uint64_t TmpInst = InstNo;
128838b4a53SJeremy Morse     return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo;
129838b4a53SJeremy Morse   }
130838b4a53SJeremy Morse 
131838b4a53SJeremy Morse   static ValueIDNum fromU64(uint64_t v) {
132838b4a53SJeremy Morse     uint64_t L = (v & 0x3FFF);
133838b4a53SJeremy Morse     return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L};
134838b4a53SJeremy Morse   }
135838b4a53SJeremy Morse 
136838b4a53SJeremy Morse   bool operator<(const ValueIDNum &Other) const {
137838b4a53SJeremy Morse     return asU64() < Other.asU64();
138838b4a53SJeremy Morse   }
139838b4a53SJeremy Morse 
140838b4a53SJeremy Morse   bool operator==(const ValueIDNum &Other) const {
141838b4a53SJeremy Morse     return std::tie(BlockNo, InstNo, LocNo) ==
142838b4a53SJeremy Morse            std::tie(Other.BlockNo, Other.InstNo, Other.LocNo);
143838b4a53SJeremy Morse   }
144838b4a53SJeremy Morse 
145838b4a53SJeremy Morse   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
146838b4a53SJeremy Morse 
147838b4a53SJeremy Morse   std::string asString(const std::string &mlocname) const {
148838b4a53SJeremy Morse     return Twine("Value{bb: ")
149838b4a53SJeremy Morse         .concat(Twine(BlockNo).concat(
150838b4a53SJeremy Morse             Twine(", inst: ")
151838b4a53SJeremy Morse                 .concat((InstNo ? Twine(InstNo) : Twine("live-in"))
152838b4a53SJeremy Morse                             .concat(Twine(", loc: ").concat(Twine(mlocname)))
153838b4a53SJeremy Morse                             .concat(Twine("}")))))
154838b4a53SJeremy Morse         .str();
155838b4a53SJeremy Morse   }
156838b4a53SJeremy Morse 
157838b4a53SJeremy Morse   static ValueIDNum EmptyValue;
158838b4a53SJeremy Morse };
159838b4a53SJeremy Morse 
160838b4a53SJeremy Morse /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
161838b4a53SJeremy Morse /// the the value, and Boolean of whether or not it's indirect.
162838b4a53SJeremy Morse class DbgValueProperties {
163838b4a53SJeremy Morse public:
164838b4a53SJeremy Morse   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
165838b4a53SJeremy Morse       : DIExpr(DIExpr), Indirect(Indirect) {}
166838b4a53SJeremy Morse 
167838b4a53SJeremy Morse   /// Extract properties from an existing DBG_VALUE instruction.
168838b4a53SJeremy Morse   DbgValueProperties(const MachineInstr &MI) {
169838b4a53SJeremy Morse     assert(MI.isDebugValue());
170838b4a53SJeremy Morse     DIExpr = MI.getDebugExpression();
171838b4a53SJeremy Morse     Indirect = MI.getOperand(1).isImm();
172838b4a53SJeremy Morse   }
173838b4a53SJeremy Morse 
174838b4a53SJeremy Morse   bool operator==(const DbgValueProperties &Other) const {
175838b4a53SJeremy Morse     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
176838b4a53SJeremy Morse   }
177838b4a53SJeremy Morse 
178838b4a53SJeremy Morse   bool operator!=(const DbgValueProperties &Other) const {
179838b4a53SJeremy Morse     return !(*this == Other);
180838b4a53SJeremy Morse   }
181838b4a53SJeremy Morse 
182838b4a53SJeremy Morse   const DIExpression *DIExpr;
183838b4a53SJeremy Morse   bool Indirect;
184838b4a53SJeremy Morse };
185838b4a53SJeremy Morse 
186838b4a53SJeremy Morse /// Class recording the (high level) _value_ of a variable. Identifies either
187838b4a53SJeremy Morse /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
188838b4a53SJeremy Morse /// This class also stores meta-information about how the value is qualified.
189838b4a53SJeremy Morse /// Used to reason about variable values when performing the second
190838b4a53SJeremy Morse /// (DebugVariable specific) dataflow analysis.
191838b4a53SJeremy Morse class DbgValue {
192838b4a53SJeremy Morse public:
193b5426cedSJeremy Morse   /// If Kind is Def, the value number that this value is based on. VPHIs set
194b5426cedSJeremy Morse   /// this field to EmptyValue if there is no machine-value for this VPHI, or
195b5426cedSJeremy Morse   /// the corresponding machine-value if there is one.
196838b4a53SJeremy Morse   ValueIDNum ID;
197838b4a53SJeremy Morse   /// If Kind is Const, the MachineOperand defining this value.
198b5426cedSJeremy Morse   Optional<MachineOperand> MO;
199b5426cedSJeremy Morse   /// For a NoVal or VPHI DbgValue, which block it was generated in.
200b5426cedSJeremy Morse   int BlockNo;
201b5426cedSJeremy Morse 
202838b4a53SJeremy Morse   /// Qualifiers for the ValueIDNum above.
203838b4a53SJeremy Morse   DbgValueProperties Properties;
204838b4a53SJeremy Morse 
205838b4a53SJeremy Morse   typedef enum {
206838b4a53SJeremy Morse     Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
207838b4a53SJeremy Morse     Def,   // This value is defined by an inst, or is a PHI value.
208838b4a53SJeremy Morse     Const, // A constant value contained in the MachineOperand field.
209b5426cedSJeremy Morse     VPHI,  // Incoming values to BlockNo differ, those values must be joined by
210b5426cedSJeremy Morse            // a PHI in this block.
211b5426cedSJeremy Morse     NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
212b5426cedSJeremy Morse            // before dominating blocks values are propagated in.
213838b4a53SJeremy Morse   } KindT;
214838b4a53SJeremy Morse   /// Discriminator for whether this is a constant or an in-program value.
215838b4a53SJeremy Morse   KindT Kind;
216838b4a53SJeremy Morse 
217838b4a53SJeremy Morse   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
218b5426cedSJeremy Morse       : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) {
219b5426cedSJeremy Morse     assert(Kind == Def);
220838b4a53SJeremy Morse   }
221838b4a53SJeremy Morse 
222838b4a53SJeremy Morse   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
223b5426cedSJeremy Morse       : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo),
224b5426cedSJeremy Morse         Properties(Prop), Kind(Kind) {
225b5426cedSJeremy Morse     assert(Kind == NoVal || Kind == VPHI);
226838b4a53SJeremy Morse   }
227838b4a53SJeremy Morse 
228838b4a53SJeremy Morse   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
229b5426cedSJeremy Morse       : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop),
230b5426cedSJeremy Morse         Kind(Kind) {
231838b4a53SJeremy Morse     assert(Kind == Const);
232838b4a53SJeremy Morse   }
233838b4a53SJeremy Morse 
234838b4a53SJeremy Morse   DbgValue(const DbgValueProperties &Prop, KindT Kind)
235b5426cedSJeremy Morse     : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop),
236b5426cedSJeremy Morse       Kind(Kind) {
237838b4a53SJeremy Morse     assert(Kind == Undef &&
238838b4a53SJeremy Morse            "Empty DbgValue constructor must pass in Undef kind");
239838b4a53SJeremy Morse   }
240838b4a53SJeremy Morse 
241d9fa186aSJeremy Morse #ifndef NDEBUG
242838b4a53SJeremy Morse   void dump(const MLocTracker *MTrack) const;
243d9fa186aSJeremy Morse #endif
244838b4a53SJeremy Morse 
245838b4a53SJeremy Morse   bool operator==(const DbgValue &Other) const {
246838b4a53SJeremy Morse     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
247838b4a53SJeremy Morse       return false;
248838b4a53SJeremy Morse     else if (Kind == Def && ID != Other.ID)
249838b4a53SJeremy Morse       return false;
250838b4a53SJeremy Morse     else if (Kind == NoVal && BlockNo != Other.BlockNo)
251838b4a53SJeremy Morse       return false;
252838b4a53SJeremy Morse     else if (Kind == Const)
253b5426cedSJeremy Morse       return MO->isIdenticalTo(*Other.MO);
254b5426cedSJeremy Morse     else if (Kind == VPHI && BlockNo != Other.BlockNo)
255b5426cedSJeremy Morse       return false;
256b5426cedSJeremy Morse     else if (Kind == VPHI && ID != Other.ID)
257b5426cedSJeremy Morse       return false;
258838b4a53SJeremy Morse 
259838b4a53SJeremy Morse     return true;
260838b4a53SJeremy Morse   }
261838b4a53SJeremy Morse 
262838b4a53SJeremy Morse   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
263838b4a53SJeremy Morse };
264838b4a53SJeremy Morse 
265838b4a53SJeremy Morse class LocIdxToIndexFunctor {
266838b4a53SJeremy Morse public:
267838b4a53SJeremy Morse   using argument_type = LocIdx;
268838b4a53SJeremy Morse   unsigned operator()(const LocIdx &L) const { return L.asU64(); }
269838b4a53SJeremy Morse };
270838b4a53SJeremy Morse 
271838b4a53SJeremy Morse /// Tracker for what values are in machine locations. Listens to the Things
272838b4a53SJeremy Morse /// being Done by various instructions, and maintains a table of what machine
273838b4a53SJeremy Morse /// locations have what values (as defined by a ValueIDNum).
274838b4a53SJeremy Morse ///
275838b4a53SJeremy Morse /// There are potentially a much larger number of machine locations on the
276838b4a53SJeremy Morse /// target machine than the actual working-set size of the function. On x86 for
277838b4a53SJeremy Morse /// example, we're extremely unlikely to want to track values through control
278838b4a53SJeremy Morse /// or debug registers. To avoid doing so, MLocTracker has several layers of
279838b4a53SJeremy Morse /// indirection going on, with two kinds of ``location'':
280838b4a53SJeremy Morse ///  * A LocID uniquely identifies a register or spill location, with a
281838b4a53SJeremy Morse ///    predictable value.
282838b4a53SJeremy Morse ///  * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum.
283838b4a53SJeremy Morse /// Whenever a location is def'd or used by a MachineInstr, we automagically
284838b4a53SJeremy Morse /// create a new LocIdx for a location, but not otherwise. This ensures we only
285838b4a53SJeremy Morse /// account for locations that are actually used or defined. The cost is another
286838b4a53SJeremy Morse /// vector lookup (of LocID -> LocIdx) over any other implementation. This is
287838b4a53SJeremy Morse /// fairly cheap, and the compiler tries to reduce the working-set at any one
288838b4a53SJeremy Morse /// time in the function anyway.
289838b4a53SJeremy Morse ///
290838b4a53SJeremy Morse /// Register mask operands completely blow this out of the water; I've just
291838b4a53SJeremy Morse /// piled hacks on top of hacks to get around that.
292838b4a53SJeremy Morse class MLocTracker {
293838b4a53SJeremy Morse public:
294838b4a53SJeremy Morse   MachineFunction &MF;
295838b4a53SJeremy Morse   const TargetInstrInfo &TII;
296838b4a53SJeremy Morse   const TargetRegisterInfo &TRI;
297838b4a53SJeremy Morse   const TargetLowering &TLI;
298838b4a53SJeremy Morse 
299838b4a53SJeremy Morse   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
300838b4a53SJeremy Morse   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
301838b4a53SJeremy Morse 
302838b4a53SJeremy Morse   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
303838b4a53SJeremy Morse   /// packed, entries only exist for locations that are being tracked.
304838b4a53SJeremy Morse   LocToValueType LocIdxToIDNum;
305838b4a53SJeremy Morse 
306838b4a53SJeremy Morse   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
307838b4a53SJeremy Morse   /// LocIdx key / number for that location. There are always at least as many
308838b4a53SJeremy Morse   /// as the number of registers on the target -- if the value in the register
309838b4a53SJeremy Morse   /// is not being tracked, then the LocIdx value will be zero. New entries are
310838b4a53SJeremy Morse   /// appended if a new spill slot begins being tracked.
311838b4a53SJeremy Morse   /// This, and the corresponding reverse map persist for the analysis of the
312838b4a53SJeremy Morse   /// whole function, and is necessarying for decoding various vectors of
313838b4a53SJeremy Morse   /// values.
314838b4a53SJeremy Morse   std::vector<LocIdx> LocIDToLocIdx;
315838b4a53SJeremy Morse 
316838b4a53SJeremy Morse   /// Inverse map of LocIDToLocIdx.
317838b4a53SJeremy Morse   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
318838b4a53SJeremy Morse 
319fbf269c7SJeremy Morse   /// When clobbering register masks, we chose to not believe the machine model
320fbf269c7SJeremy Morse   /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
321fbf269c7SJeremy Morse   /// keep a set of them here.
322fbf269c7SJeremy Morse   SmallSet<Register, 8> SPAliases;
323fbf269c7SJeremy Morse 
324838b4a53SJeremy Morse   /// Unique-ification of spill slots. Used to number them -- their LocID
325838b4a53SJeremy Morse   /// number is the index in SpillLocs minus one plus NumRegs.
326838b4a53SJeremy Morse   UniqueVector<SpillLoc> SpillLocs;
327838b4a53SJeremy Morse 
328838b4a53SJeremy Morse   // If we discover a new machine location, assign it an mphi with this
329838b4a53SJeremy Morse   // block number.
330838b4a53SJeremy Morse   unsigned CurBB;
331838b4a53SJeremy Morse 
332838b4a53SJeremy Morse   /// Cached local copy of the number of registers the target has.
333838b4a53SJeremy Morse   unsigned NumRegs;
334838b4a53SJeremy Morse 
335838b4a53SJeremy Morse   /// Collection of register mask operands that have been observed. Second part
336838b4a53SJeremy Morse   /// of pair indicates the instruction that they happened in. Used to
337838b4a53SJeremy Morse   /// reconstruct where defs happened if we start tracking a location later
338838b4a53SJeremy Morse   /// on.
339838b4a53SJeremy Morse   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
340838b4a53SJeremy Morse 
341838b4a53SJeremy Morse   /// Iterator for locations and the values they contain. Dereferencing
342838b4a53SJeremy Morse   /// produces a struct/pair containing the LocIdx key for this location,
343838b4a53SJeremy Morse   /// and a reference to the value currently stored. Simplifies the process
344838b4a53SJeremy Morse   /// of seeking a particular location.
345838b4a53SJeremy Morse   class MLocIterator {
346838b4a53SJeremy Morse     LocToValueType &ValueMap;
347838b4a53SJeremy Morse     LocIdx Idx;
348838b4a53SJeremy Morse 
349838b4a53SJeremy Morse   public:
350838b4a53SJeremy Morse     class value_type {
351838b4a53SJeremy Morse     public:
352838b4a53SJeremy Morse       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
353838b4a53SJeremy Morse       const LocIdx Idx;  /// Read-only index of this location.
354838b4a53SJeremy Morse       ValueIDNum &Value; /// Reference to the stored value at this location.
355838b4a53SJeremy Morse     };
356838b4a53SJeremy Morse 
357838b4a53SJeremy Morse     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
358838b4a53SJeremy Morse         : ValueMap(ValueMap), Idx(Idx) {}
359838b4a53SJeremy Morse 
360838b4a53SJeremy Morse     bool operator==(const MLocIterator &Other) const {
361838b4a53SJeremy Morse       assert(&ValueMap == &Other.ValueMap);
362838b4a53SJeremy Morse       return Idx == Other.Idx;
363838b4a53SJeremy Morse     }
364838b4a53SJeremy Morse 
365838b4a53SJeremy Morse     bool operator!=(const MLocIterator &Other) const {
366838b4a53SJeremy Morse       return !(*this == Other);
367838b4a53SJeremy Morse     }
368838b4a53SJeremy Morse 
369838b4a53SJeremy Morse     void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
370838b4a53SJeremy Morse 
371838b4a53SJeremy Morse     value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
372838b4a53SJeremy Morse   };
373838b4a53SJeremy Morse 
374838b4a53SJeremy Morse   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
375838b4a53SJeremy Morse               const TargetRegisterInfo &TRI, const TargetLowering &TLI);
376838b4a53SJeremy Morse 
377838b4a53SJeremy Morse   /// Produce location ID number for indexing LocIDToLocIdx. Takes the register
378838b4a53SJeremy Morse   /// or spill number, and flag for whether it's a spill or not.
379838b4a53SJeremy Morse   unsigned getLocID(Register RegOrSpill, bool isSpill) {
380838b4a53SJeremy Morse     return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id();
381838b4a53SJeremy Morse   }
382838b4a53SJeremy Morse 
383838b4a53SJeremy Morse   /// Accessor for reading the value at Idx.
384838b4a53SJeremy Morse   ValueIDNum getNumAtPos(LocIdx Idx) const {
385838b4a53SJeremy Morse     assert(Idx.asU64() < LocIdxToIDNum.size());
386838b4a53SJeremy Morse     return LocIdxToIDNum[Idx];
387838b4a53SJeremy Morse   }
388838b4a53SJeremy Morse 
389838b4a53SJeremy Morse   unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); }
390838b4a53SJeremy Morse 
391838b4a53SJeremy Morse   /// Reset all locations to contain a PHI value at the designated block. Used
392838b4a53SJeremy Morse   /// sometimes for actual PHI values, othertimes to indicate the block entry
393838b4a53SJeremy Morse   /// value (before any more information is known).
394838b4a53SJeremy Morse   void setMPhis(unsigned NewCurBB) {
395838b4a53SJeremy Morse     CurBB = NewCurBB;
396838b4a53SJeremy Morse     for (auto Location : locations())
397838b4a53SJeremy Morse       Location.Value = {CurBB, 0, Location.Idx};
398838b4a53SJeremy Morse   }
399838b4a53SJeremy Morse 
400838b4a53SJeremy Morse   /// Load values for each location from array of ValueIDNums. Take current
401838b4a53SJeremy Morse   /// bbnum just in case we read a value from a hitherto untouched register.
402838b4a53SJeremy Morse   void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
403838b4a53SJeremy Morse     CurBB = NewCurBB;
404838b4a53SJeremy Morse     // Iterate over all tracked locations, and load each locations live-in
405838b4a53SJeremy Morse     // value into our local index.
406838b4a53SJeremy Morse     for (auto Location : locations())
407838b4a53SJeremy Morse       Location.Value = Locs[Location.Idx.asU64()];
408838b4a53SJeremy Morse   }
409838b4a53SJeremy Morse 
410838b4a53SJeremy Morse   /// Wipe any un-necessary location records after traversing a block.
411838b4a53SJeremy Morse   void reset(void) {
412838b4a53SJeremy Morse     // We could reset all the location values too; however either loadFromArray
413838b4a53SJeremy Morse     // or setMPhis should be called before this object is re-used. Just
414838b4a53SJeremy Morse     // clear Masks, they're definitely not needed.
415838b4a53SJeremy Morse     Masks.clear();
416838b4a53SJeremy Morse   }
417838b4a53SJeremy Morse 
418838b4a53SJeremy Morse   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
419838b4a53SJeremy Morse   /// the information in this pass uninterpretable.
420838b4a53SJeremy Morse   void clear(void) {
421838b4a53SJeremy Morse     reset();
422838b4a53SJeremy Morse     LocIDToLocIdx.clear();
423838b4a53SJeremy Morse     LocIdxToLocID.clear();
424838b4a53SJeremy Morse     LocIdxToIDNum.clear();
425838b4a53SJeremy Morse     // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
426838b4a53SJeremy Morse     // 0
427838b4a53SJeremy Morse     SpillLocs = decltype(SpillLocs)();
428838b4a53SJeremy Morse 
429838b4a53SJeremy Morse     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
430838b4a53SJeremy Morse   }
431838b4a53SJeremy Morse 
432838b4a53SJeremy Morse   /// Set a locaiton to a certain value.
433838b4a53SJeremy Morse   void setMLoc(LocIdx L, ValueIDNum Num) {
434838b4a53SJeremy Morse     assert(L.asU64() < LocIdxToIDNum.size());
435838b4a53SJeremy Morse     LocIdxToIDNum[L] = Num;
436838b4a53SJeremy Morse   }
437838b4a53SJeremy Morse 
438838b4a53SJeremy Morse   /// Create a LocIdx for an untracked register ID. Initialize it to either an
439838b4a53SJeremy Morse   /// mphi value representing a live-in, or a recent register mask clobber.
440838b4a53SJeremy Morse   LocIdx trackRegister(unsigned ID);
441838b4a53SJeremy Morse 
442838b4a53SJeremy Morse   LocIdx lookupOrTrackRegister(unsigned ID) {
443838b4a53SJeremy Morse     LocIdx &Index = LocIDToLocIdx[ID];
444838b4a53SJeremy Morse     if (Index.isIllegal())
445838b4a53SJeremy Morse       Index = trackRegister(ID);
446838b4a53SJeremy Morse     return Index;
447838b4a53SJeremy Morse   }
448838b4a53SJeremy Morse 
449fbf269c7SJeremy Morse   /// Is register R currently tracked by MLocTracker?
450fbf269c7SJeremy Morse   bool isRegisterTracked(Register R) {
451fbf269c7SJeremy Morse     LocIdx &Index = LocIDToLocIdx[R];
452fbf269c7SJeremy Morse     return !Index.isIllegal();
453fbf269c7SJeremy Morse   }
454fbf269c7SJeremy Morse 
455838b4a53SJeremy Morse   /// Record a definition of the specified register at the given block / inst.
456838b4a53SJeremy Morse   /// This doesn't take a ValueIDNum, because the definition and its location
457838b4a53SJeremy Morse   /// are synonymous.
458838b4a53SJeremy Morse   void defReg(Register R, unsigned BB, unsigned Inst) {
459838b4a53SJeremy Morse     unsigned ID = getLocID(R, false);
460838b4a53SJeremy Morse     LocIdx Idx = lookupOrTrackRegister(ID);
461838b4a53SJeremy Morse     ValueIDNum ValueID = {BB, Inst, Idx};
462838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueID;
463838b4a53SJeremy Morse   }
464838b4a53SJeremy Morse 
465838b4a53SJeremy Morse   /// Set a register to a value number. To be used if the value number is
466838b4a53SJeremy Morse   /// known in advance.
467838b4a53SJeremy Morse   void setReg(Register R, ValueIDNum ValueID) {
468838b4a53SJeremy Morse     unsigned ID = getLocID(R, false);
469838b4a53SJeremy Morse     LocIdx Idx = lookupOrTrackRegister(ID);
470838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueID;
471838b4a53SJeremy Morse   }
472838b4a53SJeremy Morse 
473838b4a53SJeremy Morse   ValueIDNum readReg(Register R) {
474838b4a53SJeremy Morse     unsigned ID = getLocID(R, false);
475838b4a53SJeremy Morse     LocIdx Idx = lookupOrTrackRegister(ID);
476838b4a53SJeremy Morse     return LocIdxToIDNum[Idx];
477838b4a53SJeremy Morse   }
478838b4a53SJeremy Morse 
479838b4a53SJeremy Morse   /// Reset a register value to zero / empty. Needed to replicate the
480838b4a53SJeremy Morse   /// VarLoc implementation where a copy to/from a register effectively
481838b4a53SJeremy Morse   /// clears the contents of the source register. (Values can only have one
482838b4a53SJeremy Morse   ///  machine location in VarLocBasedImpl).
483838b4a53SJeremy Morse   void wipeRegister(Register R) {
484838b4a53SJeremy Morse     unsigned ID = getLocID(R, false);
485838b4a53SJeremy Morse     LocIdx Idx = LocIDToLocIdx[ID];
486838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
487838b4a53SJeremy Morse   }
488838b4a53SJeremy Morse 
489838b4a53SJeremy Morse   /// Determine the LocIdx of an existing register.
490838b4a53SJeremy Morse   LocIdx getRegMLoc(Register R) {
491838b4a53SJeremy Morse     unsigned ID = getLocID(R, false);
492838b4a53SJeremy Morse     return LocIDToLocIdx[ID];
493838b4a53SJeremy Morse   }
494838b4a53SJeremy Morse 
495838b4a53SJeremy Morse   /// Record a RegMask operand being executed. Defs any register we currently
496838b4a53SJeremy Morse   /// track, stores a pointer to the mask in case we have to account for it
497838b4a53SJeremy Morse   /// later.
498838b4a53SJeremy Morse   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
499838b4a53SJeremy Morse 
500838b4a53SJeremy Morse   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
501838b4a53SJeremy Morse   LocIdx getOrTrackSpillLoc(SpillLoc L);
502838b4a53SJeremy Morse 
503838b4a53SJeremy Morse   /// Set the value stored in a spill slot.
504838b4a53SJeremy Morse   void setSpill(SpillLoc L, ValueIDNum ValueID) {
505838b4a53SJeremy Morse     LocIdx Idx = getOrTrackSpillLoc(L);
506838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueID;
507838b4a53SJeremy Morse   }
508838b4a53SJeremy Morse 
509838b4a53SJeremy Morse   /// Read whatever value is in a spill slot, or None if it isn't tracked.
510838b4a53SJeremy Morse   Optional<ValueIDNum> readSpill(SpillLoc L) {
511838b4a53SJeremy Morse     unsigned SpillID = SpillLocs.idFor(L);
512838b4a53SJeremy Morse     if (SpillID == 0)
513838b4a53SJeremy Morse       return None;
514838b4a53SJeremy Morse 
515838b4a53SJeremy Morse     unsigned LocID = getLocID(SpillID, true);
516838b4a53SJeremy Morse     LocIdx Idx = LocIDToLocIdx[LocID];
517838b4a53SJeremy Morse     return LocIdxToIDNum[Idx];
518838b4a53SJeremy Morse   }
519838b4a53SJeremy Morse 
520838b4a53SJeremy Morse   /// Determine the LocIdx of a spill slot. Return None if it previously
521838b4a53SJeremy Morse   /// hasn't had a value assigned.
522838b4a53SJeremy Morse   Optional<LocIdx> getSpillMLoc(SpillLoc L) {
523838b4a53SJeremy Morse     unsigned SpillID = SpillLocs.idFor(L);
524838b4a53SJeremy Morse     if (SpillID == 0)
525838b4a53SJeremy Morse       return None;
526838b4a53SJeremy Morse     unsigned LocNo = getLocID(SpillID, true);
527838b4a53SJeremy Morse     return LocIDToLocIdx[LocNo];
528838b4a53SJeremy Morse   }
529838b4a53SJeremy Morse 
530838b4a53SJeremy Morse   /// Return true if Idx is a spill machine location.
531838b4a53SJeremy Morse   bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
532838b4a53SJeremy Morse 
533838b4a53SJeremy Morse   MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
534838b4a53SJeremy Morse 
535838b4a53SJeremy Morse   MLocIterator end() {
536838b4a53SJeremy Morse     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
537838b4a53SJeremy Morse   }
538838b4a53SJeremy Morse 
539838b4a53SJeremy Morse   /// Return a range over all locations currently tracked.
540838b4a53SJeremy Morse   iterator_range<MLocIterator> locations() {
541838b4a53SJeremy Morse     return llvm::make_range(begin(), end());
542838b4a53SJeremy Morse   }
543838b4a53SJeremy Morse 
544838b4a53SJeremy Morse   std::string LocIdxToName(LocIdx Idx) const;
545838b4a53SJeremy Morse 
546838b4a53SJeremy Morse   std::string IDAsString(const ValueIDNum &Num) const;
547838b4a53SJeremy Morse 
548d9fa186aSJeremy Morse #ifndef NDEBUG
549838b4a53SJeremy Morse   LLVM_DUMP_METHOD void dump();
550838b4a53SJeremy Morse 
551838b4a53SJeremy Morse   LLVM_DUMP_METHOD void dump_mloc_map();
552d9fa186aSJeremy Morse #endif
553838b4a53SJeremy Morse 
554838b4a53SJeremy Morse   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
555838b4a53SJeremy Morse   /// information in \pProperties, for variable Var. Don't insert it anywhere,
556838b4a53SJeremy Morse   /// just return the builder for it.
557838b4a53SJeremy Morse   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
558838b4a53SJeremy Morse                               const DbgValueProperties &Properties);
559838b4a53SJeremy Morse };
560838b4a53SJeremy Morse 
561b5426cedSJeremy Morse /// Collection of DBG_VALUEs observed when traversing a block. Records each
562b5426cedSJeremy Morse /// variable and the value the DBG_VALUE refers to. Requires the machine value
563b5426cedSJeremy Morse /// location dataflow algorithm to have run already, so that values can be
564b5426cedSJeremy Morse /// identified.
565b5426cedSJeremy Morse class VLocTracker {
566b5426cedSJeremy Morse public:
567b5426cedSJeremy Morse   /// Map DebugVariable to the latest Value it's defined to have.
568b5426cedSJeremy Morse   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
569b5426cedSJeremy Morse   /// the order in this container.
570b5426cedSJeremy Morse   /// We only retain the last DbgValue in each block for each variable, to
571b5426cedSJeremy Morse   /// determine the blocks live-out variable value. The Vars container forms the
572b5426cedSJeremy Morse   /// transfer function for this block, as part of the dataflow analysis. The
573b5426cedSJeremy Morse   /// movement of values between locations inside of a block is handled at a
574b5426cedSJeremy Morse   /// much later stage, in the TransferTracker class.
575b5426cedSJeremy Morse   MapVector<DebugVariable, DbgValue> Vars;
576b5426cedSJeremy Morse   DenseMap<DebugVariable, const DILocation *> Scopes;
577*cf033bb2SJeremy Morse   MachineBasicBlock *MBB = nullptr;
578b5426cedSJeremy Morse 
579b5426cedSJeremy Morse public:
580b5426cedSJeremy Morse   VLocTracker() {}
581b5426cedSJeremy Morse 
582b5426cedSJeremy Morse   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
583b5426cedSJeremy Morse               Optional<ValueIDNum> ID) {
584b5426cedSJeremy Morse     assert(MI.isDebugValue() || MI.isDebugRef());
585b5426cedSJeremy Morse     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
586b5426cedSJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
587b5426cedSJeremy Morse     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
588b5426cedSJeremy Morse                         : DbgValue(Properties, DbgValue::Undef);
589b5426cedSJeremy Morse 
590b5426cedSJeremy Morse     // Attempt insertion; overwrite if it's already mapped.
591b5426cedSJeremy Morse     auto Result = Vars.insert(std::make_pair(Var, Rec));
592b5426cedSJeremy Morse     if (!Result.second)
593b5426cedSJeremy Morse       Result.first->second = Rec;
594b5426cedSJeremy Morse     Scopes[Var] = MI.getDebugLoc().get();
595b5426cedSJeremy Morse   }
596b5426cedSJeremy Morse 
597b5426cedSJeremy Morse   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
598b5426cedSJeremy Morse     // Only DBG_VALUEs can define constant-valued variables.
599b5426cedSJeremy Morse     assert(MI.isDebugValue());
600b5426cedSJeremy Morse     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
601b5426cedSJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
602b5426cedSJeremy Morse     DbgValueProperties Properties(MI);
603b5426cedSJeremy Morse     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
604b5426cedSJeremy Morse 
605b5426cedSJeremy Morse     // Attempt insertion; overwrite if it's already mapped.
606b5426cedSJeremy Morse     auto Result = Vars.insert(std::make_pair(Var, Rec));
607b5426cedSJeremy Morse     if (!Result.second)
608b5426cedSJeremy Morse       Result.first->second = Rec;
609b5426cedSJeremy Morse     Scopes[Var] = MI.getDebugLoc().get();
610b5426cedSJeremy Morse   }
611b5426cedSJeremy Morse };
612b5426cedSJeremy Morse 
613838b4a53SJeremy Morse /// Types for recording sets of variable fragments that overlap. For a given
614838b4a53SJeremy Morse /// local variable, we record all other fragments of that variable that could
615838b4a53SJeremy Morse /// overlap it, to reduce search time.
616838b4a53SJeremy Morse using FragmentOfVar =
617838b4a53SJeremy Morse     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
618838b4a53SJeremy Morse using OverlapMap =
619838b4a53SJeremy Morse     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
620838b4a53SJeremy Morse 
621838b4a53SJeremy Morse // XXX XXX docs
622838b4a53SJeremy Morse class InstrRefBasedLDV : public LDVImpl {
623b5426cedSJeremy Morse public:
624838b4a53SJeremy Morse   friend class ::InstrRefLDVTest;
625838b4a53SJeremy Morse 
626838b4a53SJeremy Morse   using FragmentInfo = DIExpression::FragmentInfo;
627838b4a53SJeremy Morse   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
628838b4a53SJeremy Morse 
629838b4a53SJeremy Morse   // Helper while building OverlapMap, a map of all fragments seen for a given
630838b4a53SJeremy Morse   // DILocalVariable.
631838b4a53SJeremy Morse   using VarToFragments =
632838b4a53SJeremy Morse       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
633838b4a53SJeremy Morse 
634838b4a53SJeremy Morse   /// Machine location/value transfer function, a mapping of which locations
635838b4a53SJeremy Morse   /// are assigned which new values.
636838b4a53SJeremy Morse   using MLocTransferMap = std::map<LocIdx, ValueIDNum>;
637838b4a53SJeremy Morse 
638838b4a53SJeremy Morse   /// Live in/out structure for the variable values: a per-block map of
639838b4a53SJeremy Morse   /// variables to their values. XXX, better name?
640838b4a53SJeremy Morse   using LiveIdxT =
641838b4a53SJeremy Morse       DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>;
642838b4a53SJeremy Morse 
643838b4a53SJeremy Morse   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
644838b4a53SJeremy Morse 
645838b4a53SJeremy Morse   /// Type for a live-in value: the predecessor block, and its value.
646838b4a53SJeremy Morse   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
647838b4a53SJeremy Morse 
648838b4a53SJeremy Morse   /// Vector (per block) of a collection (inner smallvector) of live-ins.
649838b4a53SJeremy Morse   /// Used as the result type for the variable value dataflow problem.
650838b4a53SJeremy Morse   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
651838b4a53SJeremy Morse 
652b5426cedSJeremy Morse private:
653a3936a6cSJeremy Morse   MachineDominatorTree *DomTree;
654838b4a53SJeremy Morse   const TargetRegisterInfo *TRI;
655838b4a53SJeremy Morse   const TargetInstrInfo *TII;
656838b4a53SJeremy Morse   const TargetFrameLowering *TFI;
657838b4a53SJeremy Morse   const MachineFrameInfo *MFI;
658838b4a53SJeremy Morse   BitVector CalleeSavedRegs;
659838b4a53SJeremy Morse   LexicalScopes LS;
660838b4a53SJeremy Morse   TargetPassConfig *TPC;
661838b4a53SJeremy Morse 
662b5426cedSJeremy Morse   // An empty DIExpression. Used default / placeholder DbgValueProperties
663b5426cedSJeremy Morse   // objects, as we can't have null expressions.
664b5426cedSJeremy Morse   const DIExpression *EmptyExpr;
665b5426cedSJeremy Morse 
666838b4a53SJeremy Morse   /// Object to track machine locations as we step through a block. Could
667838b4a53SJeremy Morse   /// probably be a field rather than a pointer, as it's always used.
668838b4a53SJeremy Morse   MLocTracker *MTracker;
669838b4a53SJeremy Morse 
670838b4a53SJeremy Morse   /// Number of the current block LiveDebugValues is stepping through.
671838b4a53SJeremy Morse   unsigned CurBB;
672838b4a53SJeremy Morse 
673838b4a53SJeremy Morse   /// Number of the current instruction LiveDebugValues is evaluating.
674838b4a53SJeremy Morse   unsigned CurInst;
675838b4a53SJeremy Morse 
676838b4a53SJeremy Morse   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
677838b4a53SJeremy Morse   /// steps through a block. Reads the values at each location from the
678838b4a53SJeremy Morse   /// MLocTracker object.
679838b4a53SJeremy Morse   VLocTracker *VTracker;
680838b4a53SJeremy Morse 
681838b4a53SJeremy Morse   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
682838b4a53SJeremy Morse   /// between locations during stepping, creates new DBG_VALUEs when values move
683838b4a53SJeremy Morse   /// location.
684838b4a53SJeremy Morse   TransferTracker *TTracker;
685838b4a53SJeremy Morse 
686838b4a53SJeremy Morse   /// Blocks which are artificial, i.e. blocks which exclusively contain
687838b4a53SJeremy Morse   /// instructions without DebugLocs, or with line 0 locations.
688838b4a53SJeremy Morse   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
689838b4a53SJeremy Morse 
690838b4a53SJeremy Morse   // Mapping of blocks to and from their RPOT order.
691838b4a53SJeremy Morse   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
692b5426cedSJeremy Morse   DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
693838b4a53SJeremy Morse   DenseMap<unsigned, unsigned> BBNumToRPO;
694838b4a53SJeremy Morse 
695838b4a53SJeremy Morse   /// Pair of MachineInstr, and its 1-based offset into the containing block.
696838b4a53SJeremy Morse   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
697838b4a53SJeremy Morse   /// Map from debug instruction number to the MachineInstr labelled with that
698838b4a53SJeremy Morse   /// number, and its location within the function. Used to transform
699838b4a53SJeremy Morse   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
700838b4a53SJeremy Morse   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
701838b4a53SJeremy Morse 
702838b4a53SJeremy Morse   /// Record of where we observed a DBG_PHI instruction.
703838b4a53SJeremy Morse   class DebugPHIRecord {
704838b4a53SJeremy Morse   public:
705838b4a53SJeremy Morse     uint64_t InstrNum;      ///< Instruction number of this DBG_PHI.
706838b4a53SJeremy Morse     MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred.
707838b4a53SJeremy Morse     ValueIDNum ValueRead;   ///< The value number read by the DBG_PHI.
708838b4a53SJeremy Morse     LocIdx ReadLoc;         ///< Register/Stack location the DBG_PHI reads.
709838b4a53SJeremy Morse 
710838b4a53SJeremy Morse     operator unsigned() const { return InstrNum; }
711838b4a53SJeremy Morse   };
712838b4a53SJeremy Morse 
713838b4a53SJeremy Morse   /// Map from instruction numbers defined by DBG_PHIs to a record of what that
714838b4a53SJeremy Morse   /// DBG_PHI read and where. Populated and edited during the machine value
715838b4a53SJeremy Morse   /// location problem -- we use LLVMs SSA Updater to fix changes by
716838b4a53SJeremy Morse   /// optimizations that destroy PHI instructions.
717838b4a53SJeremy Morse   SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
718838b4a53SJeremy Morse 
719838b4a53SJeremy Morse   // Map of overlapping variable fragments.
720838b4a53SJeremy Morse   OverlapMap OverlapFragments;
721838b4a53SJeremy Morse   VarToFragments SeenFragments;
722838b4a53SJeremy Morse 
723838b4a53SJeremy Morse   /// Tests whether this instruction is a spill to a stack slot.
724838b4a53SJeremy Morse   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
725838b4a53SJeremy Morse 
726838b4a53SJeremy Morse   /// Decide if @MI is a spill instruction and return true if it is. We use 2
727838b4a53SJeremy Morse   /// criteria to make this decision:
728838b4a53SJeremy Morse   /// - Is this instruction a store to a spill slot?
729838b4a53SJeremy Morse   /// - Is there a register operand that is both used and killed?
730838b4a53SJeremy Morse   /// TODO: Store optimization can fold spills into other stores (including
731838b4a53SJeremy Morse   /// other spills). We do not handle this yet (more than one memory operand).
732838b4a53SJeremy Morse   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
733838b4a53SJeremy Morse                        unsigned &Reg);
734838b4a53SJeremy Morse 
735838b4a53SJeremy Morse   /// If a given instruction is identified as a spill, return the spill slot
736838b4a53SJeremy Morse   /// and set \p Reg to the spilled register.
737838b4a53SJeremy Morse   Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI,
738838b4a53SJeremy Morse                                           MachineFunction *MF, unsigned &Reg);
739838b4a53SJeremy Morse 
740838b4a53SJeremy Morse   /// Given a spill instruction, extract the register and offset used to
741838b4a53SJeremy Morse   /// address the spill slot in a target independent way.
742838b4a53SJeremy Morse   SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
743838b4a53SJeremy Morse 
744838b4a53SJeremy Morse   /// Observe a single instruction while stepping through a block.
745838b4a53SJeremy Morse   void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr,
746838b4a53SJeremy Morse                ValueIDNum **MLiveIns = nullptr);
747838b4a53SJeremy Morse 
748838b4a53SJeremy Morse   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
749838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
750838b4a53SJeremy Morse   bool transferDebugValue(const MachineInstr &MI);
751838b4a53SJeremy Morse 
752838b4a53SJeremy Morse   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
753838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
754838b4a53SJeremy Morse   bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts,
755838b4a53SJeremy Morse                              ValueIDNum **MLiveIns);
756838b4a53SJeremy Morse 
757838b4a53SJeremy Morse   /// Stores value-information about where this PHI occurred, and what
758838b4a53SJeremy Morse   /// instruction number is associated with it.
759838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
760838b4a53SJeremy Morse   bool transferDebugPHI(MachineInstr &MI);
761838b4a53SJeremy Morse 
762838b4a53SJeremy Morse   /// Examines whether \p MI is copy instruction, and notifies trackers.
763838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
764838b4a53SJeremy Morse   bool transferRegisterCopy(MachineInstr &MI);
765838b4a53SJeremy Morse 
766838b4a53SJeremy Morse   /// Examines whether \p MI is stack spill or restore  instruction, and
767838b4a53SJeremy Morse   /// notifies trackers. \returns true if MI was recognized and processed.
768838b4a53SJeremy Morse   bool transferSpillOrRestoreInst(MachineInstr &MI);
769838b4a53SJeremy Morse 
770838b4a53SJeremy Morse   /// Examines \p MI for any registers that it defines, and notifies trackers.
771838b4a53SJeremy Morse   void transferRegisterDef(MachineInstr &MI);
772838b4a53SJeremy Morse 
773838b4a53SJeremy Morse   /// Copy one location to the other, accounting for movement of subregisters
774838b4a53SJeremy Morse   /// too.
775838b4a53SJeremy Morse   void performCopy(Register Src, Register Dst);
776838b4a53SJeremy Morse 
777838b4a53SJeremy Morse   void accumulateFragmentMap(MachineInstr &MI);
778838b4a53SJeremy Morse 
779838b4a53SJeremy Morse   /// Determine the machine value number referred to by (potentially several)
780838b4a53SJeremy Morse   /// DBG_PHI instructions. Block duplication and tail folding can duplicate
781838b4a53SJeremy Morse   /// DBG_PHIs, shifting the position where values in registers merge, and
782838b4a53SJeremy Morse   /// forming another mini-ssa problem to solve.
783838b4a53SJeremy Morse   /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
784838b4a53SJeremy Morse   /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
785838b4a53SJeremy Morse   /// \returns The machine value number at position Here, or None.
786838b4a53SJeremy Morse   Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
787838b4a53SJeremy Morse                                       ValueIDNum **MLiveOuts,
788838b4a53SJeremy Morse                                       ValueIDNum **MLiveIns, MachineInstr &Here,
789838b4a53SJeremy Morse                                       uint64_t InstrNum);
790838b4a53SJeremy Morse 
791838b4a53SJeremy Morse   /// Step through the function, recording register definitions and movements
792838b4a53SJeremy Morse   /// in an MLocTracker. Convert the observations into a per-block transfer
793838b4a53SJeremy Morse   /// function in \p MLocTransfer, suitable for using with the machine value
794838b4a53SJeremy Morse   /// location dataflow problem.
795838b4a53SJeremy Morse   void
796838b4a53SJeremy Morse   produceMLocTransferFunction(MachineFunction &MF,
797838b4a53SJeremy Morse                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
798838b4a53SJeremy Morse                               unsigned MaxNumBlocks);
799838b4a53SJeremy Morse 
800838b4a53SJeremy Morse   /// Solve the machine value location dataflow problem. Takes as input the
801838b4a53SJeremy Morse   /// transfer functions in \p MLocTransfer. Writes the output live-in and
802838b4a53SJeremy Morse   /// live-out arrays to the (initialized to zero) multidimensional arrays in
803838b4a53SJeremy Morse   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
804838b4a53SJeremy Morse   /// number, the inner by LocIdx.
805a3936a6cSJeremy Morse   void buildMLocValueMap(MachineFunction &MF, ValueIDNum **MInLocs,
806a3936a6cSJeremy Morse                          ValueIDNum **MOutLocs,
807838b4a53SJeremy Morse                          SmallVectorImpl<MLocTransferMap> &MLocTransfer);
808838b4a53SJeremy Morse 
809fbf269c7SJeremy Morse   /// Install PHI values into the live-in array for each block, according to
810fbf269c7SJeremy Morse   /// the IDF of each register.
811fbf269c7SJeremy Morse   void placeMLocPHIs(MachineFunction &MF,
812fbf269c7SJeremy Morse                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
813fbf269c7SJeremy Morse                      ValueIDNum **MInLocs,
814fbf269c7SJeremy Morse                      SmallVectorImpl<MLocTransferMap> &MLocTransfer);
815fbf269c7SJeremy Morse 
816a3936a6cSJeremy Morse   /// Calculate the iterated-dominance-frontier for a set of defs, using the
817a3936a6cSJeremy Morse   /// existing LLVM facilities for this. Works for a single "value" or
818a3936a6cSJeremy Morse   /// machine/variable location.
819a3936a6cSJeremy Morse   /// \p AllBlocks Set of blocks where we might consume the value.
820a3936a6cSJeremy Morse   /// \p DefBlocks Set of blocks where the value/location is defined.
821a3936a6cSJeremy Morse   /// \p PHIBlocks Output set of blocks where PHIs must be placed.
822a3936a6cSJeremy Morse   void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
823a3936a6cSJeremy Morse                          const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
824a3936a6cSJeremy Morse                          SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
825a3936a6cSJeremy Morse 
826838b4a53SJeremy Morse   /// Perform a control flow join (lattice value meet) of the values in machine
827838b4a53SJeremy Morse   /// locations at \p MBB. Follows the algorithm described in the file-comment,
828838b4a53SJeremy Morse   /// reading live-outs of predecessors from \p OutLocs, the current live ins
829838b4a53SJeremy Morse   /// from \p InLocs, and assigning the newly computed live ins back into
830838b4a53SJeremy Morse   /// \p InLocs. \returns two bools -- the first indicates whether a change
831838b4a53SJeremy Morse   /// was made, the second whether a lattice downgrade occurred. If the latter
832838b4a53SJeremy Morse   /// is true, revisiting this block is necessary.
833a3936a6cSJeremy Morse   bool mlocJoin(MachineBasicBlock &MBB,
834838b4a53SJeremy Morse                 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
835838b4a53SJeremy Morse                 ValueIDNum **OutLocs, ValueIDNum *InLocs);
836838b4a53SJeremy Morse 
837838b4a53SJeremy Morse   /// Solve the variable value dataflow problem, for a single lexical scope.
838b5426cedSJeremy Morse   /// Uses the algorithm from the file comment to resolve control flow joins
839b5426cedSJeremy Morse   /// using PHI placement and value propagation. Reads the locations of machine
840b5426cedSJeremy Morse   /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
841b5426cedSJeremy Morse   /// and reads the variable values transfer function from \p AllTheVlocs.
842b5426cedSJeremy Morse   /// Live-in and Live-out variable values are stored locally, with the live-ins
843b5426cedSJeremy Morse   /// permanently stored to \p Output once a fixedpoint is reached.
844838b4a53SJeremy Morse   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
845838b4a53SJeremy Morse   /// that we should be tracking.
846b5426cedSJeremy Morse   /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
847b5426cedSJeremy Morse   /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
848b5426cedSJeremy Morse   /// locations through.
849b5426cedSJeremy Morse   void buildVLocValueMap(const DILocation *DILoc,
850838b4a53SJeremy Morse                     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
851838b4a53SJeremy Morse                     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
852838b4a53SJeremy Morse                     LiveInsT &Output, ValueIDNum **MOutLocs,
853838b4a53SJeremy Morse                     ValueIDNum **MInLocs,
854838b4a53SJeremy Morse                     SmallVectorImpl<VLocTracker> &AllTheVLocs);
855838b4a53SJeremy Morse 
856b5426cedSJeremy Morse   /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
857b5426cedSJeremy Morse   /// live-in values coming from predecessors live-outs, and replaces any PHIs
858b5426cedSJeremy Morse   /// already present in this blocks live-ins with a live-through value if the
859b5426cedSJeremy Morse   /// PHI isn't needed. Live out and live in variable values are stored in
860b5426cedSJeremy Morse   /// \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB are computed and
861b5426cedSJeremy Morse   /// stored into \p VLOCInLocs.
862b5426cedSJeremy Morse   /// \p InLocsT Output argument, where calculated live-in values are also
863b5426cedSJeremy Morse   ///          stored.
864b5426cedSJeremy Morse   /// \returns true if any live-ins change value, either from value propagation
865b5426cedSJeremy Morse   ///          or PHI elimination.
866b5426cedSJeremy Morse   bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
867b5426cedSJeremy Morse                 LiveIdxT &VLOCInLocs,
868b5426cedSJeremy Morse                 const SmallSet<DebugVariable, 4> &AllVars,
869838b4a53SJeremy Morse                 SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
870838b4a53SJeremy Morse                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
871838b4a53SJeremy Morse                 DenseMap<DebugVariable, DbgValue> &InLocsT);
872838b4a53SJeremy Morse 
873838b4a53SJeremy Morse   /// For the given block and live-outs feeding into it, try to find a
874b5426cedSJeremy Morse   /// machine location where all the variable values join together.
875b5426cedSJeremy Morse   /// \returns Value ID of a machine PHI if an appropriate one is available.
876b5426cedSJeremy Morse   Optional<ValueIDNum>
877b5426cedSJeremy Morse   pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
878838b4a53SJeremy Morse               const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
879b5426cedSJeremy Morse               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
880838b4a53SJeremy Morse 
881838b4a53SJeremy Morse   /// Given the solutions to the two dataflow problems, machine value locations
882838b4a53SJeremy Morse   /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the
883838b4a53SJeremy Morse   /// TransferTracker class over the function to produce live-in and transfer
884838b4a53SJeremy Morse   /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the
885838b4a53SJeremy Morse   /// order given by AllVarsNumbering -- this could be any stable order, but
886838b4a53SJeremy Morse   /// right now "order of appearence in function, when explored in RPO", so
887838b4a53SJeremy Morse   /// that we can compare explictly against VarLocBasedImpl.
888838b4a53SJeremy Morse   void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns,
889838b4a53SJeremy Morse                      ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
890838b4a53SJeremy Morse                      DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
891838b4a53SJeremy Morse                      const TargetPassConfig &TPC);
892838b4a53SJeremy Morse 
893838b4a53SJeremy Morse   /// Boilerplate computation of some initial sets, artifical blocks and
894838b4a53SJeremy Morse   /// RPOT block ordering.
895838b4a53SJeremy Morse   void initialSetup(MachineFunction &MF);
896838b4a53SJeremy Morse 
897a3936a6cSJeremy Morse   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
898a3936a6cSJeremy Morse                     TargetPassConfig *TPC, unsigned InputBBLimit,
899a3936a6cSJeremy Morse                     unsigned InputDbgValLimit) override;
900838b4a53SJeremy Morse 
901838b4a53SJeremy Morse public:
902838b4a53SJeremy Morse   /// Default construct and initialize the pass.
903838b4a53SJeremy Morse   InstrRefBasedLDV();
904838b4a53SJeremy Morse 
905838b4a53SJeremy Morse   LLVM_DUMP_METHOD
906838b4a53SJeremy Morse   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
907838b4a53SJeremy Morse 
908838b4a53SJeremy Morse   bool isCalleeSaved(LocIdx L) const;
909838b4a53SJeremy Morse };
910838b4a53SJeremy Morse 
911838b4a53SJeremy Morse } // namespace LiveDebugValues
912838b4a53SJeremy Morse 
913838b4a53SJeremy Morse #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
914