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"
13989f1c72Sserge-sans-paille #include "llvm/ADT/IndexedMap.h"
14838b4a53SJeremy Morse #include "llvm/ADT/SmallPtrSet.h"
15838b4a53SJeremy Morse #include "llvm/ADT/SmallVector.h"
16838b4a53SJeremy Morse #include "llvm/ADT/UniqueVector.h"
17838b4a53SJeremy Morse #include "llvm/CodeGen/LexicalScopes.h"
18838b4a53SJeremy Morse #include "llvm/CodeGen/MachineBasicBlock.h"
19838b4a53SJeremy Morse #include "llvm/CodeGen/MachineInstr.h"
20989f1c72Sserge-sans-paille #include "llvm/CodeGen/TargetRegisterInfo.h"
21838b4a53SJeremy Morse #include "llvm/IR/DebugInfoMetadata.h"
22838b4a53SJeremy Morse 
23838b4a53SJeremy Morse #include "LiveDebugValues.h"
24838b4a53SJeremy Morse 
25838b4a53SJeremy Morse class TransferTracker;
26838b4a53SJeremy Morse 
27838b4a53SJeremy Morse // Forward dec of unit test class, so that we can peer into the LDV object.
28838b4a53SJeremy Morse class InstrRefLDVTest;
29838b4a53SJeremy Morse 
30838b4a53SJeremy Morse namespace LiveDebugValues {
31838b4a53SJeremy Morse 
32838b4a53SJeremy Morse class MLocTracker;
33838b4a53SJeremy Morse 
34838b4a53SJeremy Morse using namespace llvm;
35838b4a53SJeremy Morse 
36838b4a53SJeremy Morse /// Handle-class for a particular "location". This value-type uniquely
37838b4a53SJeremy Morse /// symbolises a register or stack location, allowing manipulation of locations
38838b4a53SJeremy Morse /// without concern for where that location is. Practically, this allows us to
39838b4a53SJeremy Morse /// treat the state of the machine at a particular point as an array of values,
40838b4a53SJeremy Morse /// rather than a map of values.
41838b4a53SJeremy Morse class LocIdx {
42838b4a53SJeremy Morse   unsigned Location;
43838b4a53SJeremy Morse 
44838b4a53SJeremy Morse   // Default constructor is private, initializing to an illegal location number.
45838b4a53SJeremy Morse   // Use only for "not an entry" elements in IndexedMaps.
LocIdx()46838b4a53SJeremy Morse   LocIdx() : Location(UINT_MAX) {}
47838b4a53SJeremy Morse 
48838b4a53SJeremy Morse public:
49838b4a53SJeremy Morse #define NUM_LOC_BITS 24
LocIdx(unsigned L)50838b4a53SJeremy Morse   LocIdx(unsigned L) : Location(L) {
51838b4a53SJeremy Morse     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
52838b4a53SJeremy Morse   }
53838b4a53SJeremy Morse 
MakeIllegalLoc()54838b4a53SJeremy Morse   static LocIdx MakeIllegalLoc() { return LocIdx(); }
MakeTombstoneLoc()554136897bSJeremy Morse   static LocIdx MakeTombstoneLoc() {
564136897bSJeremy Morse     LocIdx L = LocIdx();
574136897bSJeremy Morse     --L.Location;
584136897bSJeremy Morse     return L;
594136897bSJeremy Morse   }
60838b4a53SJeremy Morse 
isIllegal()61838b4a53SJeremy Morse   bool isIllegal() const { return Location == UINT_MAX; }
62838b4a53SJeremy Morse 
asU64()63838b4a53SJeremy Morse   uint64_t asU64() const { return Location; }
64838b4a53SJeremy Morse 
65838b4a53SJeremy Morse   bool operator==(unsigned L) const { return Location == L; }
66838b4a53SJeremy Morse 
67838b4a53SJeremy Morse   bool operator==(const LocIdx &L) const { return Location == L.Location; }
68838b4a53SJeremy Morse 
69838b4a53SJeremy Morse   bool operator!=(unsigned L) const { return !(*this == L); }
70838b4a53SJeremy Morse 
71838b4a53SJeremy Morse   bool operator!=(const LocIdx &L) const { return !(*this == L); }
72838b4a53SJeremy Morse 
73838b4a53SJeremy Morse   bool operator<(const LocIdx &Other) const {
74838b4a53SJeremy Morse     return Location < Other.Location;
75838b4a53SJeremy Morse   }
76838b4a53SJeremy Morse };
77838b4a53SJeremy Morse 
78838b4a53SJeremy Morse // The location at which a spilled value resides. It consists of a register and
79838b4a53SJeremy Morse // an offset.
80838b4a53SJeremy Morse struct SpillLoc {
81838b4a53SJeremy Morse   unsigned SpillBase;
82838b4a53SJeremy Morse   StackOffset SpillOffset;
83838b4a53SJeremy Morse   bool operator==(const SpillLoc &Other) const {
84838b4a53SJeremy Morse     return std::make_pair(SpillBase, SpillOffset) ==
85838b4a53SJeremy Morse            std::make_pair(Other.SpillBase, Other.SpillOffset);
86838b4a53SJeremy Morse   }
87838b4a53SJeremy Morse   bool operator<(const SpillLoc &Other) const {
88838b4a53SJeremy Morse     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
89838b4a53SJeremy Morse                            SpillOffset.getScalable()) <
90838b4a53SJeremy Morse            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
91838b4a53SJeremy Morse                            Other.SpillOffset.getScalable());
92838b4a53SJeremy Morse   }
93838b4a53SJeremy Morse };
94838b4a53SJeremy Morse 
95838b4a53SJeremy Morse /// Unique identifier for a value defined by an instruction, as a value type.
96838b4a53SJeremy Morse /// Casts back and forth to a uint64_t. Probably replacable with something less
97838b4a53SJeremy Morse /// bit-constrained. Each value identifies the instruction and machine location
98838b4a53SJeremy Morse /// where the value is defined, although there may be no corresponding machine
99838b4a53SJeremy Morse /// operand for it (ex: regmasks clobbering values). The instructions are
100838b4a53SJeremy Morse /// one-based, and definitions that are PHIs have instruction number zero.
101838b4a53SJeremy Morse ///
102838b4a53SJeremy Morse /// The obvious limits of a 1M block function or 1M instruction blocks are
103838b4a53SJeremy Morse /// problematic; but by that point we should probably have bailed out of
104838b4a53SJeremy Morse /// trying to analyse the function.
105838b4a53SJeremy Morse class ValueIDNum {
1064136897bSJeremy Morse   union {
1074136897bSJeremy Morse     struct {
108838b4a53SJeremy Morse       uint64_t BlockNo : 20; /// The block where the def happens.
109838b4a53SJeremy Morse       uint64_t InstNo : 20;  /// The Instruction where the def happens.
110838b4a53SJeremy Morse                              /// One based, is distance from start of block.
1114136897bSJeremy Morse       uint64_t LocNo
1124136897bSJeremy Morse           : NUM_LOC_BITS; /// The machine location where the def happens.
1134136897bSJeremy Morse     } s;
1144136897bSJeremy Morse     uint64_t Value;
1154136897bSJeremy Morse   } u;
1164136897bSJeremy Morse 
1174136897bSJeremy Morse   static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
118838b4a53SJeremy Morse 
119838b4a53SJeremy Morse public:
120838b4a53SJeremy Morse   // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
121838b4a53SJeremy Morse   // of values to work.
ValueIDNum()1224136897bSJeremy Morse   ValueIDNum() { u.Value = EmptyValue.asU64(); }
123838b4a53SJeremy Morse 
ValueIDNum(uint64_t Block,uint64_t Inst,uint64_t Loc)1244136897bSJeremy Morse   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
1254136897bSJeremy Morse     u.s = {Block, Inst, Loc};
126838b4a53SJeremy Morse   }
127838b4a53SJeremy Morse 
ValueIDNum(uint64_t Block,uint64_t Inst,LocIdx Loc)1284136897bSJeremy Morse   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
1294136897bSJeremy Morse     u.s = {Block, Inst, Loc.asU64()};
1304136897bSJeremy Morse   }
1314136897bSJeremy Morse 
getBlock()1324136897bSJeremy Morse   uint64_t getBlock() const { return u.s.BlockNo; }
getInst()1334136897bSJeremy Morse   uint64_t getInst() const { return u.s.InstNo; }
getLoc()1344136897bSJeremy Morse   uint64_t getLoc() const { return u.s.LocNo; }
isPHI()1354136897bSJeremy Morse   bool isPHI() const { return u.s.InstNo == 0; }
1364136897bSJeremy Morse 
asU64()1374136897bSJeremy Morse   uint64_t asU64() const { return u.Value; }
1384136897bSJeremy Morse 
fromU64(uint64_t v)139838b4a53SJeremy Morse   static ValueIDNum fromU64(uint64_t v) {
1404136897bSJeremy Morse     ValueIDNum Val;
1414136897bSJeremy Morse     Val.u.Value = v;
1424136897bSJeremy Morse     return Val;
143838b4a53SJeremy Morse   }
144838b4a53SJeremy Morse 
145838b4a53SJeremy Morse   bool operator<(const ValueIDNum &Other) const {
146838b4a53SJeremy Morse     return asU64() < Other.asU64();
147838b4a53SJeremy Morse   }
148838b4a53SJeremy Morse 
149838b4a53SJeremy Morse   bool operator==(const ValueIDNum &Other) const {
1504136897bSJeremy Morse     return u.Value == Other.u.Value;
151838b4a53SJeremy Morse   }
152838b4a53SJeremy Morse 
153838b4a53SJeremy Morse   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
154838b4a53SJeremy Morse 
asString(const std::string & mlocname)155838b4a53SJeremy Morse   std::string asString(const std::string &mlocname) const {
156838b4a53SJeremy Morse     return Twine("Value{bb: ")
1574136897bSJeremy Morse         .concat(Twine(u.s.BlockNo)
1584136897bSJeremy Morse                     .concat(Twine(", inst: ")
1594136897bSJeremy Morse                                 .concat((u.s.InstNo ? Twine(u.s.InstNo)
1604136897bSJeremy Morse                                                     : Twine("live-in"))
1614136897bSJeremy Morse                                             .concat(Twine(", loc: ").concat(
1624136897bSJeremy Morse                                                 Twine(mlocname)))
163838b4a53SJeremy Morse                                             .concat(Twine("}")))))
164838b4a53SJeremy Morse         .str();
165838b4a53SJeremy Morse   }
166838b4a53SJeremy Morse 
167838b4a53SJeremy Morse   static ValueIDNum EmptyValue;
1684136897bSJeremy Morse   static ValueIDNum TombstoneValue;
169838b4a53SJeremy Morse };
170838b4a53SJeremy Morse 
171ab49dce0SJeremy Morse /// Type for a table of values in a block.
172ab49dce0SJeremy Morse using ValueTable = std::unique_ptr<ValueIDNum[]>;
173ab49dce0SJeremy Morse 
174ab49dce0SJeremy Morse /// Type for a table-of-table-of-values, i.e., the collection of either
175ab49dce0SJeremy Morse /// live-in or live-out values for each block in the function.
176ab49dce0SJeremy Morse using FuncValueTable = std::unique_ptr<ValueTable[]>;
177ab49dce0SJeremy Morse 
178e7084ceaSJeremy Morse /// Thin wrapper around an integer -- designed to give more type safety to
179e7084ceaSJeremy Morse /// spill location numbers.
180e7084ceaSJeremy Morse class SpillLocationNo {
181e7084ceaSJeremy Morse public:
SpillLocationNo(unsigned SpillNo)182e7084ceaSJeremy Morse   explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
183e7084ceaSJeremy Morse   unsigned SpillNo;
id()184e7084ceaSJeremy Morse   unsigned id() const { return SpillNo; }
185e7084ceaSJeremy Morse 
186e7084ceaSJeremy Morse   bool operator<(const SpillLocationNo &Other) const {
187e7084ceaSJeremy Morse     return SpillNo < Other.SpillNo;
188e7084ceaSJeremy Morse   }
189e7084ceaSJeremy Morse 
190e7084ceaSJeremy Morse   bool operator==(const SpillLocationNo &Other) const {
191e7084ceaSJeremy Morse     return SpillNo == Other.SpillNo;
192e7084ceaSJeremy Morse   }
193e7084ceaSJeremy Morse   bool operator!=(const SpillLocationNo &Other) const {
194e7084ceaSJeremy Morse     return !(*this == Other);
195e7084ceaSJeremy Morse   }
196e7084ceaSJeremy Morse };
197e7084ceaSJeremy Morse 
198838b4a53SJeremy Morse /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
19987a55137SBrian Tracy /// the value, and Boolean of whether or not it's indirect.
200838b4a53SJeremy Morse class DbgValueProperties {
201838b4a53SJeremy Morse public:
DbgValueProperties(const DIExpression * DIExpr,bool Indirect)202838b4a53SJeremy Morse   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
203838b4a53SJeremy Morse       : DIExpr(DIExpr), Indirect(Indirect) {}
204838b4a53SJeremy Morse 
205838b4a53SJeremy Morse   /// Extract properties from an existing DBG_VALUE instruction.
DbgValueProperties(const MachineInstr & MI)206838b4a53SJeremy Morse   DbgValueProperties(const MachineInstr &MI) {
207838b4a53SJeremy Morse     assert(MI.isDebugValue());
208838b4a53SJeremy Morse     DIExpr = MI.getDebugExpression();
209838b4a53SJeremy Morse     Indirect = MI.getOperand(1).isImm();
210838b4a53SJeremy Morse   }
211838b4a53SJeremy Morse 
212838b4a53SJeremy Morse   bool operator==(const DbgValueProperties &Other) const {
213838b4a53SJeremy Morse     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
214838b4a53SJeremy Morse   }
215838b4a53SJeremy Morse 
216838b4a53SJeremy Morse   bool operator!=(const DbgValueProperties &Other) const {
217838b4a53SJeremy Morse     return !(*this == Other);
218838b4a53SJeremy Morse   }
219838b4a53SJeremy Morse 
220838b4a53SJeremy Morse   const DIExpression *DIExpr;
221838b4a53SJeremy Morse   bool Indirect;
222838b4a53SJeremy Morse };
223838b4a53SJeremy Morse 
224838b4a53SJeremy Morse /// Class recording the (high level) _value_ of a variable. Identifies either
225838b4a53SJeremy Morse /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
226838b4a53SJeremy Morse /// This class also stores meta-information about how the value is qualified.
227838b4a53SJeremy Morse /// Used to reason about variable values when performing the second
228838b4a53SJeremy Morse /// (DebugVariable specific) dataflow analysis.
229838b4a53SJeremy Morse class DbgValue {
230838b4a53SJeremy Morse public:
231b5426cedSJeremy Morse   /// If Kind is Def, the value number that this value is based on. VPHIs set
232b5426cedSJeremy Morse   /// this field to EmptyValue if there is no machine-value for this VPHI, or
233b5426cedSJeremy Morse   /// the corresponding machine-value if there is one.
234838b4a53SJeremy Morse   ValueIDNum ID;
235838b4a53SJeremy Morse   /// If Kind is Const, the MachineOperand defining this value.
236b5426cedSJeremy Morse   Optional<MachineOperand> MO;
237b5426cedSJeremy Morse   /// For a NoVal or VPHI DbgValue, which block it was generated in.
238b5426cedSJeremy Morse   int BlockNo;
239b5426cedSJeremy Morse 
240838b4a53SJeremy Morse   /// Qualifiers for the ValueIDNum above.
241838b4a53SJeremy Morse   DbgValueProperties Properties;
242838b4a53SJeremy Morse 
243838b4a53SJeremy Morse   typedef enum {
244838b4a53SJeremy Morse     Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
245838b4a53SJeremy Morse     Def,   // This value is defined by an inst, or is a PHI value.
246838b4a53SJeremy Morse     Const, // A constant value contained in the MachineOperand field.
247b5426cedSJeremy Morse     VPHI,  // Incoming values to BlockNo differ, those values must be joined by
248b5426cedSJeremy Morse            // a PHI in this block.
249b5426cedSJeremy Morse     NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
250b5426cedSJeremy Morse            // before dominating blocks values are propagated in.
251838b4a53SJeremy Morse   } KindT;
252838b4a53SJeremy Morse   /// Discriminator for whether this is a constant or an in-program value.
253838b4a53SJeremy Morse   KindT Kind;
254838b4a53SJeremy Morse 
DbgValue(const ValueIDNum & Val,const DbgValueProperties & Prop,KindT Kind)255838b4a53SJeremy Morse   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
256b5426cedSJeremy Morse       : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) {
257b5426cedSJeremy Morse     assert(Kind == Def);
258838b4a53SJeremy Morse   }
259838b4a53SJeremy Morse 
DbgValue(unsigned BlockNo,const DbgValueProperties & Prop,KindT Kind)260838b4a53SJeremy Morse   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
261b5426cedSJeremy Morse       : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo),
262b5426cedSJeremy Morse         Properties(Prop), Kind(Kind) {
263b5426cedSJeremy Morse     assert(Kind == NoVal || Kind == VPHI);
264838b4a53SJeremy Morse   }
265838b4a53SJeremy Morse 
DbgValue(const MachineOperand & MO,const DbgValueProperties & Prop,KindT Kind)266838b4a53SJeremy Morse   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
267b5426cedSJeremy Morse       : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop),
268b5426cedSJeremy Morse         Kind(Kind) {
269838b4a53SJeremy Morse     assert(Kind == Const);
270838b4a53SJeremy Morse   }
271838b4a53SJeremy Morse 
DbgValue(const DbgValueProperties & Prop,KindT Kind)272838b4a53SJeremy Morse   DbgValue(const DbgValueProperties &Prop, KindT Kind)
273b5426cedSJeremy Morse     : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop),
274b5426cedSJeremy Morse       Kind(Kind) {
275838b4a53SJeremy Morse     assert(Kind == Undef &&
276838b4a53SJeremy Morse            "Empty DbgValue constructor must pass in Undef kind");
277838b4a53SJeremy Morse   }
278838b4a53SJeremy Morse 
279d9fa186aSJeremy Morse #ifndef NDEBUG
280838b4a53SJeremy Morse   void dump(const MLocTracker *MTrack) const;
281d9fa186aSJeremy Morse #endif
282838b4a53SJeremy Morse 
283838b4a53SJeremy Morse   bool operator==(const DbgValue &Other) const {
284838b4a53SJeremy Morse     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
285838b4a53SJeremy Morse       return false;
286838b4a53SJeremy Morse     else if (Kind == Def && ID != Other.ID)
287838b4a53SJeremy Morse       return false;
288838b4a53SJeremy Morse     else if (Kind == NoVal && BlockNo != Other.BlockNo)
289838b4a53SJeremy Morse       return false;
290838b4a53SJeremy Morse     else if (Kind == Const)
291b5426cedSJeremy Morse       return MO->isIdenticalTo(*Other.MO);
292b5426cedSJeremy Morse     else if (Kind == VPHI && BlockNo != Other.BlockNo)
293b5426cedSJeremy Morse       return false;
294b5426cedSJeremy Morse     else if (Kind == VPHI && ID != Other.ID)
295b5426cedSJeremy Morse       return false;
296838b4a53SJeremy Morse 
297838b4a53SJeremy Morse     return true;
298838b4a53SJeremy Morse   }
299838b4a53SJeremy Morse 
300838b4a53SJeremy Morse   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
301838b4a53SJeremy Morse };
302838b4a53SJeremy Morse 
303838b4a53SJeremy Morse class LocIdxToIndexFunctor {
304838b4a53SJeremy Morse public:
305838b4a53SJeremy Morse   using argument_type = LocIdx;
operator()306838b4a53SJeremy Morse   unsigned operator()(const LocIdx &L) const { return L.asU64(); }
307838b4a53SJeremy Morse };
308838b4a53SJeremy Morse 
309838b4a53SJeremy Morse /// Tracker for what values are in machine locations. Listens to the Things
310838b4a53SJeremy Morse /// being Done by various instructions, and maintains a table of what machine
311838b4a53SJeremy Morse /// locations have what values (as defined by a ValueIDNum).
312838b4a53SJeremy Morse ///
313838b4a53SJeremy Morse /// There are potentially a much larger number of machine locations on the
314838b4a53SJeremy Morse /// target machine than the actual working-set size of the function. On x86 for
315838b4a53SJeremy Morse /// example, we're extremely unlikely to want to track values through control
316838b4a53SJeremy Morse /// or debug registers. To avoid doing so, MLocTracker has several layers of
317e7084ceaSJeremy Morse /// indirection going on, described below, to avoid unnecessarily tracking
318e7084ceaSJeremy Morse /// any location.
319838b4a53SJeremy Morse ///
320e7084ceaSJeremy Morse /// Here's a sort of diagram of the indexes, read from the bottom up:
321e7084ceaSJeremy Morse ///
322e7084ceaSJeremy Morse ///           Size on stack   Offset on stack
323e7084ceaSJeremy Morse ///                 \              /
324e7084ceaSJeremy Morse ///          Stack Idx (Where in slot is this?)
325e7084ceaSJeremy Morse ///                         /
326e7084ceaSJeremy Morse ///                        /
327e7084ceaSJeremy Morse /// Slot Num (%stack.0)   /
328e7084ceaSJeremy Morse /// FrameIdx => SpillNum /
329e7084ceaSJeremy Morse ///              \      /
330e7084ceaSJeremy Morse ///           SpillID (int)              Register number (int)
331e7084ceaSJeremy Morse ///                      \                  /
332e7084ceaSJeremy Morse ///                      LocationID => LocIdx
333e7084ceaSJeremy Morse ///                                |
334e7084ceaSJeremy Morse ///                       LocIdx => ValueIDNum
335e7084ceaSJeremy Morse ///
336e7084ceaSJeremy Morse /// The aim here is that the LocIdx => ValueIDNum vector is just an array of
337e7084ceaSJeremy Morse /// values in numbered locations, so that later analyses can ignore whether the
338e7084ceaSJeremy Morse /// location is a register or otherwise. To map a register / spill location to
339e7084ceaSJeremy Morse /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
340e7084ceaSJeremy Morse /// build a LocationID for a stack slot, you need to combine identifiers for
341e7084ceaSJeremy Morse /// which stack slot it is and where within that slot is being described.
342e7084ceaSJeremy Morse ///
343e7084ceaSJeremy Morse /// Register mask operands cause trouble by technically defining every register;
344e7084ceaSJeremy Morse /// various hacks are used to avoid tracking registers that are never read and
345e7084ceaSJeremy Morse /// only written by regmasks.
346838b4a53SJeremy Morse class MLocTracker {
347838b4a53SJeremy Morse public:
348838b4a53SJeremy Morse   MachineFunction &MF;
349838b4a53SJeremy Morse   const TargetInstrInfo &TII;
350838b4a53SJeremy Morse   const TargetRegisterInfo &TRI;
351838b4a53SJeremy Morse   const TargetLowering &TLI;
352838b4a53SJeremy Morse 
353838b4a53SJeremy Morse   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
354838b4a53SJeremy Morse   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
355838b4a53SJeremy Morse 
356838b4a53SJeremy Morse   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
357838b4a53SJeremy Morse   /// packed, entries only exist for locations that are being tracked.
358838b4a53SJeremy Morse   LocToValueType LocIdxToIDNum;
359838b4a53SJeremy Morse 
360838b4a53SJeremy Morse   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
361838b4a53SJeremy Morse   /// LocIdx key / number for that location. There are always at least as many
362838b4a53SJeremy Morse   /// as the number of registers on the target -- if the value in the register
363838b4a53SJeremy Morse   /// is not being tracked, then the LocIdx value will be zero. New entries are
364838b4a53SJeremy Morse   /// appended if a new spill slot begins being tracked.
365838b4a53SJeremy Morse   /// This, and the corresponding reverse map persist for the analysis of the
366838b4a53SJeremy Morse   /// whole function, and is necessarying for decoding various vectors of
367838b4a53SJeremy Morse   /// values.
368838b4a53SJeremy Morse   std::vector<LocIdx> LocIDToLocIdx;
369838b4a53SJeremy Morse 
370838b4a53SJeremy Morse   /// Inverse map of LocIDToLocIdx.
371838b4a53SJeremy Morse   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
372838b4a53SJeremy Morse 
373fbf269c7SJeremy Morse   /// When clobbering register masks, we chose to not believe the machine model
374fbf269c7SJeremy Morse   /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
375fbf269c7SJeremy Morse   /// keep a set of them here.
376fbf269c7SJeremy Morse   SmallSet<Register, 8> SPAliases;
377fbf269c7SJeremy Morse 
378e7084ceaSJeremy Morse   /// Unique-ification of spill. Used to number them -- their LocID number is
379e7084ceaSJeremy Morse   /// the index in SpillLocs minus one plus NumRegs.
380838b4a53SJeremy Morse   UniqueVector<SpillLoc> SpillLocs;
381838b4a53SJeremy Morse 
382838b4a53SJeremy Morse   // If we discover a new machine location, assign it an mphi with this
383838b4a53SJeremy Morse   // block number.
384838b4a53SJeremy Morse   unsigned CurBB;
385838b4a53SJeremy Morse 
386838b4a53SJeremy Morse   /// Cached local copy of the number of registers the target has.
387838b4a53SJeremy Morse   unsigned NumRegs;
388838b4a53SJeremy Morse 
389e7084ceaSJeremy Morse   /// Number of slot indexes the target has -- distinct segments of a stack
390e7084ceaSJeremy Morse   /// slot that can take on the value of a subregister, when a super-register
391e7084ceaSJeremy Morse   /// is written to the stack.
392e7084ceaSJeremy Morse   unsigned NumSlotIdxes;
393e7084ceaSJeremy Morse 
394838b4a53SJeremy Morse   /// Collection of register mask operands that have been observed. Second part
395838b4a53SJeremy Morse   /// of pair indicates the instruction that they happened in. Used to
396838b4a53SJeremy Morse   /// reconstruct where defs happened if we start tracking a location later
397838b4a53SJeremy Morse   /// on.
398838b4a53SJeremy Morse   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
399838b4a53SJeremy Morse 
400e7084ceaSJeremy Morse   /// Pair for describing a position within a stack slot -- first the size in
401e7084ceaSJeremy Morse   /// bits, then the offset.
402e7084ceaSJeremy Morse   typedef std::pair<unsigned short, unsigned short> StackSlotPos;
403e7084ceaSJeremy Morse 
404e7084ceaSJeremy Morse   /// Map from a size/offset pair describing a position in a stack slot, to a
405e7084ceaSJeremy Morse   /// numeric identifier for that position. Allows easier identification of
406e7084ceaSJeremy Morse   /// individual positions.
407e7084ceaSJeremy Morse   DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
408e7084ceaSJeremy Morse 
409e7084ceaSJeremy Morse   /// Inverse of StackSlotIdxes.
410e7084ceaSJeremy Morse   DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
411e7084ceaSJeremy Morse 
412838b4a53SJeremy Morse   /// Iterator for locations and the values they contain. Dereferencing
413838b4a53SJeremy Morse   /// produces a struct/pair containing the LocIdx key for this location,
414838b4a53SJeremy Morse   /// and a reference to the value currently stored. Simplifies the process
415838b4a53SJeremy Morse   /// of seeking a particular location.
416838b4a53SJeremy Morse   class MLocIterator {
417838b4a53SJeremy Morse     LocToValueType &ValueMap;
418838b4a53SJeremy Morse     LocIdx Idx;
419838b4a53SJeremy Morse 
420838b4a53SJeremy Morse   public:
421838b4a53SJeremy Morse     class value_type {
422838b4a53SJeremy Morse     public:
value_type(LocIdx Idx,ValueIDNum & Value)423838b4a53SJeremy Morse       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
424838b4a53SJeremy Morse       const LocIdx Idx;  /// Read-only index of this location.
425838b4a53SJeremy Morse       ValueIDNum &Value; /// Reference to the stored value at this location.
426838b4a53SJeremy Morse     };
427838b4a53SJeremy Morse 
MLocIterator(LocToValueType & ValueMap,LocIdx Idx)428838b4a53SJeremy Morse     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
429838b4a53SJeremy Morse         : ValueMap(ValueMap), Idx(Idx) {}
430838b4a53SJeremy Morse 
431838b4a53SJeremy Morse     bool operator==(const MLocIterator &Other) const {
432838b4a53SJeremy Morse       assert(&ValueMap == &Other.ValueMap);
433838b4a53SJeremy Morse       return Idx == Other.Idx;
434838b4a53SJeremy Morse     }
435838b4a53SJeremy Morse 
436838b4a53SJeremy Morse     bool operator!=(const MLocIterator &Other) const {
437838b4a53SJeremy Morse       return !(*this == Other);
438838b4a53SJeremy Morse     }
439838b4a53SJeremy Morse 
440838b4a53SJeremy Morse     void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
441838b4a53SJeremy Morse 
442838b4a53SJeremy Morse     value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
443838b4a53SJeremy Morse   };
444838b4a53SJeremy Morse 
445838b4a53SJeremy Morse   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
446838b4a53SJeremy Morse               const TargetRegisterInfo &TRI, const TargetLowering &TLI);
447838b4a53SJeremy Morse 
448e7084ceaSJeremy Morse   /// Produce location ID number for a Register. Provides some small amount of
449e7084ceaSJeremy Morse   /// type safety.
450e7084ceaSJeremy Morse   /// \param Reg The register we're looking up.
getLocID(Register Reg)451e7084ceaSJeremy Morse   unsigned getLocID(Register Reg) { return Reg.id(); }
452e7084ceaSJeremy Morse 
453e7084ceaSJeremy Morse   /// Produce location ID number for a spill position.
454e7084ceaSJeremy Morse   /// \param Spill The number of the spill we're fetching the location for.
455e7084ceaSJeremy Morse   /// \param SpillSubReg Subregister within the spill we're addressing.
getLocID(SpillLocationNo Spill,unsigned SpillSubReg)456e7084ceaSJeremy Morse   unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
457e7084ceaSJeremy Morse     unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg);
458e7084ceaSJeremy Morse     unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg);
459e7084ceaSJeremy Morse     return getLocID(Spill, {Size, Offs});
460e7084ceaSJeremy Morse   }
461e7084ceaSJeremy Morse 
462e7084ceaSJeremy Morse   /// Produce location ID number for a spill position.
463e7084ceaSJeremy Morse   /// \param Spill The number of the spill we're fetching the location for.
464e7084ceaSJeremy Morse   /// \apram SpillIdx size/offset within the spill slot to be addressed.
getLocID(SpillLocationNo Spill,StackSlotPos Idx)465e7084ceaSJeremy Morse   unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
466e7084ceaSJeremy Morse     unsigned SlotNo = Spill.id() - 1;
467e7084ceaSJeremy Morse     SlotNo *= NumSlotIdxes;
468e7084ceaSJeremy Morse     assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end());
469e7084ceaSJeremy Morse     SlotNo += StackSlotIdxes[Idx];
470e7084ceaSJeremy Morse     SlotNo += NumRegs;
471e7084ceaSJeremy Morse     return SlotNo;
472e7084ceaSJeremy Morse   }
473e7084ceaSJeremy Morse 
474e7084ceaSJeremy Morse   /// Given a spill number, and a slot within the spill, calculate the ID number
475e7084ceaSJeremy Morse   /// for that location.
getSpillIDWithIdx(SpillLocationNo Spill,unsigned Idx)476e7084ceaSJeremy Morse   unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
477e7084ceaSJeremy Morse     unsigned SlotNo = Spill.id() - 1;
478e7084ceaSJeremy Morse     SlotNo *= NumSlotIdxes;
479e7084ceaSJeremy Morse     SlotNo += Idx;
480e7084ceaSJeremy Morse     SlotNo += NumRegs;
481e7084ceaSJeremy Morse     return SlotNo;
482e7084ceaSJeremy Morse   }
483e7084ceaSJeremy Morse 
484e7084ceaSJeremy Morse   /// Return the spill number that a location ID corresponds to.
locIDToSpill(unsigned ID)485e7084ceaSJeremy Morse   SpillLocationNo locIDToSpill(unsigned ID) const {
486e7084ceaSJeremy Morse     assert(ID >= NumRegs);
487e7084ceaSJeremy Morse     ID -= NumRegs;
488e7084ceaSJeremy Morse     // Truncate away the index part, leaving only the spill number.
489e7084ceaSJeremy Morse     ID /= NumSlotIdxes;
490e7084ceaSJeremy Morse     return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
491e7084ceaSJeremy Morse   }
492e7084ceaSJeremy Morse 
493e7084ceaSJeremy Morse   /// Returns the spill-slot size/offs that a location ID corresponds to.
locIDToSpillIdx(unsigned ID)494e7084ceaSJeremy Morse   StackSlotPos locIDToSpillIdx(unsigned ID) const {
495e7084ceaSJeremy Morse     assert(ID >= NumRegs);
496e7084ceaSJeremy Morse     ID -= NumRegs;
497e7084ceaSJeremy Morse     unsigned Idx = ID % NumSlotIdxes;
498e7084ceaSJeremy Morse     return StackIdxesToPos.find(Idx)->second;
499838b4a53SJeremy Morse   }
500838b4a53SJeremy Morse 
getNumLocs()5017e163afdSKazu Hirata   unsigned getNumLocs() const { return LocIdxToIDNum.size(); }
502838b4a53SJeremy Morse 
503838b4a53SJeremy Morse   /// Reset all locations to contain a PHI value at the designated block. Used
504838b4a53SJeremy Morse   /// sometimes for actual PHI values, othertimes to indicate the block entry
505838b4a53SJeremy Morse   /// value (before any more information is known).
setMPhis(unsigned NewCurBB)506838b4a53SJeremy Morse   void setMPhis(unsigned NewCurBB) {
507838b4a53SJeremy Morse     CurBB = NewCurBB;
508838b4a53SJeremy Morse     for (auto Location : locations())
509838b4a53SJeremy Morse       Location.Value = {CurBB, 0, Location.Idx};
510838b4a53SJeremy Morse   }
511838b4a53SJeremy Morse 
512838b4a53SJeremy Morse   /// Load values for each location from array of ValueIDNums. Take current
513838b4a53SJeremy Morse   /// bbnum just in case we read a value from a hitherto untouched register.
loadFromArray(ValueTable & Locs,unsigned NewCurBB)514ab49dce0SJeremy Morse   void loadFromArray(ValueTable &Locs, unsigned NewCurBB) {
515838b4a53SJeremy Morse     CurBB = NewCurBB;
516838b4a53SJeremy Morse     // Iterate over all tracked locations, and load each locations live-in
517838b4a53SJeremy Morse     // value into our local index.
518838b4a53SJeremy Morse     for (auto Location : locations())
519838b4a53SJeremy Morse       Location.Value = Locs[Location.Idx.asU64()];
520838b4a53SJeremy Morse   }
521838b4a53SJeremy Morse 
522838b4a53SJeremy Morse   /// Wipe any un-necessary location records after traversing a block.
reset()5237e163afdSKazu Hirata   void reset() {
524838b4a53SJeremy Morse     // We could reset all the location values too; however either loadFromArray
525838b4a53SJeremy Morse     // or setMPhis should be called before this object is re-used. Just
526838b4a53SJeremy Morse     // clear Masks, they're definitely not needed.
527838b4a53SJeremy Morse     Masks.clear();
528838b4a53SJeremy Morse   }
529838b4a53SJeremy Morse 
530838b4a53SJeremy Morse   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
531838b4a53SJeremy Morse   /// the information in this pass uninterpretable.
clear()5327e163afdSKazu Hirata   void clear() {
533838b4a53SJeremy Morse     reset();
534838b4a53SJeremy Morse     LocIDToLocIdx.clear();
535838b4a53SJeremy Morse     LocIdxToLocID.clear();
536838b4a53SJeremy Morse     LocIdxToIDNum.clear();
537838b4a53SJeremy Morse     // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
538838b4a53SJeremy Morse     // 0
539838b4a53SJeremy Morse     SpillLocs = decltype(SpillLocs)();
540e7084ceaSJeremy Morse     StackSlotIdxes.clear();
541e7084ceaSJeremy Morse     StackIdxesToPos.clear();
542838b4a53SJeremy Morse 
543838b4a53SJeremy Morse     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
544838b4a53SJeremy Morse   }
545838b4a53SJeremy Morse 
546838b4a53SJeremy Morse   /// Set a locaiton to a certain value.
setMLoc(LocIdx L,ValueIDNum Num)547838b4a53SJeremy Morse   void setMLoc(LocIdx L, ValueIDNum Num) {
548838b4a53SJeremy Morse     assert(L.asU64() < LocIdxToIDNum.size());
549838b4a53SJeremy Morse     LocIdxToIDNum[L] = Num;
550838b4a53SJeremy Morse   }
551838b4a53SJeremy Morse 
552d9eebe3cSJeremy Morse   /// Read the value of a particular location
readMLoc(LocIdx L)553d9eebe3cSJeremy Morse   ValueIDNum readMLoc(LocIdx L) {
554d9eebe3cSJeremy Morse     assert(L.asU64() < LocIdxToIDNum.size());
555d9eebe3cSJeremy Morse     return LocIdxToIDNum[L];
556d9eebe3cSJeremy Morse   }
557d9eebe3cSJeremy Morse 
558838b4a53SJeremy Morse   /// Create a LocIdx for an untracked register ID. Initialize it to either an
559838b4a53SJeremy Morse   /// mphi value representing a live-in, or a recent register mask clobber.
560838b4a53SJeremy Morse   LocIdx trackRegister(unsigned ID);
561838b4a53SJeremy Morse 
lookupOrTrackRegister(unsigned ID)562838b4a53SJeremy Morse   LocIdx lookupOrTrackRegister(unsigned ID) {
563838b4a53SJeremy Morse     LocIdx &Index = LocIDToLocIdx[ID];
564838b4a53SJeremy Morse     if (Index.isIllegal())
565838b4a53SJeremy Morse       Index = trackRegister(ID);
566838b4a53SJeremy Morse     return Index;
567838b4a53SJeremy Morse   }
568838b4a53SJeremy Morse 
569fbf269c7SJeremy Morse   /// Is register R currently tracked by MLocTracker?
isRegisterTracked(Register R)570fbf269c7SJeremy Morse   bool isRegisterTracked(Register R) {
571fbf269c7SJeremy Morse     LocIdx &Index = LocIDToLocIdx[R];
572fbf269c7SJeremy Morse     return !Index.isIllegal();
573fbf269c7SJeremy Morse   }
574fbf269c7SJeremy Morse 
575838b4a53SJeremy Morse   /// Record a definition of the specified register at the given block / inst.
576838b4a53SJeremy Morse   /// This doesn't take a ValueIDNum, because the definition and its location
577838b4a53SJeremy Morse   /// are synonymous.
defReg(Register R,unsigned BB,unsigned Inst)578838b4a53SJeremy Morse   void defReg(Register R, unsigned BB, unsigned Inst) {
579e7084ceaSJeremy Morse     unsigned ID = getLocID(R);
580838b4a53SJeremy Morse     LocIdx Idx = lookupOrTrackRegister(ID);
581838b4a53SJeremy Morse     ValueIDNum ValueID = {BB, Inst, Idx};
582838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueID;
583838b4a53SJeremy Morse   }
584838b4a53SJeremy Morse 
585838b4a53SJeremy Morse   /// Set a register to a value number. To be used if the value number is
586838b4a53SJeremy Morse   /// known in advance.
setReg(Register R,ValueIDNum ValueID)587838b4a53SJeremy Morse   void setReg(Register R, ValueIDNum ValueID) {
588e7084ceaSJeremy Morse     unsigned ID = getLocID(R);
589838b4a53SJeremy Morse     LocIdx Idx = lookupOrTrackRegister(ID);
590838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueID;
591838b4a53SJeremy Morse   }
592838b4a53SJeremy Morse 
readReg(Register R)593838b4a53SJeremy Morse   ValueIDNum readReg(Register R) {
594e7084ceaSJeremy Morse     unsigned ID = getLocID(R);
595838b4a53SJeremy Morse     LocIdx Idx = lookupOrTrackRegister(ID);
596838b4a53SJeremy Morse     return LocIdxToIDNum[Idx];
597838b4a53SJeremy Morse   }
598838b4a53SJeremy Morse 
599838b4a53SJeremy Morse   /// Reset a register value to zero / empty. Needed to replicate the
600838b4a53SJeremy Morse   /// VarLoc implementation where a copy to/from a register effectively
601838b4a53SJeremy Morse   /// clears the contents of the source register. (Values can only have one
602838b4a53SJeremy Morse   ///  machine location in VarLocBasedImpl).
wipeRegister(Register R)603838b4a53SJeremy Morse   void wipeRegister(Register R) {
604e7084ceaSJeremy Morse     unsigned ID = getLocID(R);
605838b4a53SJeremy Morse     LocIdx Idx = LocIDToLocIdx[ID];
606838b4a53SJeremy Morse     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
607838b4a53SJeremy Morse   }
608838b4a53SJeremy Morse 
609838b4a53SJeremy Morse   /// Determine the LocIdx of an existing register.
getRegMLoc(Register R)610838b4a53SJeremy Morse   LocIdx getRegMLoc(Register R) {
611e7084ceaSJeremy Morse     unsigned ID = getLocID(R);
612e7084ceaSJeremy Morse     assert(ID < LocIDToLocIdx.size());
613e7084ceaSJeremy Morse     assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap.
614838b4a53SJeremy Morse     return LocIDToLocIdx[ID];
615838b4a53SJeremy Morse   }
616838b4a53SJeremy Morse 
617838b4a53SJeremy Morse   /// Record a RegMask operand being executed. Defs any register we currently
618838b4a53SJeremy Morse   /// track, stores a pointer to the mask in case we have to account for it
619838b4a53SJeremy Morse   /// later.
620838b4a53SJeremy Morse   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
621838b4a53SJeremy Morse 
622838b4a53SJeremy Morse   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
62314aaaa12SJeremy Morse   /// Returns None when in scenarios where a spill slot could be tracked, but
62414aaaa12SJeremy Morse   /// we would likely run into resource limitations.
62514aaaa12SJeremy Morse   Optional<SpillLocationNo> getOrTrackSpillLoc(SpillLoc L);
626838b4a53SJeremy Morse 
627e7084ceaSJeremy Morse   // Get LocIdx of a spill ID.
getSpillMLoc(unsigned SpillID)628e7084ceaSJeremy Morse   LocIdx getSpillMLoc(unsigned SpillID) {
629e7084ceaSJeremy Morse     assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap.
630e7084ceaSJeremy Morse     return LocIDToLocIdx[SpillID];
631838b4a53SJeremy Morse   }
632838b4a53SJeremy Morse 
633838b4a53SJeremy Morse   /// Return true if Idx is a spill machine location.
isSpill(LocIdx Idx)634838b4a53SJeremy Morse   bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
635838b4a53SJeremy Morse 
636*a975472fSJeremy Morse   /// How large is this location (aka, how wide is a value defined there?).
getLocSizeInBits(LocIdx L)637*a975472fSJeremy Morse   unsigned getLocSizeInBits(LocIdx L) const {
638*a975472fSJeremy Morse     unsigned ID = LocIdxToLocID[L];
639*a975472fSJeremy Morse     if (!isSpill(L)) {
640*a975472fSJeremy Morse       return TRI.getRegSizeInBits(Register(ID), MF.getRegInfo());
641*a975472fSJeremy Morse     } else {
642*a975472fSJeremy Morse       // The slot location on the stack is uninteresting, we care about the
643*a975472fSJeremy Morse       // position of the value within the slot (which comes with a size).
644*a975472fSJeremy Morse       StackSlotPos Pos = locIDToSpillIdx(ID);
645*a975472fSJeremy Morse       return Pos.first;
646*a975472fSJeremy Morse     }
647*a975472fSJeremy Morse   }
648*a975472fSJeremy Morse 
begin()649838b4a53SJeremy Morse   MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
650838b4a53SJeremy Morse 
end()651838b4a53SJeremy Morse   MLocIterator end() {
652838b4a53SJeremy Morse     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
653838b4a53SJeremy Morse   }
654838b4a53SJeremy Morse 
655838b4a53SJeremy Morse   /// Return a range over all locations currently tracked.
locations()656838b4a53SJeremy Morse   iterator_range<MLocIterator> locations() {
657838b4a53SJeremy Morse     return llvm::make_range(begin(), end());
658838b4a53SJeremy Morse   }
659838b4a53SJeremy Morse 
660838b4a53SJeremy Morse   std::string LocIdxToName(LocIdx Idx) const;
661838b4a53SJeremy Morse 
662838b4a53SJeremy Morse   std::string IDAsString(const ValueIDNum &Num) const;
663838b4a53SJeremy Morse 
664d9fa186aSJeremy Morse #ifndef NDEBUG
665838b4a53SJeremy Morse   LLVM_DUMP_METHOD void dump();
666838b4a53SJeremy Morse 
667838b4a53SJeremy Morse   LLVM_DUMP_METHOD void dump_mloc_map();
668d9fa186aSJeremy Morse #endif
669838b4a53SJeremy Morse 
670838b4a53SJeremy Morse   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
671838b4a53SJeremy Morse   /// information in \pProperties, for variable Var. Don't insert it anywhere,
672838b4a53SJeremy Morse   /// just return the builder for it.
673838b4a53SJeremy Morse   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
674838b4a53SJeremy Morse                               const DbgValueProperties &Properties);
675838b4a53SJeremy Morse };
676838b4a53SJeremy Morse 
6770eee8445SJeremy Morse /// Types for recording sets of variable fragments that overlap. For a given
6780eee8445SJeremy Morse /// local variable, we record all other fragments of that variable that could
6790eee8445SJeremy Morse /// overlap it, to reduce search time.
6800eee8445SJeremy Morse using FragmentOfVar =
6810eee8445SJeremy Morse     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
6820eee8445SJeremy Morse using OverlapMap =
6830eee8445SJeremy Morse     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
6840eee8445SJeremy Morse 
685b5426cedSJeremy Morse /// Collection of DBG_VALUEs observed when traversing a block. Records each
686b5426cedSJeremy Morse /// variable and the value the DBG_VALUE refers to. Requires the machine value
687b5426cedSJeremy Morse /// location dataflow algorithm to have run already, so that values can be
688b5426cedSJeremy Morse /// identified.
689b5426cedSJeremy Morse class VLocTracker {
690b5426cedSJeremy Morse public:
691b5426cedSJeremy Morse   /// Map DebugVariable to the latest Value it's defined to have.
692b5426cedSJeremy Morse   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
693b5426cedSJeremy Morse   /// the order in this container.
694b5426cedSJeremy Morse   /// We only retain the last DbgValue in each block for each variable, to
695b5426cedSJeremy Morse   /// determine the blocks live-out variable value. The Vars container forms the
696b5426cedSJeremy Morse   /// transfer function for this block, as part of the dataflow analysis. The
697b5426cedSJeremy Morse   /// movement of values between locations inside of a block is handled at a
698b5426cedSJeremy Morse   /// much later stage, in the TransferTracker class.
699b5426cedSJeremy Morse   MapVector<DebugVariable, DbgValue> Vars;
700a80181a8SJeremy Morse   SmallDenseMap<DebugVariable, const DILocation *, 8> Scopes;
701cf033bb2SJeremy Morse   MachineBasicBlock *MBB = nullptr;
7020eee8445SJeremy Morse   const OverlapMap &OverlappingFragments;
7030eee8445SJeremy Morse   DbgValueProperties EmptyProperties;
704b5426cedSJeremy Morse 
705b5426cedSJeremy Morse public:
VLocTracker(const OverlapMap & O,const DIExpression * EmptyExpr)7060eee8445SJeremy Morse   VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr)
7070eee8445SJeremy Morse       : OverlappingFragments(O), EmptyProperties(EmptyExpr, false) {}
708b5426cedSJeremy Morse 
defVar(const MachineInstr & MI,const DbgValueProperties & Properties,Optional<ValueIDNum> ID)709b5426cedSJeremy Morse   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
710b5426cedSJeremy Morse               Optional<ValueIDNum> ID) {
711b5426cedSJeremy Morse     assert(MI.isDebugValue() || MI.isDebugRef());
712b5426cedSJeremy Morse     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
713b5426cedSJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
714b5426cedSJeremy Morse     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
715b5426cedSJeremy Morse                         : DbgValue(Properties, DbgValue::Undef);
716b5426cedSJeremy Morse 
717b5426cedSJeremy Morse     // Attempt insertion; overwrite if it's already mapped.
718b5426cedSJeremy Morse     auto Result = Vars.insert(std::make_pair(Var, Rec));
719b5426cedSJeremy Morse     if (!Result.second)
720b5426cedSJeremy Morse       Result.first->second = Rec;
721b5426cedSJeremy Morse     Scopes[Var] = MI.getDebugLoc().get();
7220eee8445SJeremy Morse 
7230eee8445SJeremy Morse     considerOverlaps(Var, MI.getDebugLoc().get());
724b5426cedSJeremy Morse   }
725b5426cedSJeremy Morse 
defVar(const MachineInstr & MI,const MachineOperand & MO)726b5426cedSJeremy Morse   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
727b5426cedSJeremy Morse     // Only DBG_VALUEs can define constant-valued variables.
728b5426cedSJeremy Morse     assert(MI.isDebugValue());
729b5426cedSJeremy Morse     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
730b5426cedSJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
731b5426cedSJeremy Morse     DbgValueProperties Properties(MI);
732b5426cedSJeremy Morse     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
733b5426cedSJeremy Morse 
734b5426cedSJeremy Morse     // Attempt insertion; overwrite if it's already mapped.
735b5426cedSJeremy Morse     auto Result = Vars.insert(std::make_pair(Var, Rec));
736b5426cedSJeremy Morse     if (!Result.second)
737b5426cedSJeremy Morse       Result.first->second = Rec;
738b5426cedSJeremy Morse     Scopes[Var] = MI.getDebugLoc().get();
7390eee8445SJeremy Morse 
7400eee8445SJeremy Morse     considerOverlaps(Var, MI.getDebugLoc().get());
7410eee8445SJeremy Morse   }
7420eee8445SJeremy Morse 
considerOverlaps(const DebugVariable & Var,const DILocation * Loc)7430eee8445SJeremy Morse   void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
7440eee8445SJeremy Morse     auto Overlaps = OverlappingFragments.find(
7450eee8445SJeremy Morse         {Var.getVariable(), Var.getFragmentOrDefault()});
7460eee8445SJeremy Morse     if (Overlaps == OverlappingFragments.end())
7470eee8445SJeremy Morse       return;
7480eee8445SJeremy Morse 
7490eee8445SJeremy Morse     // Otherwise: terminate any overlapped variable locations.
7500eee8445SJeremy Morse     for (auto FragmentInfo : Overlaps->second) {
7510eee8445SJeremy Morse       // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
7520eee8445SJeremy Morse       // that it overlaps with everything, however its cannonical representation
7530eee8445SJeremy Morse       // in a DebugVariable is as "None".
7540eee8445SJeremy Morse       Optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
7550eee8445SJeremy Morse       if (DebugVariable::isDefaultFragment(FragmentInfo))
7560eee8445SJeremy Morse         OptFragmentInfo = None;
7570eee8445SJeremy Morse 
7580eee8445SJeremy Morse       DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
7590eee8445SJeremy Morse                                Var.getInlinedAt());
7600eee8445SJeremy Morse       DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
7610eee8445SJeremy Morse 
7620eee8445SJeremy Morse       // Attempt insertion; overwrite if it's already mapped.
7630eee8445SJeremy Morse       auto Result = Vars.insert(std::make_pair(Overlapped, Rec));
7640eee8445SJeremy Morse       if (!Result.second)
7650eee8445SJeremy Morse         Result.first->second = Rec;
7660eee8445SJeremy Morse       Scopes[Overlapped] = Loc;
7670eee8445SJeremy Morse     }
768b5426cedSJeremy Morse   }
769a80181a8SJeremy Morse 
clear()770a80181a8SJeremy Morse   void clear() {
771a80181a8SJeremy Morse     Vars.clear();
772a80181a8SJeremy Morse     Scopes.clear();
773a80181a8SJeremy Morse   }
774b5426cedSJeremy Morse };
775b5426cedSJeremy Morse 
776838b4a53SJeremy Morse // XXX XXX docs
777838b4a53SJeremy Morse class InstrRefBasedLDV : public LDVImpl {
778b5426cedSJeremy Morse public:
779838b4a53SJeremy Morse   friend class ::InstrRefLDVTest;
780838b4a53SJeremy Morse 
781838b4a53SJeremy Morse   using FragmentInfo = DIExpression::FragmentInfo;
782838b4a53SJeremy Morse   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
783838b4a53SJeremy Morse 
784838b4a53SJeremy Morse   // Helper while building OverlapMap, a map of all fragments seen for a given
785838b4a53SJeremy Morse   // DILocalVariable.
786838b4a53SJeremy Morse   using VarToFragments =
787838b4a53SJeremy Morse       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
788838b4a53SJeremy Morse 
789838b4a53SJeremy Morse   /// Machine location/value transfer function, a mapping of which locations
790838b4a53SJeremy Morse   /// are assigned which new values.
7914136897bSJeremy Morse   using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
792838b4a53SJeremy Morse 
793838b4a53SJeremy Morse   /// Live in/out structure for the variable values: a per-block map of
79489950adeSJeremy Morse   /// variables to their values.
79589950adeSJeremy Morse   using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>;
796838b4a53SJeremy Morse 
797838b4a53SJeremy Morse   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
798838b4a53SJeremy Morse 
799838b4a53SJeremy Morse   /// Type for a live-in value: the predecessor block, and its value.
800838b4a53SJeremy Morse   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
801838b4a53SJeremy Morse 
802838b4a53SJeremy Morse   /// Vector (per block) of a collection (inner smallvector) of live-ins.
803838b4a53SJeremy Morse   /// Used as the result type for the variable value dataflow problem.
804838b4a53SJeremy Morse   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
805838b4a53SJeremy Morse 
8064a2cb013SJeremy Morse   /// Mapping from lexical scopes to a DILocation in that scope.
8074a2cb013SJeremy Morse   using ScopeToDILocT = DenseMap<const LexicalScope *, const DILocation *>;
8084a2cb013SJeremy Morse 
8094a2cb013SJeremy Morse   /// Mapping from lexical scopes to variables in that scope.
8104a2cb013SJeremy Morse   using ScopeToVarsT = DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>>;
8114a2cb013SJeremy Morse 
8124a2cb013SJeremy Morse   /// Mapping from lexical scopes to blocks where variables in that scope are
8134a2cb013SJeremy Morse   /// assigned. Such blocks aren't necessarily "in" the lexical scope, it's
8144a2cb013SJeremy Morse   /// just a block where an assignment happens.
8154a2cb013SJeremy Morse   using ScopeToAssignBlocksT = DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>;
8164a2cb013SJeremy Morse 
817b5426cedSJeremy Morse private:
818a3936a6cSJeremy Morse   MachineDominatorTree *DomTree;
819838b4a53SJeremy Morse   const TargetRegisterInfo *TRI;
820e7084ceaSJeremy Morse   const MachineRegisterInfo *MRI;
821838b4a53SJeremy Morse   const TargetInstrInfo *TII;
822838b4a53SJeremy Morse   const TargetFrameLowering *TFI;
823838b4a53SJeremy Morse   const MachineFrameInfo *MFI;
824838b4a53SJeremy Morse   BitVector CalleeSavedRegs;
825838b4a53SJeremy Morse   LexicalScopes LS;
826838b4a53SJeremy Morse   TargetPassConfig *TPC;
827838b4a53SJeremy Morse 
828b5426cedSJeremy Morse   // An empty DIExpression. Used default / placeholder DbgValueProperties
829b5426cedSJeremy Morse   // objects, as we can't have null expressions.
830b5426cedSJeremy Morse   const DIExpression *EmptyExpr;
831b5426cedSJeremy Morse 
832838b4a53SJeremy Morse   /// Object to track machine locations as we step through a block. Could
833838b4a53SJeremy Morse   /// probably be a field rather than a pointer, as it's always used.
834d9eebe3cSJeremy Morse   MLocTracker *MTracker = nullptr;
835838b4a53SJeremy Morse 
836838b4a53SJeremy Morse   /// Number of the current block LiveDebugValues is stepping through.
837838b4a53SJeremy Morse   unsigned CurBB;
838838b4a53SJeremy Morse 
839838b4a53SJeremy Morse   /// Number of the current instruction LiveDebugValues is evaluating.
840838b4a53SJeremy Morse   unsigned CurInst;
841838b4a53SJeremy Morse 
842838b4a53SJeremy Morse   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
843838b4a53SJeremy Morse   /// steps through a block. Reads the values at each location from the
844838b4a53SJeremy Morse   /// MLocTracker object.
845d9eebe3cSJeremy Morse   VLocTracker *VTracker = nullptr;
846838b4a53SJeremy Morse 
847838b4a53SJeremy Morse   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
848838b4a53SJeremy Morse   /// between locations during stepping, creates new DBG_VALUEs when values move
849838b4a53SJeremy Morse   /// location.
850d9eebe3cSJeremy Morse   TransferTracker *TTracker = nullptr;
851838b4a53SJeremy Morse 
852838b4a53SJeremy Morse   /// Blocks which are artificial, i.e. blocks which exclusively contain
853838b4a53SJeremy Morse   /// instructions without DebugLocs, or with line 0 locations.
8544a2cb013SJeremy Morse   SmallPtrSet<MachineBasicBlock *, 16> ArtificialBlocks;
855838b4a53SJeremy Morse 
856838b4a53SJeremy Morse   // Mapping of blocks to and from their RPOT order.
857838b4a53SJeremy Morse   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
858b5426cedSJeremy Morse   DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
859838b4a53SJeremy Morse   DenseMap<unsigned, unsigned> BBNumToRPO;
860838b4a53SJeremy Morse 
861838b4a53SJeremy Morse   /// Pair of MachineInstr, and its 1-based offset into the containing block.
862838b4a53SJeremy Morse   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
863838b4a53SJeremy Morse   /// Map from debug instruction number to the MachineInstr labelled with that
864838b4a53SJeremy Morse   /// number, and its location within the function. Used to transform
865838b4a53SJeremy Morse   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
866838b4a53SJeremy Morse   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
867838b4a53SJeremy Morse 
868838b4a53SJeremy Morse   /// Record of where we observed a DBG_PHI instruction.
869838b4a53SJeremy Morse   class DebugPHIRecord {
870838b4a53SJeremy Morse   public:
871be5734ddSJeremy Morse     /// Instruction number of this DBG_PHI.
872be5734ddSJeremy Morse     uint64_t InstrNum;
873be5734ddSJeremy Morse     /// Block where DBG_PHI occurred.
874be5734ddSJeremy Morse     MachineBasicBlock *MBB;
875be5734ddSJeremy Morse     /// The value number read by the DBG_PHI -- or None if it didn't refer to
876be5734ddSJeremy Morse     /// a value.
877be5734ddSJeremy Morse     Optional<ValueIDNum> ValueRead;
878be5734ddSJeremy Morse     /// Register/Stack location the DBG_PHI reads -- or None if it referred to
879be5734ddSJeremy Morse     /// something unexpected.
880be5734ddSJeremy Morse     Optional<LocIdx> ReadLoc;
881838b4a53SJeremy Morse 
882838b4a53SJeremy Morse     operator unsigned() const { return InstrNum; }
883838b4a53SJeremy Morse   };
884838b4a53SJeremy Morse 
885838b4a53SJeremy Morse   /// Map from instruction numbers defined by DBG_PHIs to a record of what that
886838b4a53SJeremy Morse   /// DBG_PHI read and where. Populated and edited during the machine value
887838b4a53SJeremy Morse   /// location problem -- we use LLVMs SSA Updater to fix changes by
888838b4a53SJeremy Morse   /// optimizations that destroy PHI instructions.
889838b4a53SJeremy Morse   SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
890838b4a53SJeremy Morse 
891838b4a53SJeremy Morse   // Map of overlapping variable fragments.
892838b4a53SJeremy Morse   OverlapMap OverlapFragments;
893838b4a53SJeremy Morse   VarToFragments SeenFragments;
894838b4a53SJeremy Morse 
895d556eb7eSJeremy Morse   /// Mapping of DBG_INSTR_REF instructions to their values, for those
896d556eb7eSJeremy Morse   /// DBG_INSTR_REFs that call resolveDbgPHIs. These variable references solve
897d556eb7eSJeremy Morse   /// a mini SSA problem caused by DBG_PHIs being cloned, this collection caches
898d556eb7eSJeremy Morse   /// the result.
899d556eb7eSJeremy Morse   DenseMap<MachineInstr *, Optional<ValueIDNum>> SeenDbgPHIs;
900d556eb7eSJeremy Morse 
901bfadc5dcSJeremy Morse   /// True if we need to examine call instructions for stack clobbers. We
902bfadc5dcSJeremy Morse   /// normally assume that they don't clobber SP, but stack probes on Windows
903bfadc5dcSJeremy Morse   /// do.
904bfadc5dcSJeremy Morse   bool AdjustsStackInCalls = false;
905bfadc5dcSJeremy Morse 
906bfadc5dcSJeremy Morse   /// If AdjustsStackInCalls is true, this holds the name of the target's stack
907bfadc5dcSJeremy Morse   /// probe function, which is the function we expect will alter the stack
908bfadc5dcSJeremy Morse   /// pointer.
909bfadc5dcSJeremy Morse   StringRef StackProbeSymbolName;
910bfadc5dcSJeremy Morse 
911838b4a53SJeremy Morse   /// Tests whether this instruction is a spill to a stack slot.
91214aaaa12SJeremy Morse   Optional<SpillLocationNo> isSpillInstruction(const MachineInstr &MI,
91314aaaa12SJeremy Morse                                                MachineFunction *MF);
914838b4a53SJeremy Morse 
915838b4a53SJeremy Morse   /// Decide if @MI is a spill instruction and return true if it is. We use 2
916838b4a53SJeremy Morse   /// criteria to make this decision:
917838b4a53SJeremy Morse   /// - Is this instruction a store to a spill slot?
918838b4a53SJeremy Morse   /// - Is there a register operand that is both used and killed?
919838b4a53SJeremy Morse   /// TODO: Store optimization can fold spills into other stores (including
920838b4a53SJeremy Morse   /// other spills). We do not handle this yet (more than one memory operand).
921838b4a53SJeremy Morse   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
922838b4a53SJeremy Morse                        unsigned &Reg);
923838b4a53SJeremy Morse 
924838b4a53SJeremy Morse   /// If a given instruction is identified as a spill, return the spill slot
925838b4a53SJeremy Morse   /// and set \p Reg to the spilled register.
926e7084ceaSJeremy Morse   Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
927838b4a53SJeremy Morse                                           MachineFunction *MF, unsigned &Reg);
928838b4a53SJeremy Morse 
929e7084ceaSJeremy Morse   /// Given a spill instruction, extract the spill slot information, ensure it's
930e7084ceaSJeremy Morse   /// tracked, and return the spill number.
93114aaaa12SJeremy Morse   Optional<SpillLocationNo>
93214aaaa12SJeremy Morse   extractSpillBaseRegAndOffset(const MachineInstr &MI);
933838b4a53SJeremy Morse 
934838b4a53SJeremy Morse   /// Observe a single instruction while stepping through a block.
935ab49dce0SJeremy Morse   void process(MachineInstr &MI, const ValueTable *MLiveOuts,
936ab49dce0SJeremy Morse                const ValueTable *MLiveIns);
937838b4a53SJeremy Morse 
938838b4a53SJeremy Morse   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
939838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
940838b4a53SJeremy Morse   bool transferDebugValue(const MachineInstr &MI);
941838b4a53SJeremy Morse 
942838b4a53SJeremy Morse   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
943838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
944ab49dce0SJeremy Morse   bool transferDebugInstrRef(MachineInstr &MI, const ValueTable *MLiveOuts,
945ab49dce0SJeremy Morse                              const ValueTable *MLiveIns);
946838b4a53SJeremy Morse 
947838b4a53SJeremy Morse   /// Stores value-information about where this PHI occurred, and what
948838b4a53SJeremy Morse   /// instruction number is associated with it.
949838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
950838b4a53SJeremy Morse   bool transferDebugPHI(MachineInstr &MI);
951838b4a53SJeremy Morse 
952838b4a53SJeremy Morse   /// Examines whether \p MI is copy instruction, and notifies trackers.
953838b4a53SJeremy Morse   /// \returns true if MI was recognized and processed.
954838b4a53SJeremy Morse   bool transferRegisterCopy(MachineInstr &MI);
955838b4a53SJeremy Morse 
956838b4a53SJeremy Morse   /// Examines whether \p MI is stack spill or restore  instruction, and
957838b4a53SJeremy Morse   /// notifies trackers. \returns true if MI was recognized and processed.
958838b4a53SJeremy Morse   bool transferSpillOrRestoreInst(MachineInstr &MI);
959838b4a53SJeremy Morse 
960838b4a53SJeremy Morse   /// Examines \p MI for any registers that it defines, and notifies trackers.
961838b4a53SJeremy Morse   void transferRegisterDef(MachineInstr &MI);
962838b4a53SJeremy Morse 
963838b4a53SJeremy Morse   /// Copy one location to the other, accounting for movement of subregisters
964838b4a53SJeremy Morse   /// too.
965838b4a53SJeremy Morse   void performCopy(Register Src, Register Dst);
966838b4a53SJeremy Morse 
967838b4a53SJeremy Morse   void accumulateFragmentMap(MachineInstr &MI);
968838b4a53SJeremy Morse 
969838b4a53SJeremy Morse   /// Determine the machine value number referred to by (potentially several)
970838b4a53SJeremy Morse   /// DBG_PHI instructions. Block duplication and tail folding can duplicate
971838b4a53SJeremy Morse   /// DBG_PHIs, shifting the position where values in registers merge, and
972838b4a53SJeremy Morse   /// forming another mini-ssa problem to solve.
973838b4a53SJeremy Morse   /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
974838b4a53SJeremy Morse   /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
975838b4a53SJeremy Morse   /// \returns The machine value number at position Here, or None.
976838b4a53SJeremy Morse   Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
977ab49dce0SJeremy Morse                                       const ValueTable *MLiveOuts,
978ab49dce0SJeremy Morse                                       const ValueTable *MLiveIns,
979ab49dce0SJeremy Morse                                       MachineInstr &Here, uint64_t InstrNum);
980838b4a53SJeremy Morse 
981d556eb7eSJeremy Morse   Optional<ValueIDNum> resolveDbgPHIsImpl(MachineFunction &MF,
982ab49dce0SJeremy Morse                                           const ValueTable *MLiveOuts,
983ab49dce0SJeremy Morse                                           const ValueTable *MLiveIns,
984d556eb7eSJeremy Morse                                           MachineInstr &Here,
985d556eb7eSJeremy Morse                                           uint64_t InstrNum);
986d556eb7eSJeremy Morse 
987838b4a53SJeremy Morse   /// Step through the function, recording register definitions and movements
988838b4a53SJeremy Morse   /// in an MLocTracker. Convert the observations into a per-block transfer
989838b4a53SJeremy Morse   /// function in \p MLocTransfer, suitable for using with the machine value
990838b4a53SJeremy Morse   /// location dataflow problem.
991838b4a53SJeremy Morse   void
992838b4a53SJeremy Morse   produceMLocTransferFunction(MachineFunction &MF,
993838b4a53SJeremy Morse                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
994838b4a53SJeremy Morse                               unsigned MaxNumBlocks);
995838b4a53SJeremy Morse 
996838b4a53SJeremy Morse   /// Solve the machine value location dataflow problem. Takes as input the
997838b4a53SJeremy Morse   /// transfer functions in \p MLocTransfer. Writes the output live-in and
998838b4a53SJeremy Morse   /// live-out arrays to the (initialized to zero) multidimensional arrays in
999838b4a53SJeremy Morse   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1000838b4a53SJeremy Morse   /// number, the inner by LocIdx.
1001ab49dce0SJeremy Morse   void buildMLocValueMap(MachineFunction &MF, FuncValueTable &MInLocs,
1002ab49dce0SJeremy Morse                          FuncValueTable &MOutLocs,
1003838b4a53SJeremy Morse                          SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1004838b4a53SJeremy Morse 
100597ddf49eSJeremy Morse   /// Examine the stack indexes (i.e. offsets within the stack) to find the
100697ddf49eSJeremy Morse   /// basic units of interference -- like reg units, but for the stack.
100797ddf49eSJeremy Morse   void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
100897ddf49eSJeremy Morse 
1009fbf269c7SJeremy Morse   /// Install PHI values into the live-in array for each block, according to
1010fbf269c7SJeremy Morse   /// the IDF of each register.
1011fbf269c7SJeremy Morse   void placeMLocPHIs(MachineFunction &MF,
1012fbf269c7SJeremy Morse                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1013ab49dce0SJeremy Morse                      FuncValueTable &MInLocs,
1014fbf269c7SJeremy Morse                      SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1015fbf269c7SJeremy Morse 
1016c703d77aSJeremy Morse   /// Propagate variable values to blocks in the common case where there's
1017c703d77aSJeremy Morse   /// only one value assigned to the variable. This function has better
1018c703d77aSJeremy Morse   /// performance as it doesn't have to find the dominance frontier between
1019c703d77aSJeremy Morse   /// different assignments.
1020c703d77aSJeremy Morse   void placePHIsForSingleVarDefinition(
1021c703d77aSJeremy Morse           const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
1022c703d77aSJeremy Morse           MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
1023c703d77aSJeremy Morse           const DebugVariable &Var, LiveInsT &Output);
1024c703d77aSJeremy Morse 
1025a3936a6cSJeremy Morse   /// Calculate the iterated-dominance-frontier for a set of defs, using the
1026a3936a6cSJeremy Morse   /// existing LLVM facilities for this. Works for a single "value" or
1027a3936a6cSJeremy Morse   /// machine/variable location.
1028a3936a6cSJeremy Morse   /// \p AllBlocks Set of blocks where we might consume the value.
1029a3936a6cSJeremy Morse   /// \p DefBlocks Set of blocks where the value/location is defined.
1030a3936a6cSJeremy Morse   /// \p PHIBlocks Output set of blocks where PHIs must be placed.
1031a3936a6cSJeremy Morse   void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1032a3936a6cSJeremy Morse                          const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
1033a3936a6cSJeremy Morse                          SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
1034a3936a6cSJeremy Morse 
1035838b4a53SJeremy Morse   /// Perform a control flow join (lattice value meet) of the values in machine
1036838b4a53SJeremy Morse   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1037838b4a53SJeremy Morse   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1038838b4a53SJeremy Morse   /// from \p InLocs, and assigning the newly computed live ins back into
1039838b4a53SJeremy Morse   /// \p InLocs. \returns two bools -- the first indicates whether a change
1040838b4a53SJeremy Morse   /// was made, the second whether a lattice downgrade occurred. If the latter
1041838b4a53SJeremy Morse   /// is true, revisiting this block is necessary.
1042a3936a6cSJeremy Morse   bool mlocJoin(MachineBasicBlock &MBB,
1043838b4a53SJeremy Morse                 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1044ab49dce0SJeremy Morse                 FuncValueTable &OutLocs, ValueTable &InLocs);
1045838b4a53SJeremy Morse 
10464a2cb013SJeremy Morse   /// Produce a set of blocks that are in the current lexical scope. This means
10474a2cb013SJeremy Morse   /// those blocks that contain instructions "in" the scope, blocks where
10484a2cb013SJeremy Morse   /// assignments to variables in scope occur, and artificial blocks that are
10494a2cb013SJeremy Morse   /// successors to any of the earlier blocks. See https://llvm.org/PR48091 for
10504a2cb013SJeremy Morse   /// more commentry on what "in scope" means.
10514a2cb013SJeremy Morse   /// \p DILoc A location in the scope that we're fetching blocks for.
10524a2cb013SJeremy Morse   /// \p Output Set to put in-scope-blocks into.
10534a2cb013SJeremy Morse   /// \p AssignBlocks Blocks known to contain assignments of variables in scope.
10544a2cb013SJeremy Morse   void
10554a2cb013SJeremy Morse   getBlocksForScope(const DILocation *DILoc,
10564a2cb013SJeremy Morse                     SmallPtrSetImpl<const MachineBasicBlock *> &Output,
10574a2cb013SJeremy Morse                     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks);
10584a2cb013SJeremy Morse 
1059838b4a53SJeremy Morse   /// Solve the variable value dataflow problem, for a single lexical scope.
1060b5426cedSJeremy Morse   /// Uses the algorithm from the file comment to resolve control flow joins
1061b5426cedSJeremy Morse   /// using PHI placement and value propagation. Reads the locations of machine
1062b5426cedSJeremy Morse   /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
1063b5426cedSJeremy Morse   /// and reads the variable values transfer function from \p AllTheVlocs.
1064b5426cedSJeremy Morse   /// Live-in and Live-out variable values are stored locally, with the live-ins
1065b5426cedSJeremy Morse   /// permanently stored to \p Output once a fixedpoint is reached.
1066838b4a53SJeremy Morse   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1067838b4a53SJeremy Morse   /// that we should be tracking.
1068b5426cedSJeremy Morse   /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
1069b5426cedSJeremy Morse   /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
1070b5426cedSJeremy Morse   /// locations through.
1071b5426cedSJeremy Morse   void buildVLocValueMap(const DILocation *DILoc,
1072838b4a53SJeremy Morse                          const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1073838b4a53SJeremy Morse                          SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1074ab49dce0SJeremy Morse                          LiveInsT &Output, FuncValueTable &MOutLocs,
1075ab49dce0SJeremy Morse                          FuncValueTable &MInLocs,
1076838b4a53SJeremy Morse                          SmallVectorImpl<VLocTracker> &AllTheVLocs);
1077838b4a53SJeremy Morse 
1078b5426cedSJeremy Morse   /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
1079b5426cedSJeremy Morse   /// live-in values coming from predecessors live-outs, and replaces any PHIs
1080b5426cedSJeremy Morse   /// already present in this blocks live-ins with a live-through value if the
108189950adeSJeremy Morse   /// PHI isn't needed.
108289950adeSJeremy Morse   /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
1083b5426cedSJeremy Morse   /// \returns true if any live-ins change value, either from value propagation
1084b5426cedSJeremy Morse   ///          or PHI elimination.
1085b5426cedSJeremy Morse   bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
1086838b4a53SJeremy Morse                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
108789950adeSJeremy Morse                 DbgValue &LiveIn);
1088838b4a53SJeremy Morse 
1089838b4a53SJeremy Morse   /// For the given block and live-outs feeding into it, try to find a
1090b5426cedSJeremy Morse   /// machine location where all the variable values join together.
1091b5426cedSJeremy Morse   /// \returns Value ID of a machine PHI if an appropriate one is available.
1092b5426cedSJeremy Morse   Optional<ValueIDNum>
1093b5426cedSJeremy Morse   pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
1094ab49dce0SJeremy Morse               const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
1095b5426cedSJeremy Morse               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1096838b4a53SJeremy Morse 
10974a2cb013SJeremy Morse   /// Take collections of DBG_VALUE instructions stored in TTracker, and
10984a2cb013SJeremy Morse   /// install them into their output blocks. Preserves a stable order of
10994a2cb013SJeremy Morse   /// DBG_VALUEs produced (which would otherwise cause nondeterminism) through
11004a2cb013SJeremy Morse   /// the AllVarsNumbering order.
11014a2cb013SJeremy Morse   bool emitTransfers(DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
11024a2cb013SJeremy Morse 
1103838b4a53SJeremy Morse   /// Boilerplate computation of some initial sets, artifical blocks and
1104838b4a53SJeremy Morse   /// RPOT block ordering.
1105838b4a53SJeremy Morse   void initialSetup(MachineFunction &MF);
1106838b4a53SJeremy Morse 
11079fd9d56dSJeremy Morse   /// Produce a map of the last lexical scope that uses a block, using the
11089fd9d56dSJeremy Morse   /// scopes DFSOut number. Mapping is block-number to DFSOut.
11099fd9d56dSJeremy Morse   /// \p EjectionMap Pre-allocated vector in which to install the built ma.
11109fd9d56dSJeremy Morse   /// \p ScopeToDILocation Mapping of LexicalScopes to their DILocations.
11119fd9d56dSJeremy Morse   /// \p AssignBlocks Map of blocks where assignments happen for a scope.
11129fd9d56dSJeremy Morse   void makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> &EjectionMap,
11139fd9d56dSJeremy Morse                                  const ScopeToDILocT &ScopeToDILocation,
11149fd9d56dSJeremy Morse                                  ScopeToAssignBlocksT &AssignBlocks);
11159fd9d56dSJeremy Morse 
11169fd9d56dSJeremy Morse   /// When determining per-block variable values and emitting to DBG_VALUEs,
11179fd9d56dSJeremy Morse   /// this function explores by lexical scope depth. Doing so means that per
11189fd9d56dSJeremy Morse   /// block information can be fully computed before exploration finishes,
11199fd9d56dSJeremy Morse   /// allowing us to emit it and free data structures earlier than otherwise.
11209fd9d56dSJeremy Morse   /// It's also good for locality.
11219fd9d56dSJeremy Morse   bool depthFirstVLocAndEmit(
11229fd9d56dSJeremy Morse       unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
11239fd9d56dSJeremy Morse       const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToBlocks,
1124ab49dce0SJeremy Morse       LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
11259fd9d56dSJeremy Morse       SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
11269fd9d56dSJeremy Morse       DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
11279fd9d56dSJeremy Morse       const TargetPassConfig &TPC);
11289fd9d56dSJeremy Morse 
1129a3936a6cSJeremy Morse   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1130a3936a6cSJeremy Morse                     TargetPassConfig *TPC, unsigned InputBBLimit,
1131a3936a6cSJeremy Morse                     unsigned InputDbgValLimit) override;
1132838b4a53SJeremy Morse 
1133838b4a53SJeremy Morse public:
1134838b4a53SJeremy Morse   /// Default construct and initialize the pass.
1135838b4a53SJeremy Morse   InstrRefBasedLDV();
1136838b4a53SJeremy Morse 
1137838b4a53SJeremy Morse   LLVM_DUMP_METHOD
1138838b4a53SJeremy Morse   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1139838b4a53SJeremy Morse 
1140838b4a53SJeremy Morse   bool isCalleeSaved(LocIdx L) const;
1141ee3eee71SJeremy Morse 
hasFoldedStackStore(const MachineInstr & MI)1142ee3eee71SJeremy Morse   bool hasFoldedStackStore(const MachineInstr &MI) {
1143ee3eee71SJeremy Morse     // Instruction must have a memory operand that's a stack slot, and isn't
1144ee3eee71SJeremy Morse     // aliased, meaning it's a spill from regalloc instead of a variable.
1145ee3eee71SJeremy Morse     // If it's aliased, we can't guarantee its value.
1146ee3eee71SJeremy Morse     if (!MI.hasOneMemOperand())
1147ee3eee71SJeremy Morse       return false;
1148ee3eee71SJeremy Morse     auto *MemOperand = *MI.memoperands_begin();
1149ee3eee71SJeremy Morse     return MemOperand->isStore() &&
1150ee3eee71SJeremy Morse            MemOperand->getPseudoValue() &&
1151ee3eee71SJeremy Morse            MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
1152ee3eee71SJeremy Morse            && !MemOperand->getPseudoValue()->isAliased(MFI);
1153ee3eee71SJeremy Morse   }
1154ee3eee71SJeremy Morse 
1155ee3eee71SJeremy Morse   Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
1156838b4a53SJeremy Morse };
1157838b4a53SJeremy Morse 
1158838b4a53SJeremy Morse } // namespace LiveDebugValues
1159838b4a53SJeremy Morse 
11604136897bSJeremy Morse namespace llvm {
11614136897bSJeremy Morse using namespace LiveDebugValues;
11624136897bSJeremy Morse 
11634136897bSJeremy Morse template <> struct DenseMapInfo<LocIdx> {
11644136897bSJeremy Morse   static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); }
11654136897bSJeremy Morse   static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); }
11664136897bSJeremy Morse 
11674136897bSJeremy Morse   static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
11684136897bSJeremy Morse 
11694136897bSJeremy Morse   static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
11704136897bSJeremy Morse };
11714136897bSJeremy Morse 
11724136897bSJeremy Morse template <> struct DenseMapInfo<ValueIDNum> {
11734136897bSJeremy Morse   static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; }
11744136897bSJeremy Morse   static inline ValueIDNum getTombstoneKey() {
11754136897bSJeremy Morse     return ValueIDNum::TombstoneValue;
11764136897bSJeremy Morse   }
11774136897bSJeremy Morse 
1178cbaae614SNikita Popov   static unsigned getHashValue(const ValueIDNum &Val) {
1179cbaae614SNikita Popov     return hash_value(Val.asU64());
1180cbaae614SNikita Popov   }
11814136897bSJeremy Morse 
11824136897bSJeremy Morse   static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
11834136897bSJeremy Morse     return A == B;
11844136897bSJeremy Morse   }
11854136897bSJeremy Morse };
11864136897bSJeremy Morse 
11874136897bSJeremy Morse } // end namespace llvm
11884136897bSJeremy Morse 
1189838b4a53SJeremy Morse #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
1190