1 //===- InstrRefBasedImpl.h - Tracking Debug Value MIs ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
10 #define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
11 
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/IndexedMap.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/UniqueVector.h"
17 #include "llvm/CodeGen/LexicalScopes.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/TargetRegisterInfo.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 
23 #include "LiveDebugValues.h"
24 
25 class TransferTracker;
26 
27 // Forward dec of unit test class, so that we can peer into the LDV object.
28 class InstrRefLDVTest;
29 
30 namespace LiveDebugValues {
31 
32 class MLocTracker;
33 
34 using namespace llvm;
35 
36 /// Handle-class for a particular "location". This value-type uniquely
37 /// symbolises a register or stack location, allowing manipulation of locations
38 /// without concern for where that location is. Practically, this allows us to
39 /// treat the state of the machine at a particular point as an array of values,
40 /// rather than a map of values.
41 class LocIdx {
42   unsigned Location;
43 
44   // Default constructor is private, initializing to an illegal location number.
45   // Use only for "not an entry" elements in IndexedMaps.
46   LocIdx() : Location(UINT_MAX) {}
47 
48 public:
49 #define NUM_LOC_BITS 24
50   LocIdx(unsigned L) : Location(L) {
51     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
52   }
53 
54   static LocIdx MakeIllegalLoc() { return LocIdx(); }
55   static LocIdx MakeTombstoneLoc() {
56     LocIdx L = LocIdx();
57     --L.Location;
58     return L;
59   }
60 
61   bool isIllegal() const { return Location == UINT_MAX; }
62 
63   uint64_t asU64() const { return Location; }
64 
65   bool operator==(unsigned L) const { return Location == L; }
66 
67   bool operator==(const LocIdx &L) const { return Location == L.Location; }
68 
69   bool operator!=(unsigned L) const { return !(*this == L); }
70 
71   bool operator!=(const LocIdx &L) const { return !(*this == L); }
72 
73   bool operator<(const LocIdx &Other) const {
74     return Location < Other.Location;
75   }
76 };
77 
78 // The location at which a spilled value resides. It consists of a register and
79 // an offset.
80 struct SpillLoc {
81   unsigned SpillBase;
82   StackOffset SpillOffset;
83   bool operator==(const SpillLoc &Other) const {
84     return std::make_pair(SpillBase, SpillOffset) ==
85            std::make_pair(Other.SpillBase, Other.SpillOffset);
86   }
87   bool operator<(const SpillLoc &Other) const {
88     return std::make_tuple(SpillBase, SpillOffset.getFixed(),
89                            SpillOffset.getScalable()) <
90            std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
91                            Other.SpillOffset.getScalable());
92   }
93 };
94 
95 /// Unique identifier for a value defined by an instruction, as a value type.
96 /// Casts back and forth to a uint64_t. Probably replacable with something less
97 /// bit-constrained. Each value identifies the instruction and machine location
98 /// where the value is defined, although there may be no corresponding machine
99 /// operand for it (ex: regmasks clobbering values). The instructions are
100 /// one-based, and definitions that are PHIs have instruction number zero.
101 ///
102 /// The obvious limits of a 1M block function or 1M instruction blocks are
103 /// problematic; but by that point we should probably have bailed out of
104 /// trying to analyse the function.
105 class ValueIDNum {
106   union {
107     struct {
108       uint64_t BlockNo : 20; /// The block where the def happens.
109       uint64_t InstNo : 20;  /// The Instruction where the def happens.
110                              /// One based, is distance from start of block.
111       uint64_t LocNo
112           : NUM_LOC_BITS; /// The machine location where the def happens.
113     } s;
114     uint64_t Value;
115   } u;
116 
117   static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
118 
119 public:
120   // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
121   // of values to work.
122   ValueIDNum() { u.Value = EmptyValue.asU64(); }
123 
124   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
125     u.s = {Block, Inst, Loc};
126   }
127 
128   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
129     u.s = {Block, Inst, Loc.asU64()};
130   }
131 
132   uint64_t getBlock() const { return u.s.BlockNo; }
133   uint64_t getInst() const { return u.s.InstNo; }
134   uint64_t getLoc() const { return u.s.LocNo; }
135   bool isPHI() const { return u.s.InstNo == 0; }
136 
137   uint64_t asU64() const { return u.Value; }
138 
139   static ValueIDNum fromU64(uint64_t v) {
140     ValueIDNum Val;
141     Val.u.Value = v;
142     return Val;
143   }
144 
145   bool operator<(const ValueIDNum &Other) const {
146     return asU64() < Other.asU64();
147   }
148 
149   bool operator==(const ValueIDNum &Other) const {
150     return u.Value == Other.u.Value;
151   }
152 
153   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
154 
155   std::string asString(const std::string &mlocname) const {
156     return Twine("Value{bb: ")
157         .concat(Twine(u.s.BlockNo)
158                     .concat(Twine(", inst: ")
159                                 .concat((u.s.InstNo ? Twine(u.s.InstNo)
160                                                     : Twine("live-in"))
161                                             .concat(Twine(", loc: ").concat(
162                                                 Twine(mlocname)))
163                                             .concat(Twine("}")))))
164         .str();
165   }
166 
167   static ValueIDNum EmptyValue;
168   static ValueIDNum TombstoneValue;
169 };
170 
171 /// Type for a table of values in a block.
172 using ValueTable = std::unique_ptr<ValueIDNum[]>;
173 
174 /// Type for a table-of-table-of-values, i.e., the collection of either
175 /// live-in or live-out values for each block in the function.
176 using FuncValueTable = std::unique_ptr<ValueTable[]>;
177 
178 /// Thin wrapper around an integer -- designed to give more type safety to
179 /// spill location numbers.
180 class SpillLocationNo {
181 public:
182   explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
183   unsigned SpillNo;
184   unsigned id() const { return SpillNo; }
185 
186   bool operator<(const SpillLocationNo &Other) const {
187     return SpillNo < Other.SpillNo;
188   }
189 
190   bool operator==(const SpillLocationNo &Other) const {
191     return SpillNo == Other.SpillNo;
192   }
193   bool operator!=(const SpillLocationNo &Other) const {
194     return !(*this == Other);
195   }
196 };
197 
198 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
199 /// the value, and Boolean of whether or not it's indirect.
200 class DbgValueProperties {
201 public:
202   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
203       : DIExpr(DIExpr), Indirect(Indirect) {}
204 
205   /// Extract properties from an existing DBG_VALUE instruction.
206   DbgValueProperties(const MachineInstr &MI) {
207     assert(MI.isDebugValue());
208     DIExpr = MI.getDebugExpression();
209     Indirect = MI.getOperand(1).isImm();
210   }
211 
212   bool operator==(const DbgValueProperties &Other) const {
213     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
214   }
215 
216   bool operator!=(const DbgValueProperties &Other) const {
217     return !(*this == Other);
218   }
219 
220   const DIExpression *DIExpr;
221   bool Indirect;
222 };
223 
224 /// Class recording the (high level) _value_ of a variable. Identifies either
225 /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
226 /// This class also stores meta-information about how the value is qualified.
227 /// Used to reason about variable values when performing the second
228 /// (DebugVariable specific) dataflow analysis.
229 class DbgValue {
230 public:
231   /// If Kind is Def, the value number that this value is based on. VPHIs set
232   /// this field to EmptyValue if there is no machine-value for this VPHI, or
233   /// the corresponding machine-value if there is one.
234   ValueIDNum ID;
235   /// If Kind is Const, the MachineOperand defining this value.
236   Optional<MachineOperand> MO;
237   /// For a NoVal or VPHI DbgValue, which block it was generated in.
238   int BlockNo;
239 
240   /// Qualifiers for the ValueIDNum above.
241   DbgValueProperties Properties;
242 
243   typedef enum {
244     Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
245     Def,   // This value is defined by an inst, or is a PHI value.
246     Const, // A constant value contained in the MachineOperand field.
247     VPHI,  // Incoming values to BlockNo differ, those values must be joined by
248            // a PHI in this block.
249     NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
250            // before dominating blocks values are propagated in.
251   } KindT;
252   /// Discriminator for whether this is a constant or an in-program value.
253   KindT Kind;
254 
255   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
256       : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) {
257     assert(Kind == Def);
258   }
259 
260   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
261       : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo),
262         Properties(Prop), Kind(Kind) {
263     assert(Kind == NoVal || Kind == VPHI);
264   }
265 
266   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
267       : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop),
268         Kind(Kind) {
269     assert(Kind == Const);
270   }
271 
272   DbgValue(const DbgValueProperties &Prop, KindT Kind)
273     : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop),
274       Kind(Kind) {
275     assert(Kind == Undef &&
276            "Empty DbgValue constructor must pass in Undef kind");
277   }
278 
279 #ifndef NDEBUG
280   void dump(const MLocTracker *MTrack) const;
281 #endif
282 
283   bool operator==(const DbgValue &Other) const {
284     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
285       return false;
286     else if (Kind == Def && ID != Other.ID)
287       return false;
288     else if (Kind == NoVal && BlockNo != Other.BlockNo)
289       return false;
290     else if (Kind == Const)
291       return MO->isIdenticalTo(*Other.MO);
292     else if (Kind == VPHI && BlockNo != Other.BlockNo)
293       return false;
294     else if (Kind == VPHI && ID != Other.ID)
295       return false;
296 
297     return true;
298   }
299 
300   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
301 };
302 
303 class LocIdxToIndexFunctor {
304 public:
305   using argument_type = LocIdx;
306   unsigned operator()(const LocIdx &L) const { return L.asU64(); }
307 };
308 
309 /// Tracker for what values are in machine locations. Listens to the Things
310 /// being Done by various instructions, and maintains a table of what machine
311 /// locations have what values (as defined by a ValueIDNum).
312 ///
313 /// There are potentially a much larger number of machine locations on the
314 /// target machine than the actual working-set size of the function. On x86 for
315 /// example, we're extremely unlikely to want to track values through control
316 /// or debug registers. To avoid doing so, MLocTracker has several layers of
317 /// indirection going on, described below, to avoid unnecessarily tracking
318 /// any location.
319 ///
320 /// Here's a sort of diagram of the indexes, read from the bottom up:
321 ///
322 ///           Size on stack   Offset on stack
323 ///                 \              /
324 ///          Stack Idx (Where in slot is this?)
325 ///                         /
326 ///                        /
327 /// Slot Num (%stack.0)   /
328 /// FrameIdx => SpillNum /
329 ///              \      /
330 ///           SpillID (int)              Register number (int)
331 ///                      \                  /
332 ///                      LocationID => LocIdx
333 ///                                |
334 ///                       LocIdx => ValueIDNum
335 ///
336 /// The aim here is that the LocIdx => ValueIDNum vector is just an array of
337 /// values in numbered locations, so that later analyses can ignore whether the
338 /// location is a register or otherwise. To map a register / spill location to
339 /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
340 /// build a LocationID for a stack slot, you need to combine identifiers for
341 /// which stack slot it is and where within that slot is being described.
342 ///
343 /// Register mask operands cause trouble by technically defining every register;
344 /// various hacks are used to avoid tracking registers that are never read and
345 /// only written by regmasks.
346 class MLocTracker {
347 public:
348   MachineFunction &MF;
349   const TargetInstrInfo &TII;
350   const TargetRegisterInfo &TRI;
351   const TargetLowering &TLI;
352 
353   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
354   using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
355 
356   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
357   /// packed, entries only exist for locations that are being tracked.
358   LocToValueType LocIdxToIDNum;
359 
360   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
361   /// LocIdx key / number for that location. There are always at least as many
362   /// as the number of registers on the target -- if the value in the register
363   /// is not being tracked, then the LocIdx value will be zero. New entries are
364   /// appended if a new spill slot begins being tracked.
365   /// This, and the corresponding reverse map persist for the analysis of the
366   /// whole function, and is necessarying for decoding various vectors of
367   /// values.
368   std::vector<LocIdx> LocIDToLocIdx;
369 
370   /// Inverse map of LocIDToLocIdx.
371   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
372 
373   /// When clobbering register masks, we chose to not believe the machine model
374   /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
375   /// keep a set of them here.
376   SmallSet<Register, 8> SPAliases;
377 
378   /// Unique-ification of spill. Used to number them -- their LocID number is
379   /// the index in SpillLocs minus one plus NumRegs.
380   UniqueVector<SpillLoc> SpillLocs;
381 
382   // If we discover a new machine location, assign it an mphi with this
383   // block number.
384   unsigned CurBB;
385 
386   /// Cached local copy of the number of registers the target has.
387   unsigned NumRegs;
388 
389   /// Number of slot indexes the target has -- distinct segments of a stack
390   /// slot that can take on the value of a subregister, when a super-register
391   /// is written to the stack.
392   unsigned NumSlotIdxes;
393 
394   /// Collection of register mask operands that have been observed. Second part
395   /// of pair indicates the instruction that they happened in. Used to
396   /// reconstruct where defs happened if we start tracking a location later
397   /// on.
398   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
399 
400   /// Pair for describing a position within a stack slot -- first the size in
401   /// bits, then the offset.
402   typedef std::pair<unsigned short, unsigned short> StackSlotPos;
403 
404   /// Map from a size/offset pair describing a position in a stack slot, to a
405   /// numeric identifier for that position. Allows easier identification of
406   /// individual positions.
407   DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
408 
409   /// Inverse of StackSlotIdxes.
410   DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
411 
412   /// Iterator for locations and the values they contain. Dereferencing
413   /// produces a struct/pair containing the LocIdx key for this location,
414   /// and a reference to the value currently stored. Simplifies the process
415   /// of seeking a particular location.
416   class MLocIterator {
417     LocToValueType &ValueMap;
418     LocIdx Idx;
419 
420   public:
421     class value_type {
422     public:
423       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
424       const LocIdx Idx;  /// Read-only index of this location.
425       ValueIDNum &Value; /// Reference to the stored value at this location.
426     };
427 
428     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
429         : ValueMap(ValueMap), Idx(Idx) {}
430 
431     bool operator==(const MLocIterator &Other) const {
432       assert(&ValueMap == &Other.ValueMap);
433       return Idx == Other.Idx;
434     }
435 
436     bool operator!=(const MLocIterator &Other) const {
437       return !(*this == Other);
438     }
439 
440     void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
441 
442     value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
443   };
444 
445   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
446               const TargetRegisterInfo &TRI, const TargetLowering &TLI);
447 
448   /// Produce location ID number for a Register. Provides some small amount of
449   /// type safety.
450   /// \param Reg The register we're looking up.
451   unsigned getLocID(Register Reg) { return Reg.id(); }
452 
453   /// Produce location ID number for a spill position.
454   /// \param Spill The number of the spill we're fetching the location for.
455   /// \param SpillSubReg Subregister within the spill we're addressing.
456   unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
457     unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg);
458     unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg);
459     return getLocID(Spill, {Size, Offs});
460   }
461 
462   /// Produce location ID number for a spill position.
463   /// \param Spill The number of the spill we're fetching the location for.
464   /// \apram SpillIdx size/offset within the spill slot to be addressed.
465   unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
466     unsigned SlotNo = Spill.id() - 1;
467     SlotNo *= NumSlotIdxes;
468     assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end());
469     SlotNo += StackSlotIdxes[Idx];
470     SlotNo += NumRegs;
471     return SlotNo;
472   }
473 
474   /// Given a spill number, and a slot within the spill, calculate the ID number
475   /// for that location.
476   unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
477     unsigned SlotNo = Spill.id() - 1;
478     SlotNo *= NumSlotIdxes;
479     SlotNo += Idx;
480     SlotNo += NumRegs;
481     return SlotNo;
482   }
483 
484   /// Return the spill number that a location ID corresponds to.
485   SpillLocationNo locIDToSpill(unsigned ID) const {
486     assert(ID >= NumRegs);
487     ID -= NumRegs;
488     // Truncate away the index part, leaving only the spill number.
489     ID /= NumSlotIdxes;
490     return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
491   }
492 
493   /// Returns the spill-slot size/offs that a location ID corresponds to.
494   StackSlotPos locIDToSpillIdx(unsigned ID) const {
495     assert(ID >= NumRegs);
496     ID -= NumRegs;
497     unsigned Idx = ID % NumSlotIdxes;
498     return StackIdxesToPos.find(Idx)->second;
499   }
500 
501   unsigned getNumLocs() const { return LocIdxToIDNum.size(); }
502 
503   /// Reset all locations to contain a PHI value at the designated block. Used
504   /// sometimes for actual PHI values, othertimes to indicate the block entry
505   /// value (before any more information is known).
506   void setMPhis(unsigned NewCurBB) {
507     CurBB = NewCurBB;
508     for (auto Location : locations())
509       Location.Value = {CurBB, 0, Location.Idx};
510   }
511 
512   /// Load values for each location from array of ValueIDNums. Take current
513   /// bbnum just in case we read a value from a hitherto untouched register.
514   void loadFromArray(ValueTable &Locs, unsigned NewCurBB) {
515     CurBB = NewCurBB;
516     // Iterate over all tracked locations, and load each locations live-in
517     // value into our local index.
518     for (auto Location : locations())
519       Location.Value = Locs[Location.Idx.asU64()];
520   }
521 
522   /// Wipe any un-necessary location records after traversing a block.
523   void reset() {
524     // We could reset all the location values too; however either loadFromArray
525     // or setMPhis should be called before this object is re-used. Just
526     // clear Masks, they're definitely not needed.
527     Masks.clear();
528   }
529 
530   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
531   /// the information in this pass uninterpretable.
532   void clear() {
533     reset();
534     LocIDToLocIdx.clear();
535     LocIdxToLocID.clear();
536     LocIdxToIDNum.clear();
537     // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
538     // 0
539     SpillLocs = decltype(SpillLocs)();
540     StackSlotIdxes.clear();
541     StackIdxesToPos.clear();
542 
543     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
544   }
545 
546   /// Set a locaiton to a certain value.
547   void setMLoc(LocIdx L, ValueIDNum Num) {
548     assert(L.asU64() < LocIdxToIDNum.size());
549     LocIdxToIDNum[L] = Num;
550   }
551 
552   /// Read the value of a particular location
553   ValueIDNum readMLoc(LocIdx L) {
554     assert(L.asU64() < LocIdxToIDNum.size());
555     return LocIdxToIDNum[L];
556   }
557 
558   /// Create a LocIdx for an untracked register ID. Initialize it to either an
559   /// mphi value representing a live-in, or a recent register mask clobber.
560   LocIdx trackRegister(unsigned ID);
561 
562   LocIdx lookupOrTrackRegister(unsigned ID) {
563     LocIdx &Index = LocIDToLocIdx[ID];
564     if (Index.isIllegal())
565       Index = trackRegister(ID);
566     return Index;
567   }
568 
569   /// Is register R currently tracked by MLocTracker?
570   bool isRegisterTracked(Register R) {
571     LocIdx &Index = LocIDToLocIdx[R];
572     return !Index.isIllegal();
573   }
574 
575   /// Record a definition of the specified register at the given block / inst.
576   /// This doesn't take a ValueIDNum, because the definition and its location
577   /// are synonymous.
578   void defReg(Register R, unsigned BB, unsigned Inst) {
579     unsigned ID = getLocID(R);
580     LocIdx Idx = lookupOrTrackRegister(ID);
581     ValueIDNum ValueID = {BB, Inst, Idx};
582     LocIdxToIDNum[Idx] = ValueID;
583   }
584 
585   /// Set a register to a value number. To be used if the value number is
586   /// known in advance.
587   void setReg(Register R, ValueIDNum ValueID) {
588     unsigned ID = getLocID(R);
589     LocIdx Idx = lookupOrTrackRegister(ID);
590     LocIdxToIDNum[Idx] = ValueID;
591   }
592 
593   ValueIDNum readReg(Register R) {
594     unsigned ID = getLocID(R);
595     LocIdx Idx = lookupOrTrackRegister(ID);
596     return LocIdxToIDNum[Idx];
597   }
598 
599   /// Reset a register value to zero / empty. Needed to replicate the
600   /// VarLoc implementation where a copy to/from a register effectively
601   /// clears the contents of the source register. (Values can only have one
602   ///  machine location in VarLocBasedImpl).
603   void wipeRegister(Register R) {
604     unsigned ID = getLocID(R);
605     LocIdx Idx = LocIDToLocIdx[ID];
606     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
607   }
608 
609   /// Determine the LocIdx of an existing register.
610   LocIdx getRegMLoc(Register R) {
611     unsigned ID = getLocID(R);
612     assert(ID < LocIDToLocIdx.size());
613     assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap.
614     return LocIDToLocIdx[ID];
615   }
616 
617   /// Record a RegMask operand being executed. Defs any register we currently
618   /// track, stores a pointer to the mask in case we have to account for it
619   /// later.
620   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
621 
622   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
623   /// Returns None when in scenarios where a spill slot could be tracked, but
624   /// we would likely run into resource limitations.
625   Optional<SpillLocationNo> getOrTrackSpillLoc(SpillLoc L);
626 
627   // Get LocIdx of a spill ID.
628   LocIdx getSpillMLoc(unsigned SpillID) {
629     assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap.
630     return LocIDToLocIdx[SpillID];
631   }
632 
633   /// Return true if Idx is a spill machine location.
634   bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
635 
636   /// How large is this location (aka, how wide is a value defined there?).
637   unsigned getLocSizeInBits(LocIdx L) const {
638     unsigned ID = LocIdxToLocID[L];
639     if (!isSpill(L)) {
640       return TRI.getRegSizeInBits(Register(ID), MF.getRegInfo());
641     } else {
642       // The slot location on the stack is uninteresting, we care about the
643       // position of the value within the slot (which comes with a size).
644       StackSlotPos Pos = locIDToSpillIdx(ID);
645       return Pos.first;
646     }
647   }
648 
649   MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
650 
651   MLocIterator end() {
652     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
653   }
654 
655   /// Return a range over all locations currently tracked.
656   iterator_range<MLocIterator> locations() {
657     return llvm::make_range(begin(), end());
658   }
659 
660   std::string LocIdxToName(LocIdx Idx) const;
661 
662   std::string IDAsString(const ValueIDNum &Num) const;
663 
664 #ifndef NDEBUG
665   LLVM_DUMP_METHOD void dump();
666 
667   LLVM_DUMP_METHOD void dump_mloc_map();
668 #endif
669 
670   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
671   /// information in \pProperties, for variable Var. Don't insert it anywhere,
672   /// just return the builder for it.
673   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
674                               const DbgValueProperties &Properties);
675 };
676 
677 /// Types for recording sets of variable fragments that overlap. For a given
678 /// local variable, we record all other fragments of that variable that could
679 /// overlap it, to reduce search time.
680 using FragmentOfVar =
681     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
682 using OverlapMap =
683     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
684 
685 /// Collection of DBG_VALUEs observed when traversing a block. Records each
686 /// variable and the value the DBG_VALUE refers to. Requires the machine value
687 /// location dataflow algorithm to have run already, so that values can be
688 /// identified.
689 class VLocTracker {
690 public:
691   /// Map DebugVariable to the latest Value it's defined to have.
692   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
693   /// the order in this container.
694   /// We only retain the last DbgValue in each block for each variable, to
695   /// determine the blocks live-out variable value. The Vars container forms the
696   /// transfer function for this block, as part of the dataflow analysis. The
697   /// movement of values between locations inside of a block is handled at a
698   /// much later stage, in the TransferTracker class.
699   MapVector<DebugVariable, DbgValue> Vars;
700   SmallDenseMap<DebugVariable, const DILocation *, 8> Scopes;
701   MachineBasicBlock *MBB = nullptr;
702   const OverlapMap &OverlappingFragments;
703   DbgValueProperties EmptyProperties;
704 
705 public:
706   VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr)
707       : OverlappingFragments(O), EmptyProperties(EmptyExpr, false) {}
708 
709   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
710               Optional<ValueIDNum> ID) {
711     assert(MI.isDebugValue() || MI.isDebugRef());
712     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
713                       MI.getDebugLoc()->getInlinedAt());
714     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
715                         : DbgValue(Properties, DbgValue::Undef);
716 
717     // Attempt insertion; overwrite if it's already mapped.
718     auto Result = Vars.insert(std::make_pair(Var, Rec));
719     if (!Result.second)
720       Result.first->second = Rec;
721     Scopes[Var] = MI.getDebugLoc().get();
722 
723     considerOverlaps(Var, MI.getDebugLoc().get());
724   }
725 
726   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
727     // Only DBG_VALUEs can define constant-valued variables.
728     assert(MI.isDebugValue());
729     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
730                       MI.getDebugLoc()->getInlinedAt());
731     DbgValueProperties Properties(MI);
732     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
733 
734     // Attempt insertion; overwrite if it's already mapped.
735     auto Result = Vars.insert(std::make_pair(Var, Rec));
736     if (!Result.second)
737       Result.first->second = Rec;
738     Scopes[Var] = MI.getDebugLoc().get();
739 
740     considerOverlaps(Var, MI.getDebugLoc().get());
741   }
742 
743   void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
744     auto Overlaps = OverlappingFragments.find(
745         {Var.getVariable(), Var.getFragmentOrDefault()});
746     if (Overlaps == OverlappingFragments.end())
747       return;
748 
749     // Otherwise: terminate any overlapped variable locations.
750     for (auto FragmentInfo : Overlaps->second) {
751       // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
752       // that it overlaps with everything, however its cannonical representation
753       // in a DebugVariable is as "None".
754       Optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
755       if (DebugVariable::isDefaultFragment(FragmentInfo))
756         OptFragmentInfo = None;
757 
758       DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
759                                Var.getInlinedAt());
760       DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
761 
762       // Attempt insertion; overwrite if it's already mapped.
763       auto Result = Vars.insert(std::make_pair(Overlapped, Rec));
764       if (!Result.second)
765         Result.first->second = Rec;
766       Scopes[Overlapped] = Loc;
767     }
768   }
769 
770   void clear() {
771     Vars.clear();
772     Scopes.clear();
773   }
774 };
775 
776 // XXX XXX docs
777 class InstrRefBasedLDV : public LDVImpl {
778 public:
779   friend class ::InstrRefLDVTest;
780 
781   using FragmentInfo = DIExpression::FragmentInfo;
782   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
783 
784   // Helper while building OverlapMap, a map of all fragments seen for a given
785   // DILocalVariable.
786   using VarToFragments =
787       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
788 
789   /// Machine location/value transfer function, a mapping of which locations
790   /// are assigned which new values.
791   using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
792 
793   /// Live in/out structure for the variable values: a per-block map of
794   /// variables to their values.
795   using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>;
796 
797   using VarAndLoc = std::pair<DebugVariable, DbgValue>;
798 
799   /// Type for a live-in value: the predecessor block, and its value.
800   using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
801 
802   /// Vector (per block) of a collection (inner smallvector) of live-ins.
803   /// Used as the result type for the variable value dataflow problem.
804   using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
805 
806   /// Mapping from lexical scopes to a DILocation in that scope.
807   using ScopeToDILocT = DenseMap<const LexicalScope *, const DILocation *>;
808 
809   /// Mapping from lexical scopes to variables in that scope.
810   using ScopeToVarsT = DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>>;
811 
812   /// Mapping from lexical scopes to blocks where variables in that scope are
813   /// assigned. Such blocks aren't necessarily "in" the lexical scope, it's
814   /// just a block where an assignment happens.
815   using ScopeToAssignBlocksT = DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>;
816 
817 private:
818   MachineDominatorTree *DomTree;
819   const TargetRegisterInfo *TRI;
820   const MachineRegisterInfo *MRI;
821   const TargetInstrInfo *TII;
822   const TargetFrameLowering *TFI;
823   const MachineFrameInfo *MFI;
824   BitVector CalleeSavedRegs;
825   LexicalScopes LS;
826   TargetPassConfig *TPC;
827 
828   // An empty DIExpression. Used default / placeholder DbgValueProperties
829   // objects, as we can't have null expressions.
830   const DIExpression *EmptyExpr;
831 
832   /// Object to track machine locations as we step through a block. Could
833   /// probably be a field rather than a pointer, as it's always used.
834   MLocTracker *MTracker = nullptr;
835 
836   /// Number of the current block LiveDebugValues is stepping through.
837   unsigned CurBB;
838 
839   /// Number of the current instruction LiveDebugValues is evaluating.
840   unsigned CurInst;
841 
842   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
843   /// steps through a block. Reads the values at each location from the
844   /// MLocTracker object.
845   VLocTracker *VTracker = nullptr;
846 
847   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
848   /// between locations during stepping, creates new DBG_VALUEs when values move
849   /// location.
850   TransferTracker *TTracker = nullptr;
851 
852   /// Blocks which are artificial, i.e. blocks which exclusively contain
853   /// instructions without DebugLocs, or with line 0 locations.
854   SmallPtrSet<MachineBasicBlock *, 16> ArtificialBlocks;
855 
856   // Mapping of blocks to and from their RPOT order.
857   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
858   DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
859   DenseMap<unsigned, unsigned> BBNumToRPO;
860 
861   /// Pair of MachineInstr, and its 1-based offset into the containing block.
862   using InstAndNum = std::pair<const MachineInstr *, unsigned>;
863   /// Map from debug instruction number to the MachineInstr labelled with that
864   /// number, and its location within the function. Used to transform
865   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
866   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
867 
868   /// Record of where we observed a DBG_PHI instruction.
869   class DebugPHIRecord {
870   public:
871     /// Instruction number of this DBG_PHI.
872     uint64_t InstrNum;
873     /// Block where DBG_PHI occurred.
874     MachineBasicBlock *MBB;
875     /// The value number read by the DBG_PHI -- or None if it didn't refer to
876     /// a value.
877     Optional<ValueIDNum> ValueRead;
878     /// Register/Stack location the DBG_PHI reads -- or None if it referred to
879     /// something unexpected.
880     Optional<LocIdx> ReadLoc;
881 
882     operator unsigned() const { return InstrNum; }
883   };
884 
885   /// Map from instruction numbers defined by DBG_PHIs to a record of what that
886   /// DBG_PHI read and where. Populated and edited during the machine value
887   /// location problem -- we use LLVMs SSA Updater to fix changes by
888   /// optimizations that destroy PHI instructions.
889   SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
890 
891   // Map of overlapping variable fragments.
892   OverlapMap OverlapFragments;
893   VarToFragments SeenFragments;
894 
895   /// Mapping of DBG_INSTR_REF instructions to their values, for those
896   /// DBG_INSTR_REFs that call resolveDbgPHIs. These variable references solve
897   /// a mini SSA problem caused by DBG_PHIs being cloned, this collection caches
898   /// the result.
899   DenseMap<MachineInstr *, Optional<ValueIDNum>> SeenDbgPHIs;
900 
901   /// True if we need to examine call instructions for stack clobbers. We
902   /// normally assume that they don't clobber SP, but stack probes on Windows
903   /// do.
904   bool AdjustsStackInCalls = false;
905 
906   /// If AdjustsStackInCalls is true, this holds the name of the target's stack
907   /// probe function, which is the function we expect will alter the stack
908   /// pointer.
909   StringRef StackProbeSymbolName;
910 
911   /// Tests whether this instruction is a spill to a stack slot.
912   Optional<SpillLocationNo> isSpillInstruction(const MachineInstr &MI,
913                                                MachineFunction *MF);
914 
915   /// Decide if @MI is a spill instruction and return true if it is. We use 2
916   /// criteria to make this decision:
917   /// - Is this instruction a store to a spill slot?
918   /// - Is there a register operand that is both used and killed?
919   /// TODO: Store optimization can fold spills into other stores (including
920   /// other spills). We do not handle this yet (more than one memory operand).
921   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
922                        unsigned &Reg);
923 
924   /// If a given instruction is identified as a spill, return the spill slot
925   /// and set \p Reg to the spilled register.
926   Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
927                                           MachineFunction *MF, unsigned &Reg);
928 
929   /// Given a spill instruction, extract the spill slot information, ensure it's
930   /// tracked, and return the spill number.
931   Optional<SpillLocationNo>
932   extractSpillBaseRegAndOffset(const MachineInstr &MI);
933 
934   /// Observe a single instruction while stepping through a block.
935   void process(MachineInstr &MI, const ValueTable *MLiveOuts,
936                const ValueTable *MLiveIns);
937 
938   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
939   /// \returns true if MI was recognized and processed.
940   bool transferDebugValue(const MachineInstr &MI);
941 
942   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
943   /// \returns true if MI was recognized and processed.
944   bool transferDebugInstrRef(MachineInstr &MI, const ValueTable *MLiveOuts,
945                              const ValueTable *MLiveIns);
946 
947   /// Stores value-information about where this PHI occurred, and what
948   /// instruction number is associated with it.
949   /// \returns true if MI was recognized and processed.
950   bool transferDebugPHI(MachineInstr &MI);
951 
952   /// Examines whether \p MI is copy instruction, and notifies trackers.
953   /// \returns true if MI was recognized and processed.
954   bool transferRegisterCopy(MachineInstr &MI);
955 
956   /// Examines whether \p MI is stack spill or restore  instruction, and
957   /// notifies trackers. \returns true if MI was recognized and processed.
958   bool transferSpillOrRestoreInst(MachineInstr &MI);
959 
960   /// Examines \p MI for any registers that it defines, and notifies trackers.
961   void transferRegisterDef(MachineInstr &MI);
962 
963   /// Copy one location to the other, accounting for movement of subregisters
964   /// too.
965   void performCopy(Register Src, Register Dst);
966 
967   void accumulateFragmentMap(MachineInstr &MI);
968 
969   /// Determine the machine value number referred to by (potentially several)
970   /// DBG_PHI instructions. Block duplication and tail folding can duplicate
971   /// DBG_PHIs, shifting the position where values in registers merge, and
972   /// forming another mini-ssa problem to solve.
973   /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
974   /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
975   /// \returns The machine value number at position Here, or None.
976   Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
977                                       const ValueTable *MLiveOuts,
978                                       const ValueTable *MLiveIns,
979                                       MachineInstr &Here, uint64_t InstrNum);
980 
981   Optional<ValueIDNum> resolveDbgPHIsImpl(MachineFunction &MF,
982                                           const ValueTable *MLiveOuts,
983                                           const ValueTable *MLiveIns,
984                                           MachineInstr &Here,
985                                           uint64_t InstrNum);
986 
987   /// Step through the function, recording register definitions and movements
988   /// in an MLocTracker. Convert the observations into a per-block transfer
989   /// function in \p MLocTransfer, suitable for using with the machine value
990   /// location dataflow problem.
991   void
992   produceMLocTransferFunction(MachineFunction &MF,
993                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
994                               unsigned MaxNumBlocks);
995 
996   /// Solve the machine value location dataflow problem. Takes as input the
997   /// transfer functions in \p MLocTransfer. Writes the output live-in and
998   /// live-out arrays to the (initialized to zero) multidimensional arrays in
999   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1000   /// number, the inner by LocIdx.
1001   void buildMLocValueMap(MachineFunction &MF, FuncValueTable &MInLocs,
1002                          FuncValueTable &MOutLocs,
1003                          SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1004 
1005   /// Examine the stack indexes (i.e. offsets within the stack) to find the
1006   /// basic units of interference -- like reg units, but for the stack.
1007   void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
1008 
1009   /// Install PHI values into the live-in array for each block, according to
1010   /// the IDF of each register.
1011   void placeMLocPHIs(MachineFunction &MF,
1012                      SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1013                      FuncValueTable &MInLocs,
1014                      SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1015 
1016   /// Propagate variable values to blocks in the common case where there's
1017   /// only one value assigned to the variable. This function has better
1018   /// performance as it doesn't have to find the dominance frontier between
1019   /// different assignments.
1020   void placePHIsForSingleVarDefinition(
1021           const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
1022           MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
1023           const DebugVariable &Var, LiveInsT &Output);
1024 
1025   /// Calculate the iterated-dominance-frontier for a set of defs, using the
1026   /// existing LLVM facilities for this. Works for a single "value" or
1027   /// machine/variable location.
1028   /// \p AllBlocks Set of blocks where we might consume the value.
1029   /// \p DefBlocks Set of blocks where the value/location is defined.
1030   /// \p PHIBlocks Output set of blocks where PHIs must be placed.
1031   void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1032                          const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
1033                          SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
1034 
1035   /// Perform a control flow join (lattice value meet) of the values in machine
1036   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1037   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1038   /// from \p InLocs, and assigning the newly computed live ins back into
1039   /// \p InLocs. \returns two bools -- the first indicates whether a change
1040   /// was made, the second whether a lattice downgrade occurred. If the latter
1041   /// is true, revisiting this block is necessary.
1042   bool mlocJoin(MachineBasicBlock &MBB,
1043                 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1044                 FuncValueTable &OutLocs, ValueTable &InLocs);
1045 
1046   /// Produce a set of blocks that are in the current lexical scope. This means
1047   /// those blocks that contain instructions "in" the scope, blocks where
1048   /// assignments to variables in scope occur, and artificial blocks that are
1049   /// successors to any of the earlier blocks. See https://llvm.org/PR48091 for
1050   /// more commentry on what "in scope" means.
1051   /// \p DILoc A location in the scope that we're fetching blocks for.
1052   /// \p Output Set to put in-scope-blocks into.
1053   /// \p AssignBlocks Blocks known to contain assignments of variables in scope.
1054   void
1055   getBlocksForScope(const DILocation *DILoc,
1056                     SmallPtrSetImpl<const MachineBasicBlock *> &Output,
1057                     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks);
1058 
1059   /// Solve the variable value dataflow problem, for a single lexical scope.
1060   /// Uses the algorithm from the file comment to resolve control flow joins
1061   /// using PHI placement and value propagation. Reads the locations of machine
1062   /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
1063   /// and reads the variable values transfer function from \p AllTheVlocs.
1064   /// Live-in and Live-out variable values are stored locally, with the live-ins
1065   /// permanently stored to \p Output once a fixedpoint is reached.
1066   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1067   /// that we should be tracking.
1068   /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
1069   /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
1070   /// locations through.
1071   void buildVLocValueMap(const DILocation *DILoc,
1072                          const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1073                          SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1074                          LiveInsT &Output, FuncValueTable &MOutLocs,
1075                          FuncValueTable &MInLocs,
1076                          SmallVectorImpl<VLocTracker> &AllTheVLocs);
1077 
1078   /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
1079   /// live-in values coming from predecessors live-outs, and replaces any PHIs
1080   /// already present in this blocks live-ins with a live-through value if the
1081   /// PHI isn't needed.
1082   /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
1083   /// \returns true if any live-ins change value, either from value propagation
1084   ///          or PHI elimination.
1085   bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
1086                 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1087                 DbgValue &LiveIn);
1088 
1089   /// For the given block and live-outs feeding into it, try to find a
1090   /// machine location where all the variable values join together.
1091   /// \returns Value ID of a machine PHI if an appropriate one is available.
1092   Optional<ValueIDNum>
1093   pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
1094               const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
1095               const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
1096 
1097   /// Take collections of DBG_VALUE instructions stored in TTracker, and
1098   /// install them into their output blocks. Preserves a stable order of
1099   /// DBG_VALUEs produced (which would otherwise cause nondeterminism) through
1100   /// the AllVarsNumbering order.
1101   bool emitTransfers(DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
1102 
1103   /// Boilerplate computation of some initial sets, artifical blocks and
1104   /// RPOT block ordering.
1105   void initialSetup(MachineFunction &MF);
1106 
1107   /// Produce a map of the last lexical scope that uses a block, using the
1108   /// scopes DFSOut number. Mapping is block-number to DFSOut.
1109   /// \p EjectionMap Pre-allocated vector in which to install the built ma.
1110   /// \p ScopeToDILocation Mapping of LexicalScopes to their DILocations.
1111   /// \p AssignBlocks Map of blocks where assignments happen for a scope.
1112   void makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> &EjectionMap,
1113                                  const ScopeToDILocT &ScopeToDILocation,
1114                                  ScopeToAssignBlocksT &AssignBlocks);
1115 
1116   /// When determining per-block variable values and emitting to DBG_VALUEs,
1117   /// this function explores by lexical scope depth. Doing so means that per
1118   /// block information can be fully computed before exploration finishes,
1119   /// allowing us to emit it and free data structures earlier than otherwise.
1120   /// It's also good for locality.
1121   bool depthFirstVLocAndEmit(
1122       unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
1123       const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToBlocks,
1124       LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
1125       SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
1126       DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
1127       const TargetPassConfig &TPC);
1128 
1129   bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1130                     TargetPassConfig *TPC, unsigned InputBBLimit,
1131                     unsigned InputDbgValLimit) override;
1132 
1133 public:
1134   /// Default construct and initialize the pass.
1135   InstrRefBasedLDV();
1136 
1137   LLVM_DUMP_METHOD
1138   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1139 
1140   bool isCalleeSaved(LocIdx L) const;
1141 
1142   bool hasFoldedStackStore(const MachineInstr &MI) {
1143     // Instruction must have a memory operand that's a stack slot, and isn't
1144     // aliased, meaning it's a spill from regalloc instead of a variable.
1145     // If it's aliased, we can't guarantee its value.
1146     if (!MI.hasOneMemOperand())
1147       return false;
1148     auto *MemOperand = *MI.memoperands_begin();
1149     return MemOperand->isStore() &&
1150            MemOperand->getPseudoValue() &&
1151            MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
1152            && !MemOperand->getPseudoValue()->isAliased(MFI);
1153   }
1154 
1155   Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
1156 };
1157 
1158 } // namespace LiveDebugValues
1159 
1160 namespace llvm {
1161 using namespace LiveDebugValues;
1162 
1163 template <> struct DenseMapInfo<LocIdx> {
1164   static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); }
1165   static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); }
1166 
1167   static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
1168 
1169   static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
1170 };
1171 
1172 template <> struct DenseMapInfo<ValueIDNum> {
1173   static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; }
1174   static inline ValueIDNum getTombstoneKey() {
1175     return ValueIDNum::TombstoneValue;
1176   }
1177 
1178   static unsigned getHashValue(const ValueIDNum &Val) {
1179     return hash_value(Val.asU64());
1180   }
1181 
1182   static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
1183     return A == B;
1184   }
1185 };
1186 
1187 } // end namespace llvm
1188 
1189 #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */
1190