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