1 //===- InstrRefBasedImpl.cpp - 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 /// \file InstrRefBasedImpl.cpp
9 ///
10 /// This is a separate implementation of LiveDebugValues, see
11 /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12 ///
13 /// This pass propagates variable locations between basic blocks, resolving
14 /// control flow conflicts between them. The problem is much like SSA
15 /// construction, where each DBG_VALUE instruction assigns the *value* that
16 /// a variable has, and every instruction where the variable is in scope uses
17 /// that variable. The resulting map of instruction-to-value is then translated
18 /// into a register (or spill) location for each variable over each instruction.
19 ///
20 /// This pass determines which DBG_VALUE dominates which instructions, or if
21 /// none do, where values must be merged (like PHI nodes). The added
22 /// complication is that because codegen has already finished, a PHI node may
23 /// be needed for a variable location to be correct, but no register or spill
24 /// slot merges the necessary values. In these circumstances, the variable
25 /// location is dropped.
26 ///
27 /// What makes this analysis non-trivial is loops: we cannot tell in advance
28 /// whether a variable location is live throughout a loop, or whether its
29 /// location is clobbered (or redefined by another DBG_VALUE), without
30 /// exploring all the way through.
31 ///
32 /// To make this simpler we perform two kinds of analysis. First, we identify
33 /// every value defined by every instruction (ignoring those that only move
34 /// another value), then compute a map of which values are available for each
35 /// instruction. This is stronger than a reaching-def analysis, as we create
36 /// PHI values where other values merge.
37 ///
38 /// Secondly, for each variable, we effectively re-construct SSA using each
39 /// DBG_VALUE as a def. The DBG_VALUEs read a value-number computed by the
40 /// first analysis from the location they refer to. We can then compute the
41 /// dominance frontiers of where a variable has a value, and create PHI nodes
42 /// where they merge.
43 /// This isn't precisely SSA-construction though, because the function shape
44 /// is pre-defined. If a variable location requires a PHI node, but no
45 /// PHI for the relevant values is present in the function (as computed by the
46 /// first analysis), the location must be dropped.
47 ///
48 /// Once both are complete, we can pass back over all instructions knowing:
49 ///  * What _value_ each variable should contain, either defined by an
50 ///    instruction or where control flow merges
51 ///  * What the location of that value is (if any).
52 /// Allowing us to create appropriate live-in DBG_VALUEs, and DBG_VALUEs when
53 /// a value moves location. After this pass runs, all variable locations within
54 /// a block should be specified by DBG_VALUEs within that block, allowing
55 /// DbgEntityHistoryCalculator to focus on individual blocks.
56 ///
57 /// This pass is able to go fast because the size of the first
58 /// reaching-definition analysis is proportional to the working-set size of
59 /// the function, which the compiler tries to keep small. (It's also
60 /// proportional to the number of blocks). Additionally, we repeatedly perform
61 /// the second reaching-definition analysis with only the variables and blocks
62 /// in a single lexical scope, exploiting their locality.
63 ///
64 /// Determining where PHIs happen is trickier with this approach, and it comes
65 /// to a head in the major problem for LiveDebugValues: is a value live-through
66 /// a loop, or not? Your garden-variety dataflow analysis aims to build a set of
67 /// facts about a function, however this analysis needs to generate new value
68 /// numbers at joins.
69 ///
70 /// To do this, consider a lattice of all definition values, from instructions
71 /// and from PHIs. Each PHI is characterised by the RPO number of the block it
72 /// occurs in. Each value pair A, B can be ordered by RPO(A) < RPO(B):
73 /// with non-PHI values at the top, and any PHI value in the last block (by RPO
74 /// order) at the bottom.
75 ///
76 /// (Awkwardly: lower-down-the _lattice_ means a greater RPO _number_. Below,
77 /// "rank" always refers to the former).
78 ///
79 /// At any join, for each register, we consider:
80 ///  * All incoming values, and
81 ///  * The PREVIOUS live-in value at this join.
82 /// If all incoming values agree: that's the live-in value. If they do not, the
83 /// incoming values are ranked according to the partial order, and the NEXT
84 /// LOWEST rank after the PREVIOUS live-in value is picked (multiple values of
85 /// the same rank are ignored as conflicting). If there are no candidate values,
86 /// or if the rank of the live-in would be lower than the rank of the current
87 /// blocks PHIs, create a new PHI value.
88 ///
89 /// Intuitively: if it's not immediately obvious what value a join should result
90 /// in, we iteratively descend from instruction-definitions down through PHI
91 /// values, getting closer to the current block each time. If the current block
92 /// is a loop head, this ordering is effectively searching outer levels of
93 /// loops, to find a value that's live-through the current loop.
94 ///
95 /// If there is no value that's live-through this loop, a PHI is created for
96 /// this location instead. We can't use a lower-ranked PHI because by definition
97 /// it doesn't dominate the current block. We can't create a PHI value any
98 /// earlier, because we risk creating a PHI value at a location where values do
99 /// not in fact merge, thus misrepresenting the truth, and not making the true
100 /// live-through value for variable locations.
101 ///
102 /// This algorithm applies to both calculating the availability of values in
103 /// the first analysis, and the location of variables in the second. However
104 /// for the second we add an extra dimension of pain: creating a variable
105 /// location PHI is only valid if, for each incoming edge,
106 ///  * There is a value for the variable on the incoming edge, and
107 ///  * All the edges have that value in the same register.
108 /// Or put another way: we can only create a variable-location PHI if there is
109 /// a matching machine-location PHI, each input to which is the variables value
110 /// in the predecessor block.
111 ///
112 /// To accommodate this difference, each point on the lattice is split in
113 /// two: a "proposed" PHI and "definite" PHI. Any PHI that can immediately
114 /// have a location determined are "definite" PHIs, and no further work is
115 /// needed. Otherwise, a location that all non-backedge predecessors agree
116 /// on is picked and propagated as a "proposed" PHI value. If that PHI value
117 /// is truly live-through, it'll appear on the loop backedges on the next
118 /// dataflow iteration, after which the block live-in moves to be a "definite"
119 /// PHI. If it's not truly live-through, the variable value will be downgraded
120 /// further as we explore the lattice, or remains "proposed" and is considered
121 /// invalid once dataflow completes.
122 ///
123 /// ### Terminology
124 ///
125 /// A machine location is a register or spill slot, a value is something that's
126 /// defined by an instruction or PHI node, while a variable value is the value
127 /// assigned to a variable. A variable location is a machine location, that must
128 /// contain the appropriate variable value. A value that is a PHI node is
129 /// occasionally called an mphi.
130 ///
131 /// The first dataflow problem is the "machine value location" problem,
132 /// because we're determining which machine locations contain which values.
133 /// The "locations" are constant: what's unknown is what value they contain.
134 ///
135 /// The second dataflow problem (the one for variables) is the "variable value
136 /// problem", because it's determining what values a variable has, rather than
137 /// what location those values are placed in. Unfortunately, it's not that
138 /// simple, because producing a PHI value always involves picking a location.
139 /// This is an imperfection that we just have to accept, at least for now.
140 ///
141 /// TODO:
142 ///   Overlapping fragments
143 ///   Entry values
144 ///   Add back DEBUG statements for debugging this
145 ///   Collect statistics
146 ///
147 //===----------------------------------------------------------------------===//
148 
149 #include "llvm/ADT/DenseMap.h"
150 #include "llvm/ADT/PostOrderIterator.h"
151 #include "llvm/ADT/SmallPtrSet.h"
152 #include "llvm/ADT/SmallSet.h"
153 #include "llvm/ADT/SmallVector.h"
154 #include "llvm/ADT/Statistic.h"
155 #include "llvm/ADT/UniqueVector.h"
156 #include "llvm/CodeGen/LexicalScopes.h"
157 #include "llvm/CodeGen/MachineBasicBlock.h"
158 #include "llvm/CodeGen/MachineFrameInfo.h"
159 #include "llvm/CodeGen/MachineFunction.h"
160 #include "llvm/CodeGen/MachineFunctionPass.h"
161 #include "llvm/CodeGen/MachineInstr.h"
162 #include "llvm/CodeGen/MachineInstrBuilder.h"
163 #include "llvm/CodeGen/MachineMemOperand.h"
164 #include "llvm/CodeGen/MachineOperand.h"
165 #include "llvm/CodeGen/PseudoSourceValue.h"
166 #include "llvm/CodeGen/RegisterScavenging.h"
167 #include "llvm/CodeGen/TargetFrameLowering.h"
168 #include "llvm/CodeGen/TargetInstrInfo.h"
169 #include "llvm/CodeGen/TargetLowering.h"
170 #include "llvm/CodeGen/TargetPassConfig.h"
171 #include "llvm/CodeGen/TargetRegisterInfo.h"
172 #include "llvm/CodeGen/TargetSubtargetInfo.h"
173 #include "llvm/Config/llvm-config.h"
174 #include "llvm/IR/DIBuilder.h"
175 #include "llvm/IR/DebugInfoMetadata.h"
176 #include "llvm/IR/DebugLoc.h"
177 #include "llvm/IR/Function.h"
178 #include "llvm/IR/Module.h"
179 #include "llvm/InitializePasses.h"
180 #include "llvm/MC/MCRegisterInfo.h"
181 #include "llvm/Pass.h"
182 #include "llvm/Support/Casting.h"
183 #include "llvm/Support/Compiler.h"
184 #include "llvm/Support/Debug.h"
185 #include "llvm/Support/raw_ostream.h"
186 #include <algorithm>
187 #include <cassert>
188 #include <cstdint>
189 #include <functional>
190 #include <queue>
191 #include <tuple>
192 #include <utility>
193 #include <vector>
194 #include <limits.h>
195 #include <limits>
196 
197 #include "LiveDebugValues.h"
198 
199 using namespace llvm;
200 
201 #define DEBUG_TYPE "livedebugvalues"
202 
203 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
204 STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed");
205 
206 // Act more like the VarLoc implementation, by propagating some locations too
207 // far and ignoring some transfers.
208 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
209                                    cl::desc("Act like old LiveDebugValues did"),
210                                    cl::init(false));
211 
212 // Rely on isStoreToStackSlotPostFE and similar to observe all stack spills.
213 static cl::opt<bool>
214     ObserveAllStackops("observe-all-stack-ops", cl::Hidden,
215                        cl::desc("Allow non-kill spill and restores"),
216                        cl::init(false));
217 
218 namespace {
219 
220 // The location at which a spilled value resides. It consists of a register and
221 // an offset.
222 struct SpillLoc {
223   unsigned SpillBase;
224   int SpillOffset;
225   bool operator==(const SpillLoc &Other) const {
226     return std::tie(SpillBase, SpillOffset) ==
227            std::tie(Other.SpillBase, Other.SpillOffset);
228   }
229   bool operator<(const SpillLoc &Other) const {
230     return std::tie(SpillBase, SpillOffset) <
231            std::tie(Other.SpillBase, Other.SpillOffset);
232   }
233 };
234 
235 class LocIdx {
236   unsigned Location;
237 
238   // Default constructor is private, initializing to an illegal location number.
239   // Use only for "not an entry" elements in IndexedMaps.
240   LocIdx() : Location(UINT_MAX) { }
241 
242 public:
243   #define NUM_LOC_BITS 24
244   LocIdx(unsigned L) : Location(L) {
245     assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
246   }
247 
248   static LocIdx MakeIllegalLoc() {
249     return LocIdx();
250   }
251 
252   bool isIllegal() const {
253     return Location == UINT_MAX;
254   }
255 
256   uint64_t asU64() const {
257     return Location;
258   }
259 
260   bool operator==(unsigned L) const {
261     return Location == L;
262   }
263 
264   bool operator==(const LocIdx &L) const {
265     return Location == L.Location;
266   }
267 
268   bool operator!=(unsigned L) const {
269     return !(*this == L);
270   }
271 
272   bool operator!=(const LocIdx &L) const {
273     return !(*this == L);
274   }
275 
276   bool operator<(const LocIdx &Other) const {
277     return Location < Other.Location;
278   }
279 };
280 
281 class LocIdxToIndexFunctor {
282 public:
283   using argument_type = LocIdx;
284   unsigned operator()(const LocIdx &L) const {
285     return L.asU64();
286   }
287 };
288 
289 /// Unique identifier for a value defined by an instruction, as a value type.
290 /// Casts back and forth to a uint64_t. Probably replacable with something less
291 /// bit-constrained. Each value identifies the instruction and machine location
292 /// where the value is defined, although there may be no corresponding machine
293 /// operand for it (ex: regmasks clobbering values). The instructions are
294 /// one-based, and definitions that are PHIs have instruction number zero.
295 ///
296 /// The obvious limits of a 1M block function or 1M instruction blocks are
297 /// problematic; but by that point we should probably have bailed out of
298 /// trying to analyse the function.
299 class ValueIDNum {
300   uint64_t BlockNo : 20;         /// The block where the def happens.
301   uint64_t InstNo : 20;          /// The Instruction where the def happens.
302                                  /// One based, is distance from start of block.
303   uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens.
304 
305 public:
306   // XXX -- temporarily enabled while the live-in / live-out tables are moved
307   // to something more type-y
308   ValueIDNum() : BlockNo(0xFFFFF),
309                  InstNo(0xFFFFF),
310                  LocNo(0xFFFFFF) { }
311 
312   ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc)
313     : BlockNo(Block), InstNo(Inst), LocNo(Loc) { }
314 
315   ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc)
316     : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) { }
317 
318   uint64_t getBlock() const { return BlockNo; }
319   uint64_t getInst() const { return InstNo; }
320   uint64_t getLoc() const { return LocNo; }
321   bool isPHI() const { return InstNo == 0; }
322 
323   uint64_t asU64() const {
324     uint64_t TmpBlock = BlockNo;
325     uint64_t TmpInst = InstNo;
326     return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo;
327   }
328 
329   static ValueIDNum fromU64(uint64_t v) {
330     uint64_t L = (v & 0x3FFF);
331     return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L};
332   }
333 
334   bool operator<(const ValueIDNum &Other) const {
335     return asU64() < Other.asU64();
336   }
337 
338   bool operator==(const ValueIDNum &Other) const {
339     return std::tie(BlockNo, InstNo, LocNo) ==
340            std::tie(Other.BlockNo, Other.InstNo, Other.LocNo);
341   }
342 
343   bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
344 
345   std::string asString(const std::string &mlocname) const {
346     return Twine("bb ")
347         .concat(Twine(BlockNo).concat(Twine(" inst ").concat(
348             Twine(InstNo).concat(Twine(" loc ").concat(Twine(mlocname))))))
349         .str();
350   }
351 
352   static ValueIDNum EmptyValue;
353 };
354 
355 } // end anonymous namespace
356 
357 namespace {
358 
359 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
360 /// the the value, and Boolean of whether or not it's indirect.
361 class DbgValueProperties {
362 public:
363   DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
364       : DIExpr(DIExpr), Indirect(Indirect) {}
365 
366   /// Extract properties from an existing DBG_VALUE instruction.
367   DbgValueProperties(const MachineInstr &MI) {
368     assert(MI.isDebugValue());
369     DIExpr = MI.getDebugExpression();
370     Indirect = MI.getOperand(1).isImm();
371   }
372 
373   bool operator==(const DbgValueProperties &Other) const {
374     return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
375   }
376 
377   bool operator!=(const DbgValueProperties &Other) const {
378     return !(*this == Other);
379   }
380 
381   const DIExpression *DIExpr;
382   bool Indirect;
383 };
384 
385 /// Tracker for what values are in machine locations. Listens to the Things
386 /// being Done by various instructions, and maintains a table of what machine
387 /// locations have what values (as defined by a ValueIDNum).
388 ///
389 /// There are potentially a much larger number of machine locations on the
390 /// target machine than the actual working-set size of the function. On x86 for
391 /// example, we're extremely unlikely to want to track values through control
392 /// or debug registers. To avoid doing so, MLocTracker has several layers of
393 /// indirection going on, with two kinds of ``location'':
394 ///  * A LocID uniquely identifies a register or spill location, with a
395 ///    predictable value.
396 ///  * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum.
397 /// Whenever a location is def'd or used by a MachineInstr, we automagically
398 /// create a new LocIdx for a location, but not otherwise. This ensures we only
399 /// account for locations that are actually used or defined. The cost is another
400 /// vector lookup (of LocID -> LocIdx) over any other implementation. This is
401 /// fairly cheap, and the compiler tries to reduce the working-set at any one
402 /// time in the function anyway.
403 ///
404 /// Register mask operands completely blow this out of the water; I've just
405 /// piled hacks on top of hacks to get around that.
406 class MLocTracker {
407 public:
408   MachineFunction &MF;
409   const TargetInstrInfo &TII;
410   const TargetRegisterInfo &TRI;
411   const TargetLowering &TLI;
412 
413   /// IndexedMap type, mapping from LocIdx to ValueIDNum.
414   typedef IndexedMap<ValueIDNum, LocIdxToIndexFunctor> LocToValueType;
415 
416   /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
417   /// packed, entries only exist for locations that are being tracked.
418   LocToValueType LocIdxToIDNum;
419 
420   /// "Map" of machine location IDs (i.e., raw register or spill number) to the
421   /// LocIdx key / number for that location. There are always at least as many
422   /// as the number of registers on the target -- if the value in the register
423   /// is not being tracked, then the LocIdx value will be zero. New entries are
424   /// appended if a new spill slot begins being tracked.
425   /// This, and the corresponding reverse map persist for the analysis of the
426   /// whole function, and is necessarying for decoding various vectors of
427   /// values.
428   std::vector<LocIdx> LocIDToLocIdx;
429 
430   /// Inverse map of LocIDToLocIdx.
431   IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
432 
433   /// Unique-ification of spill slots. Used to number them -- their LocID
434   /// number is the index in SpillLocs minus one plus NumRegs.
435   UniqueVector<SpillLoc> SpillLocs;
436 
437   // If we discover a new machine location, assign it an mphi with this
438   // block number.
439   unsigned CurBB;
440 
441   /// Cached local copy of the number of registers the target has.
442   unsigned NumRegs;
443 
444   /// Collection of register mask operands that have been observed. Second part
445   /// of pair indicates the instruction that they happened in. Used to
446   /// reconstruct where defs happened if we start tracking a location later
447   /// on.
448   SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
449 
450   /// Iterator for locations and the values they contain. Dereferencing
451   /// produces a struct/pair containing the LocIdx key for this location,
452   /// and a reference to the value currently stored. Simplifies the process
453   /// of seeking a particular location.
454   class MLocIterator {
455     LocToValueType &ValueMap;
456     LocIdx Idx;
457 
458   public:
459     class value_type {
460       public:
461       value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) { }
462       const LocIdx Idx;  /// Read-only index of this location.
463       ValueIDNum &Value; /// Reference to the stored value at this location.
464     };
465 
466     MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
467       : ValueMap(ValueMap), Idx(Idx) { }
468 
469     bool operator==(const MLocIterator &Other) const {
470       assert(&ValueMap == &Other.ValueMap);
471       return Idx == Other.Idx;
472     }
473 
474     bool operator!=(const MLocIterator &Other) const {
475       return !(*this == Other);
476     }
477 
478     void operator++() {
479       Idx = LocIdx(Idx.asU64() + 1);
480     }
481 
482     value_type operator*() {
483       return value_type(Idx, ValueMap[LocIdx(Idx)]);
484     }
485   };
486 
487   MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
488               const TargetRegisterInfo &TRI, const TargetLowering &TLI)
489       : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
490         LocIdxToIDNum(ValueIDNum::EmptyValue),
491         LocIdxToLocID(0) {
492     NumRegs = TRI.getNumRegs();
493     reset();
494     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
495     assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
496 
497     // Always track SP. This avoids the implicit clobbering caused by regmasks
498     // from affectings its values. (LiveDebugValues disbelieves calls and
499     // regmasks that claim to clobber SP).
500     Register SP = TLI.getStackPointerRegisterToSaveRestore();
501     if (SP) {
502       unsigned ID = getLocID(SP, false);
503       (void)lookupOrTrackRegister(ID);
504     }
505   }
506 
507   /// Produce location ID number for indexing LocIDToLocIdx. Takes the register
508   /// or spill number, and flag for whether it's a spill or not.
509   unsigned getLocID(Register RegOrSpill, bool isSpill) {
510     return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id();
511   }
512 
513   /// Accessor for reading the value at Idx.
514   ValueIDNum getNumAtPos(LocIdx Idx) const {
515     assert(Idx.asU64() < LocIdxToIDNum.size());
516     return LocIdxToIDNum[Idx];
517   }
518 
519   unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); }
520 
521   /// Reset all locations to contain a PHI value at the designated block. Used
522   /// sometimes for actual PHI values, othertimes to indicate the block entry
523   /// value (before any more information is known).
524   void setMPhis(unsigned NewCurBB) {
525     CurBB = NewCurBB;
526     for (auto Location : locations())
527       Location.Value = {CurBB, 0, Location.Idx};
528   }
529 
530   /// Load values for each location from array of ValueIDNums. Take current
531   /// bbnum just in case we read a value from a hitherto untouched register.
532   void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
533     CurBB = NewCurBB;
534     // Iterate over all tracked locations, and load each locations live-in
535     // value into our local index.
536     for (auto Location : locations())
537       Location.Value = Locs[Location.Idx.asU64()];
538   }
539 
540   /// Wipe any un-necessary location records after traversing a block.
541   void reset(void) {
542     // We could reset all the location values too; however either loadFromArray
543     // or setMPhis should be called before this object is re-used. Just
544     // clear Masks, they're definitely not needed.
545     Masks.clear();
546   }
547 
548   /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
549   /// the information in this pass uninterpretable.
550   void clear(void) {
551     reset();
552     LocIDToLocIdx.clear();
553     LocIdxToLocID.clear();
554     LocIdxToIDNum.clear();
555     //SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 0
556     SpillLocs = decltype(SpillLocs)();
557 
558     LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
559   }
560 
561   /// Set a locaiton to a certain value.
562   void setMLoc(LocIdx L, ValueIDNum Num) {
563     assert(L.asU64() < LocIdxToIDNum.size());
564     LocIdxToIDNum[L] = Num;
565   }
566 
567   /// Create a LocIdx for an untracked register ID. Initialize it to either an
568   /// mphi value representing a live-in, or a recent register mask clobber.
569   LocIdx trackRegister(unsigned ID) {
570     assert(ID != 0);
571     LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
572     LocIdxToIDNum.grow(NewIdx);
573     LocIdxToLocID.grow(NewIdx);
574 
575     // Default: it's an mphi.
576     ValueIDNum ValNum = {CurBB, 0, NewIdx};
577     // Was this reg ever touched by a regmask?
578     for (const auto &MaskPair : reverse(Masks)) {
579       if (MaskPair.first->clobbersPhysReg(ID)) {
580         // There was an earlier def we skipped.
581         ValNum = {CurBB, MaskPair.second, NewIdx};
582         break;
583       }
584     }
585 
586     LocIdxToIDNum[NewIdx] = ValNum;
587     LocIdxToLocID[NewIdx] = ID;
588     return NewIdx;
589   }
590 
591   LocIdx lookupOrTrackRegister(unsigned ID) {
592     LocIdx &Index = LocIDToLocIdx[ID];
593     if (Index.isIllegal())
594       Index = trackRegister(ID);
595     return Index;
596   }
597 
598   /// Record a definition of the specified register at the given block / inst.
599   /// This doesn't take a ValueIDNum, because the definition and its location
600   /// are synonymous.
601   void defReg(Register R, unsigned BB, unsigned Inst) {
602     unsigned ID = getLocID(R, false);
603     LocIdx Idx = lookupOrTrackRegister(ID);
604     ValueIDNum ValueID = {BB, Inst, Idx};
605     LocIdxToIDNum[Idx] = ValueID;
606   }
607 
608   /// Set a register to a value number. To be used if the value number is
609   /// known in advance.
610   void setReg(Register R, ValueIDNum ValueID) {
611     unsigned ID = getLocID(R, false);
612     LocIdx Idx = lookupOrTrackRegister(ID);
613     LocIdxToIDNum[Idx] = ValueID;
614   }
615 
616   ValueIDNum readReg(Register R) {
617     unsigned ID = getLocID(R, false);
618     LocIdx Idx = lookupOrTrackRegister(ID);
619     return LocIdxToIDNum[Idx];
620   }
621 
622   /// Reset a register value to zero / empty. Needed to replicate the
623   /// VarLoc implementation where a copy to/from a register effectively
624   /// clears the contents of the source register. (Values can only have one
625   ///  machine location in VarLocBasedImpl).
626   void wipeRegister(Register R) {
627     unsigned ID = getLocID(R, false);
628     LocIdx Idx = LocIDToLocIdx[ID];
629     LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
630   }
631 
632   /// Determine the LocIdx of an existing register.
633   LocIdx getRegMLoc(Register R) {
634     unsigned ID = getLocID(R, false);
635     return LocIDToLocIdx[ID];
636   }
637 
638   /// Record a RegMask operand being executed. Defs any register we currently
639   /// track, stores a pointer to the mask in case we have to account for it
640   /// later.
641   void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID) {
642     // Ensure SP exists, so that we don't override it later.
643     Register SP = TLI.getStackPointerRegisterToSaveRestore();
644 
645     // Def any register we track have that isn't preserved. The regmask
646     // terminates the liveness of a register, meaning its value can't be
647     // relied upon -- we represent this by giving it a new value.
648     for (auto Location : locations()) {
649       unsigned ID = LocIdxToLocID[Location.Idx];
650       // Don't clobber SP, even if the mask says it's clobbered.
651       if (ID < NumRegs && ID != SP && MO->clobbersPhysReg(ID))
652         defReg(ID, CurBB, InstID);
653     }
654     Masks.push_back(std::make_pair(MO, InstID));
655   }
656 
657   /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
658   LocIdx getOrTrackSpillLoc(SpillLoc L) {
659     unsigned SpillID = SpillLocs.idFor(L);
660     if (SpillID == 0) {
661       SpillID = SpillLocs.insert(L);
662       unsigned L = getLocID(SpillID, true);
663       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
664       LocIdxToIDNum.grow(Idx);
665       LocIdxToLocID.grow(Idx);
666       LocIDToLocIdx.push_back(Idx);
667       LocIdxToLocID[Idx] = L;
668       return Idx;
669     } else {
670       unsigned L = getLocID(SpillID, true);
671       LocIdx Idx = LocIDToLocIdx[L];
672       return Idx;
673     }
674   }
675 
676   /// Set the value stored in a spill slot.
677   void setSpill(SpillLoc L, ValueIDNum ValueID) {
678     LocIdx Idx = getOrTrackSpillLoc(L);
679     LocIdxToIDNum[Idx] = ValueID;
680   }
681 
682   /// Read whatever value is in a spill slot, or None if it isn't tracked.
683   Optional<ValueIDNum> readSpill(SpillLoc L) {
684     unsigned SpillID = SpillLocs.idFor(L);
685     if (SpillID == 0)
686       return None;
687 
688     unsigned LocID = getLocID(SpillID, true);
689     LocIdx Idx = LocIDToLocIdx[LocID];
690     return LocIdxToIDNum[Idx];
691   }
692 
693   /// Determine the LocIdx of a spill slot. Return None if it previously
694   /// hasn't had a value assigned.
695   Optional<LocIdx> getSpillMLoc(SpillLoc L) {
696     unsigned SpillID = SpillLocs.idFor(L);
697     if (SpillID == 0)
698       return None;
699     unsigned LocNo = getLocID(SpillID, true);
700     return LocIDToLocIdx[LocNo];
701   }
702 
703   /// Return true if Idx is a spill machine location.
704   bool isSpill(LocIdx Idx) const {
705     return LocIdxToLocID[Idx] >= NumRegs;
706   }
707 
708   MLocIterator begin() {
709     return MLocIterator(LocIdxToIDNum, 0);
710   }
711 
712   MLocIterator end() {
713     return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
714   }
715 
716   /// Return a range over all locations currently tracked.
717   iterator_range<MLocIterator> locations() {
718     return llvm::make_range(begin(), end());
719   }
720 
721   std::string LocIdxToName(LocIdx Idx) const {
722     unsigned ID = LocIdxToLocID[Idx];
723     if (ID >= NumRegs)
724       return Twine("slot ").concat(Twine(ID - NumRegs)).str();
725     else
726       return TRI.getRegAsmName(ID).str();
727   }
728 
729   std::string IDAsString(const ValueIDNum &Num) const {
730     std::string DefName = LocIdxToName(Num.getLoc());
731     return Num.asString(DefName);
732   }
733 
734   LLVM_DUMP_METHOD
735   void dump() {
736     for (auto Location : locations()) {
737       std::string MLocName = LocIdxToName(Location.Value.getLoc());
738       std::string DefName = Location.Value.asString(MLocName);
739       dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
740     }
741   }
742 
743   LLVM_DUMP_METHOD
744   void dump_mloc_map() {
745     for (auto Location : locations()) {
746       std::string foo = LocIdxToName(Location.Idx);
747       dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
748     }
749   }
750 
751   /// Create a DBG_VALUE based on  machine location \p MLoc. Qualify it with the
752   /// information in \pProperties, for variable Var. Don't insert it anywhere,
753   /// just return the builder for it.
754   MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
755                               const DbgValueProperties &Properties) {
756     DebugLoc DL =
757         DebugLoc::get(0, 0, Var.getVariable()->getScope(), Var.getInlinedAt());
758     auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
759 
760     const DIExpression *Expr = Properties.DIExpr;
761     if (!MLoc) {
762       // No location -> DBG_VALUE $noreg
763       MIB.addReg(0, RegState::Debug);
764       MIB.addReg(0, RegState::Debug);
765     } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
766       unsigned LocID = LocIdxToLocID[*MLoc];
767       const SpillLoc &Spill = SpillLocs[LocID - NumRegs + 1];
768       Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset,
769                                    Spill.SpillOffset);
770       unsigned Base = Spill.SpillBase;
771       MIB.addReg(Base, RegState::Debug);
772       MIB.addImm(0);
773     } else {
774       unsigned LocID = LocIdxToLocID[*MLoc];
775       MIB.addReg(LocID, RegState::Debug);
776       if (Properties.Indirect)
777         MIB.addImm(0);
778       else
779         MIB.addReg(0, RegState::Debug);
780     }
781 
782     MIB.addMetadata(Var.getVariable());
783     MIB.addMetadata(Expr);
784     return MIB;
785   }
786 };
787 
788 /// Class recording the (high level) _value_ of a variable. Identifies either
789 /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
790 /// This class also stores meta-information about how the value is qualified.
791 /// Used to reason about variable values when performing the second
792 /// (DebugVariable specific) dataflow analysis.
793 class DbgValue {
794 public:
795   union {
796     /// If Kind is Def, the value number that this value is based on.
797     ValueIDNum ID;
798     /// If Kind is Const, the MachineOperand defining this value.
799     MachineOperand MO;
800     /// For a NoVal DbgValue, which block it was generated in.
801     unsigned BlockNo;
802   };
803   /// Qualifiers for the ValueIDNum above.
804   DbgValueProperties Properties;
805 
806   typedef enum {
807     Undef,     // Represents a DBG_VALUE $noreg in the transfer function only.
808     Def,       // This value is defined by an inst, or is a PHI value.
809     Const,     // A constant value contained in the MachineOperand field.
810     Proposed,  // This is a tentative PHI value, which may be confirmed or
811                // invalidated later.
812     NoVal      // Empty DbgValue, generated during dataflow. BlockNo stores
813                // which block this was generated in.
814    } KindT;
815   /// Discriminator for whether this is a constant or an in-program value.
816   KindT Kind;
817 
818   DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
819     : ID(Val), Properties(Prop), Kind(Kind) {
820     assert(Kind == Def || Kind == Proposed);
821   }
822 
823   DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
824     : BlockNo(BlockNo), Properties(Prop), Kind(Kind) {
825     assert(Kind == NoVal);
826   }
827 
828   DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
829     : MO(MO), Properties(Prop), Kind(Kind) {
830     assert(Kind == Const);
831   }
832 
833   DbgValue(const DbgValueProperties &Prop, KindT Kind)
834     : Properties(Prop), Kind(Kind) {
835     assert(Kind == Undef &&
836            "Empty DbgValue constructor must pass in Undef kind");
837   }
838 
839   void dump(const MLocTracker *MTrack) const {
840     if (Kind == Const) {
841       MO.dump();
842     } else if (Kind == NoVal) {
843       dbgs() << "NoVal(" << BlockNo << ")";
844     } else if (Kind == Proposed) {
845       dbgs() << "VPHI(" << MTrack->IDAsString(ID) << ")";
846     } else {
847       assert(Kind == Def);
848       dbgs() << MTrack->IDAsString(ID);
849     }
850     if (Properties.Indirect)
851       dbgs() << " indir";
852     if (Properties.DIExpr)
853       dbgs() << " " << *Properties.DIExpr;
854   }
855 
856   bool operator==(const DbgValue &Other) const {
857     if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
858       return false;
859     else if (Kind == Proposed && ID != Other.ID)
860       return false;
861     else if (Kind == Def && ID != Other.ID)
862       return false;
863     else if (Kind == NoVal && BlockNo != Other.BlockNo)
864       return false;
865     else if (Kind == Const)
866       return MO.isIdenticalTo(Other.MO);
867 
868     return true;
869   }
870 
871   bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
872 };
873 
874 /// Types for recording sets of variable fragments that overlap. For a given
875 /// local variable, we record all other fragments of that variable that could
876 /// overlap it, to reduce search time.
877 using FragmentOfVar =
878     std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
879 using OverlapMap =
880     DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
881 
882 /// Collection of DBG_VALUEs observed when traversing a block. Records each
883 /// variable and the value the DBG_VALUE refers to. Requires the machine value
884 /// location dataflow algorithm to have run already, so that values can be
885 /// identified.
886 class VLocTracker {
887 public:
888   /// Map DebugVariable to the latest Value it's defined to have.
889   /// Needs to be a MapVector because we determine order-in-the-input-MIR from
890   /// the order in this container.
891   /// We only retain the last DbgValue in each block for each variable, to
892   /// determine the blocks live-out variable value. The Vars container forms the
893   /// transfer function for this block, as part of the dataflow analysis. The
894   /// movement of values between locations inside of a block is handled at a
895   /// much later stage, in the TransferTracker class.
896   MapVector<DebugVariable, DbgValue> Vars;
897   DenseMap<DebugVariable, const DILocation *> Scopes;
898   MachineBasicBlock *MBB;
899 
900 public:
901   VLocTracker() {}
902 
903   void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
904               Optional<ValueIDNum> ID) {
905     assert(MI.isDebugValue() || MI.isDebugRef());
906     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
907                       MI.getDebugLoc()->getInlinedAt());
908     DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
909                         : DbgValue(Properties, DbgValue::Undef);
910 
911     // Attempt insertion; overwrite if it's already mapped.
912     auto Result = Vars.insert(std::make_pair(Var, Rec));
913     if (!Result.second)
914       Result.first->second = Rec;
915     Scopes[Var] = MI.getDebugLoc().get();
916   }
917 
918   void defVar(const MachineInstr &MI, const MachineOperand &MO) {
919     // Only DBG_VALUEs can define constant-valued variables.
920     assert(MI.isDebugValue());
921     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
922                       MI.getDebugLoc()->getInlinedAt());
923     DbgValueProperties Properties(MI);
924     DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
925 
926     // Attempt insertion; overwrite if it's already mapped.
927     auto Result = Vars.insert(std::make_pair(Var, Rec));
928     if (!Result.second)
929       Result.first->second = Rec;
930     Scopes[Var] = MI.getDebugLoc().get();
931   }
932 };
933 
934 /// Tracker for converting machine value locations and variable values into
935 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
936 /// specifying block live-in locations and transfers within blocks.
937 ///
938 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
939 /// and must be initialized with the set of variable values that are live-in to
940 /// the block. The caller then repeatedly calls process(). TransferTracker picks
941 /// out variable locations for the live-in variable values (if there _is_ a
942 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
943 /// stepped through, transfers of values between machine locations are
944 /// identified and if profitable, a DBG_VALUE created.
945 ///
946 /// This is where debug use-before-defs would be resolved: a variable with an
947 /// unavailable value could materialize in the middle of a block, when the
948 /// value becomes available. Or, we could detect clobbers and re-specify the
949 /// variable in a backup location. (XXX these are unimplemented).
950 class TransferTracker {
951 public:
952   const TargetInstrInfo *TII;
953   /// This machine location tracker is assumed to always contain the up-to-date
954   /// value mapping for all machine locations. TransferTracker only reads
955   /// information from it. (XXX make it const?)
956   MLocTracker *MTracker;
957   MachineFunction &MF;
958 
959   /// Record of all changes in variable locations at a block position. Awkwardly
960   /// we allow inserting either before or after the point: MBB != nullptr
961   /// indicates it's before, otherwise after.
962   struct Transfer {
963     MachineBasicBlock::iterator Pos; /// Position to insert DBG_VALUes
964     MachineBasicBlock *MBB;          /// non-null if we should insert after.
965     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
966   };
967 
968   typedef struct {
969     LocIdx Loc;
970     DbgValueProperties Properties;
971   } LocAndProperties;
972 
973   /// Collection of transfers (DBG_VALUEs) to be inserted.
974   SmallVector<Transfer, 32> Transfers;
975 
976   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
977   /// between TransferTrackers view of variable locations and MLocTrackers. For
978   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
979   /// does not.
980   std::vector<ValueIDNum> VarLocs;
981 
982   /// Map from LocIdxes to which DebugVariables are based that location.
983   /// Mantained while stepping through the block. Not accurate if
984   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
985   std::map<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
986 
987   /// Map from DebugVariable to it's current location and qualifying meta
988   /// information. To be used in conjunction with ActiveMLocs to construct
989   /// enough information for the DBG_VALUEs for a particular LocIdx.
990   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
991 
992   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
993   SmallVector<MachineInstr *, 4> PendingDbgValues;
994 
995   /// Record of a use-before-def: created when a value that's live-in to the
996   /// current block isn't available in any machine location, but it will be
997   /// defined in this block.
998   struct UseBeforeDef {
999     /// Value of this variable, def'd in block.
1000     ValueIDNum ID;
1001     /// Identity of this variable.
1002     DebugVariable Var;
1003     /// Additional variable properties.
1004     DbgValueProperties Properties;
1005   };
1006 
1007   /// Map from instruction index (within the block) to the set of UseBeforeDefs
1008   /// that become defined at that instruction.
1009   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
1010 
1011   /// The set of variables that are in UseBeforeDefs and can become a location
1012   /// once the relevant value is defined. An element being erased from this
1013   /// collection prevents the use-before-def materializing.
1014   DenseSet<DebugVariable> UseBeforeDefVariables;
1015 
1016   const TargetRegisterInfo &TRI;
1017   const BitVector &CalleeSavedRegs;
1018 
1019   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
1020                   MachineFunction &MF, const TargetRegisterInfo &TRI,
1021                   const BitVector &CalleeSavedRegs)
1022       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
1023         CalleeSavedRegs(CalleeSavedRegs) {}
1024 
1025   /// Load object with live-in variable values. \p mlocs contains the live-in
1026   /// values in each machine location, while \p vlocs the live-in variable
1027   /// values. This method picks variable locations for the live-in variables,
1028   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
1029   /// object fields to track variable locations as we step through the block.
1030   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
1031   void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs,
1032                   SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
1033                   unsigned NumLocs) {
1034     ActiveMLocs.clear();
1035     ActiveVLocs.clear();
1036     VarLocs.clear();
1037     VarLocs.reserve(NumLocs);
1038     UseBeforeDefs.clear();
1039     UseBeforeDefVariables.clear();
1040 
1041     auto isCalleeSaved = [&](LocIdx L) {
1042       unsigned Reg = MTracker->LocIdxToLocID[L];
1043       if (Reg >= MTracker->NumRegs)
1044         return false;
1045       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
1046         if (CalleeSavedRegs.test(*RAI))
1047           return true;
1048       return false;
1049     };
1050 
1051     // Map of the preferred location for each value.
1052     std::map<ValueIDNum, LocIdx> ValueToLoc;
1053 
1054     // Produce a map of value numbers to the current machine locs they live
1055     // in. When emulating VarLocBasedImpl, there should only be one
1056     // location; when not, we get to pick.
1057     for (auto Location : MTracker->locations()) {
1058       LocIdx Idx = Location.Idx;
1059       ValueIDNum &VNum = MLocs[Idx.asU64()];
1060       VarLocs.push_back(VNum);
1061       auto it = ValueToLoc.find(VNum);
1062       // In order of preference, pick:
1063       //  * Callee saved registers,
1064       //  * Other registers,
1065       //  * Spill slots.
1066       if (it == ValueToLoc.end() || MTracker->isSpill(it->second) ||
1067           (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) {
1068         // Insert, or overwrite if insertion failed.
1069         auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx));
1070         if (!PrefLocRes.second)
1071           PrefLocRes.first->second = Idx;
1072       }
1073     }
1074 
1075     // Now map variables to their picked LocIdxes.
1076     for (auto Var : VLocs) {
1077       if (Var.second.Kind == DbgValue::Const) {
1078         PendingDbgValues.push_back(
1079             emitMOLoc(Var.second.MO, Var.first, Var.second.Properties));
1080         continue;
1081       }
1082 
1083       // If the value has no location, we can't make a variable location.
1084       const ValueIDNum &Num = Var.second.ID;
1085       auto ValuesPreferredLoc = ValueToLoc.find(Num);
1086       if (ValuesPreferredLoc == ValueToLoc.end()) {
1087         // If it's a def that occurs in this block, register it as a
1088         // use-before-def to be resolved as we step through the block.
1089         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
1090           addUseBeforeDef(Var.first, Var.second.Properties, Num);
1091         continue;
1092       }
1093 
1094       LocIdx M = ValuesPreferredLoc->second;
1095       auto NewValue = LocAndProperties{M, Var.second.Properties};
1096       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
1097       if (!Result.second)
1098         Result.first->second = NewValue;
1099       ActiveMLocs[M].insert(Var.first);
1100       PendingDbgValues.push_back(
1101           MTracker->emitLoc(M, Var.first, Var.second.Properties));
1102     }
1103     flushDbgValues(MBB.begin(), &MBB);
1104   }
1105 
1106   /// Record that \p Var has value \p ID, a value that becomes available
1107   /// later in the function.
1108   void addUseBeforeDef(const DebugVariable &Var,
1109                        const DbgValueProperties &Properties, ValueIDNum ID) {
1110     UseBeforeDef UBD = {ID, Var, Properties};
1111     UseBeforeDefs[ID.getInst()].push_back(UBD);
1112     UseBeforeDefVariables.insert(Var);
1113   }
1114 
1115   /// After the instruction at index \p Inst and position \p pos has been
1116   /// processed, check whether it defines a variable value in a use-before-def.
1117   /// If so, and the variable value hasn't changed since the start of the
1118   /// block, create a DBG_VALUE.
1119   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
1120     auto MIt = UseBeforeDefs.find(Inst);
1121     if (MIt == UseBeforeDefs.end())
1122       return;
1123 
1124     for (auto &Use : MIt->second) {
1125       LocIdx L = Use.ID.getLoc();
1126 
1127       // If something goes very wrong, we might end up labelling a COPY
1128       // instruction or similar with an instruction number, where it doesn't
1129       // actually define a new value, instead it moves a value. In case this
1130       // happens, discard.
1131       if (MTracker->LocIdxToIDNum[L] != Use.ID)
1132         continue;
1133 
1134       // If a different debug instruction defined the variable value / location
1135       // since the start of the block, don't materialize this use-before-def.
1136       if (!UseBeforeDefVariables.count(Use.Var))
1137         continue;
1138 
1139       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
1140     }
1141     flushDbgValues(pos, nullptr);
1142   }
1143 
1144   /// Helper to move created DBG_VALUEs into Transfers collection.
1145   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
1146     if (PendingDbgValues.size() > 0) {
1147       Transfers.push_back({Pos, MBB, PendingDbgValues});
1148       PendingDbgValues.clear();
1149     }
1150   }
1151 
1152   /// Change a variable value after encountering a DBG_VALUE inside a block.
1153   void redefVar(const MachineInstr &MI) {
1154     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1155                       MI.getDebugLoc()->getInlinedAt());
1156     DbgValueProperties Properties(MI);
1157 
1158     const MachineOperand &MO = MI.getOperand(0);
1159 
1160     // Ignore non-register locations, we don't transfer those.
1161     if (!MO.isReg() || MO.getReg() == 0) {
1162       auto It = ActiveVLocs.find(Var);
1163       if (It != ActiveVLocs.end()) {
1164         ActiveMLocs[It->second.Loc].erase(Var);
1165         ActiveVLocs.erase(It);
1166      }
1167       // Any use-before-defs no longer apply.
1168       UseBeforeDefVariables.erase(Var);
1169       return;
1170     }
1171 
1172     Register Reg = MO.getReg();
1173     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
1174     redefVar(MI, Properties, NewLoc);
1175   }
1176 
1177   /// Handle a change in variable location within a block. Terminate the
1178   /// variables current location, and record the value it now refers to, so
1179   /// that we can detect location transfers later on.
1180   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
1181                 Optional<LocIdx> OptNewLoc) {
1182     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1183                       MI.getDebugLoc()->getInlinedAt());
1184     // Any use-before-defs no longer apply.
1185     UseBeforeDefVariables.erase(Var);
1186 
1187     // Erase any previous location,
1188     auto It = ActiveVLocs.find(Var);
1189     if (It != ActiveVLocs.end())
1190       ActiveMLocs[It->second.Loc].erase(Var);
1191 
1192     // If there _is_ no new location, all we had to do was erase.
1193     if (!OptNewLoc)
1194       return;
1195     LocIdx NewLoc = *OptNewLoc;
1196 
1197     // Check whether our local copy of values-by-location in #VarLocs is out of
1198     // date. Wipe old tracking data for the location if it's been clobbered in
1199     // the meantime.
1200     if (MTracker->getNumAtPos(NewLoc) != VarLocs[NewLoc.asU64()]) {
1201       for (auto &P : ActiveMLocs[NewLoc]) {
1202         ActiveVLocs.erase(P);
1203       }
1204       ActiveMLocs[NewLoc.asU64()].clear();
1205       VarLocs[NewLoc.asU64()] = MTracker->getNumAtPos(NewLoc);
1206     }
1207 
1208     ActiveMLocs[NewLoc].insert(Var);
1209     if (It == ActiveVLocs.end()) {
1210       ActiveVLocs.insert(
1211           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
1212     } else {
1213       It->second.Loc = NewLoc;
1214       It->second.Properties = Properties;
1215     }
1216   }
1217 
1218   /// Explicitly terminate variable locations based on \p mloc. Creates undef
1219   /// DBG_VALUEs for any variables that were located there, and clears
1220   /// #ActiveMLoc / #ActiveVLoc tracking information for that location.
1221   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos) {
1222     assert(MTracker->isSpill(MLoc));
1223     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
1224     if (ActiveMLocIt == ActiveMLocs.end())
1225       return;
1226 
1227     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
1228 
1229     for (auto &Var : ActiveMLocIt->second) {
1230       auto ActiveVLocIt = ActiveVLocs.find(Var);
1231       // Create an undef. We can't feed in a nullptr DIExpression alas,
1232       // so use the variables last expression. Pass None as the location.
1233       const DIExpression *Expr = ActiveVLocIt->second.Properties.DIExpr;
1234       DbgValueProperties Properties(Expr, false);
1235       PendingDbgValues.push_back(MTracker->emitLoc(None, Var, Properties));
1236       ActiveVLocs.erase(ActiveVLocIt);
1237     }
1238     flushDbgValues(Pos, nullptr);
1239 
1240     ActiveMLocIt->second.clear();
1241   }
1242 
1243   /// Transfer variables based on \p Src to be based on \p Dst. This handles
1244   /// both register copies as well as spills and restores. Creates DBG_VALUEs
1245   /// describing the movement.
1246   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
1247     // Does Src still contain the value num we expect? If not, it's been
1248     // clobbered in the meantime, and our variable locations are stale.
1249     if (VarLocs[Src.asU64()] != MTracker->getNumAtPos(Src))
1250       return;
1251 
1252     // assert(ActiveMLocs[Dst].size() == 0);
1253     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
1254     ActiveMLocs[Dst] = ActiveMLocs[Src];
1255     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
1256 
1257     // For each variable based on Src; create a location at Dst.
1258     for (auto &Var : ActiveMLocs[Src]) {
1259       auto ActiveVLocIt = ActiveVLocs.find(Var);
1260       assert(ActiveVLocIt != ActiveVLocs.end());
1261       ActiveVLocIt->second.Loc = Dst;
1262 
1263       assert(Dst != 0);
1264       MachineInstr *MI =
1265           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
1266       PendingDbgValues.push_back(MI);
1267     }
1268     ActiveMLocs[Src].clear();
1269     flushDbgValues(Pos, nullptr);
1270 
1271     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
1272     // about the old location.
1273     if (EmulateOldLDV)
1274       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
1275   }
1276 
1277   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
1278                                 const DebugVariable &Var,
1279                                 const DbgValueProperties &Properties) {
1280     DebugLoc DL =
1281         DebugLoc::get(0, 0, Var.getVariable()->getScope(), Var.getInlinedAt());
1282     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
1283     MIB.add(MO);
1284     if (Properties.Indirect)
1285       MIB.addImm(0);
1286     else
1287       MIB.addReg(0);
1288     MIB.addMetadata(Var.getVariable());
1289     MIB.addMetadata(Properties.DIExpr);
1290     return MIB;
1291   }
1292 };
1293 
1294 class InstrRefBasedLDV : public LDVImpl {
1295 private:
1296   using FragmentInfo = DIExpression::FragmentInfo;
1297   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
1298 
1299   // Helper while building OverlapMap, a map of all fragments seen for a given
1300   // DILocalVariable.
1301   using VarToFragments =
1302       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
1303 
1304   /// Machine location/value transfer function, a mapping of which locations
1305   // are assigned which new values.
1306   typedef std::map<LocIdx, ValueIDNum> MLocTransferMap;
1307 
1308   /// Live in/out structure for the variable values: a per-block map of
1309   /// variables to their values. XXX, better name?
1310   typedef DenseMap<const MachineBasicBlock *,
1311                    DenseMap<DebugVariable, DbgValue> *>
1312       LiveIdxT;
1313 
1314   typedef std::pair<DebugVariable, DbgValue> VarAndLoc;
1315 
1316   /// Type for a live-in value: the predecessor block, and its value.
1317   typedef std::pair<MachineBasicBlock *, DbgValue *> InValueT;
1318 
1319   /// Vector (per block) of a collection (inner smallvector) of live-ins.
1320   /// Used as the result type for the variable value dataflow problem.
1321   typedef SmallVector<SmallVector<VarAndLoc, 8>, 8> LiveInsT;
1322 
1323   const TargetRegisterInfo *TRI;
1324   const TargetInstrInfo *TII;
1325   const TargetFrameLowering *TFI;
1326   BitVector CalleeSavedRegs;
1327   LexicalScopes LS;
1328   TargetPassConfig *TPC;
1329 
1330   /// Object to track machine locations as we step through a block. Could
1331   /// probably be a field rather than a pointer, as it's always used.
1332   MLocTracker *MTracker;
1333 
1334   /// Number of the current block LiveDebugValues is stepping through.
1335   unsigned CurBB;
1336 
1337   /// Number of the current instruction LiveDebugValues is evaluating.
1338   unsigned CurInst;
1339 
1340   /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
1341   /// steps through a block. Reads the values at each location from the
1342   /// MLocTracker object.
1343   VLocTracker *VTracker;
1344 
1345   /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
1346   /// between locations during stepping, creates new DBG_VALUEs when values move
1347   /// location.
1348   TransferTracker *TTracker;
1349 
1350   /// Blocks which are artificial, i.e. blocks which exclusively contain
1351   /// instructions without DebugLocs, or with line 0 locations.
1352   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1353 
1354   // Mapping of blocks to and from their RPOT order.
1355   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1356   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1357   DenseMap<unsigned, unsigned> BBNumToRPO;
1358 
1359   /// Pair of MachineInstr, and its 1-based offset into the containing block.
1360   typedef std::pair<const MachineInstr *, unsigned> InstAndNum;
1361   /// Map from debug instruction number to the MachineInstr labelled with that
1362   /// number, and its location within the function. Used to transform
1363   /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
1364   std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
1365 
1366   // Map of overlapping variable fragments.
1367   OverlapMap OverlapFragments;
1368   VarToFragments SeenFragments;
1369 
1370   /// Tests whether this instruction is a spill to a stack slot.
1371   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
1372 
1373   /// Decide if @MI is a spill instruction and return true if it is. We use 2
1374   /// criteria to make this decision:
1375   /// - Is this instruction a store to a spill slot?
1376   /// - Is there a register operand that is both used and killed?
1377   /// TODO: Store optimization can fold spills into other stores (including
1378   /// other spills). We do not handle this yet (more than one memory operand).
1379   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1380                        unsigned &Reg);
1381 
1382   /// If a given instruction is identified as a spill, return the spill slot
1383   /// and set \p Reg to the spilled register.
1384   Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI,
1385                                           MachineFunction *MF, unsigned &Reg);
1386 
1387   /// Given a spill instruction, extract the register and offset used to
1388   /// address the spill slot in a target independent way.
1389   SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
1390 
1391   /// Observe a single instruction while stepping through a block.
1392   void process(MachineInstr &MI);
1393 
1394   /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
1395   /// \returns true if MI was recognized and processed.
1396   bool transferDebugValue(const MachineInstr &MI);
1397 
1398   /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
1399   /// \returns true if MI was recognized and processed.
1400   bool transferDebugInstrRef(MachineInstr &MI);
1401 
1402   /// Examines whether \p MI is copy instruction, and notifies trackers.
1403   /// \returns true if MI was recognized and processed.
1404   bool transferRegisterCopy(MachineInstr &MI);
1405 
1406   /// Examines whether \p MI is stack spill or restore  instruction, and
1407   /// notifies trackers. \returns true if MI was recognized and processed.
1408   bool transferSpillOrRestoreInst(MachineInstr &MI);
1409 
1410   /// Examines \p MI for any registers that it defines, and notifies trackers.
1411   void transferRegisterDef(MachineInstr &MI);
1412 
1413   /// Copy one location to the other, accounting for movement of subregisters
1414   /// too.
1415   void performCopy(Register Src, Register Dst);
1416 
1417   void accumulateFragmentMap(MachineInstr &MI);
1418 
1419   /// Step through the function, recording register definitions and movements
1420   /// in an MLocTracker. Convert the observations into a per-block transfer
1421   /// function in \p MLocTransfer, suitable for using with the machine value
1422   /// location dataflow problem.
1423   void
1424   produceMLocTransferFunction(MachineFunction &MF,
1425                               SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1426                               unsigned MaxNumBlocks);
1427 
1428   /// Solve the machine value location dataflow problem. Takes as input the
1429   /// transfer functions in \p MLocTransfer. Writes the output live-in and
1430   /// live-out arrays to the (initialized to zero) multidimensional arrays in
1431   /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1432   /// number, the inner by LocIdx.
1433   void mlocDataflow(ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
1434                     SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1435 
1436   /// Perform a control flow join (lattice value meet) of the values in machine
1437   /// locations at \p MBB. Follows the algorithm described in the file-comment,
1438   /// reading live-outs of predecessors from \p OutLocs, the current live ins
1439   /// from \p InLocs, and assigning the newly computed live ins back into
1440   /// \p InLocs. \returns two bools -- the first indicates whether a change
1441   /// was made, the second whether a lattice downgrade occurred. If the latter
1442   /// is true, revisiting this block is necessary.
1443   std::tuple<bool, bool>
1444   mlocJoin(MachineBasicBlock &MBB,
1445            SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1446            ValueIDNum **OutLocs, ValueIDNum *InLocs);
1447 
1448   /// Solve the variable value dataflow problem, for a single lexical scope.
1449   /// Uses the algorithm from the file comment to resolve control flow joins,
1450   /// although there are extra hacks, see vlocJoin. Reads the
1451   /// locations of values from the \p MInLocs and \p MOutLocs arrays (see
1452   /// mlocDataflow) and reads the variable values transfer function from
1453   /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally,
1454   /// with the live-ins permanently stored to \p Output once the fixedpoint is
1455   /// reached.
1456   /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1457   /// that we should be tracking.
1458   /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but
1459   /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations
1460   /// through.
1461   void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc,
1462                     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1463                     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1464                     LiveInsT &Output, ValueIDNum **MOutLocs,
1465                     ValueIDNum **MInLocs,
1466                     SmallVectorImpl<VLocTracker> &AllTheVLocs);
1467 
1468   /// Compute the live-ins to a block, considering control flow merges according
1469   /// to the method in the file comment. Live out and live in variable values
1470   /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB
1471   /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins
1472   /// are modified.
1473   /// \p InLocsT Output argument, storage for calculated live-ins.
1474   /// \returns two bools -- the first indicates whether a change
1475   /// was made, the second whether a lattice downgrade occurred. If the latter
1476   /// is true, revisiting this block is necessary.
1477   std::tuple<bool, bool>
1478   vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
1479            SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited,
1480            unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars,
1481            ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
1482            SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
1483            SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1484            DenseMap<DebugVariable, DbgValue> &InLocsT);
1485 
1486   /// Continue exploration of the variable-value lattice, as explained in the
1487   /// file-level comment. \p OldLiveInLocation contains the current
1488   /// exploration position, from which we need to descend further. \p Values
1489   /// contains the set of live-in values, \p CurBlockRPONum the RPO number of
1490   /// the current block, and \p CandidateLocations a set of locations that
1491   /// should be considered as PHI locations, if we reach the bottom of the
1492   /// lattice. \returns true if we should downgrade; the value is the agreeing
1493   /// value number in a non-backedge predecessor.
1494   bool vlocDowngradeLattice(const MachineBasicBlock &MBB,
1495                             const DbgValue &OldLiveInLocation,
1496                             const SmallVectorImpl<InValueT> &Values,
1497                             unsigned CurBlockRPONum);
1498 
1499   /// For the given block and live-outs feeding into it, try to find a
1500   /// machine location where they all join. If a solution for all predecessors
1501   /// can't be found, a location where all non-backedge-predecessors join
1502   /// will be returned instead. While this method finds a join location, this
1503   /// says nothing as to whether it should be used.
1504   /// \returns Pair of value ID if found, and true when the correct value
1505   /// is available on all predecessor edges, or false if it's only available
1506   /// for non-backedge predecessors.
1507   std::tuple<Optional<ValueIDNum>, bool>
1508   pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var,
1509               const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
1510               ValueIDNum **MInLocs,
1511               const SmallVectorImpl<MachineBasicBlock *> &BlockOrders);
1512 
1513   /// Given the solutions to the two dataflow problems, machine value locations
1514   /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the
1515   /// TransferTracker class over the function to produce live-in and transfer
1516   /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the
1517   /// order given by AllVarsNumbering -- this could be any stable order, but
1518   /// right now "order of appearence in function, when explored in RPO", so
1519   /// that we can compare explictly against VarLocBasedImpl.
1520   void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns,
1521                      ValueIDNum **MInLocs,
1522                      DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
1523 
1524   /// Boilerplate computation of some initial sets, artifical blocks and
1525   /// RPOT block ordering.
1526   void initialSetup(MachineFunction &MF);
1527 
1528   bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override;
1529 
1530 public:
1531   /// Default construct and initialize the pass.
1532   InstrRefBasedLDV();
1533 
1534   LLVM_DUMP_METHOD
1535   void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1536 
1537   bool isCalleeSaved(LocIdx L) {
1538     unsigned Reg = MTracker->LocIdxToLocID[L];
1539     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1540       if (CalleeSavedRegs.test(*RAI))
1541         return true;
1542     return false;
1543   }
1544 };
1545 
1546 } // end anonymous namespace
1547 
1548 //===----------------------------------------------------------------------===//
1549 //            Implementation
1550 //===----------------------------------------------------------------------===//
1551 
1552 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
1553 
1554 /// Default construct and initialize the pass.
1555 InstrRefBasedLDV::InstrRefBasedLDV() {}
1556 
1557 //===----------------------------------------------------------------------===//
1558 //            Debug Range Extension Implementation
1559 //===----------------------------------------------------------------------===//
1560 
1561 #ifndef NDEBUG
1562 // Something to restore in the future.
1563 // void InstrRefBasedLDV::printVarLocInMBB(..)
1564 #endif
1565 
1566 SpillLoc
1567 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1568   assert(MI.hasOneMemOperand() &&
1569          "Spill instruction does not have exactly one memory operand?");
1570   auto MMOI = MI.memoperands_begin();
1571   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1572   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1573          "Inconsistent memory operand in spill instruction");
1574   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1575   const MachineBasicBlock *MBB = MI.getParent();
1576   Register Reg;
1577   int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1578   return {Reg, Offset};
1579 }
1580 
1581 /// End all previous ranges related to @MI and start a new range from @MI
1582 /// if it is a DBG_VALUE instr.
1583 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1584   if (!MI.isDebugValue())
1585     return false;
1586 
1587   const DILocalVariable *Var = MI.getDebugVariable();
1588   const DIExpression *Expr = MI.getDebugExpression();
1589   const DILocation *DebugLoc = MI.getDebugLoc();
1590   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1591   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1592          "Expected inlined-at fields to agree");
1593 
1594   DebugVariable V(Var, Expr, InlinedAt);
1595   DbgValueProperties Properties(MI);
1596 
1597   // If there are no instructions in this lexical scope, do no location tracking
1598   // at all, this variable shouldn't get a legitimate location range.
1599   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1600   if (Scope == nullptr)
1601     return true; // handled it; by doing nothing
1602 
1603   const MachineOperand &MO = MI.getOperand(0);
1604 
1605   // MLocTracker needs to know that this register is read, even if it's only
1606   // read by a debug inst.
1607   if (MO.isReg() && MO.getReg() != 0)
1608     (void)MTracker->readReg(MO.getReg());
1609 
1610   // If we're preparing for the second analysis (variables), the machine value
1611   // locations are already solved, and we report this DBG_VALUE and the value
1612   // it refers to to VLocTracker.
1613   if (VTracker) {
1614     if (MO.isReg()) {
1615       // Feed defVar the new variable location, or if this is a
1616       // DBG_VALUE $noreg, feed defVar None.
1617       if (MO.getReg())
1618         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1619       else
1620         VTracker->defVar(MI, Properties, None);
1621     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1622                MI.getOperand(0).isCImm()) {
1623       VTracker->defVar(MI, MI.getOperand(0));
1624     }
1625   }
1626 
1627   // If performing final tracking of transfers, report this variable definition
1628   // to the TransferTracker too.
1629   if (TTracker)
1630     TTracker->redefVar(MI);
1631   return true;
1632 }
1633 
1634 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI) {
1635   if (!MI.isDebugRef())
1636     return false;
1637 
1638   // Only handle this instruction when we are building the variable value
1639   // transfer function.
1640   if (!VTracker)
1641     return false;
1642 
1643   unsigned InstNo = MI.getOperand(0).getImm();
1644   unsigned OpNo = MI.getOperand(1).getImm();
1645 
1646   const DILocalVariable *Var = MI.getDebugVariable();
1647   const DIExpression *Expr = MI.getDebugExpression();
1648   const DILocation *DebugLoc = MI.getDebugLoc();
1649   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1650   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1651          "Expected inlined-at fields to agree");
1652 
1653   DebugVariable V(Var, Expr, InlinedAt);
1654 
1655   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1656   if (Scope == nullptr)
1657     return true; // Handled by doing nothing. This variable is never in scope.
1658 
1659   const MachineFunction &MF = *MI.getParent()->getParent();
1660 
1661   // Various optimizations may have happened to the value during codegen,
1662   // recorded in the value substitution table. Apply any substitutions to
1663   // the instruction / operand number in this DBG_INSTR_REF.
1664   auto Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo));
1665   while (Sub != MF.DebugValueSubstitutions.end()) {
1666     InstNo = Sub->second.first;
1667     OpNo = Sub->second.second;
1668     Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo));
1669   }
1670 
1671   // Default machine value number is <None> -- if no instruction defines
1672   // the corresponding value, it must have been optimized out.
1673   Optional<ValueIDNum> NewID = None;
1674 
1675   // Try to lookup the instruction number, and find the machine value number
1676   // that it defines.
1677   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1678   if (InstrIt != DebugInstrNumToInstr.end()) {
1679     const MachineInstr &TargetInstr = *InstrIt->second.first;
1680     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1681 
1682     // Pick out the designated operand.
1683     assert(OpNo < TargetInstr.getNumOperands());
1684     const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1685 
1686     // Today, this can only be a register.
1687     assert(MO.isReg() && MO.isDef());
1688 
1689     unsigned LocID = MTracker->getLocID(MO.getReg(), false);
1690     LocIdx L = MTracker->LocIDToLocIdx[LocID];
1691     NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1692   }
1693 
1694   // We, we have a value number or None. Tell the variable value tracker about
1695   // it. The rest of this LiveDebugValues implementation acts exactly the same
1696   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1697   // aren't immediately available).
1698   DbgValueProperties Properties(Expr, false);
1699   VTracker->defVar(MI, Properties, NewID);
1700 
1701   // If we're on the final pass through the function, decompose this INSTR_REF
1702   // into a plain DBG_VALUE.
1703   if (!TTracker)
1704     return true;
1705 
1706   // Pick a location for the machine value number, if such a location exists.
1707   // (This information could be stored in TransferTracker to make it faster).
1708   Optional<LocIdx> FoundLoc = None;
1709   for (auto Location : MTracker->locations()) {
1710     LocIdx CurL = Location.Idx;
1711     ValueIDNum ID = MTracker->LocIdxToIDNum[CurL];
1712     if (NewID && ID == NewID) {
1713       // If this is the first location with that value, pick it. Otherwise,
1714       // consider whether it's a "longer term" location.
1715       if (!FoundLoc) {
1716         FoundLoc = CurL;
1717         continue;
1718       }
1719 
1720       if (MTracker->isSpill(CurL))
1721         FoundLoc = CurL; // Spills are a longer term location.
1722       else if (!MTracker->isSpill(*FoundLoc) &&
1723                !MTracker->isSpill(CurL) &&
1724                !isCalleeSaved(*FoundLoc) &&
1725                isCalleeSaved(CurL))
1726         FoundLoc = CurL; // Callee saved regs are longer term than normal.
1727     }
1728   }
1729 
1730   // Tell transfer tracker that the variable value has changed.
1731   TTracker->redefVar(MI, Properties, FoundLoc);
1732 
1733   // If there was a value with no location; but the value is defined in a
1734   // later instruction in this block, this is a block-local use-before-def.
1735   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1736       NewID->getInst() > CurInst)
1737     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1738 
1739   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1740   // This DBG_VALUE is potentially a $noreg / undefined location, if
1741   // FoundLoc is None.
1742   // (XXX -- could morph the DBG_INSTR_REF in the future).
1743   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1744   TTracker->PendingDbgValues.push_back(DbgMI);
1745   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1746 
1747   return true;
1748 }
1749 
1750 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1751   // Meta Instructions do not affect the debug liveness of any register they
1752   // define.
1753   if (MI.isImplicitDef()) {
1754     // Except when there's an implicit def, and the location it's defining has
1755     // no value number. The whole point of an implicit def is to announce that
1756     // the register is live, without be specific about it's value. So define
1757     // a value if there isn't one already.
1758     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1759     // Has a legitimate value -> ignore the implicit def.
1760     if (Num.getLoc() != 0)
1761       return;
1762     // Otherwise, def it here.
1763   } else if (MI.isMetaInstruction())
1764     return;
1765 
1766   MachineFunction *MF = MI.getMF();
1767   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1768   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1769 
1770   // Find the regs killed by MI, and find regmasks of preserved regs.
1771   // Max out the number of statically allocated elements in `DeadRegs`, as this
1772   // prevents fallback to std::set::count() operations.
1773   SmallSet<uint32_t, 32> DeadRegs;
1774   SmallVector<const uint32_t *, 4> RegMasks;
1775   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1776   for (const MachineOperand &MO : MI.operands()) {
1777     // Determine whether the operand is a register def.
1778     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1779         Register::isPhysicalRegister(MO.getReg()) &&
1780         !(MI.isCall() && MO.getReg() == SP)) {
1781       // Remove ranges of all aliased registers.
1782       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1783         // FIXME: Can we break out of this loop early if no insertion occurs?
1784         DeadRegs.insert(*RAI);
1785     } else if (MO.isRegMask()) {
1786       RegMasks.push_back(MO.getRegMask());
1787       RegMaskPtrs.push_back(&MO);
1788     }
1789   }
1790 
1791   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1792   for (uint32_t DeadReg : DeadRegs)
1793     MTracker->defReg(DeadReg, CurBB, CurInst);
1794 
1795   for (auto *MO : RegMaskPtrs)
1796     MTracker->writeRegMask(MO, CurBB, CurInst);
1797 }
1798 
1799 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1800   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1801 
1802   MTracker->setReg(DstRegNum, SrcValue);
1803 
1804   // In all circumstances, re-def the super registers. It's definitely a new
1805   // value now. This doesn't uniquely identify the composition of subregs, for
1806   // example, two identical values in subregisters composed in different
1807   // places would not get equal value numbers.
1808   for (MCSuperRegIterator SRI(DstRegNum, TRI); SRI.isValid(); ++SRI)
1809     MTracker->defReg(*SRI, CurBB, CurInst);
1810 
1811   // If we're emulating VarLocBasedImpl, just define all the subregisters.
1812   // DBG_VALUEs of them will expect to be tracked from the DBG_VALUE, not
1813   // through prior copies.
1814   if (EmulateOldLDV) {
1815     for (MCSubRegIndexIterator DRI(DstRegNum, TRI); DRI.isValid(); ++DRI)
1816       MTracker->defReg(DRI.getSubReg(), CurBB, CurInst);
1817     return;
1818   }
1819 
1820   // Otherwise, actually copy subregisters from one location to another.
1821   // XXX: in addition, any subregisters of DstRegNum that don't line up with
1822   // the source register should be def'd.
1823   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1824     unsigned SrcSubReg = SRI.getSubReg();
1825     unsigned SubRegIdx = SRI.getSubRegIndex();
1826     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1827     if (!DstSubReg)
1828       continue;
1829 
1830     // Do copy. There are two matching subregisters, the source value should
1831     // have been def'd when the super-reg was, the latter might not be tracked
1832     // yet.
1833     // This will force SrcSubReg to be tracked, if it isn't yet.
1834     (void)MTracker->readReg(SrcSubReg);
1835     LocIdx SrcL = MTracker->getRegMLoc(SrcSubReg);
1836     assert(SrcL.asU64());
1837     (void)MTracker->readReg(DstSubReg);
1838     LocIdx DstL = MTracker->getRegMLoc(DstSubReg);
1839     assert(DstL.asU64());
1840     (void)DstL;
1841     ValueIDNum CpyValue = {SrcValue.getBlock(), SrcValue.getInst(), SrcL};
1842 
1843     MTracker->setReg(DstSubReg, CpyValue);
1844   }
1845 }
1846 
1847 bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1848                                           MachineFunction *MF) {
1849   // TODO: Handle multiple stores folded into one.
1850   if (!MI.hasOneMemOperand())
1851     return false;
1852 
1853   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1854     return false; // This is not a spill instruction, since no valid size was
1855                   // returned from either function.
1856 
1857   return true;
1858 }
1859 
1860 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1861                                        MachineFunction *MF, unsigned &Reg) {
1862   if (!isSpillInstruction(MI, MF))
1863     return false;
1864 
1865   // XXX FIXME: On x86, isStoreToStackSlotPostFE returns '1' instead of an
1866   // actual register number.
1867   if (ObserveAllStackops) {
1868     int FI;
1869     Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1870     return Reg != 0;
1871   }
1872 
1873   auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
1874     if (!MO.isReg() || !MO.isUse()) {
1875       Reg = 0;
1876       return false;
1877     }
1878     Reg = MO.getReg();
1879     return MO.isKill();
1880   };
1881 
1882   for (const MachineOperand &MO : MI.operands()) {
1883     // In a spill instruction generated by the InlineSpiller the spilled
1884     // register has its kill flag set.
1885     if (isKilledReg(MO, Reg))
1886       return true;
1887     if (Reg != 0) {
1888       // Check whether next instruction kills the spilled register.
1889       // FIXME: Current solution does not cover search for killed register in
1890       // bundles and instructions further down the chain.
1891       auto NextI = std::next(MI.getIterator());
1892       // Skip next instruction that points to basic block end iterator.
1893       if (MI.getParent()->end() == NextI)
1894         continue;
1895       unsigned RegNext;
1896       for (const MachineOperand &MONext : NextI->operands()) {
1897         // Return true if we came across the register from the
1898         // previous spill instruction that is killed in NextI.
1899         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1900           return true;
1901       }
1902     }
1903   }
1904   // Return false if we didn't find spilled register.
1905   return false;
1906 }
1907 
1908 Optional<SpillLoc>
1909 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1910                                        MachineFunction *MF, unsigned &Reg) {
1911   if (!MI.hasOneMemOperand())
1912     return None;
1913 
1914   // FIXME: Handle folded restore instructions with more than one memory
1915   // operand.
1916   if (MI.getRestoreSize(TII)) {
1917     Reg = MI.getOperand(0).getReg();
1918     return extractSpillBaseRegAndOffset(MI);
1919   }
1920   return None;
1921 }
1922 
1923 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1924   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1925   // limitations under the new model. Therefore, when comparing them, compare
1926   // versions that don't attempt spills or restores at all.
1927   if (EmulateOldLDV)
1928     return false;
1929 
1930   MachineFunction *MF = MI.getMF();
1931   unsigned Reg;
1932   Optional<SpillLoc> Loc;
1933 
1934   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1935 
1936   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1937   // written to, terminate that variable location. The value in memory
1938   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
1939   if (isSpillInstruction(MI, MF)) {
1940     Loc = extractSpillBaseRegAndOffset(MI);
1941 
1942     if (TTracker) {
1943       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(*Loc);
1944       if (MLoc)
1945         TTracker->clobberMloc(*MLoc, MI.getIterator());
1946     }
1947   }
1948 
1949   // Try to recognise spill and restore instructions that may transfer a value.
1950   if (isLocationSpill(MI, MF, Reg)) {
1951     Loc = extractSpillBaseRegAndOffset(MI);
1952     auto ValueID = MTracker->readReg(Reg);
1953 
1954     // If the location is empty, produce a phi, signify it's the live-in value.
1955     if (ValueID.getLoc() == 0)
1956       ValueID = {CurBB, 0, MTracker->getRegMLoc(Reg)};
1957 
1958     MTracker->setSpill(*Loc, ValueID);
1959     auto OptSpillLocIdx = MTracker->getSpillMLoc(*Loc);
1960     assert(OptSpillLocIdx && "Spill slot set but has no LocIdx?");
1961     LocIdx SpillLocIdx = *OptSpillLocIdx;
1962 
1963     // Tell TransferTracker about this spill, produce DBG_VALUEs for it.
1964     if (TTracker)
1965       TTracker->transferMlocs(MTracker->getRegMLoc(Reg), SpillLocIdx,
1966                               MI.getIterator());
1967 
1968     // VarLocBasedImpl would, at this point, stop tracking the source
1969     // register of the store.
1970     if (EmulateOldLDV) {
1971       for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1972         MTracker->defReg(*RAI, CurBB, CurInst);
1973     }
1974   } else {
1975     if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1976       return false;
1977 
1978     // Is there a value to be restored?
1979     auto OptValueID = MTracker->readSpill(*Loc);
1980     if (OptValueID) {
1981       ValueIDNum ValueID = *OptValueID;
1982       LocIdx SpillLocIdx = *MTracker->getSpillMLoc(*Loc);
1983       // XXX -- can we recover sub-registers of this value? Until we can, first
1984       // overwrite all defs of the register being restored to.
1985       for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1986         MTracker->defReg(*RAI, CurBB, CurInst);
1987 
1988       // Now override the reg we're restoring to.
1989       MTracker->setReg(Reg, ValueID);
1990 
1991       // Report this restore to the transfer tracker too.
1992       if (TTracker)
1993         TTracker->transferMlocs(SpillLocIdx, MTracker->getRegMLoc(Reg),
1994                                 MI.getIterator());
1995     } else {
1996       // There isn't anything in the location; not clear if this is a code path
1997       // that still runs. Def this register anyway just in case.
1998       for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1999         MTracker->defReg(*RAI, CurBB, CurInst);
2000 
2001       // Force the spill slot to be tracked.
2002       LocIdx L = MTracker->getOrTrackSpillLoc(*Loc);
2003 
2004       // Set the restored value to be a machine phi number, signifying that it's
2005       // whatever the spills live-in value is in this block. Definitely has
2006       // a LocIdx due to the setSpill above.
2007       ValueIDNum ValueID = {CurBB, 0, L};
2008       MTracker->setReg(Reg, ValueID);
2009       MTracker->setSpill(*Loc, ValueID);
2010     }
2011   }
2012   return true;
2013 }
2014 
2015 bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2016   auto DestSrc = TII->isCopyInstr(MI);
2017   if (!DestSrc)
2018     return false;
2019 
2020   const MachineOperand *DestRegOp = DestSrc->Destination;
2021   const MachineOperand *SrcRegOp = DestSrc->Source;
2022 
2023   auto isCalleeSavedReg = [&](unsigned Reg) {
2024     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2025       if (CalleeSavedRegs.test(*RAI))
2026         return true;
2027     return false;
2028   };
2029 
2030   Register SrcReg = SrcRegOp->getReg();
2031   Register DestReg = DestRegOp->getReg();
2032 
2033   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2034   if (SrcReg == DestReg)
2035     return true;
2036 
2037   // For emulating VarLocBasedImpl:
2038   // We want to recognize instructions where destination register is callee
2039   // saved register. If register that could be clobbered by the call is
2040   // included, there would be a great chance that it is going to be clobbered
2041   // soon. It is more likely that previous register, which is callee saved, is
2042   // going to stay unclobbered longer, even if it is killed.
2043   //
2044   // For InstrRefBasedImpl, we can track multiple locations per value, so
2045   // ignore this condition.
2046   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
2047     return false;
2048 
2049   // InstrRefBasedImpl only followed killing copies.
2050   if (EmulateOldLDV && !SrcRegOp->isKill())
2051     return false;
2052 
2053   // Copy MTracker info, including subregs if available.
2054   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
2055 
2056   // Only produce a transfer of DBG_VALUE within a block where old LDV
2057   // would have. We might make use of the additional value tracking in some
2058   // other way, later.
2059   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
2060     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
2061                             MTracker->getRegMLoc(DestReg), MI.getIterator());
2062 
2063   // VarLocBasedImpl would quit tracking the old location after copying.
2064   if (EmulateOldLDV && SrcReg != DestReg)
2065     MTracker->defReg(SrcReg, CurBB, CurInst);
2066 
2067   return true;
2068 }
2069 
2070 /// Accumulate a mapping between each DILocalVariable fragment and other
2071 /// fragments of that DILocalVariable which overlap. This reduces work during
2072 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
2073 /// known-to-overlap fragments are present".
2074 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
2075 ///           fragment usage.
2076 void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2077   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2078                       MI.getDebugLoc()->getInlinedAt());
2079   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2080 
2081   // If this is the first sighting of this variable, then we are guaranteed
2082   // there are currently no overlapping fragments either. Initialize the set
2083   // of seen fragments, record no overlaps for the current one, and return.
2084   auto SeenIt = SeenFragments.find(MIVar.getVariable());
2085   if (SeenIt == SeenFragments.end()) {
2086     SmallSet<FragmentInfo, 4> OneFragment;
2087     OneFragment.insert(ThisFragment);
2088     SeenFragments.insert({MIVar.getVariable(), OneFragment});
2089 
2090     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2091     return;
2092   }
2093 
2094   // If this particular Variable/Fragment pair already exists in the overlap
2095   // map, it has already been accounted for.
2096   auto IsInOLapMap =
2097       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2098   if (!IsInOLapMap.second)
2099     return;
2100 
2101   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2102   auto &AllSeenFragments = SeenIt->second;
2103 
2104   // Otherwise, examine all other seen fragments for this variable, with "this"
2105   // fragment being a previously unseen fragment. Record any pair of
2106   // overlapping fragments.
2107   for (auto &ASeenFragment : AllSeenFragments) {
2108     // Does this previously seen fragment overlap?
2109     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
2110       // Yes: Mark the current fragment as being overlapped.
2111       ThisFragmentsOverlaps.push_back(ASeenFragment);
2112       // Mark the previously seen fragment as being overlapped by the current
2113       // one.
2114       auto ASeenFragmentsOverlaps =
2115           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
2116       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2117              "Previously seen var fragment has no vector of overlaps");
2118       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
2119     }
2120   }
2121 
2122   AllSeenFragments.insert(ThisFragment);
2123 }
2124 
2125 void InstrRefBasedLDV::process(MachineInstr &MI) {
2126   // Try to interpret an MI as a debug or transfer instruction. Only if it's
2127   // none of these should we interpret it's register defs as new value
2128   // definitions.
2129   if (transferDebugValue(MI))
2130     return;
2131   if (transferDebugInstrRef(MI))
2132     return;
2133   if (transferRegisterCopy(MI))
2134     return;
2135   if (transferSpillOrRestoreInst(MI))
2136     return;
2137   transferRegisterDef(MI);
2138 }
2139 
2140 void InstrRefBasedLDV::produceMLocTransferFunction(
2141     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2142     unsigned MaxNumBlocks) {
2143   // Because we try to optimize around register mask operands by ignoring regs
2144   // that aren't currently tracked, we set up something ugly for later: RegMask
2145   // operands that are seen earlier than the first use of a register, still need
2146   // to clobber that register in the transfer function. But this information
2147   // isn't actively recorded. Instead, we track each RegMask used in each block,
2148   // and accumulated the clobbered but untracked registers in each block into
2149   // the following bitvector. Later, if new values are tracked, we can add
2150   // appropriate clobbers.
2151   SmallVector<BitVector, 32> BlockMasks;
2152   BlockMasks.resize(MaxNumBlocks);
2153 
2154   // Reserve one bit per register for the masks described above.
2155   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
2156   for (auto &BV : BlockMasks)
2157     BV.resize(TRI->getNumRegs(), true);
2158 
2159   // Step through all instructions and inhale the transfer function.
2160   for (auto &MBB : MF) {
2161     // Object fields that are read by trackers to know where we are in the
2162     // function.
2163     CurBB = MBB.getNumber();
2164     CurInst = 1;
2165 
2166     // Set all machine locations to a PHI value. For transfer function
2167     // production only, this signifies the live-in value to the block.
2168     MTracker->reset();
2169     MTracker->setMPhis(CurBB);
2170 
2171     // Step through each instruction in this block.
2172     for (auto &MI : MBB) {
2173       process(MI);
2174       // Also accumulate fragment map.
2175       if (MI.isDebugValue())
2176         accumulateFragmentMap(MI);
2177 
2178       // Create a map from the instruction number (if present) to the
2179       // MachineInstr and its position.
2180       if (MI.peekDebugInstrNum()) {
2181         uint64_t InstrNo = MI.peekDebugInstrNum();
2182         auto InstrAndPos = std::make_pair(&MI, CurInst);
2183         auto InsertResult =
2184             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
2185 
2186         // There should never be duplicate instruction numbers.
2187         assert(InsertResult.second);
2188         (void)InsertResult;
2189       }
2190 
2191       ++CurInst;
2192     }
2193 
2194     // Produce the transfer function, a map of machine location to new value. If
2195     // any machine location has the live-in phi value from the start of the
2196     // block, it's live-through and doesn't need recording in the transfer
2197     // function.
2198     for (auto Location : MTracker->locations()) {
2199       LocIdx Idx = Location.Idx;
2200       ValueIDNum &P = Location.Value;
2201       if (P.isPHI() && P.getLoc() == Idx.asU64())
2202         continue;
2203 
2204       // Insert-or-update.
2205       auto &TransferMap = MLocTransfer[CurBB];
2206       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
2207       if (!Result.second)
2208         Result.first->second = P;
2209     }
2210 
2211     // Accumulate any bitmask operands into the clobberred reg mask for this
2212     // block.
2213     for (auto &P : MTracker->Masks) {
2214       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
2215     }
2216   }
2217 
2218   // Compute a bitvector of all the registers that are tracked in this block.
2219   const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2220   Register SP = TLI->getStackPointerRegisterToSaveRestore();
2221   BitVector UsedRegs(TRI->getNumRegs());
2222   for (auto Location : MTracker->locations()) {
2223     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2224     if (ID >= TRI->getNumRegs() || ID == SP)
2225       continue;
2226     UsedRegs.set(ID);
2227   }
2228 
2229   // Check that any regmask-clobber of a register that gets tracked, is not
2230   // live-through in the transfer function. It needs to be clobbered at the
2231   // very least.
2232   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2233     BitVector &BV = BlockMasks[I];
2234     BV.flip();
2235     BV &= UsedRegs;
2236     // This produces all the bits that we clobber, but also use. Check that
2237     // they're all clobbered or at least set in the designated transfer
2238     // elem.
2239     for (unsigned Bit : BV.set_bits()) {
2240       unsigned ID = MTracker->getLocID(Bit, false);
2241       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2242       auto &TransferMap = MLocTransfer[I];
2243 
2244       // Install a value representing the fact that this location is effectively
2245       // written to in this block. As there's no reserved value, instead use
2246       // a value number that is never generated. Pick the value number for the
2247       // first instruction in the block, def'ing this location, which we know
2248       // this block never used anyway.
2249       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2250       auto Result =
2251         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
2252       if (!Result.second) {
2253         ValueIDNum &ValueID = Result.first->second;
2254         if (ValueID.getBlock() == I && ValueID.isPHI())
2255           // It was left as live-through. Set it to clobbered.
2256           ValueID = NotGeneratedNum;
2257       }
2258     }
2259   }
2260 }
2261 
2262 std::tuple<bool, bool>
2263 InstrRefBasedLDV::mlocJoin(MachineBasicBlock &MBB,
2264                            SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
2265                            ValueIDNum **OutLocs, ValueIDNum *InLocs) {
2266   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2267   bool Changed = false;
2268   bool DowngradeOccurred = false;
2269 
2270   // Collect predecessors that have been visited. Anything that hasn't been
2271   // visited yet is a backedge on the first iteration, and the meet of it's
2272   // lattice value for all locations will be unaffected.
2273   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
2274   for (auto Pred : MBB.predecessors()) {
2275     if (Visited.count(Pred)) {
2276       BlockOrders.push_back(Pred);
2277     }
2278   }
2279 
2280   // Visit predecessors in RPOT order.
2281   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2282     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2283   };
2284   llvm::sort(BlockOrders.begin(), BlockOrders.end(), Cmp);
2285 
2286   // Skip entry block.
2287   if (BlockOrders.size() == 0)
2288     return std::tuple<bool, bool>(false, false);
2289 
2290   // Step through all machine locations, then look at each predecessor and
2291   // detect disagreements.
2292   unsigned ThisBlockRPO = BBToOrder.find(&MBB)->second;
2293   for (auto Location : MTracker->locations()) {
2294     LocIdx Idx = Location.Idx;
2295     // Pick out the first predecessors live-out value for this location. It's
2296     // guaranteed to be not a backedge, as we order by RPO.
2297     ValueIDNum BaseVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
2298 
2299     // Some flags for whether there's a disagreement, and whether it's a
2300     // disagreement with a backedge or not.
2301     bool Disagree = false;
2302     bool NonBackEdgeDisagree = false;
2303 
2304     // Loop around everything that wasn't 'base'.
2305     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2306       auto *MBB = BlockOrders[I];
2307       if (BaseVal != OutLocs[MBB->getNumber()][Idx.asU64()]) {
2308         // Live-out of a predecessor disagrees with the first predecessor.
2309         Disagree = true;
2310 
2311         // Test whether it's a disagreemnt in the backedges or not.
2312         if (BBToOrder.find(MBB)->second < ThisBlockRPO) // might be self b/e
2313           NonBackEdgeDisagree = true;
2314       }
2315     }
2316 
2317     bool OverRide = false;
2318     if (Disagree && !NonBackEdgeDisagree) {
2319       // Only the backedges disagree. Consider demoting the livein
2320       // lattice value, as per the file level comment. The value we consider
2321       // demoting to is the value that the non-backedge predecessors agree on.
2322       // The order of values is that non-PHIs are \top, a PHI at this block
2323       // \bot, and phis between the two are ordered by their RPO number.
2324       // If there's no agreement, or we've already demoted to this PHI value
2325       // before, replace with a PHI value at this block.
2326 
2327       // Calculate order numbers: zero means normal def, nonzero means RPO
2328       // number.
2329       unsigned BaseBlockRPONum = BBNumToRPO[BaseVal.getBlock()] + 1;
2330       if (!BaseVal.isPHI())
2331         BaseBlockRPONum = 0;
2332 
2333       ValueIDNum &InLocID = InLocs[Idx.asU64()];
2334       unsigned InLocRPONum = BBNumToRPO[InLocID.getBlock()] + 1;
2335       if (!InLocID.isPHI())
2336         InLocRPONum = 0;
2337 
2338       // Should we ignore the disagreeing backedges, and override with the
2339       // value the other predecessors agree on (in "base")?
2340       unsigned ThisBlockRPONum = BBNumToRPO[MBB.getNumber()] + 1;
2341       if (BaseBlockRPONum > InLocRPONum && BaseBlockRPONum < ThisBlockRPONum) {
2342         // Override.
2343         OverRide = true;
2344         DowngradeOccurred = true;
2345       }
2346     }
2347     // else: if we disagree in the non-backedges, then this is definitely
2348     // a control flow merge where different values merge. Make it a PHI.
2349 
2350     // Generate a phi...
2351     ValueIDNum PHI = {(uint64_t)MBB.getNumber(), 0, Idx};
2352     ValueIDNum NewVal = (Disagree && !OverRide) ? PHI : BaseVal;
2353     if (InLocs[Idx.asU64()] != NewVal) {
2354       Changed |= true;
2355       InLocs[Idx.asU64()] = NewVal;
2356     }
2357   }
2358 
2359   // Uhhhhhh, reimplement NumInserted and NumRemoved pls.
2360   return std::tuple<bool, bool>(Changed, DowngradeOccurred);
2361 }
2362 
2363 void InstrRefBasedLDV::mlocDataflow(
2364     ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
2365     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2366   std::priority_queue<unsigned int, std::vector<unsigned int>,
2367                       std::greater<unsigned int>>
2368       Worklist, Pending;
2369 
2370   // We track what is on the current and pending worklist to avoid inserting
2371   // the same thing twice. We could avoid this with a custom priority queue,
2372   // but this is probably not worth it.
2373   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2374 
2375   // Initialize worklist with every block to be visited.
2376   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2377     Worklist.push(I);
2378     OnWorklist.insert(OrderToBB[I]);
2379   }
2380 
2381   MTracker->reset();
2382 
2383   // Set inlocs for entry block -- each as a PHI at the entry block. Represents
2384   // the incoming value to the function.
2385   MTracker->setMPhis(0);
2386   for (auto Location : MTracker->locations())
2387     MInLocs[0][Location.Idx.asU64()] = Location.Value;
2388 
2389   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2390   while (!Worklist.empty() || !Pending.empty()) {
2391     // Vector for storing the evaluated block transfer function.
2392     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2393 
2394     while (!Worklist.empty()) {
2395       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2396       CurBB = MBB->getNumber();
2397       Worklist.pop();
2398 
2399       // Join the values in all predecessor blocks.
2400       bool InLocsChanged, DowngradeOccurred;
2401       std::tie(InLocsChanged, DowngradeOccurred) =
2402           mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2403       InLocsChanged |= Visited.insert(MBB).second;
2404 
2405       // If a downgrade occurred, book us in for re-examination on the next
2406       // iteration.
2407       if (DowngradeOccurred && OnPending.insert(MBB).second)
2408         Pending.push(BBToOrder[MBB]);
2409 
2410       // Don't examine transfer function if we've visited this loc at least
2411       // once, and inlocs haven't changed.
2412       if (!InLocsChanged)
2413         continue;
2414 
2415       // Load the current set of live-ins into MLocTracker.
2416       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2417 
2418       // Each element of the transfer function can be a new def, or a read of
2419       // a live-in value. Evaluate each element, and store to "ToRemap".
2420       ToRemap.clear();
2421       for (auto &P : MLocTransfer[CurBB]) {
2422         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2423           // This is a movement of whatever was live in. Read it.
2424           ValueIDNum NewID = MTracker->getNumAtPos(P.second.getLoc());
2425           ToRemap.push_back(std::make_pair(P.first, NewID));
2426         } else {
2427           // It's a def. Just set it.
2428           assert(P.second.getBlock() == CurBB);
2429           ToRemap.push_back(std::make_pair(P.first, P.second));
2430         }
2431       }
2432 
2433       // Commit the transfer function changes into mloc tracker, which
2434       // transforms the contents of the MLocTracker into the live-outs.
2435       for (auto &P : ToRemap)
2436         MTracker->setMLoc(P.first, P.second);
2437 
2438       // Now copy out-locs from mloc tracker into out-loc vector, checking
2439       // whether changes have occurred. These changes can have come from both
2440       // the transfer function, and mlocJoin.
2441       bool OLChanged = false;
2442       for (auto Location : MTracker->locations()) {
2443         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2444         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2445       }
2446 
2447       MTracker->reset();
2448 
2449       // No need to examine successors again if out-locs didn't change.
2450       if (!OLChanged)
2451         continue;
2452 
2453       // All successors should be visited: put any back-edges on the pending
2454       // list for the next dataflow iteration, and any other successors to be
2455       // visited this iteration, if they're not going to be already.
2456       for (auto s : MBB->successors()) {
2457         // Does branching to this successor represent a back-edge?
2458         if (BBToOrder[s] > BBToOrder[MBB]) {
2459           // No: visit it during this dataflow iteration.
2460           if (OnWorklist.insert(s).second)
2461             Worklist.push(BBToOrder[s]);
2462         } else {
2463           // Yes: visit it on the next iteration.
2464           if (OnPending.insert(s).second)
2465             Pending.push(BBToOrder[s]);
2466         }
2467       }
2468     }
2469 
2470     Worklist.swap(Pending);
2471     std::swap(OnPending, OnWorklist);
2472     OnPending.clear();
2473     // At this point, pending must be empty, since it was just the empty
2474     // worklist
2475     assert(Pending.empty() && "Pending should be empty");
2476   }
2477 
2478   // Once all the live-ins don't change on mlocJoin(), we've reached a
2479   // fixedpoint.
2480 }
2481 
2482 bool InstrRefBasedLDV::vlocDowngradeLattice(
2483     const MachineBasicBlock &MBB, const DbgValue &OldLiveInLocation,
2484     const SmallVectorImpl<InValueT> &Values, unsigned CurBlockRPONum) {
2485   // Ranking value preference: see file level comment, the highest rank is
2486   // a plain def, followed by PHI values in reverse post-order. Numerically,
2487   // we assign all defs the rank '0', all PHIs their blocks RPO number plus
2488   // one, and consider the lowest value the highest ranked.
2489   int OldLiveInRank = BBNumToRPO[OldLiveInLocation.ID.getBlock()] + 1;
2490   if (!OldLiveInLocation.ID.isPHI())
2491     OldLiveInRank = 0;
2492 
2493   // Allow any unresolvable conflict to be over-ridden.
2494   if (OldLiveInLocation.Kind == DbgValue::NoVal) {
2495     // Although if it was an unresolvable conflict from _this_ block, then
2496     // all other seeking of downgrades and PHIs must have failed before hand.
2497     if (OldLiveInLocation.BlockNo == (unsigned)MBB.getNumber())
2498       return false;
2499     OldLiveInRank = INT_MIN;
2500   }
2501 
2502   auto &InValue = *Values[0].second;
2503 
2504   if (InValue.Kind == DbgValue::Const || InValue.Kind == DbgValue::NoVal)
2505     return false;
2506 
2507   unsigned ThisRPO = BBNumToRPO[InValue.ID.getBlock()];
2508   int ThisRank = ThisRPO + 1;
2509   if (!InValue.ID.isPHI())
2510     ThisRank = 0;
2511 
2512   // Too far down the lattice?
2513   if (ThisRPO >= CurBlockRPONum)
2514     return false;
2515 
2516   // Higher in the lattice than what we've already explored?
2517   if (ThisRank <= OldLiveInRank)
2518     return false;
2519 
2520   return true;
2521 }
2522 
2523 std::tuple<Optional<ValueIDNum>, bool> InstrRefBasedLDV::pickVPHILoc(
2524     MachineBasicBlock &MBB, const DebugVariable &Var, const LiveIdxT &LiveOuts,
2525     ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2526     const SmallVectorImpl<MachineBasicBlock *> &BlockOrders) {
2527   // Collect a set of locations from predecessor where its live-out value can
2528   // be found.
2529   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2530   unsigned NumLocs = MTracker->getNumLocs();
2531   unsigned BackEdgesStart = 0;
2532 
2533   for (auto p : BlockOrders) {
2534     // Pick out where backedges start in the list of predecessors. Relies on
2535     // BlockOrders being sorted by RPO.
2536     if (BBToOrder[p] < BBToOrder[&MBB])
2537       ++BackEdgesStart;
2538 
2539     // For each predecessor, create a new set of locations.
2540     Locs.resize(Locs.size() + 1);
2541     unsigned ThisBBNum = p->getNumber();
2542     auto LiveOutMap = LiveOuts.find(p);
2543     if (LiveOutMap == LiveOuts.end())
2544       // This predecessor isn't in scope, it must have no live-in/live-out
2545       // locations.
2546       continue;
2547 
2548     auto It = LiveOutMap->second->find(Var);
2549     if (It == LiveOutMap->second->end())
2550       // There's no value recorded for this variable in this predecessor,
2551       // leave an empty set of locations.
2552       continue;
2553 
2554     const DbgValue &OutVal = It->second;
2555 
2556     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2557       // Consts and no-values cannot have locations we can join on.
2558       continue;
2559 
2560     assert(OutVal.Kind == DbgValue::Proposed || OutVal.Kind == DbgValue::Def);
2561     ValueIDNum ValToLookFor = OutVal.ID;
2562 
2563     // Search the live-outs of the predecessor for the specified value.
2564     for (unsigned int I = 0; I < NumLocs; ++I) {
2565       if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2566         Locs.back().push_back(LocIdx(I));
2567     }
2568   }
2569 
2570   // If there were no locations at all, return an empty result.
2571   if (Locs.empty())
2572     return std::tuple<Optional<ValueIDNum>, bool>(None, false);
2573 
2574   // Lambda for seeking a common location within a range of location-sets.
2575   typedef SmallVector<SmallVector<LocIdx, 4>, 8>::iterator LocsIt;
2576   auto SeekLocation =
2577       [&Locs](llvm::iterator_range<LocsIt> SearchRange) -> Optional<LocIdx> {
2578     // Starting with the first set of locations, take the intersection with
2579     // subsequent sets.
2580     SmallVector<LocIdx, 4> base = Locs[0];
2581     for (auto &S : SearchRange) {
2582       SmallVector<LocIdx, 4> new_base;
2583       std::set_intersection(base.begin(), base.end(), S.begin(), S.end(),
2584                             std::inserter(new_base, new_base.begin()));
2585       base = new_base;
2586     }
2587     if (base.empty())
2588       return None;
2589 
2590     // We now have a set of LocIdxes that contain the right output value in
2591     // each of the predecessors. Pick the lowest; if there's a register loc,
2592     // that'll be it.
2593     return *base.begin();
2594   };
2595 
2596   // Search for a common location for all predecessors. If we can't, then fall
2597   // back to only finding a common location between non-backedge predecessors.
2598   bool ValidForAllLocs = true;
2599   auto TheLoc = SeekLocation(Locs);
2600   if (!TheLoc) {
2601     ValidForAllLocs = false;
2602     TheLoc =
2603         SeekLocation(make_range(Locs.begin(), Locs.begin() + BackEdgesStart));
2604   }
2605 
2606   if (!TheLoc)
2607     return std::tuple<Optional<ValueIDNum>, bool>(None, false);
2608 
2609   // Return a PHI-value-number for the found location.
2610   LocIdx L = *TheLoc;
2611   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2612   return std::tuple<Optional<ValueIDNum>, bool>(PHIVal, ValidForAllLocs);
2613 }
2614 
2615 std::tuple<bool, bool> InstrRefBasedLDV::vlocJoin(
2616     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
2617     SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, unsigned BBNum,
2618     const SmallSet<DebugVariable, 4> &AllVars, ValueIDNum **MOutLocs,
2619     ValueIDNum **MInLocs,
2620     SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
2621     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2622     DenseMap<DebugVariable, DbgValue> &InLocsT) {
2623   bool DowngradeOccurred = false;
2624 
2625   // To emulate VarLocBasedImpl, process this block if it's not in scope but
2626   // _does_ assign a variable value. No live-ins for this scope are transferred
2627   // in though, so we can return immediately.
2628   if (InScopeBlocks.count(&MBB) == 0 && !ArtificialBlocks.count(&MBB)) {
2629     if (VLOCVisited)
2630       return std::tuple<bool, bool>(true, false);
2631     return std::tuple<bool, bool>(false, false);
2632   }
2633 
2634   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2635   bool Changed = false;
2636 
2637   // Find any live-ins computed in a prior iteration.
2638   auto ILSIt = VLOCInLocs.find(&MBB);
2639   assert(ILSIt != VLOCInLocs.end());
2640   auto &ILS = *ILSIt->second;
2641 
2642   // Order predecessors by RPOT order, for exploring them in that order.
2643   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2644   for (auto p : MBB.predecessors())
2645     BlockOrders.push_back(p);
2646 
2647   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2648     return BBToOrder[A] < BBToOrder[B];
2649   };
2650 
2651   llvm::sort(BlockOrders.begin(), BlockOrders.end(), Cmp);
2652 
2653   unsigned CurBlockRPONum = BBToOrder[&MBB];
2654 
2655   // Force a re-visit to loop heads in the first dataflow iteration.
2656   // FIXME: if we could "propose" Const values this wouldn't be needed,
2657   // because they'd need to be confirmed before being emitted.
2658   if (!BlockOrders.empty() &&
2659       BBToOrder[BlockOrders[BlockOrders.size() - 1]] >= CurBlockRPONum &&
2660       VLOCVisited)
2661     DowngradeOccurred = true;
2662 
2663   auto ConfirmValue = [&InLocsT](const DebugVariable &DV, DbgValue VR) {
2664     auto Result = InLocsT.insert(std::make_pair(DV, VR));
2665     (void)Result;
2666     assert(Result.second);
2667   };
2668 
2669   auto ConfirmNoVal = [&ConfirmValue, &MBB](const DebugVariable &Var, const DbgValueProperties &Properties) {
2670     DbgValue NoLocPHIVal(MBB.getNumber(), Properties, DbgValue::NoVal);
2671 
2672     ConfirmValue(Var, NoLocPHIVal);
2673   };
2674 
2675   // Attempt to join the values for each variable.
2676   for (auto &Var : AllVars) {
2677     // Collect all the DbgValues for this variable.
2678     SmallVector<InValueT, 8> Values;
2679     bool Bail = false;
2680     unsigned BackEdgesStart = 0;
2681     for (auto p : BlockOrders) {
2682       // If the predecessor isn't in scope / to be explored, we'll never be
2683       // able to join any locations.
2684       if (BlocksToExplore.find(p) == BlocksToExplore.end()) {
2685         Bail = true;
2686         break;
2687       }
2688 
2689       // Don't attempt to handle unvisited predecessors: they're implicitly
2690       // "unknown"s in the lattice.
2691       if (VLOCVisited && !VLOCVisited->count(p))
2692         continue;
2693 
2694       // If the predecessors OutLocs is absent, there's not much we can do.
2695       auto OL = VLOCOutLocs.find(p);
2696       if (OL == VLOCOutLocs.end()) {
2697         Bail = true;
2698         break;
2699       }
2700 
2701       // No live-out value for this predecessor also means we can't produce
2702       // a joined value.
2703       auto VIt = OL->second->find(Var);
2704       if (VIt == OL->second->end()) {
2705         Bail = true;
2706         break;
2707       }
2708 
2709       // Keep track of where back-edges begin in the Values vector. Relies on
2710       // BlockOrders being sorted by RPO.
2711       unsigned ThisBBRPONum = BBToOrder[p];
2712       if (ThisBBRPONum < CurBlockRPONum)
2713         ++BackEdgesStart;
2714 
2715       Values.push_back(std::make_pair(p, &VIt->second));
2716     }
2717 
2718     // If there were no values, or one of the predecessors couldn't have a
2719     // value, then give up immediately. It's not safe to produce a live-in
2720     // value.
2721     if (Bail || Values.size() == 0)
2722       continue;
2723 
2724     // Enumeration identifying the current state of the predecessors values.
2725     enum {
2726       Unset = 0,
2727       Agreed,       // All preds agree on the variable value.
2728       PropDisagree, // All preds agree, but the value kind is Proposed in some.
2729       BEDisagree,   // Only back-edges disagree on variable value.
2730       PHINeeded,    // Non-back-edge predecessors have conflicing values.
2731       NoSolution    // Conflicting Value metadata makes solution impossible.
2732     } OurState = Unset;
2733 
2734     // All (non-entry) blocks have at least one non-backedge predecessor.
2735     // Pick the variable value from the first of these, to compare against
2736     // all others.
2737     const DbgValue &FirstVal = *Values[0].second;
2738     const ValueIDNum &FirstID = FirstVal.ID;
2739 
2740     // Scan for variable values that can't be resolved: if they have different
2741     // DIExpressions, different indirectness, or are mixed constants /
2742     // non-constants.
2743     for (auto &V : Values) {
2744       if (V.second->Properties != FirstVal.Properties)
2745         OurState = NoSolution;
2746       if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
2747         OurState = NoSolution;
2748     }
2749 
2750     // Flags diagnosing _how_ the values disagree.
2751     bool NonBackEdgeDisagree = false;
2752     bool DisagreeOnPHINess = false;
2753     bool IDDisagree = false;
2754     bool Disagree = false;
2755     if (OurState == Unset) {
2756       for (auto &V : Values) {
2757         if (*V.second == FirstVal)
2758           continue; // No disagreement.
2759 
2760         Disagree = true;
2761 
2762         // Flag whether the value number actually diagrees.
2763         if (V.second->ID != FirstID)
2764           IDDisagree = true;
2765 
2766         // Distinguish whether disagreement happens in backedges or not.
2767         // Relies on Values (and BlockOrders) being sorted by RPO.
2768         unsigned ThisBBRPONum = BBToOrder[V.first];
2769         if (ThisBBRPONum < CurBlockRPONum)
2770           NonBackEdgeDisagree = true;
2771 
2772         // Is there a difference in whether the value is definite or only
2773         // proposed?
2774         if (V.second->Kind != FirstVal.Kind &&
2775             (V.second->Kind == DbgValue::Proposed ||
2776              V.second->Kind == DbgValue::Def) &&
2777             (FirstVal.Kind == DbgValue::Proposed ||
2778              FirstVal.Kind == DbgValue::Def))
2779           DisagreeOnPHINess = true;
2780       }
2781 
2782       // Collect those flags together and determine an overall state for
2783       // what extend the predecessors agree on a live-in value.
2784       if (!Disagree)
2785         OurState = Agreed;
2786       else if (!IDDisagree && DisagreeOnPHINess)
2787         OurState = PropDisagree;
2788       else if (!NonBackEdgeDisagree)
2789         OurState = BEDisagree;
2790       else
2791         OurState = PHINeeded;
2792     }
2793 
2794     // An extra indicator: if we only disagree on whether the value is a
2795     // Def, or proposed, then also flag whether that disagreement happens
2796     // in backedges only.
2797     bool PropOnlyInBEs = Disagree && !IDDisagree && DisagreeOnPHINess &&
2798                          !NonBackEdgeDisagree && FirstVal.Kind == DbgValue::Def;
2799 
2800     const auto &Properties = FirstVal.Properties;
2801 
2802     auto OldLiveInIt = ILS.find(Var);
2803     const DbgValue *OldLiveInLocation =
2804         (OldLiveInIt != ILS.end()) ? &OldLiveInIt->second : nullptr;
2805 
2806     bool OverRide = false;
2807     if (OurState == BEDisagree && OldLiveInLocation) {
2808       // Only backedges disagree: we can consider downgrading. If there was a
2809       // previous live-in value, use it to work out whether the current
2810       // incoming value represents a lattice downgrade or not.
2811       OverRide =
2812           vlocDowngradeLattice(MBB, *OldLiveInLocation, Values, CurBlockRPONum);
2813     }
2814 
2815     // Use the current state of predecessor agreement and other flags to work
2816     // out what to do next. Possibilities include:
2817     //  * Accept a value all predecessors agree on, or accept one that
2818     //    represents a step down the exploration lattice,
2819     //  * Use a PHI value number, if one can be found,
2820     //  * Propose a PHI value number, and see if it gets confirmed later,
2821     //  * Emit a 'NoVal' value, indicating we couldn't resolve anything.
2822     if (OurState == Agreed) {
2823       // Easiest solution: all predecessors agree on the variable value.
2824       ConfirmValue(Var, FirstVal);
2825     } else if (OurState == BEDisagree && OverRide) {
2826       // Only backedges disagree, and the other predecessors have produced
2827       // a new live-in value further down the exploration lattice.
2828       DowngradeOccurred = true;
2829       ConfirmValue(Var, FirstVal);
2830     } else if (OurState == PropDisagree) {
2831       // Predecessors agree on value, but some say it's only a proposed value.
2832       // Propagate it as proposed: unless it was proposed in this block, in
2833       // which case we're able to confirm the value.
2834       if (FirstID.getBlock() == (uint64_t)MBB.getNumber() && FirstID.isPHI()) {
2835         ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def));
2836       } else if (PropOnlyInBEs) {
2837         // If only backedges disagree, a higher (in RPO) block confirmed this
2838         // location, and we need to propagate it into this loop.
2839         ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def));
2840       } else {
2841         // Otherwise; a Def meeting a Proposed is still a Proposed.
2842         ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Proposed));
2843       }
2844     } else if ((OurState == PHINeeded || OurState == BEDisagree)) {
2845       // Predecessors disagree and can't be downgraded: this can only be
2846       // solved with a PHI. Use pickVPHILoc to go look for one.
2847       Optional<ValueIDNum> VPHI;
2848       bool AllEdgesVPHI = false;
2849       std::tie(VPHI, AllEdgesVPHI) =
2850           pickVPHILoc(MBB, Var, VLOCOutLocs, MOutLocs, MInLocs, BlockOrders);
2851 
2852       if (VPHI && AllEdgesVPHI) {
2853         // There's a PHI value that's valid for all predecessors -- we can use
2854         // it. If any of the non-backedge predecessors have proposed values
2855         // though, this PHI is also only proposed, until the predecessors are
2856         // confirmed.
2857         DbgValue::KindT K = DbgValue::Def;
2858         for (unsigned int I = 0; I < BackEdgesStart; ++I)
2859           if (Values[I].second->Kind == DbgValue::Proposed)
2860             K = DbgValue::Proposed;
2861 
2862         ConfirmValue(Var, DbgValue(*VPHI, Properties, K));
2863       } else if (VPHI) {
2864         // There's a PHI value, but it's only legal for backedges. Leave this
2865         // as a proposed PHI value: it might come back on the backedges,
2866         // and allow us to confirm it in the future.
2867         DbgValue NoBEValue = DbgValue(*VPHI, Properties, DbgValue::Proposed);
2868         ConfirmValue(Var, NoBEValue);
2869       } else {
2870         ConfirmNoVal(Var, Properties);
2871       }
2872     } else {
2873       // Otherwise: we don't know. Emit a "phi but no real loc" phi.
2874       ConfirmNoVal(Var, Properties);
2875     }
2876   }
2877 
2878   // Store newly calculated in-locs into VLOCInLocs, if they've changed.
2879   Changed = ILS != InLocsT;
2880   if (Changed)
2881     ILS = InLocsT;
2882 
2883   return std::tuple<bool, bool>(Changed, DowngradeOccurred);
2884 }
2885 
2886 void InstrRefBasedLDV::vlocDataflow(
2887     const LexicalScope *Scope, const DILocation *DILoc,
2888     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2889     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2890     ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2891     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2892   // This method is much like mlocDataflow: but focuses on a single
2893   // LexicalScope at a time. Pick out a set of blocks and variables that are
2894   // to have their value assignments solved, then run our dataflow algorithm
2895   // until a fixedpoint is reached.
2896   std::priority_queue<unsigned int, std::vector<unsigned int>,
2897                       std::greater<unsigned int>>
2898       Worklist, Pending;
2899   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2900 
2901   // The set of blocks we'll be examining.
2902   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2903 
2904   // The order in which to examine them (RPO).
2905   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2906 
2907   // RPO ordering function.
2908   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2909     return BBToOrder[A] < BBToOrder[B];
2910   };
2911 
2912   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
2913 
2914   // A separate container to distinguish "blocks we're exploring" versus
2915   // "blocks that are potentially in scope. See comment at start of vlocJoin.
2916   SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore;
2917 
2918   // Old LiveDebugValues tracks variable locations that come out of blocks
2919   // not in scope, where DBG_VALUEs occur. This is something we could
2920   // legitimately ignore, but lets allow it for now.
2921   if (EmulateOldLDV)
2922     BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
2923 
2924   // We also need to propagate variable values through any artificial blocks
2925   // that immediately follow blocks in scope.
2926   DenseSet<const MachineBasicBlock *> ToAdd;
2927 
2928   // Helper lambda: For a given block in scope, perform a depth first search
2929   // of all the artificial successors, adding them to the ToAdd collection.
2930   auto AccumulateArtificialBlocks =
2931       [this, &ToAdd, &BlocksToExplore,
2932        &InScopeBlocks](const MachineBasicBlock *MBB) {
2933         // Depth-first-search state: each node is a block and which successor
2934         // we're currently exploring.
2935         SmallVector<std::pair<const MachineBasicBlock *,
2936                               MachineBasicBlock::const_succ_iterator>,
2937                     8>
2938             DFS;
2939 
2940         // Find any artificial successors not already tracked.
2941         for (auto *succ : MBB->successors()) {
2942           if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ))
2943             continue;
2944           if (!ArtificialBlocks.count(succ))
2945             continue;
2946           DFS.push_back(std::make_pair(succ, succ->succ_begin()));
2947           ToAdd.insert(succ);
2948         }
2949 
2950         // Search all those blocks, depth first.
2951         while (!DFS.empty()) {
2952           const MachineBasicBlock *CurBB = DFS.back().first;
2953           MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
2954           // Walk back if we've explored this blocks successors to the end.
2955           if (CurSucc == CurBB->succ_end()) {
2956             DFS.pop_back();
2957             continue;
2958           }
2959 
2960           // If the current successor is artificial and unexplored, descend into
2961           // it.
2962           if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
2963             DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin()));
2964             ToAdd.insert(*CurSucc);
2965             continue;
2966           }
2967 
2968           ++CurSucc;
2969         }
2970       };
2971 
2972   // Search in-scope blocks and those containing a DBG_VALUE from this scope
2973   // for artificial successors.
2974   for (auto *MBB : BlocksToExplore)
2975     AccumulateArtificialBlocks(MBB);
2976   for (auto *MBB : InScopeBlocks)
2977     AccumulateArtificialBlocks(MBB);
2978 
2979   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
2980   InScopeBlocks.insert(ToAdd.begin(), ToAdd.end());
2981 
2982   // Single block scope: not interesting! No propagation at all. Note that
2983   // this could probably go above ArtificialBlocks without damage, but
2984   // that then produces output differences from original-live-debug-values,
2985   // which propagates from a single block into many artificial ones.
2986   if (BlocksToExplore.size() == 1)
2987     return;
2988 
2989   // Picks out relevants blocks RPO order and sort them.
2990   for (auto *MBB : BlocksToExplore)
2991     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2992 
2993   llvm::sort(BlockOrders.begin(), BlockOrders.end(), Cmp);
2994   unsigned NumBlocks = BlockOrders.size();
2995 
2996   // Allocate some vectors for storing the live ins and live outs. Large.
2997   SmallVector<DenseMap<DebugVariable, DbgValue>, 32> LiveIns, LiveOuts;
2998   LiveIns.resize(NumBlocks);
2999   LiveOuts.resize(NumBlocks);
3000 
3001   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3002   // vlocJoin.
3003   LiveIdxT LiveOutIdx, LiveInIdx;
3004   LiveOutIdx.reserve(NumBlocks);
3005   LiveInIdx.reserve(NumBlocks);
3006   for (unsigned I = 0; I < NumBlocks; ++I) {
3007     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3008     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3009   }
3010 
3011   for (auto *MBB : BlockOrders) {
3012     Worklist.push(BBToOrder[MBB]);
3013     OnWorklist.insert(MBB);
3014   }
3015 
3016   // Iterate over all the blocks we selected, propagating variable values.
3017   bool FirstTrip = true;
3018   SmallPtrSet<const MachineBasicBlock *, 16> VLOCVisited;
3019   while (!Worklist.empty() || !Pending.empty()) {
3020     while (!Worklist.empty()) {
3021       auto *MBB = OrderToBB[Worklist.top()];
3022       CurBB = MBB->getNumber();
3023       Worklist.pop();
3024 
3025       DenseMap<DebugVariable, DbgValue> JoinedInLocs;
3026 
3027       // Join values from predecessors. Updates LiveInIdx, and writes output
3028       // into JoinedInLocs.
3029       bool InLocsChanged, DowngradeOccurred;
3030       std::tie(InLocsChanged, DowngradeOccurred) = vlocJoin(
3031           *MBB, LiveOutIdx, LiveInIdx, (FirstTrip) ? &VLOCVisited : nullptr,
3032           CurBB, VarsWeCareAbout, MOutLocs, MInLocs, InScopeBlocks,
3033           BlocksToExplore, JoinedInLocs);
3034 
3035       bool FirstVisit = VLOCVisited.insert(MBB).second;
3036 
3037       // Always explore transfer function if inlocs changed, or if we've not
3038       // visited this block before.
3039       InLocsChanged |= FirstVisit;
3040 
3041       // If a downgrade occurred, book us in for re-examination on the next
3042       // iteration.
3043       if (DowngradeOccurred && OnPending.insert(MBB).second)
3044         Pending.push(BBToOrder[MBB]);
3045 
3046       if (!InLocsChanged)
3047         continue;
3048 
3049       // Do transfer function.
3050       auto &VTracker = AllTheVLocs[MBB->getNumber()];
3051       for (auto &Transfer : VTracker.Vars) {
3052         // Is this var we're mangling in this scope?
3053         if (VarsWeCareAbout.count(Transfer.first)) {
3054           // Erase on empty transfer (DBG_VALUE $noreg).
3055           if (Transfer.second.Kind == DbgValue::Undef) {
3056             JoinedInLocs.erase(Transfer.first);
3057           } else {
3058             // Insert new variable value; or overwrite.
3059             auto NewValuePair = std::make_pair(Transfer.first, Transfer.second);
3060             auto Result = JoinedInLocs.insert(NewValuePair);
3061             if (!Result.second)
3062               Result.first->second = Transfer.second;
3063           }
3064         }
3065       }
3066 
3067       // Did the live-out locations change?
3068       bool OLChanged = JoinedInLocs != *LiveOutIdx[MBB];
3069 
3070       // If they haven't changed, there's no need to explore further.
3071       if (!OLChanged)
3072         continue;
3073 
3074       // Commit to the live-out record.
3075       *LiveOutIdx[MBB] = JoinedInLocs;
3076 
3077       // We should visit all successors. Ensure we'll visit any non-backedge
3078       // successors during this dataflow iteration; book backedge successors
3079       // to be visited next time around.
3080       for (auto s : MBB->successors()) {
3081         // Ignore out of scope / not-to-be-explored successors.
3082         if (LiveInIdx.find(s) == LiveInIdx.end())
3083           continue;
3084 
3085         if (BBToOrder[s] > BBToOrder[MBB]) {
3086           if (OnWorklist.insert(s).second)
3087             Worklist.push(BBToOrder[s]);
3088         } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
3089           Pending.push(BBToOrder[s]);
3090         }
3091       }
3092     }
3093     Worklist.swap(Pending);
3094     std::swap(OnWorklist, OnPending);
3095     OnPending.clear();
3096     assert(Pending.empty());
3097     FirstTrip = false;
3098   }
3099 
3100   // Dataflow done. Now what? Save live-ins. Ignore any that are still marked
3101   // as being variable-PHIs, because those did not have their machine-PHI
3102   // value confirmed. Such variable values are places that could have been
3103   // PHIs, but are not.
3104   for (auto *MBB : BlockOrders) {
3105     auto &VarMap = *LiveInIdx[MBB];
3106     for (auto &P : VarMap) {
3107       if (P.second.Kind == DbgValue::Proposed ||
3108           P.second.Kind == DbgValue::NoVal)
3109         continue;
3110       Output[MBB->getNumber()].push_back(P);
3111     }
3112   }
3113 
3114   BlockOrders.clear();
3115   BlocksToExplore.clear();
3116 }
3117 
3118 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3119 void InstrRefBasedLDV::dump_mloc_transfer(
3120     const MLocTransferMap &mloc_transfer) const {
3121   for (auto &P : mloc_transfer) {
3122     std::string foo = MTracker->LocIdxToName(P.first);
3123     std::string bar = MTracker->IDAsString(P.second);
3124     dbgs() << "Loc " << foo << " --> " << bar << "\n";
3125   }
3126 }
3127 #endif
3128 
3129 void InstrRefBasedLDV::emitLocations(
3130     MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MInLocs,
3131     DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
3132   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs);
3133   unsigned NumLocs = MTracker->getNumLocs();
3134 
3135   // For each block, load in the machine value locations and variable value
3136   // live-ins, then step through each instruction in the block. New DBG_VALUEs
3137   // to be inserted will be created along the way.
3138   for (MachineBasicBlock &MBB : MF) {
3139     unsigned bbnum = MBB.getNumber();
3140     MTracker->reset();
3141     MTracker->loadFromArray(MInLocs[bbnum], bbnum);
3142     TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()],
3143                          NumLocs);
3144 
3145     CurBB = bbnum;
3146     CurInst = 1;
3147     for (auto &MI : MBB) {
3148       process(MI);
3149       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
3150       ++CurInst;
3151     }
3152   }
3153 
3154   // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer
3155   // in DWARF in different orders. Use the order that they appear when walking
3156   // through each block / each instruction, stored in AllVarsNumbering.
3157   auto OrderDbgValues = [&](const MachineInstr *A,
3158                             const MachineInstr *B) -> bool {
3159     DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(),
3160                        A->getDebugLoc()->getInlinedAt());
3161     DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(),
3162                        B->getDebugLoc()->getInlinedAt());
3163     return AllVarsNumbering.find(VarA)->second <
3164            AllVarsNumbering.find(VarB)->second;
3165   };
3166 
3167   // Go through all the transfers recorded in the TransferTracker -- this is
3168   // both the live-ins to a block, and any movements of values that happen
3169   // in the middle.
3170   for (auto &P : TTracker->Transfers) {
3171     // Sort them according to appearance order.
3172     llvm::sort(P.Insts.begin(), P.Insts.end(), OrderDbgValues);
3173     // Insert either before or after the designated point...
3174     if (P.MBB) {
3175       MachineBasicBlock &MBB = *P.MBB;
3176       for (auto *MI : P.Insts) {
3177         MBB.insert(P.Pos, MI);
3178       }
3179     } else {
3180       MachineBasicBlock &MBB = *P.Pos->getParent();
3181       for (auto *MI : P.Insts) {
3182         MBB.insertAfter(P.Pos, MI);
3183       }
3184     }
3185   }
3186 }
3187 
3188 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3189   // Build some useful data structures.
3190   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3191     if (const DebugLoc &DL = MI.getDebugLoc())
3192       return DL.getLine() != 0;
3193     return false;
3194   };
3195   // Collect a set of all the artificial blocks.
3196   for (auto &MBB : MF)
3197     if (none_of(MBB.instrs(), hasNonArtificialLocation))
3198       ArtificialBlocks.insert(&MBB);
3199 
3200   // Compute mappings of block <=> RPO order.
3201   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3202   unsigned int RPONumber = 0;
3203   for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
3204     OrderToBB[RPONumber] = *RI;
3205     BBToOrder[*RI] = RPONumber;
3206     BBNumToRPO[(*RI)->getNumber()] = RPONumber;
3207     ++RPONumber;
3208   }
3209 }
3210 
3211 /// Calculate the liveness information for the given machine function and
3212 /// extend ranges across basic blocks.
3213 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3214                                     TargetPassConfig *TPC) {
3215   // No subprogram means this function contains no debuginfo.
3216   if (!MF.getFunction().getSubprogram())
3217     return false;
3218 
3219   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3220   this->TPC = TPC;
3221 
3222   TRI = MF.getSubtarget().getRegisterInfo();
3223   TII = MF.getSubtarget().getInstrInfo();
3224   TFI = MF.getSubtarget().getFrameLowering();
3225   TFI->getCalleeSaves(MF, CalleeSavedRegs);
3226   LS.initialize(MF);
3227 
3228   MTracker =
3229       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3230   VTracker = nullptr;
3231   TTracker = nullptr;
3232 
3233   SmallVector<MLocTransferMap, 32> MLocTransfer;
3234   SmallVector<VLocTracker, 8> vlocs;
3235   LiveInsT SavedLiveIns;
3236 
3237   int MaxNumBlocks = -1;
3238   for (auto &MBB : MF)
3239     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3240   assert(MaxNumBlocks >= 0);
3241   ++MaxNumBlocks;
3242 
3243   MLocTransfer.resize(MaxNumBlocks);
3244   vlocs.resize(MaxNumBlocks);
3245   SavedLiveIns.resize(MaxNumBlocks);
3246 
3247   initialSetup(MF);
3248 
3249   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3250 
3251   // Allocate and initialize two array-of-arrays for the live-in and live-out
3252   // machine values. The outer dimension is the block number; while the inner
3253   // dimension is a LocIdx from MLocTracker.
3254   ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks];
3255   ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks];
3256   unsigned NumLocs = MTracker->getNumLocs();
3257   for (int i = 0; i < MaxNumBlocks; ++i) {
3258     MOutLocs[i] = new ValueIDNum[NumLocs];
3259     MInLocs[i] = new ValueIDNum[NumLocs];
3260   }
3261 
3262   // Solve the machine value dataflow problem using the MLocTransfer function,
3263   // storing the computed live-ins / live-outs into the array-of-arrays. We use
3264   // both live-ins and live-outs for decision making in the variable value
3265   // dataflow problem.
3266   mlocDataflow(MInLocs, MOutLocs, MLocTransfer);
3267 
3268   // Walk back through each block / instruction, collecting DBG_VALUE
3269   // instructions and recording what machine value their operands refer to.
3270   for (auto &OrderPair : OrderToBB) {
3271     MachineBasicBlock &MBB = *OrderPair.second;
3272     CurBB = MBB.getNumber();
3273     VTracker = &vlocs[CurBB];
3274     VTracker->MBB = &MBB;
3275     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3276     CurInst = 1;
3277     for (auto &MI : MBB) {
3278       process(MI);
3279       ++CurInst;
3280     }
3281     MTracker->reset();
3282   }
3283 
3284   // Number all variables in the order that they appear, to be used as a stable
3285   // insertion order later.
3286   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3287 
3288   // Map from one LexicalScope to all the variables in that scope.
3289   DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars;
3290 
3291   // Map from One lexical scope to all blocks in that scope.
3292   DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>
3293       ScopeToBlocks;
3294 
3295   // Store a DILocation that describes a scope.
3296   DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation;
3297 
3298   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3299   // the order is unimportant, it just has to be stable.
3300   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3301     auto *MBB = OrderToBB[I];
3302     auto *VTracker = &vlocs[MBB->getNumber()];
3303     // Collect each variable with a DBG_VALUE in this block.
3304     for (auto &idx : VTracker->Vars) {
3305       const auto &Var = idx.first;
3306       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3307       assert(ScopeLoc != nullptr);
3308       auto *Scope = LS.findLexicalScope(ScopeLoc);
3309 
3310       // No insts in scope -> shouldn't have been recorded.
3311       assert(Scope != nullptr);
3312 
3313       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3314       ScopeToVars[Scope].insert(Var);
3315       ScopeToBlocks[Scope].insert(VTracker->MBB);
3316       ScopeToDILocation[Scope] = ScopeLoc;
3317     }
3318   }
3319 
3320   // OK. Iterate over scopes: there might be something to be said for
3321   // ordering them by size/locality, but that's for the future. For each scope,
3322   // solve the variable value problem, producing a map of variables to values
3323   // in SavedLiveIns.
3324   for (auto &P : ScopeToVars) {
3325     vlocDataflow(P.first, ScopeToDILocation[P.first], P.second,
3326                  ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs,
3327                  vlocs);
3328   }
3329 
3330   // Using the computed value locations and variable values for each block,
3331   // create the DBG_VALUE instructions representing the extended variable
3332   // locations.
3333   emitLocations(MF, SavedLiveIns, MInLocs, AllVarsNumbering);
3334 
3335   for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) {
3336     delete[] MOutLocs[Idx];
3337     delete[] MInLocs[Idx];
3338   }
3339   delete[] MOutLocs;
3340   delete[] MInLocs;
3341 
3342   // Did we actually make any changes? If we created any DBG_VALUEs, then yes.
3343   bool Changed = TTracker->Transfers.size() != 0;
3344 
3345   delete MTracker;
3346   delete TTracker;
3347   MTracker = nullptr;
3348   VTracker = nullptr;
3349   TTracker = nullptr;
3350 
3351   ArtificialBlocks.clear();
3352   OrderToBB.clear();
3353   BBToOrder.clear();
3354   BBNumToRPO.clear();
3355   DebugInstrNumToInstr.clear();
3356 
3357   return Changed;
3358 }
3359 
3360 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3361   return new InstrRefBasedLDV();
3362 }
3363