xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.h (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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"
13349cc55cSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
14349cc55cSDimitry Andric #include "llvm/ADT/SmallVector.h"
15349cc55cSDimitry Andric #include "llvm/ADT/UniqueVector.h"
16349cc55cSDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
17349cc55cSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
18349cc55cSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
19349cc55cSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
20349cc55cSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
21349cc55cSDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
22349cc55cSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
23349cc55cSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
24349cc55cSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
25349cc55cSDimitry Andric 
26349cc55cSDimitry Andric #include "LiveDebugValues.h"
27349cc55cSDimitry Andric 
28349cc55cSDimitry Andric class TransferTracker;
29349cc55cSDimitry Andric 
30349cc55cSDimitry Andric // Forward dec of unit test class, so that we can peer into the LDV object.
31349cc55cSDimitry Andric class InstrRefLDVTest;
32349cc55cSDimitry Andric 
33349cc55cSDimitry Andric namespace LiveDebugValues {
34349cc55cSDimitry Andric 
35349cc55cSDimitry Andric class MLocTracker;
36349cc55cSDimitry Andric 
37349cc55cSDimitry Andric using namespace llvm;
38349cc55cSDimitry Andric 
39349cc55cSDimitry Andric /// Handle-class for a particular "location". This value-type uniquely
40349cc55cSDimitry Andric /// symbolises a register or stack location, allowing manipulation of locations
41349cc55cSDimitry Andric /// without concern for where that location is. Practically, this allows us to
42349cc55cSDimitry Andric /// treat the state of the machine at a particular point as an array of values,
43349cc55cSDimitry Andric /// rather than a map of values.
44349cc55cSDimitry Andric class LocIdx {
45349cc55cSDimitry Andric   unsigned Location;
46349cc55cSDimitry Andric 
47349cc55cSDimitry Andric   // Default constructor is private, initializing to an illegal location number.
48349cc55cSDimitry Andric   // Use only for "not an entry" elements in IndexedMaps.
49349cc55cSDimitry Andric   LocIdx() : Location(UINT_MAX) {}
50349cc55cSDimitry Andric 
51349cc55cSDimitry Andric public:
52349cc55cSDimitry Andric #define NUM_LOC_BITS 24
53349cc55cSDimitry Andric   LocIdx(unsigned L) : Location(L) {
54349cc55cSDimitry Andric     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
55349cc55cSDimitry Andric   }
56349cc55cSDimitry Andric 
57349cc55cSDimitry Andric   static LocIdx MakeIllegalLoc() { return LocIdx(); }
58349cc55cSDimitry Andric   static LocIdx MakeTombstoneLoc() {
59349cc55cSDimitry Andric     LocIdx L = LocIdx();
60349cc55cSDimitry Andric     --L.Location;
61349cc55cSDimitry Andric     return L;
62349cc55cSDimitry Andric   }
63349cc55cSDimitry Andric 
64349cc55cSDimitry Andric   bool isIllegal() const { return Location == UINT_MAX; }
65349cc55cSDimitry Andric 
66349cc55cSDimitry Andric   uint64_t asU64() const { return Location; }
67349cc55cSDimitry Andric 
68349cc55cSDimitry Andric   bool operator==(unsigned L) const { return Location == L; }
69349cc55cSDimitry Andric 
70349cc55cSDimitry Andric   bool operator==(const LocIdx &L) const { return Location == L.Location; }
71349cc55cSDimitry Andric 
72349cc55cSDimitry Andric   bool operator!=(unsigned L) const { return !(*this == L); }
73349cc55cSDimitry Andric 
74349cc55cSDimitry Andric   bool operator!=(const LocIdx &L) const { return !(*this == L); }
75349cc55cSDimitry Andric 
76349cc55cSDimitry Andric   bool operator<(const LocIdx &Other) const {
77349cc55cSDimitry Andric     return Location < Other.Location;
78349cc55cSDimitry Andric   }
79349cc55cSDimitry Andric };
80349cc55cSDimitry Andric 
81349cc55cSDimitry Andric // The location at which a spilled value resides. It consists of a register and
82349cc55cSDimitry Andric // an offset.
83349cc55cSDimitry Andric struct SpillLoc {
84349cc55cSDimitry Andric   unsigned SpillBase;
85349cc55cSDimitry Andric   StackOffset SpillOffset;
86349cc55cSDimitry Andric   bool operator==(const SpillLoc &Other) const {
87349cc55cSDimitry Andric     return std::make_pair(SpillBase, SpillOffset) ==
88349cc55cSDimitry Andric            std::make_pair(Other.SpillBase, Other.SpillOffset);
89349cc55cSDimitry Andric   }
90349cc55cSDimitry Andric   bool operator<(const SpillLoc &Other) const {
91349cc55cSDimitry Andric     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
92349cc55cSDimitry Andric                            SpillOffset.getScalable()) <
93349cc55cSDimitry Andric            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
94349cc55cSDimitry Andric                            Other.SpillOffset.getScalable());
95349cc55cSDimitry Andric   }
96349cc55cSDimitry Andric };
97349cc55cSDimitry Andric 
98349cc55cSDimitry Andric /// Unique identifier for a value defined by an instruction, as a value type.
99349cc55cSDimitry Andric /// Casts back and forth to a uint64_t. Probably replacable with something less
100349cc55cSDimitry Andric /// bit-constrained. Each value identifies the instruction and machine location
101349cc55cSDimitry Andric /// where the value is defined, although there may be no corresponding machine
102349cc55cSDimitry Andric /// operand for it (ex: regmasks clobbering values). The instructions are
103349cc55cSDimitry Andric /// one-based, and definitions that are PHIs have instruction number zero.
104349cc55cSDimitry Andric ///
105349cc55cSDimitry Andric /// The obvious limits of a 1M block function or 1M instruction blocks are
106349cc55cSDimitry Andric /// problematic; but by that point we should probably have bailed out of
107349cc55cSDimitry Andric /// trying to analyse the function.
108349cc55cSDimitry Andric class ValueIDNum {
109349cc55cSDimitry Andric   union {
110349cc55cSDimitry Andric     struct {
111349cc55cSDimitry Andric       uint64_t BlockNo : 20; /// The block where the def happens.
112349cc55cSDimitry Andric       uint64_t InstNo : 20;  /// The Instruction where the def happens.
113349cc55cSDimitry Andric                              /// One based, is distance from start of block.
114349cc55cSDimitry Andric       uint64_t LocNo
115349cc55cSDimitry Andric           : NUM_LOC_BITS; /// The machine location where the def happens.
116349cc55cSDimitry Andric     } s;
117349cc55cSDimitry Andric     uint64_t Value;
118349cc55cSDimitry Andric   } u;
119349cc55cSDimitry Andric 
120349cc55cSDimitry Andric   static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
121349cc55cSDimitry Andric 
122349cc55cSDimitry Andric public:
123349cc55cSDimitry Andric   // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
124349cc55cSDimitry Andric   // of values to work.
125349cc55cSDimitry Andric   ValueIDNum() { u.Value = EmptyValue.asU64(); }
126349cc55cSDimitry Andric 
127349cc55cSDimitry Andric   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
128349cc55cSDimitry Andric     u.s = {Block, Inst, Loc};
129349cc55cSDimitry Andric   }
130349cc55cSDimitry Andric 
131349cc55cSDimitry Andric   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
132349cc55cSDimitry Andric     u.s = {Block, Inst, Loc.asU64()};
133349cc55cSDimitry Andric   }
134349cc55cSDimitry Andric 
135349cc55cSDimitry Andric   uint64_t getBlock() const { return u.s.BlockNo; }
136349cc55cSDimitry Andric   uint64_t getInst() const { return u.s.InstNo; }
137349cc55cSDimitry Andric   uint64_t getLoc() const { return u.s.LocNo; }
138349cc55cSDimitry Andric   bool isPHI() const { return u.s.InstNo == 0; }
139349cc55cSDimitry Andric 
140349cc55cSDimitry Andric   uint64_t asU64() const { return u.Value; }
141349cc55cSDimitry Andric 
142349cc55cSDimitry Andric   static ValueIDNum fromU64(uint64_t v) {
143349cc55cSDimitry Andric     ValueIDNum Val;
144349cc55cSDimitry Andric     Val.u.Value = v;
145349cc55cSDimitry Andric     return Val;
146349cc55cSDimitry Andric   }
147349cc55cSDimitry Andric 
148349cc55cSDimitry Andric   bool operator<(const ValueIDNum &Other) const {
149349cc55cSDimitry Andric     return asU64() < Other.asU64();
150349cc55cSDimitry Andric   }
151349cc55cSDimitry Andric 
152349cc55cSDimitry Andric   bool operator==(const ValueIDNum &Other) const {
153349cc55cSDimitry Andric     return u.Value == Other.u.Value;
154349cc55cSDimitry Andric   }
155349cc55cSDimitry Andric 
156349cc55cSDimitry Andric   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
157349cc55cSDimitry Andric 
158349cc55cSDimitry Andric   std::string asString(const std::string &mlocname) const {
159349cc55cSDimitry Andric     return Twine("Value{bb: ")
160349cc55cSDimitry Andric         .concat(Twine(u.s.BlockNo)
161349cc55cSDimitry Andric                     .concat(Twine(", inst: ")
162349cc55cSDimitry Andric                                 .concat((u.s.InstNo ? Twine(u.s.InstNo)
163349cc55cSDimitry Andric                                                     : Twine("live-in"))
164349cc55cSDimitry Andric                                             .concat(Twine(", loc: ").concat(
165349cc55cSDimitry Andric                                                 Twine(mlocname)))
166349cc55cSDimitry Andric                                             .concat(Twine("}")))))
167349cc55cSDimitry Andric         .str();
168349cc55cSDimitry Andric   }
169349cc55cSDimitry Andric 
170349cc55cSDimitry Andric   static ValueIDNum EmptyValue;
171349cc55cSDimitry Andric   static ValueIDNum TombstoneValue;
172349cc55cSDimitry Andric };
173349cc55cSDimitry Andric 
174349cc55cSDimitry Andric /// Thin wrapper around an integer -- designed to give more type safety to
175349cc55cSDimitry Andric /// spill location numbers.
176349cc55cSDimitry Andric class SpillLocationNo {
177349cc55cSDimitry Andric public:
178349cc55cSDimitry Andric   explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
179349cc55cSDimitry Andric   unsigned SpillNo;
180349cc55cSDimitry Andric   unsigned id() const { return SpillNo; }
181349cc55cSDimitry Andric 
182349cc55cSDimitry Andric   bool operator<(const SpillLocationNo &Other) const {
183349cc55cSDimitry Andric     return SpillNo < Other.SpillNo;
184349cc55cSDimitry Andric   }
185349cc55cSDimitry Andric 
186349cc55cSDimitry Andric   bool operator==(const SpillLocationNo &Other) const {
187349cc55cSDimitry Andric     return SpillNo == Other.SpillNo;
188349cc55cSDimitry Andric   }
189349cc55cSDimitry Andric   bool operator!=(const SpillLocationNo &Other) const {
190349cc55cSDimitry Andric     return !(*this == Other);
191349cc55cSDimitry Andric   }
192349cc55cSDimitry Andric };
193349cc55cSDimitry Andric 
194349cc55cSDimitry Andric /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
195349cc55cSDimitry Andric /// the the value, and Boolean of whether or not it's indirect.
196349cc55cSDimitry Andric class DbgValueProperties {
197349cc55cSDimitry Andric public:
198349cc55cSDimitry Andric   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
199349cc55cSDimitry Andric       : DIExpr(DIExpr), Indirect(Indirect) {}
200349cc55cSDimitry Andric 
201349cc55cSDimitry Andric   /// Extract properties from an existing DBG_VALUE instruction.
202349cc55cSDimitry Andric   DbgValueProperties(const MachineInstr &MI) {
203349cc55cSDimitry Andric     assert(MI.isDebugValue());
204349cc55cSDimitry Andric     DIExpr = MI.getDebugExpression();
205349cc55cSDimitry Andric     Indirect = MI.getOperand(1).isImm();
206349cc55cSDimitry Andric   }
207349cc55cSDimitry Andric 
208349cc55cSDimitry Andric   bool operator==(const DbgValueProperties &Other) const {
209349cc55cSDimitry Andric     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
210349cc55cSDimitry Andric   }
211349cc55cSDimitry Andric 
212349cc55cSDimitry Andric   bool operator!=(const DbgValueProperties &Other) const {
213349cc55cSDimitry Andric     return !(*this == Other);
214349cc55cSDimitry Andric   }
215349cc55cSDimitry Andric 
216349cc55cSDimitry Andric   const DIExpression *DIExpr;
217349cc55cSDimitry Andric   bool Indirect;
218349cc55cSDimitry Andric };
219349cc55cSDimitry Andric 
220349cc55cSDimitry Andric /// Class recording the (high level) _value_ of a variable. Identifies either
221349cc55cSDimitry Andric /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
222349cc55cSDimitry Andric /// This class also stores meta-information about how the value is qualified.
223349cc55cSDimitry Andric /// Used to reason about variable values when performing the second
224349cc55cSDimitry Andric /// (DebugVariable specific) dataflow analysis.
225349cc55cSDimitry Andric class DbgValue {
226349cc55cSDimitry Andric public:
227349cc55cSDimitry Andric   /// If Kind is Def, the value number that this value is based on. VPHIs set
228349cc55cSDimitry Andric   /// this field to EmptyValue if there is no machine-value for this VPHI, or
229349cc55cSDimitry Andric   /// the corresponding machine-value if there is one.
230349cc55cSDimitry Andric   ValueIDNum ID;
231349cc55cSDimitry Andric   /// If Kind is Const, the MachineOperand defining this value.
232349cc55cSDimitry Andric   Optional<MachineOperand> MO;
233349cc55cSDimitry Andric   /// For a NoVal or VPHI DbgValue, which block it was generated in.
234349cc55cSDimitry Andric   int BlockNo;
235349cc55cSDimitry Andric 
236349cc55cSDimitry Andric   /// Qualifiers for the ValueIDNum above.
237349cc55cSDimitry Andric   DbgValueProperties Properties;
238349cc55cSDimitry Andric 
239349cc55cSDimitry Andric   typedef enum {
240349cc55cSDimitry Andric     Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
241349cc55cSDimitry Andric     Def,   // This value is defined by an inst, or is a PHI value.
242349cc55cSDimitry Andric     Const, // A constant value contained in the MachineOperand field.
243349cc55cSDimitry Andric     VPHI,  // Incoming values to BlockNo differ, those values must be joined by
244349cc55cSDimitry Andric            // a PHI in this block.
245349cc55cSDimitry Andric     NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
246349cc55cSDimitry Andric            // before dominating blocks values are propagated in.
247349cc55cSDimitry Andric   } KindT;
248349cc55cSDimitry Andric   /// Discriminator for whether this is a constant or an in-program value.
249349cc55cSDimitry Andric   KindT Kind;
250349cc55cSDimitry Andric 
251349cc55cSDimitry Andric   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
252349cc55cSDimitry Andric       : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) {
253349cc55cSDimitry Andric     assert(Kind == Def);
254349cc55cSDimitry Andric   }
255349cc55cSDimitry Andric 
256349cc55cSDimitry Andric   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
257349cc55cSDimitry Andric       : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo),
258349cc55cSDimitry Andric         Properties(Prop), Kind(Kind) {
259349cc55cSDimitry Andric     assert(Kind == NoVal || Kind == VPHI);
260349cc55cSDimitry Andric   }
261349cc55cSDimitry Andric 
262349cc55cSDimitry Andric   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
263349cc55cSDimitry Andric       : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop),
264349cc55cSDimitry Andric         Kind(Kind) {
265349cc55cSDimitry Andric     assert(Kind == Const);
266349cc55cSDimitry Andric   }
267349cc55cSDimitry Andric 
268349cc55cSDimitry Andric   DbgValue(const DbgValueProperties &Prop, KindT Kind)
269349cc55cSDimitry Andric     : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop),
270349cc55cSDimitry Andric       Kind(Kind) {
271349cc55cSDimitry Andric     assert(Kind == Undef &&
272349cc55cSDimitry Andric            "Empty DbgValue constructor must pass in Undef kind");
273349cc55cSDimitry Andric   }
274349cc55cSDimitry Andric 
275349cc55cSDimitry Andric #ifndef NDEBUG
276349cc55cSDimitry Andric   void dump(const MLocTracker *MTrack) const;
277349cc55cSDimitry Andric #endif
278349cc55cSDimitry Andric 
279349cc55cSDimitry Andric   bool operator==(const DbgValue &Other) const {
280349cc55cSDimitry Andric     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
281349cc55cSDimitry Andric       return false;
282349cc55cSDimitry Andric     else if (Kind == Def && ID != Other.ID)
283349cc55cSDimitry Andric       return false;
284349cc55cSDimitry Andric     else if (Kind == NoVal && BlockNo != Other.BlockNo)
285349cc55cSDimitry Andric       return false;
286349cc55cSDimitry Andric     else if (Kind == Const)
287349cc55cSDimitry Andric       return MO->isIdenticalTo(*Other.MO);
288349cc55cSDimitry Andric     else if (Kind == VPHI && BlockNo != Other.BlockNo)
289349cc55cSDimitry Andric       return false;
290349cc55cSDimitry Andric     else if (Kind == VPHI && ID != Other.ID)
291349cc55cSDimitry Andric       return false;
292349cc55cSDimitry Andric 
293349cc55cSDimitry Andric     return true;
294349cc55cSDimitry Andric   }
295349cc55cSDimitry Andric 
296349cc55cSDimitry Andric   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
297349cc55cSDimitry Andric };
298349cc55cSDimitry Andric 
299349cc55cSDimitry Andric class LocIdxToIndexFunctor {
300349cc55cSDimitry Andric public:
301349cc55cSDimitry Andric   using argument_type = LocIdx;
302349cc55cSDimitry Andric   unsigned operator()(const LocIdx &L) const { return L.asU64(); }
303349cc55cSDimitry Andric };
304349cc55cSDimitry Andric 
305349cc55cSDimitry Andric /// Tracker for what values are in machine locations. Listens to the Things
306349cc55cSDimitry Andric /// being Done by various instructions, and maintains a table of what machine
307349cc55cSDimitry Andric /// locations have what values (as defined by a ValueIDNum).
308349cc55cSDimitry Andric ///
309349cc55cSDimitry Andric /// There are potentially a much larger number of machine locations on the
310349cc55cSDimitry Andric /// target machine than the actual working-set size of the function. On x86 for
311349cc55cSDimitry Andric /// example, we're extremely unlikely to want to track values through control
312349cc55cSDimitry Andric /// or debug registers. To avoid doing so, MLocTracker has several layers of
313349cc55cSDimitry Andric /// indirection going on, described below, to avoid unnecessarily tracking
314349cc55cSDimitry Andric /// any location.
315349cc55cSDimitry Andric ///
316349cc55cSDimitry Andric /// Here's a sort of diagram of the indexes, read from the bottom up:
317349cc55cSDimitry Andric ///
318349cc55cSDimitry Andric ///           Size on stack   Offset on stack
319349cc55cSDimitry Andric ///                 \              /
320349cc55cSDimitry Andric ///          Stack Idx (Where in slot is this?)
321349cc55cSDimitry Andric ///                         /
322349cc55cSDimitry Andric ///                        /
323349cc55cSDimitry Andric /// Slot Num (%stack.0)   /
324349cc55cSDimitry Andric /// FrameIdx => SpillNum /
325349cc55cSDimitry Andric ///              \      /
326349cc55cSDimitry Andric ///           SpillID (int)              Register number (int)
327349cc55cSDimitry Andric ///                      \                  /
328349cc55cSDimitry Andric ///                      LocationID => LocIdx
329349cc55cSDimitry Andric ///                                |
330349cc55cSDimitry Andric ///                       LocIdx => ValueIDNum
331349cc55cSDimitry Andric ///
332349cc55cSDimitry Andric /// The aim here is that the LocIdx => ValueIDNum vector is just an array of
333349cc55cSDimitry Andric /// values in numbered locations, so that later analyses can ignore whether the
334349cc55cSDimitry Andric /// location is a register or otherwise. To map a register / spill location to
335349cc55cSDimitry Andric /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
336349cc55cSDimitry Andric /// build a LocationID for a stack slot, you need to combine identifiers for
337349cc55cSDimitry Andric /// which stack slot it is and where within that slot is being described.
338349cc55cSDimitry Andric ///
339349cc55cSDimitry Andric /// Register mask operands cause trouble by technically defining every register;
340349cc55cSDimitry Andric /// various hacks are used to avoid tracking registers that are never read and
341349cc55cSDimitry Andric /// only written by regmasks.
342349cc55cSDimitry Andric class MLocTracker {
343349cc55cSDimitry Andric public:
344349cc55cSDimitry Andric   MachineFunction &MF;
345349cc55cSDimitry Andric   const TargetInstrInfo &TII;
346349cc55cSDimitry Andric   const TargetRegisterInfo &TRI;
347349cc55cSDimitry Andric   const TargetLowering &TLI;
348349cc55cSDimitry Andric 
349349cc55cSDimitry Andric   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
350349cc55cSDimitry Andric   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
351349cc55cSDimitry Andric 
352349cc55cSDimitry Andric   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
353349cc55cSDimitry Andric   /// packed, entries only exist for locations that are being tracked.
354349cc55cSDimitry Andric   LocToValueType LocIdxToIDNum;
355349cc55cSDimitry Andric 
356349cc55cSDimitry Andric   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
357349cc55cSDimitry Andric   /// LocIdx key / number for that location. There are always at least as many
358349cc55cSDimitry Andric   /// as the number of registers on the target -- if the value in the register
359349cc55cSDimitry Andric   /// is not being tracked, then the LocIdx value will be zero. New entries are
360349cc55cSDimitry Andric   /// appended if a new spill slot begins being tracked.
361349cc55cSDimitry Andric   /// This, and the corresponding reverse map persist for the analysis of the
362349cc55cSDimitry Andric   /// whole function, and is necessarying for decoding various vectors of
363349cc55cSDimitry Andric   /// values.
364349cc55cSDimitry Andric   std::vector<LocIdx> LocIDToLocIdx;
365349cc55cSDimitry Andric 
366349cc55cSDimitry Andric   /// Inverse map of LocIDToLocIdx.
367349cc55cSDimitry Andric   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
368349cc55cSDimitry Andric 
369349cc55cSDimitry Andric   /// When clobbering register masks, we chose to not believe the machine model
370349cc55cSDimitry Andric   /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
371349cc55cSDimitry Andric   /// keep a set of them here.
372349cc55cSDimitry Andric   SmallSet<Register, 8> SPAliases;
373349cc55cSDimitry Andric 
374349cc55cSDimitry Andric   /// Unique-ification of spill. Used to number them -- their LocID number is
375349cc55cSDimitry Andric   /// the index in SpillLocs minus one plus NumRegs.
376349cc55cSDimitry Andric   UniqueVector<SpillLoc> SpillLocs;
377349cc55cSDimitry Andric 
378349cc55cSDimitry Andric   // If we discover a new machine location, assign it an mphi with this
379349cc55cSDimitry Andric   // block number.
380349cc55cSDimitry Andric   unsigned CurBB;
381349cc55cSDimitry Andric 
382349cc55cSDimitry Andric   /// Cached local copy of the number of registers the target has.
383349cc55cSDimitry Andric   unsigned NumRegs;
384349cc55cSDimitry Andric 
385349cc55cSDimitry Andric   /// Number of slot indexes the target has -- distinct segments of a stack
386349cc55cSDimitry Andric   /// slot that can take on the value of a subregister, when a super-register
387349cc55cSDimitry Andric   /// is written to the stack.
388349cc55cSDimitry Andric   unsigned NumSlotIdxes;
389349cc55cSDimitry Andric 
390349cc55cSDimitry Andric   /// Collection of register mask operands that have been observed. Second part
391349cc55cSDimitry Andric   /// of pair indicates the instruction that they happened in. Used to
392349cc55cSDimitry Andric   /// reconstruct where defs happened if we start tracking a location later
393349cc55cSDimitry Andric   /// on.
394349cc55cSDimitry Andric   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
395349cc55cSDimitry Andric 
396349cc55cSDimitry Andric   /// Pair for describing a position within a stack slot -- first the size in
397349cc55cSDimitry Andric   /// bits, then the offset.
398349cc55cSDimitry Andric   typedef std::pair<unsigned short, unsigned short> StackSlotPos;
399349cc55cSDimitry Andric 
400349cc55cSDimitry Andric   /// Map from a size/offset pair describing a position in a stack slot, to a
401349cc55cSDimitry Andric   /// numeric identifier for that position. Allows easier identification of
402349cc55cSDimitry Andric   /// individual positions.
403349cc55cSDimitry Andric   DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
404349cc55cSDimitry Andric 
405349cc55cSDimitry Andric   /// Inverse of StackSlotIdxes.
406349cc55cSDimitry Andric   DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
407349cc55cSDimitry Andric 
408349cc55cSDimitry Andric   /// Iterator for locations and the values they contain. Dereferencing
409349cc55cSDimitry Andric   /// produces a struct/pair containing the LocIdx key for this location,
410349cc55cSDimitry Andric   /// and a reference to the value currently stored. Simplifies the process
411349cc55cSDimitry Andric   /// of seeking a particular location.
412349cc55cSDimitry Andric   class MLocIterator {
413349cc55cSDimitry Andric     LocToValueType &ValueMap;
414349cc55cSDimitry Andric     LocIdx Idx;
415349cc55cSDimitry Andric 
416349cc55cSDimitry Andric   public:
417349cc55cSDimitry Andric     class value_type {
418349cc55cSDimitry Andric     public:
419349cc55cSDimitry Andric       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
420349cc55cSDimitry Andric       const LocIdx Idx;  /// Read-only index of this location.
421349cc55cSDimitry Andric       ValueIDNum &Value; /// Reference to the stored value at this location.
422349cc55cSDimitry Andric     };
423349cc55cSDimitry Andric 
424349cc55cSDimitry Andric     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
425349cc55cSDimitry Andric         : ValueMap(ValueMap), Idx(Idx) {}
426349cc55cSDimitry Andric 
427349cc55cSDimitry Andric     bool operator==(const MLocIterator &Other) const {
428349cc55cSDimitry Andric       assert(&ValueMap == &Other.ValueMap);
429349cc55cSDimitry Andric       return Idx == Other.Idx;
430349cc55cSDimitry Andric     }
431349cc55cSDimitry Andric 
432349cc55cSDimitry Andric     bool operator!=(const MLocIterator &Other) const {
433349cc55cSDimitry Andric       return !(*this == Other);
434349cc55cSDimitry Andric     }
435349cc55cSDimitry Andric 
436349cc55cSDimitry Andric     void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
437349cc55cSDimitry Andric 
438349cc55cSDimitry Andric     value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
439349cc55cSDimitry Andric   };
440349cc55cSDimitry Andric 
441349cc55cSDimitry Andric   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
442349cc55cSDimitry Andric               const TargetRegisterInfo &TRI, const TargetLowering &TLI);
443349cc55cSDimitry Andric 
444349cc55cSDimitry Andric   /// Produce location ID number for a Register. Provides some small amount of
445349cc55cSDimitry Andric   /// type safety.
446349cc55cSDimitry Andric   /// \param Reg The register we're looking up.
447349cc55cSDimitry Andric   unsigned getLocID(Register Reg) { return Reg.id(); }
448349cc55cSDimitry Andric 
449349cc55cSDimitry Andric   /// Produce location ID number for a spill position.
450349cc55cSDimitry Andric   /// \param Spill The number of the spill we're fetching the location for.
451349cc55cSDimitry Andric   /// \param SpillSubReg Subregister within the spill we're addressing.
452349cc55cSDimitry Andric   unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
453349cc55cSDimitry Andric     unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg);
454349cc55cSDimitry Andric     unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg);
455349cc55cSDimitry Andric     return getLocID(Spill, {Size, Offs});
456349cc55cSDimitry Andric   }
457349cc55cSDimitry Andric 
458349cc55cSDimitry Andric   /// Produce location ID number for a spill position.
459349cc55cSDimitry Andric   /// \param Spill The number of the spill we're fetching the location for.
460349cc55cSDimitry Andric   /// \apram SpillIdx size/offset within the spill slot to be addressed.
461349cc55cSDimitry Andric   unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
462349cc55cSDimitry Andric     unsigned SlotNo = Spill.id() - 1;
463349cc55cSDimitry Andric     SlotNo *= NumSlotIdxes;
464349cc55cSDimitry Andric     assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end());
465349cc55cSDimitry Andric     SlotNo += StackSlotIdxes[Idx];
466349cc55cSDimitry Andric     SlotNo += NumRegs;
467349cc55cSDimitry Andric     return SlotNo;
468349cc55cSDimitry Andric   }
469349cc55cSDimitry Andric 
470349cc55cSDimitry Andric   /// Given a spill number, and a slot within the spill, calculate the ID number
471349cc55cSDimitry Andric   /// for that location.
472349cc55cSDimitry Andric   unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
473349cc55cSDimitry Andric     unsigned SlotNo = Spill.id() - 1;
474349cc55cSDimitry Andric     SlotNo *= NumSlotIdxes;
475349cc55cSDimitry Andric     SlotNo += Idx;
476349cc55cSDimitry Andric     SlotNo += NumRegs;
477349cc55cSDimitry Andric     return SlotNo;
478349cc55cSDimitry Andric   }
479349cc55cSDimitry Andric 
480349cc55cSDimitry Andric   /// Return the spill number that a location ID corresponds to.
481349cc55cSDimitry Andric   SpillLocationNo locIDToSpill(unsigned ID) const {
482349cc55cSDimitry Andric     assert(ID >= NumRegs);
483349cc55cSDimitry Andric     ID -= NumRegs;
484349cc55cSDimitry Andric     // Truncate away the index part, leaving only the spill number.
485349cc55cSDimitry Andric     ID /= NumSlotIdxes;
486349cc55cSDimitry Andric     return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
487349cc55cSDimitry Andric   }
488349cc55cSDimitry Andric 
489349cc55cSDimitry Andric   /// Returns the spill-slot size/offs that a location ID corresponds to.
490349cc55cSDimitry Andric   StackSlotPos locIDToSpillIdx(unsigned ID) const {
491349cc55cSDimitry Andric     assert(ID >= NumRegs);
492349cc55cSDimitry Andric     ID -= NumRegs;
493349cc55cSDimitry Andric     unsigned Idx = ID % NumSlotIdxes;
494349cc55cSDimitry Andric     return StackIdxesToPos.find(Idx)->second;
495349cc55cSDimitry Andric   }
496349cc55cSDimitry Andric 
497349cc55cSDimitry Andric   unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); }
498349cc55cSDimitry Andric 
499349cc55cSDimitry Andric   /// Reset all locations to contain a PHI value at the designated block. Used
500349cc55cSDimitry Andric   /// sometimes for actual PHI values, othertimes to indicate the block entry
501349cc55cSDimitry Andric   /// value (before any more information is known).
502349cc55cSDimitry Andric   void setMPhis(unsigned NewCurBB) {
503349cc55cSDimitry Andric     CurBB = NewCurBB;
504349cc55cSDimitry Andric     for (auto Location : locations())
505349cc55cSDimitry Andric       Location.Value = {CurBB, 0, Location.Idx};
506349cc55cSDimitry Andric   }
507349cc55cSDimitry Andric 
508349cc55cSDimitry Andric   /// Load values for each location from array of ValueIDNums. Take current
509349cc55cSDimitry Andric   /// bbnum just in case we read a value from a hitherto untouched register.
510349cc55cSDimitry Andric   void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
511349cc55cSDimitry Andric     CurBB = NewCurBB;
512349cc55cSDimitry Andric     // Iterate over all tracked locations, and load each locations live-in
513349cc55cSDimitry Andric     // value into our local index.
514349cc55cSDimitry Andric     for (auto Location : locations())
515349cc55cSDimitry Andric       Location.Value = Locs[Location.Idx.asU64()];
516349cc55cSDimitry Andric   }
517349cc55cSDimitry Andric 
518349cc55cSDimitry Andric   /// Wipe any un-necessary location records after traversing a block.
519349cc55cSDimitry Andric   void reset(void) {
520349cc55cSDimitry Andric     // We could reset all the location values too; however either loadFromArray
521349cc55cSDimitry Andric     // or setMPhis should be called before this object is re-used. Just
522349cc55cSDimitry Andric     // clear Masks, they're definitely not needed.
523349cc55cSDimitry Andric     Masks.clear();
524349cc55cSDimitry Andric   }
525349cc55cSDimitry Andric 
526349cc55cSDimitry Andric   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
527349cc55cSDimitry Andric   /// the information in this pass uninterpretable.
528349cc55cSDimitry Andric   void clear(void) {
529349cc55cSDimitry Andric     reset();
530349cc55cSDimitry Andric     LocIDToLocIdx.clear();
531349cc55cSDimitry Andric     LocIdxToLocID.clear();
532349cc55cSDimitry Andric     LocIdxToIDNum.clear();
533349cc55cSDimitry Andric     // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
534349cc55cSDimitry Andric     // 0
535349cc55cSDimitry Andric     SpillLocs = decltype(SpillLocs)();
536349cc55cSDimitry Andric     StackSlotIdxes.clear();
537349cc55cSDimitry Andric     StackIdxesToPos.clear();
538349cc55cSDimitry Andric 
539349cc55cSDimitry Andric     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
540349cc55cSDimitry Andric   }
541349cc55cSDimitry Andric 
542349cc55cSDimitry Andric   /// Set a locaiton to a certain value.
543349cc55cSDimitry Andric   void setMLoc(LocIdx L, ValueIDNum Num) {
544349cc55cSDimitry Andric     assert(L.asU64() < LocIdxToIDNum.size());
545349cc55cSDimitry Andric     LocIdxToIDNum[L] = Num;
546349cc55cSDimitry Andric   }
547349cc55cSDimitry Andric 
548349cc55cSDimitry Andric   /// Read the value of a particular location
549349cc55cSDimitry Andric   ValueIDNum readMLoc(LocIdx L) {
550349cc55cSDimitry Andric     assert(L.asU64() < LocIdxToIDNum.size());
551349cc55cSDimitry Andric     return LocIdxToIDNum[L];
552349cc55cSDimitry Andric   }
553349cc55cSDimitry Andric 
554349cc55cSDimitry Andric   /// Create a LocIdx for an untracked register ID. Initialize it to either an
555349cc55cSDimitry Andric   /// mphi value representing a live-in, or a recent register mask clobber.
556349cc55cSDimitry Andric   LocIdx trackRegister(unsigned ID);
557349cc55cSDimitry Andric 
558349cc55cSDimitry Andric   LocIdx lookupOrTrackRegister(unsigned ID) {
559349cc55cSDimitry Andric     LocIdx &Index = LocIDToLocIdx[ID];
560349cc55cSDimitry Andric     if (Index.isIllegal())
561349cc55cSDimitry Andric       Index = trackRegister(ID);
562349cc55cSDimitry Andric     return Index;
563349cc55cSDimitry Andric   }
564349cc55cSDimitry Andric 
565349cc55cSDimitry Andric   /// Is register R currently tracked by MLocTracker?
566349cc55cSDimitry Andric   bool isRegisterTracked(Register R) {
567349cc55cSDimitry Andric     LocIdx &Index = LocIDToLocIdx[R];
568349cc55cSDimitry Andric     return !Index.isIllegal();
569349cc55cSDimitry Andric   }
570349cc55cSDimitry Andric 
571349cc55cSDimitry Andric   /// Record a definition of the specified register at the given block / inst.
572349cc55cSDimitry Andric   /// This doesn't take a ValueIDNum, because the definition and its location
573349cc55cSDimitry Andric   /// are synonymous.
574349cc55cSDimitry Andric   void defReg(Register R, unsigned BB, unsigned Inst) {
575349cc55cSDimitry Andric     unsigned ID = getLocID(R);
576349cc55cSDimitry Andric     LocIdx Idx = lookupOrTrackRegister(ID);
577349cc55cSDimitry Andric     ValueIDNum ValueID = {BB, Inst, Idx};
578349cc55cSDimitry Andric     LocIdxToIDNum[Idx] = ValueID;
579349cc55cSDimitry Andric   }
580349cc55cSDimitry Andric 
581349cc55cSDimitry Andric   /// Set a register to a value number. To be used if the value number is
582349cc55cSDimitry Andric   /// known in advance.
583349cc55cSDimitry Andric   void setReg(Register R, ValueIDNum ValueID) {
584349cc55cSDimitry Andric     unsigned ID = getLocID(R);
585349cc55cSDimitry Andric     LocIdx Idx = lookupOrTrackRegister(ID);
586349cc55cSDimitry Andric     LocIdxToIDNum[Idx] = ValueID;
587349cc55cSDimitry Andric   }
588349cc55cSDimitry Andric 
589349cc55cSDimitry Andric   ValueIDNum readReg(Register R) {
590349cc55cSDimitry Andric     unsigned ID = getLocID(R);
591349cc55cSDimitry Andric     LocIdx Idx = lookupOrTrackRegister(ID);
592349cc55cSDimitry Andric     return LocIdxToIDNum[Idx];
593349cc55cSDimitry Andric   }
594349cc55cSDimitry Andric 
595349cc55cSDimitry Andric   /// Reset a register value to zero / empty. Needed to replicate the
596349cc55cSDimitry Andric   /// VarLoc implementation where a copy to/from a register effectively
597349cc55cSDimitry Andric   /// clears the contents of the source register. (Values can only have one
598349cc55cSDimitry Andric   ///  machine location in VarLocBasedImpl).
599349cc55cSDimitry Andric   void wipeRegister(Register R) {
600349cc55cSDimitry Andric     unsigned ID = getLocID(R);
601349cc55cSDimitry Andric     LocIdx Idx = LocIDToLocIdx[ID];
602349cc55cSDimitry Andric     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
603349cc55cSDimitry Andric   }
604349cc55cSDimitry Andric 
605349cc55cSDimitry Andric   /// Determine the LocIdx of an existing register.
606349cc55cSDimitry Andric   LocIdx getRegMLoc(Register R) {
607349cc55cSDimitry Andric     unsigned ID = getLocID(R);
608349cc55cSDimitry Andric     assert(ID < LocIDToLocIdx.size());
609349cc55cSDimitry Andric     assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap.
610349cc55cSDimitry Andric     return LocIDToLocIdx[ID];
611349cc55cSDimitry Andric   }
612349cc55cSDimitry Andric 
613349cc55cSDimitry Andric   /// Record a RegMask operand being executed. Defs any register we currently
614349cc55cSDimitry Andric   /// track, stores a pointer to the mask in case we have to account for it
615349cc55cSDimitry Andric   /// later.
616349cc55cSDimitry Andric   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
617349cc55cSDimitry Andric 
618349cc55cSDimitry Andric   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
619349cc55cSDimitry Andric   SpillLocationNo getOrTrackSpillLoc(SpillLoc L);
620349cc55cSDimitry Andric 
621349cc55cSDimitry Andric   // Get LocIdx of a spill ID.
622349cc55cSDimitry Andric   LocIdx getSpillMLoc(unsigned SpillID) {
623349cc55cSDimitry Andric     assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap.
624349cc55cSDimitry Andric     return LocIDToLocIdx[SpillID];
625349cc55cSDimitry Andric   }
626349cc55cSDimitry Andric 
627349cc55cSDimitry Andric   /// Return true if Idx is a spill machine location.
628349cc55cSDimitry Andric   bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
629349cc55cSDimitry Andric 
630349cc55cSDimitry Andric   MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
631349cc55cSDimitry Andric 
632349cc55cSDimitry Andric   MLocIterator end() {
633349cc55cSDimitry Andric     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
634349cc55cSDimitry Andric   }
635349cc55cSDimitry Andric 
636349cc55cSDimitry Andric   /// Return a range over all locations currently tracked.
637349cc55cSDimitry Andric   iterator_range<MLocIterator> locations() {
638349cc55cSDimitry Andric     return llvm::make_range(begin(), end());
639349cc55cSDimitry Andric   }
640349cc55cSDimitry Andric 
641349cc55cSDimitry Andric   std::string LocIdxToName(LocIdx Idx) const;
642349cc55cSDimitry Andric 
643349cc55cSDimitry Andric   std::string IDAsString(const ValueIDNum &Num) const;
644349cc55cSDimitry Andric 
645349cc55cSDimitry Andric #ifndef NDEBUG
646349cc55cSDimitry Andric   LLVM_DUMP_METHOD void dump();
647349cc55cSDimitry Andric 
648349cc55cSDimitry Andric   LLVM_DUMP_METHOD void dump_mloc_map();
649349cc55cSDimitry Andric #endif
650349cc55cSDimitry Andric 
651349cc55cSDimitry Andric   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
652349cc55cSDimitry Andric   /// information in \pProperties, for variable Var. Don't insert it anywhere,
653349cc55cSDimitry Andric   /// just return the builder for it.
654349cc55cSDimitry Andric   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
655349cc55cSDimitry Andric                               const DbgValueProperties &Properties);
656349cc55cSDimitry Andric };
657349cc55cSDimitry Andric 
658*4824e7fdSDimitry Andric /// Types for recording sets of variable fragments that overlap. For a given
659*4824e7fdSDimitry Andric /// local variable, we record all other fragments of that variable that could
660*4824e7fdSDimitry Andric /// overlap it, to reduce search time.
661*4824e7fdSDimitry Andric using FragmentOfVar =
662*4824e7fdSDimitry Andric     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
663*4824e7fdSDimitry Andric using OverlapMap =
664*4824e7fdSDimitry Andric     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
665*4824e7fdSDimitry Andric 
666349cc55cSDimitry Andric /// Collection of DBG_VALUEs observed when traversing a block. Records each
667349cc55cSDimitry Andric /// variable and the value the DBG_VALUE refers to. Requires the machine value
668349cc55cSDimitry Andric /// location dataflow algorithm to have run already, so that values can be
669349cc55cSDimitry Andric /// identified.
670349cc55cSDimitry Andric class VLocTracker {
671349cc55cSDimitry Andric public:
672349cc55cSDimitry Andric   /// Map DebugVariable to the latest Value it's defined to have.
673349cc55cSDimitry Andric   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
674349cc55cSDimitry Andric   /// the order in this container.
675349cc55cSDimitry Andric   /// We only retain the last DbgValue in each block for each variable, to
676349cc55cSDimitry Andric   /// determine the blocks live-out variable value. The Vars container forms the
677349cc55cSDimitry Andric   /// transfer function for this block, as part of the dataflow analysis. The
678349cc55cSDimitry Andric   /// movement of values between locations inside of a block is handled at a
679349cc55cSDimitry Andric   /// much later stage, in the TransferTracker class.
680349cc55cSDimitry Andric   MapVector<DebugVariable, DbgValue> Vars;
681349cc55cSDimitry Andric   DenseMap<DebugVariable, const DILocation *> Scopes;
682349cc55cSDimitry Andric   MachineBasicBlock *MBB = nullptr;
683*4824e7fdSDimitry Andric   const OverlapMap &OverlappingFragments;
684*4824e7fdSDimitry Andric   DbgValueProperties EmptyProperties;
685349cc55cSDimitry Andric 
686349cc55cSDimitry Andric public:
687*4824e7fdSDimitry Andric   VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr)
688*4824e7fdSDimitry Andric       : OverlappingFragments(O), EmptyProperties(EmptyExpr, false) {}
689349cc55cSDimitry Andric 
690349cc55cSDimitry Andric   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
691349cc55cSDimitry Andric               Optional<ValueIDNum> ID) {
692349cc55cSDimitry Andric     assert(MI.isDebugValue() || MI.isDebugRef());
693349cc55cSDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
694349cc55cSDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
695349cc55cSDimitry Andric     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
696349cc55cSDimitry Andric                         : DbgValue(Properties, DbgValue::Undef);
697349cc55cSDimitry Andric 
698349cc55cSDimitry Andric     // Attempt insertion; overwrite if it's already mapped.
699349cc55cSDimitry Andric     auto Result = Vars.insert(std::make_pair(Var, Rec));
700349cc55cSDimitry Andric     if (!Result.second)
701349cc55cSDimitry Andric       Result.first->second = Rec;
702349cc55cSDimitry Andric     Scopes[Var] = MI.getDebugLoc().get();
703*4824e7fdSDimitry Andric 
704*4824e7fdSDimitry Andric     considerOverlaps(Var, MI.getDebugLoc().get());
705349cc55cSDimitry Andric   }
706349cc55cSDimitry Andric 
707349cc55cSDimitry Andric   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
708349cc55cSDimitry Andric     // Only DBG_VALUEs can define constant-valued variables.
709349cc55cSDimitry Andric     assert(MI.isDebugValue());
710349cc55cSDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
711349cc55cSDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
712349cc55cSDimitry Andric     DbgValueProperties Properties(MI);
713349cc55cSDimitry Andric     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
714349cc55cSDimitry Andric 
715349cc55cSDimitry Andric     // Attempt insertion; overwrite if it's already mapped.
716349cc55cSDimitry Andric     auto Result = Vars.insert(std::make_pair(Var, Rec));
717349cc55cSDimitry Andric     if (!Result.second)
718349cc55cSDimitry Andric       Result.first->second = Rec;
719349cc55cSDimitry Andric     Scopes[Var] = MI.getDebugLoc().get();
720*4824e7fdSDimitry Andric 
721*4824e7fdSDimitry Andric     considerOverlaps(Var, MI.getDebugLoc().get());
722*4824e7fdSDimitry Andric   }
723*4824e7fdSDimitry Andric 
724*4824e7fdSDimitry Andric   void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
725*4824e7fdSDimitry Andric     auto Overlaps = OverlappingFragments.find(
726*4824e7fdSDimitry Andric         {Var.getVariable(), Var.getFragmentOrDefault()});
727*4824e7fdSDimitry Andric     if (Overlaps == OverlappingFragments.end())
728*4824e7fdSDimitry Andric       return;
729*4824e7fdSDimitry Andric 
730*4824e7fdSDimitry Andric     // Otherwise: terminate any overlapped variable locations.
731*4824e7fdSDimitry Andric     for (auto FragmentInfo : Overlaps->second) {
732*4824e7fdSDimitry Andric       // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
733*4824e7fdSDimitry Andric       // that it overlaps with everything, however its cannonical representation
734*4824e7fdSDimitry Andric       // in a DebugVariable is as "None".
735*4824e7fdSDimitry Andric       Optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
736*4824e7fdSDimitry Andric       if (DebugVariable::isDefaultFragment(FragmentInfo))
737*4824e7fdSDimitry Andric         OptFragmentInfo = None;
738*4824e7fdSDimitry Andric 
739*4824e7fdSDimitry Andric       DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
740*4824e7fdSDimitry Andric                                Var.getInlinedAt());
741*4824e7fdSDimitry Andric       DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
742*4824e7fdSDimitry Andric 
743*4824e7fdSDimitry Andric       // Attempt insertion; overwrite if it's already mapped.
744*4824e7fdSDimitry Andric       auto Result = Vars.insert(std::make_pair(Overlapped, Rec));
745*4824e7fdSDimitry Andric       if (!Result.second)
746*4824e7fdSDimitry Andric         Result.first->second = Rec;
747*4824e7fdSDimitry Andric       Scopes[Overlapped] = Loc;
748*4824e7fdSDimitry Andric     }
749349cc55cSDimitry Andric   }
750349cc55cSDimitry Andric };
751349cc55cSDimitry Andric 
752349cc55cSDimitry Andric // XXX XXX docs
753349cc55cSDimitry Andric class InstrRefBasedLDV : public LDVImpl {
754349cc55cSDimitry Andric public:
755349cc55cSDimitry Andric   friend class ::InstrRefLDVTest;
756349cc55cSDimitry Andric 
757349cc55cSDimitry Andric   using FragmentInfo = DIExpression::FragmentInfo;
758349cc55cSDimitry Andric   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
759349cc55cSDimitry Andric 
760349cc55cSDimitry Andric   // Helper while building OverlapMap, a map of all fragments seen for a given
761349cc55cSDimitry Andric   // DILocalVariable.
762349cc55cSDimitry Andric   using VarToFragments =
763349cc55cSDimitry Andric       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
764349cc55cSDimitry Andric 
765349cc55cSDimitry Andric   /// Machine location/value transfer function, a mapping of which locations
766349cc55cSDimitry Andric   /// are assigned which new values.
767349cc55cSDimitry Andric   using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
768349cc55cSDimitry Andric 
769349cc55cSDimitry Andric   /// Live in/out structure for the variable values: a per-block map of
770349cc55cSDimitry Andric   /// variables to their values.
771349cc55cSDimitry Andric   using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>;
772349cc55cSDimitry Andric 
773349cc55cSDimitry Andric   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
774349cc55cSDimitry Andric 
775349cc55cSDimitry Andric   /// Type for a live-in value: the predecessor block, and its value.
776349cc55cSDimitry Andric   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
777349cc55cSDimitry Andric 
778349cc55cSDimitry Andric   /// Vector (per block) of a collection (inner smallvector) of live-ins.
779349cc55cSDimitry Andric   /// Used as the result type for the variable value dataflow problem.
780349cc55cSDimitry Andric   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
781349cc55cSDimitry Andric 
782349cc55cSDimitry Andric private:
783349cc55cSDimitry Andric   MachineDominatorTree *DomTree;
784349cc55cSDimitry Andric   const TargetRegisterInfo *TRI;
785349cc55cSDimitry Andric   const MachineRegisterInfo *MRI;
786349cc55cSDimitry Andric   const TargetInstrInfo *TII;
787349cc55cSDimitry Andric   const TargetFrameLowering *TFI;
788349cc55cSDimitry Andric   const MachineFrameInfo *MFI;
789349cc55cSDimitry Andric   BitVector CalleeSavedRegs;
790349cc55cSDimitry Andric   LexicalScopes LS;
791349cc55cSDimitry Andric   TargetPassConfig *TPC;
792349cc55cSDimitry Andric 
793349cc55cSDimitry Andric   // An empty DIExpression. Used default / placeholder DbgValueProperties
794349cc55cSDimitry Andric   // objects, as we can't have null expressions.
795349cc55cSDimitry Andric   const DIExpression *EmptyExpr;
796349cc55cSDimitry Andric 
797349cc55cSDimitry Andric   /// Object to track machine locations as we step through a block. Could
798349cc55cSDimitry Andric   /// probably be a field rather than a pointer, as it's always used.
799349cc55cSDimitry Andric   MLocTracker *MTracker = nullptr;
800349cc55cSDimitry Andric 
801349cc55cSDimitry Andric   /// Number of the current block LiveDebugValues is stepping through.
802349cc55cSDimitry Andric   unsigned CurBB;
803349cc55cSDimitry Andric 
804349cc55cSDimitry Andric   /// Number of the current instruction LiveDebugValues is evaluating.
805349cc55cSDimitry Andric   unsigned CurInst;
806349cc55cSDimitry Andric 
807349cc55cSDimitry Andric   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
808349cc55cSDimitry Andric   /// steps through a block. Reads the values at each location from the
809349cc55cSDimitry Andric   /// MLocTracker object.
810349cc55cSDimitry Andric   VLocTracker *VTracker = nullptr;
811349cc55cSDimitry Andric 
812349cc55cSDimitry Andric   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
813349cc55cSDimitry Andric   /// between locations during stepping, creates new DBG_VALUEs when values move
814349cc55cSDimitry Andric   /// location.
815349cc55cSDimitry Andric   TransferTracker *TTracker = nullptr;
816349cc55cSDimitry Andric 
817349cc55cSDimitry Andric   /// Blocks which are artificial, i.e. blocks which exclusively contain
818349cc55cSDimitry Andric   /// instructions without DebugLocs, or with line 0 locations.
819349cc55cSDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
820349cc55cSDimitry Andric 
821349cc55cSDimitry Andric   // Mapping of blocks to and from their RPOT order.
822349cc55cSDimitry Andric   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
823349cc55cSDimitry Andric   DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
824349cc55cSDimitry Andric   DenseMap<unsigned, unsigned> BBNumToRPO;
825349cc55cSDimitry Andric 
826349cc55cSDimitry Andric   /// Pair of MachineInstr, and its 1-based offset into the containing block.
827349cc55cSDimitry Andric   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
828349cc55cSDimitry Andric   /// Map from debug instruction number to the MachineInstr labelled with that
829349cc55cSDimitry Andric   /// number, and its location within the function. Used to transform
830349cc55cSDimitry Andric   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
831349cc55cSDimitry Andric   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
832349cc55cSDimitry Andric 
833349cc55cSDimitry Andric   /// Record of where we observed a DBG_PHI instruction.
834349cc55cSDimitry Andric   class DebugPHIRecord {
835349cc55cSDimitry Andric   public:
836349cc55cSDimitry Andric     uint64_t InstrNum;      ///< Instruction number of this DBG_PHI.
837349cc55cSDimitry Andric     MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred.
838349cc55cSDimitry Andric     ValueIDNum ValueRead;   ///< The value number read by the DBG_PHI.
839349cc55cSDimitry Andric     LocIdx ReadLoc;         ///< Register/Stack location the DBG_PHI reads.
840349cc55cSDimitry Andric 
841349cc55cSDimitry Andric     operator unsigned() const { return InstrNum; }
842349cc55cSDimitry Andric   };
843349cc55cSDimitry Andric 
844349cc55cSDimitry Andric   /// Map from instruction numbers defined by DBG_PHIs to a record of what that
845349cc55cSDimitry Andric   /// DBG_PHI read and where. Populated and edited during the machine value
846349cc55cSDimitry Andric   /// location problem -- we use LLVMs SSA Updater to fix changes by
847349cc55cSDimitry Andric   /// optimizations that destroy PHI instructions.
848349cc55cSDimitry Andric   SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
849349cc55cSDimitry Andric 
850349cc55cSDimitry Andric   // Map of overlapping variable fragments.
851349cc55cSDimitry Andric   OverlapMap OverlapFragments;
852349cc55cSDimitry Andric   VarToFragments SeenFragments;
853349cc55cSDimitry Andric 
854*4824e7fdSDimitry Andric   /// True if we need to examine call instructions for stack clobbers. We
855*4824e7fdSDimitry Andric   /// normally assume that they don't clobber SP, but stack probes on Windows
856*4824e7fdSDimitry Andric   /// do.
857*4824e7fdSDimitry Andric   bool AdjustsStackInCalls = false;
858*4824e7fdSDimitry Andric 
859*4824e7fdSDimitry Andric   /// If AdjustsStackInCalls is true, this holds the name of the target's stack
860*4824e7fdSDimitry Andric   /// probe function, which is the function we expect will alter the stack
861*4824e7fdSDimitry Andric   /// pointer.
862*4824e7fdSDimitry Andric   StringRef StackProbeSymbolName;
863*4824e7fdSDimitry Andric 
864349cc55cSDimitry Andric   /// Tests whether this instruction is a spill to a stack slot.
865349cc55cSDimitry Andric   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
866349cc55cSDimitry Andric 
867349cc55cSDimitry Andric   /// Decide if @MI is a spill instruction and return true if it is. We use 2
868349cc55cSDimitry Andric   /// criteria to make this decision:
869349cc55cSDimitry Andric   /// - Is this instruction a store to a spill slot?
870349cc55cSDimitry Andric   /// - Is there a register operand that is both used and killed?
871349cc55cSDimitry Andric   /// TODO: Store optimization can fold spills into other stores (including
872349cc55cSDimitry Andric   /// other spills). We do not handle this yet (more than one memory operand).
873349cc55cSDimitry Andric   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
874349cc55cSDimitry Andric                        unsigned &Reg);
875349cc55cSDimitry Andric 
876349cc55cSDimitry Andric   /// If a given instruction is identified as a spill, return the spill slot
877349cc55cSDimitry Andric   /// and set \p Reg to the spilled register.
878349cc55cSDimitry Andric   Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
879349cc55cSDimitry Andric                                           MachineFunction *MF, unsigned &Reg);
880349cc55cSDimitry Andric 
881349cc55cSDimitry Andric   /// Given a spill instruction, extract the spill slot information, ensure it's
882349cc55cSDimitry Andric   /// tracked, and return the spill number.
883349cc55cSDimitry Andric   SpillLocationNo extractSpillBaseRegAndOffset(const MachineInstr &MI);
884349cc55cSDimitry Andric 
885349cc55cSDimitry Andric   /// Observe a single instruction while stepping through a block.
886349cc55cSDimitry Andric   void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr,
887349cc55cSDimitry Andric                ValueIDNum **MLiveIns = nullptr);
888349cc55cSDimitry Andric 
889349cc55cSDimitry Andric   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
890349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
891349cc55cSDimitry Andric   bool transferDebugValue(const MachineInstr &MI);
892349cc55cSDimitry Andric 
893349cc55cSDimitry Andric   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
894349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
895349cc55cSDimitry Andric   bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts,
896349cc55cSDimitry Andric                              ValueIDNum **MLiveIns);
897349cc55cSDimitry Andric 
898349cc55cSDimitry Andric   /// Stores value-information about where this PHI occurred, and what
899349cc55cSDimitry Andric   /// instruction number is associated with it.
900349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
901349cc55cSDimitry Andric   bool transferDebugPHI(MachineInstr &MI);
902349cc55cSDimitry Andric 
903349cc55cSDimitry Andric   /// Examines whether \p MI is copy instruction, and notifies trackers.
904349cc55cSDimitry Andric   /// \returns true if MI was recognized and processed.
905349cc55cSDimitry Andric   bool transferRegisterCopy(MachineInstr &MI);
906349cc55cSDimitry Andric 
907349cc55cSDimitry Andric   /// Examines whether \p MI is stack spill or restore  instruction, and
908349cc55cSDimitry Andric   /// notifies trackers. \returns true if MI was recognized and processed.
909349cc55cSDimitry Andric   bool transferSpillOrRestoreInst(MachineInstr &MI);
910349cc55cSDimitry Andric 
911349cc55cSDimitry Andric   /// Examines \p MI for any registers that it defines, and notifies trackers.
912349cc55cSDimitry Andric   void transferRegisterDef(MachineInstr &MI);
913349cc55cSDimitry Andric 
914349cc55cSDimitry Andric   /// Copy one location to the other, accounting for movement of subregisters
915349cc55cSDimitry Andric   /// too.
916349cc55cSDimitry Andric   void performCopy(Register Src, Register Dst);
917349cc55cSDimitry Andric 
918349cc55cSDimitry Andric   void accumulateFragmentMap(MachineInstr &MI);
919349cc55cSDimitry Andric 
920349cc55cSDimitry Andric   /// Determine the machine value number referred to by (potentially several)
921349cc55cSDimitry Andric   /// DBG_PHI instructions. Block duplication and tail folding can duplicate
922349cc55cSDimitry Andric   /// DBG_PHIs, shifting the position where values in registers merge, and
923349cc55cSDimitry Andric   /// forming another mini-ssa problem to solve.
924349cc55cSDimitry Andric   /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
925349cc55cSDimitry Andric   /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
926349cc55cSDimitry Andric   /// \returns The machine value number at position Here, or None.
927349cc55cSDimitry Andric   Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
928349cc55cSDimitry Andric                                       ValueIDNum **MLiveOuts,
929349cc55cSDimitry Andric                                       ValueIDNum **MLiveIns, MachineInstr &Here,
930349cc55cSDimitry Andric                                       uint64_t InstrNum);
931349cc55cSDimitry Andric 
932349cc55cSDimitry Andric   /// Step through the function, recording register definitions and movements
933349cc55cSDimitry Andric   /// in an MLocTracker. Convert the observations into a per-block transfer
934349cc55cSDimitry Andric   /// function in \p MLocTransfer, suitable for using with the machine value
935349cc55cSDimitry Andric   /// location dataflow problem.
936349cc55cSDimitry Andric   void
937349cc55cSDimitry Andric   produceMLocTransferFunction(MachineFunction &MF,
938349cc55cSDimitry Andric                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
939349cc55cSDimitry Andric                               unsigned MaxNumBlocks);
940349cc55cSDimitry Andric 
941349cc55cSDimitry Andric   /// Solve the machine value location dataflow problem. Takes as input the
942349cc55cSDimitry Andric   /// transfer functions in \p MLocTransfer. Writes the output live-in and
943349cc55cSDimitry Andric   /// live-out arrays to the (initialized to zero) multidimensional arrays in
944349cc55cSDimitry Andric   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
945349cc55cSDimitry Andric   /// number, the inner by LocIdx.
946349cc55cSDimitry Andric   void buildMLocValueMap(MachineFunction &MF, ValueIDNum **MInLocs,
947349cc55cSDimitry Andric                          ValueIDNum **MOutLocs,
948349cc55cSDimitry Andric                          SmallVectorImpl<MLocTransferMap> &MLocTransfer);
949349cc55cSDimitry Andric 
950349cc55cSDimitry Andric   /// Examine the stack indexes (i.e. offsets within the stack) to find the
951349cc55cSDimitry Andric   /// basic units of interference -- like reg units, but for the stack.
952349cc55cSDimitry Andric   void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
953349cc55cSDimitry Andric 
954349cc55cSDimitry Andric   /// Install PHI values into the live-in array for each block, according to
955349cc55cSDimitry Andric   /// the IDF of each register.
956349cc55cSDimitry Andric   void placeMLocPHIs(MachineFunction &MF,
957349cc55cSDimitry Andric                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
958349cc55cSDimitry Andric                      ValueIDNum **MInLocs,
959349cc55cSDimitry Andric                      SmallVectorImpl<MLocTransferMap> &MLocTransfer);
960349cc55cSDimitry Andric 
961349cc55cSDimitry Andric   /// Calculate the iterated-dominance-frontier for a set of defs, using the
962349cc55cSDimitry Andric   /// existing LLVM facilities for this. Works for a single "value" or
963349cc55cSDimitry Andric   /// machine/variable location.
964349cc55cSDimitry Andric   /// \p AllBlocks Set of blocks where we might consume the value.
965349cc55cSDimitry Andric   /// \p DefBlocks Set of blocks where the value/location is defined.
966349cc55cSDimitry Andric   /// \p PHIBlocks Output set of blocks where PHIs must be placed.
967349cc55cSDimitry Andric   void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
968349cc55cSDimitry Andric                          const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
969349cc55cSDimitry Andric                          SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
970349cc55cSDimitry Andric 
971349cc55cSDimitry Andric   /// Perform a control flow join (lattice value meet) of the values in machine
972349cc55cSDimitry Andric   /// locations at \p MBB. Follows the algorithm described in the file-comment,
973349cc55cSDimitry Andric   /// reading live-outs of predecessors from \p OutLocs, the current live ins
974349cc55cSDimitry Andric   /// from \p InLocs, and assigning the newly computed live ins back into
975349cc55cSDimitry Andric   /// \p InLocs. \returns two bools -- the first indicates whether a change
976349cc55cSDimitry Andric   /// was made, the second whether a lattice downgrade occurred. If the latter
977349cc55cSDimitry Andric   /// is true, revisiting this block is necessary.
978349cc55cSDimitry Andric   bool mlocJoin(MachineBasicBlock &MBB,
979349cc55cSDimitry Andric                 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
980349cc55cSDimitry Andric                 ValueIDNum **OutLocs, ValueIDNum *InLocs);
981349cc55cSDimitry Andric 
982349cc55cSDimitry Andric   /// Solve the variable value dataflow problem, for a single lexical scope.
983349cc55cSDimitry Andric   /// Uses the algorithm from the file comment to resolve control flow joins
984349cc55cSDimitry Andric   /// using PHI placement and value propagation. Reads the locations of machine
985349cc55cSDimitry Andric   /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
986349cc55cSDimitry Andric   /// and reads the variable values transfer function from \p AllTheVlocs.
987349cc55cSDimitry Andric   /// Live-in and Live-out variable values are stored locally, with the live-ins
988349cc55cSDimitry Andric   /// permanently stored to \p Output once a fixedpoint is reached.
989349cc55cSDimitry Andric   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
990349cc55cSDimitry Andric   /// that we should be tracking.
991349cc55cSDimitry Andric   /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
992349cc55cSDimitry Andric   /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
993349cc55cSDimitry Andric   /// locations through.
994349cc55cSDimitry Andric   void buildVLocValueMap(const DILocation *DILoc,
995349cc55cSDimitry Andric                     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
996349cc55cSDimitry Andric                     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
997349cc55cSDimitry Andric                     LiveInsT &Output, ValueIDNum **MOutLocs,
998349cc55cSDimitry Andric                     ValueIDNum **MInLocs,
999349cc55cSDimitry Andric                     SmallVectorImpl<VLocTracker> &AllTheVLocs);
1000349cc55cSDimitry Andric 
1001349cc55cSDimitry Andric   /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
1002349cc55cSDimitry Andric   /// live-in values coming from predecessors live-outs, and replaces any PHIs
1003349cc55cSDimitry Andric   /// already present in this blocks live-ins with a live-through value if the
1004349cc55cSDimitry Andric   /// PHI isn't needed.
1005349cc55cSDimitry Andric   /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
1006349cc55cSDimitry Andric   /// \returns true if any live-ins change value, either from value propagation
1007349cc55cSDimitry Andric   ///          or PHI elimination.
1008349cc55cSDimitry Andric   bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
1009349cc55cSDimitry Andric                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1010349cc55cSDimitry Andric                 DbgValue &LiveIn);
1011349cc55cSDimitry Andric 
1012349cc55cSDimitry Andric   /// For the given block and live-outs feeding into it, try to find a
1013349cc55cSDimitry Andric   /// machine location where all the variable values join together.
1014349cc55cSDimitry Andric   /// \returns Value ID of a machine PHI if an appropriate one is available.
1015349cc55cSDimitry Andric   Optional<ValueIDNum>
1016349cc55cSDimitry Andric   pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
1017349cc55cSDimitry Andric               const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
1018349cc55cSDimitry Andric               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1019349cc55cSDimitry Andric 
1020349cc55cSDimitry Andric   /// Given the solutions to the two dataflow problems, machine value locations
1021349cc55cSDimitry Andric   /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the
1022349cc55cSDimitry Andric   /// TransferTracker class over the function to produce live-in and transfer
1023349cc55cSDimitry Andric   /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the
1024349cc55cSDimitry Andric   /// order given by AllVarsNumbering -- this could be any stable order, but
1025349cc55cSDimitry Andric   /// right now "order of appearence in function, when explored in RPO", so
1026349cc55cSDimitry Andric   /// that we can compare explictly against VarLocBasedImpl.
1027349cc55cSDimitry Andric   void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns,
1028349cc55cSDimitry Andric                      ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
1029349cc55cSDimitry Andric                      DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
1030349cc55cSDimitry Andric                      const TargetPassConfig &TPC);
1031349cc55cSDimitry Andric 
1032349cc55cSDimitry Andric   /// Boilerplate computation of some initial sets, artifical blocks and
1033349cc55cSDimitry Andric   /// RPOT block ordering.
1034349cc55cSDimitry Andric   void initialSetup(MachineFunction &MF);
1035349cc55cSDimitry Andric 
1036349cc55cSDimitry Andric   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1037349cc55cSDimitry Andric                     TargetPassConfig *TPC, unsigned InputBBLimit,
1038349cc55cSDimitry Andric                     unsigned InputDbgValLimit) override;
1039349cc55cSDimitry Andric 
1040349cc55cSDimitry Andric public:
1041349cc55cSDimitry Andric   /// Default construct and initialize the pass.
1042349cc55cSDimitry Andric   InstrRefBasedLDV();
1043349cc55cSDimitry Andric 
1044349cc55cSDimitry Andric   LLVM_DUMP_METHOD
1045349cc55cSDimitry Andric   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1046349cc55cSDimitry Andric 
1047349cc55cSDimitry Andric   bool isCalleeSaved(LocIdx L) const;
1048349cc55cSDimitry Andric 
1049349cc55cSDimitry Andric   bool hasFoldedStackStore(const MachineInstr &MI) {
1050349cc55cSDimitry Andric     // Instruction must have a memory operand that's a stack slot, and isn't
1051349cc55cSDimitry Andric     // aliased, meaning it's a spill from regalloc instead of a variable.
1052349cc55cSDimitry Andric     // If it's aliased, we can't guarantee its value.
1053349cc55cSDimitry Andric     if (!MI.hasOneMemOperand())
1054349cc55cSDimitry Andric       return false;
1055349cc55cSDimitry Andric     auto *MemOperand = *MI.memoperands_begin();
1056349cc55cSDimitry Andric     return MemOperand->isStore() &&
1057349cc55cSDimitry Andric            MemOperand->getPseudoValue() &&
1058349cc55cSDimitry Andric            MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
1059349cc55cSDimitry Andric            && !MemOperand->getPseudoValue()->isAliased(MFI);
1060349cc55cSDimitry Andric   }
1061349cc55cSDimitry Andric 
1062349cc55cSDimitry Andric   Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
1063349cc55cSDimitry Andric };
1064349cc55cSDimitry Andric 
1065349cc55cSDimitry Andric } // namespace LiveDebugValues
1066349cc55cSDimitry Andric 
1067349cc55cSDimitry Andric namespace llvm {
1068349cc55cSDimitry Andric using namespace LiveDebugValues;
1069349cc55cSDimitry Andric 
1070349cc55cSDimitry Andric template <> struct DenseMapInfo<LocIdx> {
1071349cc55cSDimitry Andric   static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); }
1072349cc55cSDimitry Andric   static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); }
1073349cc55cSDimitry Andric 
1074349cc55cSDimitry Andric   static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
1075349cc55cSDimitry Andric 
1076349cc55cSDimitry Andric   static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
1077349cc55cSDimitry Andric };
1078349cc55cSDimitry Andric 
1079349cc55cSDimitry Andric template <> struct DenseMapInfo<ValueIDNum> {
1080349cc55cSDimitry Andric   static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; }
1081349cc55cSDimitry Andric   static inline ValueIDNum getTombstoneKey() {
1082349cc55cSDimitry Andric     return ValueIDNum::TombstoneValue;
1083349cc55cSDimitry Andric   }
1084349cc55cSDimitry Andric 
1085349cc55cSDimitry Andric   static unsigned getHashValue(const ValueIDNum &Val) { return Val.asU64(); }
1086349cc55cSDimitry Andric 
1087349cc55cSDimitry Andric   static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
1088349cc55cSDimitry Andric     return A == B;
1089349cc55cSDimitry Andric   }
1090349cc55cSDimitry Andric };
1091349cc55cSDimitry Andric 
1092349cc55cSDimitry Andric } // end namespace llvm
1093349cc55cSDimitry Andric 
1094349cc55cSDimitry Andric #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
1095