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 SSA construction, where
15 /// each debug instruction assigns the *value* that a variable has, and every
16 /// instruction where the variable is in scope uses that variable. The resulting
17 /// map of instruction-to-value is then translated into a register (or spill)
18 /// location for each variable over each instruction.
19 ///
20 /// The primary difference from normal SSA construction is that we cannot
21 /// _create_ PHI values that contain variable values. CodeGen has already
22 /// completed, and we can't alter it just to make debug-info complete. Thus:
23 /// we can identify function positions where we would like a PHI value for a
24 /// variable, but must search the MachineFunction to see whether such a PHI is
25 /// available. If no such PHI exists, the variable location must be dropped.
26 ///
27 /// To achieve this, we perform two kinds of analysis. First, we identify
28 /// every value defined by every instruction (ignoring those that only move
29 /// another value), then re-compute an SSA-form representation of the
30 /// MachineFunction, using value propagation to eliminate any un-necessary
31 /// PHI values. This gives us a map of every value computed in the function,
32 /// and its location within the register file / stack.
33 ///
34 /// Secondly, for each variable we perform the same analysis, where each debug
35 /// instruction is considered a def, and every instruction where the variable
36 /// is in lexical scope as a use. Value propagation is used again to eliminate
37 /// any un-necessary PHIs. This gives us a map of each variable to the value
38 /// it should have in a block.
39 ///
40 /// Once both are complete, we have two maps for each block:
41 ///  * Variables to the values they should have,
42 ///  * Values to the register / spill slot they are located in.
43 /// After which we can marry-up variable values with a location, and emit
44 /// DBG_VALUE instructions specifying those locations. Variable locations may
45 /// be dropped in this process due to the desired variable value not being
46 /// resident in any machine location, or because there is no PHI value in any
47 /// location that accurately represents the desired value.  The building of
48 /// location lists for each block is left to DbgEntityHistoryCalculator.
49 ///
50 /// This pass is kept efficient because the size of the first SSA problem
51 /// is proportional to the working-set size of the function, which the compiler
52 /// tries to keep small. (It's also proportional to the number of blocks).
53 /// Additionally, we repeatedly perform the second SSA problem analysis with
54 /// only the variables and blocks in a single lexical scope, exploiting their
55 /// locality.
56 ///
57 /// ### Terminology
58 ///
59 /// A machine location is a register or spill slot, a value is something that's
60 /// defined by an instruction or PHI node, while a variable value is the value
61 /// assigned to a variable. A variable location is a machine location, that must
62 /// contain the appropriate variable value. A value that is a PHI node is
63 /// occasionally called an mphi.
64 ///
65 /// The first SSA problem is the "machine value location" problem,
66 /// because we're determining which machine locations contain which values.
67 /// The "locations" are constant: what's unknown is what value they contain.
68 ///
69 /// The second SSA problem (the one for variables) is the "variable value
70 /// problem", because it's determining what values a variable has, rather than
71 /// what location those values are placed in.
72 ///
73 /// TODO:
74 ///   Overlapping fragments
75 ///   Entry values
76 ///   Add back DEBUG statements for debugging this
77 ///   Collect statistics
78 ///
79 //===----------------------------------------------------------------------===//
80 
81 #include "llvm/ADT/DenseMap.h"
82 #include "llvm/ADT/PostOrderIterator.h"
83 #include "llvm/ADT/STLExtras.h"
84 #include "llvm/ADT/SmallPtrSet.h"
85 #include "llvm/ADT/SmallSet.h"
86 #include "llvm/ADT/SmallVector.h"
87 #include "llvm/BinaryFormat/Dwarf.h"
88 #include "llvm/CodeGen/LexicalScopes.h"
89 #include "llvm/CodeGen/MachineBasicBlock.h"
90 #include "llvm/CodeGen/MachineDominators.h"
91 #include "llvm/CodeGen/MachineFrameInfo.h"
92 #include "llvm/CodeGen/MachineFunction.h"
93 #include "llvm/CodeGen/MachineInstr.h"
94 #include "llvm/CodeGen/MachineInstrBuilder.h"
95 #include "llvm/CodeGen/MachineInstrBundle.h"
96 #include "llvm/CodeGen/MachineMemOperand.h"
97 #include "llvm/CodeGen/MachineOperand.h"
98 #include "llvm/CodeGen/PseudoSourceValue.h"
99 #include "llvm/CodeGen/TargetFrameLowering.h"
100 #include "llvm/CodeGen/TargetInstrInfo.h"
101 #include "llvm/CodeGen/TargetLowering.h"
102 #include "llvm/CodeGen/TargetPassConfig.h"
103 #include "llvm/CodeGen/TargetRegisterInfo.h"
104 #include "llvm/CodeGen/TargetSubtargetInfo.h"
105 #include "llvm/Config/llvm-config.h"
106 #include "llvm/IR/DebugInfoMetadata.h"
107 #include "llvm/IR/DebugLoc.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/MC/MCRegisterInfo.h"
110 #include "llvm/Support/Casting.h"
111 #include "llvm/Support/Compiler.h"
112 #include "llvm/Support/Debug.h"
113 #include "llvm/Support/GenericIteratedDominanceFrontier.h"
114 #include "llvm/Support/TypeSize.h"
115 #include "llvm/Support/raw_ostream.h"
116 #include "llvm/Target/TargetMachine.h"
117 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
118 #include <algorithm>
119 #include <cassert>
120 #include <climits>
121 #include <cstdint>
122 #include <functional>
123 #include <queue>
124 #include <tuple>
125 #include <utility>
126 #include <vector>
127 
128 #include "InstrRefBasedImpl.h"
129 #include "LiveDebugValues.h"
130 
131 using namespace llvm;
132 using namespace LiveDebugValues;
133 
134 // SSAUpdaterImple sets DEBUG_TYPE, change it.
135 #undef DEBUG_TYPE
136 #define DEBUG_TYPE "livedebugvalues"
137 
138 // Act more like the VarLoc implementation, by propagating some locations too
139 // far and ignoring some transfers.
140 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
141                                    cl::desc("Act like old LiveDebugValues did"),
142                                    cl::init(false));
143 
144 // Limit for the maximum number of stack slots we should track, past which we
145 // will ignore any spills. InstrRefBasedLDV gathers detailed information on all
146 // stack slots which leads to high memory consumption, and in some scenarios
147 // (such as asan with very many locals) the working set of the function can be
148 // very large, causing many spills. In these scenarios, it is very unlikely that
149 // the developer has hundreds of variables live at the same time that they're
150 // carefully thinking about -- instead, they probably autogenerated the code.
151 // When this happens, gracefully stop tracking excess spill slots, rather than
152 // consuming all the developer's memory.
153 static cl::opt<unsigned>
154     StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
155                          cl::desc("livedebugvalues-stack-ws-limit"),
156                          cl::init(250));
157 
158 /// Tracker for converting machine value locations and variable values into
159 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
160 /// specifying block live-in locations and transfers within blocks.
161 ///
162 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
163 /// and must be initialized with the set of variable values that are live-in to
164 /// the block. The caller then repeatedly calls process(). TransferTracker picks
165 /// out variable locations for the live-in variable values (if there _is_ a
166 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
167 /// stepped through, transfers of values between machine locations are
168 /// identified and if profitable, a DBG_VALUE created.
169 ///
170 /// This is where debug use-before-defs would be resolved: a variable with an
171 /// unavailable value could materialize in the middle of a block, when the
172 /// value becomes available. Or, we could detect clobbers and re-specify the
173 /// variable in a backup location. (XXX these are unimplemented).
174 class TransferTracker {
175 public:
176   const TargetInstrInfo *TII;
177   const TargetLowering *TLI;
178   /// This machine location tracker is assumed to always contain the up-to-date
179   /// value mapping for all machine locations. TransferTracker only reads
180   /// information from it. (XXX make it const?)
181   MLocTracker *MTracker;
182   MachineFunction &MF;
183   bool ShouldEmitDebugEntryValues;
184 
185   /// Record of all changes in variable locations at a block position. Awkwardly
186   /// we allow inserting either before or after the point: MBB != nullptr
187   /// indicates it's before, otherwise after.
188   struct Transfer {
189     MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
190     MachineBasicBlock *MBB; /// non-null if we should insert after.
191     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
192   };
193 
194   struct LocAndProperties {
195     LocIdx Loc;
196     DbgValueProperties Properties;
197   };
198 
199   /// Collection of transfers (DBG_VALUEs) to be inserted.
200   SmallVector<Transfer, 32> Transfers;
201 
202   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
203   /// between TransferTrackers view of variable locations and MLocTrackers. For
204   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
205   /// does not.
206   SmallVector<ValueIDNum, 32> VarLocs;
207 
208   /// Map from LocIdxes to which DebugVariables are based that location.
209   /// Mantained while stepping through the block. Not accurate if
210   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
211   DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
212 
213   /// Map from DebugVariable to it's current location and qualifying meta
214   /// information. To be used in conjunction with ActiveMLocs to construct
215   /// enough information for the DBG_VALUEs for a particular LocIdx.
216   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
217 
218   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
219   SmallVector<MachineInstr *, 4> PendingDbgValues;
220 
221   /// Record of a use-before-def: created when a value that's live-in to the
222   /// current block isn't available in any machine location, but it will be
223   /// defined in this block.
224   struct UseBeforeDef {
225     /// Value of this variable, def'd in block.
226     ValueIDNum ID;
227     /// Identity of this variable.
228     DebugVariable Var;
229     /// Additional variable properties.
230     DbgValueProperties Properties;
231   };
232 
233   /// Map from instruction index (within the block) to the set of UseBeforeDefs
234   /// that become defined at that instruction.
235   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
236 
237   /// The set of variables that are in UseBeforeDefs and can become a location
238   /// once the relevant value is defined. An element being erased from this
239   /// collection prevents the use-before-def materializing.
240   DenseSet<DebugVariable> UseBeforeDefVariables;
241 
242   const TargetRegisterInfo &TRI;
243   const BitVector &CalleeSavedRegs;
244 
245   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
246                   MachineFunction &MF, const TargetRegisterInfo &TRI,
247                   const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
248       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
249         CalleeSavedRegs(CalleeSavedRegs) {
250     TLI = MF.getSubtarget().getTargetLowering();
251     auto &TM = TPC.getTM<TargetMachine>();
252     ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
253   }
254 
255   /// Load object with live-in variable values. \p mlocs contains the live-in
256   /// values in each machine location, while \p vlocs the live-in variable
257   /// values. This method picks variable locations for the live-in variables,
258   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
259   /// object fields to track variable locations as we step through the block.
260   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
261   void
262   loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs,
263              const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
264              unsigned NumLocs) {
265     ActiveMLocs.clear();
266     ActiveVLocs.clear();
267     VarLocs.clear();
268     VarLocs.reserve(NumLocs);
269     UseBeforeDefs.clear();
270     UseBeforeDefVariables.clear();
271 
272     auto isCalleeSaved = [&](LocIdx L) {
273       unsigned Reg = MTracker->LocIdxToLocID[L];
274       if (Reg >= MTracker->NumRegs)
275         return false;
276       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
277         if (CalleeSavedRegs.test(*RAI))
278           return true;
279       return false;
280     };
281 
282     // Map of the preferred location for each value.
283     DenseMap<ValueIDNum, LocIdx> ValueToLoc;
284 
285     // Initialized the preferred-location map with illegal locations, to be
286     // filled in later.
287     for (auto &VLoc : VLocs)
288       if (VLoc.second.Kind == DbgValue::Def)
289         ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()});
290 
291     ActiveMLocs.reserve(VLocs.size());
292     ActiveVLocs.reserve(VLocs.size());
293 
294     // Produce a map of value numbers to the current machine locs they live
295     // in. When emulating VarLocBasedImpl, there should only be one
296     // location; when not, we get to pick.
297     for (auto Location : MTracker->locations()) {
298       LocIdx Idx = Location.Idx;
299       ValueIDNum &VNum = MLocs[Idx.asU64()];
300       VarLocs.push_back(VNum);
301 
302       // Is there a variable that wants a location for this value? If not, skip.
303       auto VIt = ValueToLoc.find(VNum);
304       if (VIt == ValueToLoc.end())
305         continue;
306 
307       LocIdx CurLoc = VIt->second;
308       // In order of preference, pick:
309       //  * Callee saved registers,
310       //  * Other registers,
311       //  * Spill slots.
312       if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) ||
313           (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) {
314         // Insert, or overwrite if insertion failed.
315         VIt->second = Idx;
316       }
317     }
318 
319     // Now map variables to their picked LocIdxes.
320     for (const auto &Var : VLocs) {
321       if (Var.second.Kind == DbgValue::Const) {
322         PendingDbgValues.push_back(
323             emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties));
324         continue;
325       }
326 
327       // If the value has no location, we can't make a variable location.
328       const ValueIDNum &Num = Var.second.ID;
329       auto ValuesPreferredLoc = ValueToLoc.find(Num);
330       if (ValuesPreferredLoc->second.isIllegal()) {
331         // If it's a def that occurs in this block, register it as a
332         // use-before-def to be resolved as we step through the block.
333         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
334           addUseBeforeDef(Var.first, Var.second.Properties, Num);
335         else
336           recoverAsEntryValue(Var.first, Var.second.Properties, Num);
337         continue;
338       }
339 
340       LocIdx M = ValuesPreferredLoc->second;
341       auto NewValue = LocAndProperties{M, Var.second.Properties};
342       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
343       if (!Result.second)
344         Result.first->second = NewValue;
345       ActiveMLocs[M].insert(Var.first);
346       PendingDbgValues.push_back(
347           MTracker->emitLoc(M, Var.first, Var.second.Properties));
348     }
349     flushDbgValues(MBB.begin(), &MBB);
350   }
351 
352   /// Record that \p Var has value \p ID, a value that becomes available
353   /// later in the function.
354   void addUseBeforeDef(const DebugVariable &Var,
355                        const DbgValueProperties &Properties, ValueIDNum ID) {
356     UseBeforeDef UBD = {ID, Var, Properties};
357     UseBeforeDefs[ID.getInst()].push_back(UBD);
358     UseBeforeDefVariables.insert(Var);
359   }
360 
361   /// After the instruction at index \p Inst and position \p pos has been
362   /// processed, check whether it defines a variable value in a use-before-def.
363   /// If so, and the variable value hasn't changed since the start of the
364   /// block, create a DBG_VALUE.
365   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
366     auto MIt = UseBeforeDefs.find(Inst);
367     if (MIt == UseBeforeDefs.end())
368       return;
369 
370     for (auto &Use : MIt->second) {
371       LocIdx L = Use.ID.getLoc();
372 
373       // If something goes very wrong, we might end up labelling a COPY
374       // instruction or similar with an instruction number, where it doesn't
375       // actually define a new value, instead it moves a value. In case this
376       // happens, discard.
377       if (MTracker->readMLoc(L) != Use.ID)
378         continue;
379 
380       // If a different debug instruction defined the variable value / location
381       // since the start of the block, don't materialize this use-before-def.
382       if (!UseBeforeDefVariables.count(Use.Var))
383         continue;
384 
385       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
386     }
387     flushDbgValues(pos, nullptr);
388   }
389 
390   /// Helper to move created DBG_VALUEs into Transfers collection.
391   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
392     if (PendingDbgValues.size() == 0)
393       return;
394 
395     // Pick out the instruction start position.
396     MachineBasicBlock::instr_iterator BundleStart;
397     if (MBB && Pos == MBB->begin())
398       BundleStart = MBB->instr_begin();
399     else
400       BundleStart = getBundleStart(Pos->getIterator());
401 
402     Transfers.push_back({BundleStart, MBB, PendingDbgValues});
403     PendingDbgValues.clear();
404   }
405 
406   bool isEntryValueVariable(const DebugVariable &Var,
407                             const DIExpression *Expr) const {
408     if (!Var.getVariable()->isParameter())
409       return false;
410 
411     if (Var.getInlinedAt())
412       return false;
413 
414     if (Expr->getNumElements() > 0)
415       return false;
416 
417     return true;
418   }
419 
420   bool isEntryValueValue(const ValueIDNum &Val) const {
421     // Must be in entry block (block number zero), and be a PHI / live-in value.
422     if (Val.getBlock() || !Val.isPHI())
423       return false;
424 
425     // Entry values must enter in a register.
426     if (MTracker->isSpill(Val.getLoc()))
427       return false;
428 
429     Register SP = TLI->getStackPointerRegisterToSaveRestore();
430     Register FP = TRI.getFrameRegister(MF);
431     Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
432     return Reg != SP && Reg != FP;
433   }
434 
435   bool recoverAsEntryValue(const DebugVariable &Var,
436                            const DbgValueProperties &Prop,
437                            const ValueIDNum &Num) {
438     // Is this variable location a candidate to be an entry value. First,
439     // should we be trying this at all?
440     if (!ShouldEmitDebugEntryValues)
441       return false;
442 
443     // Is the variable appropriate for entry values (i.e., is a parameter).
444     if (!isEntryValueVariable(Var, Prop.DIExpr))
445       return false;
446 
447     // Is the value assigned to this variable still the entry value?
448     if (!isEntryValueValue(Num))
449       return false;
450 
451     // Emit a variable location using an entry value expression.
452     DIExpression *NewExpr =
453         DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue);
454     Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
455     MachineOperand MO = MachineOperand::CreateReg(Reg, false);
456 
457     PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect}));
458     return true;
459   }
460 
461   /// Change a variable value after encountering a DBG_VALUE inside a block.
462   void redefVar(const MachineInstr &MI) {
463     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
464                       MI.getDebugLoc()->getInlinedAt());
465     DbgValueProperties Properties(MI);
466 
467     const MachineOperand &MO = MI.getOperand(0);
468 
469     // Ignore non-register locations, we don't transfer those.
470     if (!MO.isReg() || MO.getReg() == 0) {
471       auto It = ActiveVLocs.find(Var);
472       if (It != ActiveVLocs.end()) {
473         ActiveMLocs[It->second.Loc].erase(Var);
474         ActiveVLocs.erase(It);
475      }
476       // Any use-before-defs no longer apply.
477       UseBeforeDefVariables.erase(Var);
478       return;
479     }
480 
481     Register Reg = MO.getReg();
482     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
483     redefVar(MI, Properties, NewLoc);
484   }
485 
486   /// Handle a change in variable location within a block. Terminate the
487   /// variables current location, and record the value it now refers to, so
488   /// that we can detect location transfers later on.
489   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
490                 Optional<LocIdx> OptNewLoc) {
491     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
492                       MI.getDebugLoc()->getInlinedAt());
493     // Any use-before-defs no longer apply.
494     UseBeforeDefVariables.erase(Var);
495 
496     // Erase any previous location,
497     auto It = ActiveVLocs.find(Var);
498     if (It != ActiveVLocs.end())
499       ActiveMLocs[It->second.Loc].erase(Var);
500 
501     // If there _is_ no new location, all we had to do was erase.
502     if (!OptNewLoc)
503       return;
504     LocIdx NewLoc = *OptNewLoc;
505 
506     // Check whether our local copy of values-by-location in #VarLocs is out of
507     // date. Wipe old tracking data for the location if it's been clobbered in
508     // the meantime.
509     if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
510       for (auto &P : ActiveMLocs[NewLoc]) {
511         ActiveVLocs.erase(P);
512       }
513       ActiveMLocs[NewLoc.asU64()].clear();
514       VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
515     }
516 
517     ActiveMLocs[NewLoc].insert(Var);
518     if (It == ActiveVLocs.end()) {
519       ActiveVLocs.insert(
520           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
521     } else {
522       It->second.Loc = NewLoc;
523       It->second.Properties = Properties;
524     }
525   }
526 
527   /// Account for a location \p mloc being clobbered. Examine the variable
528   /// locations that will be terminated: and try to recover them by using
529   /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
530   /// explicitly terminate a location if it can't be recovered.
531   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
532                    bool MakeUndef = true) {
533     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
534     if (ActiveMLocIt == ActiveMLocs.end())
535       return;
536 
537     // What was the old variable value?
538     ValueIDNum OldValue = VarLocs[MLoc.asU64()];
539     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
540 
541     // Examine the remaining variable locations: if we can find the same value
542     // again, we can recover the location.
543     Optional<LocIdx> NewLoc = None;
544     for (auto Loc : MTracker->locations())
545       if (Loc.Value == OldValue)
546         NewLoc = Loc.Idx;
547 
548     // If there is no location, and we weren't asked to make the variable
549     // explicitly undef, then stop here.
550     if (!NewLoc && !MakeUndef) {
551       // Try and recover a few more locations with entry values.
552       for (auto &Var : ActiveMLocIt->second) {
553         auto &Prop = ActiveVLocs.find(Var)->second.Properties;
554         recoverAsEntryValue(Var, Prop, OldValue);
555       }
556       flushDbgValues(Pos, nullptr);
557       return;
558     }
559 
560     // Examine all the variables based on this location.
561     DenseSet<DebugVariable> NewMLocs;
562     for (auto &Var : ActiveMLocIt->second) {
563       auto ActiveVLocIt = ActiveVLocs.find(Var);
564       // Re-state the variable location: if there's no replacement then NewLoc
565       // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE
566       // identifying the alternative location will be emitted.
567       const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
568       PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties));
569 
570       // Update machine locations <=> variable locations maps. Defer updating
571       // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator.
572       if (!NewLoc) {
573         ActiveVLocs.erase(ActiveVLocIt);
574       } else {
575         ActiveVLocIt->second.Loc = *NewLoc;
576         NewMLocs.insert(Var);
577       }
578     }
579 
580     // Commit any deferred ActiveMLoc changes.
581     if (!NewMLocs.empty())
582       for (auto &Var : NewMLocs)
583         ActiveMLocs[*NewLoc].insert(Var);
584 
585     // We lazily track what locations have which values; if we've found a new
586     // location for the clobbered value, remember it.
587     if (NewLoc)
588       VarLocs[NewLoc->asU64()] = OldValue;
589 
590     flushDbgValues(Pos, nullptr);
591 
592     // Re-find ActiveMLocIt, iterator could have been invalidated.
593     ActiveMLocIt = ActiveMLocs.find(MLoc);
594     ActiveMLocIt->second.clear();
595   }
596 
597   /// Transfer variables based on \p Src to be based on \p Dst. This handles
598   /// both register copies as well as spills and restores. Creates DBG_VALUEs
599   /// describing the movement.
600   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
601     // Does Src still contain the value num we expect? If not, it's been
602     // clobbered in the meantime, and our variable locations are stale.
603     if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
604       return;
605 
606     // assert(ActiveMLocs[Dst].size() == 0);
607     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
608 
609     // Move set of active variables from one location to another.
610     auto MovingVars = ActiveMLocs[Src];
611     ActiveMLocs[Dst] = MovingVars;
612     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
613 
614     // For each variable based on Src; create a location at Dst.
615     for (auto &Var : MovingVars) {
616       auto ActiveVLocIt = ActiveVLocs.find(Var);
617       assert(ActiveVLocIt != ActiveVLocs.end());
618       ActiveVLocIt->second.Loc = Dst;
619 
620       MachineInstr *MI =
621           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
622       PendingDbgValues.push_back(MI);
623     }
624     ActiveMLocs[Src].clear();
625     flushDbgValues(Pos, nullptr);
626 
627     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
628     // about the old location.
629     if (EmulateOldLDV)
630       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
631   }
632 
633   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
634                                 const DebugVariable &Var,
635                                 const DbgValueProperties &Properties) {
636     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
637                                   Var.getVariable()->getScope(),
638                                   const_cast<DILocation *>(Var.getInlinedAt()));
639     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
640     MIB.add(MO);
641     if (Properties.Indirect)
642       MIB.addImm(0);
643     else
644       MIB.addReg(0);
645     MIB.addMetadata(Var.getVariable());
646     MIB.addMetadata(Properties.DIExpr);
647     return MIB;
648   }
649 };
650 
651 //===----------------------------------------------------------------------===//
652 //            Implementation
653 //===----------------------------------------------------------------------===//
654 
655 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
656 ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
657 
658 #ifndef NDEBUG
659 void DbgValue::dump(const MLocTracker *MTrack) const {
660   if (Kind == Const) {
661     MO->dump();
662   } else if (Kind == NoVal) {
663     dbgs() << "NoVal(" << BlockNo << ")";
664   } else if (Kind == VPHI) {
665     dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")";
666   } else {
667     assert(Kind == Def);
668     dbgs() << MTrack->IDAsString(ID);
669   }
670   if (Properties.Indirect)
671     dbgs() << " indir";
672   if (Properties.DIExpr)
673     dbgs() << " " << *Properties.DIExpr;
674 }
675 #endif
676 
677 MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
678                          const TargetRegisterInfo &TRI,
679                          const TargetLowering &TLI)
680     : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
681       LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
682   NumRegs = TRI.getNumRegs();
683   reset();
684   LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
685   assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
686 
687   // Always track SP. This avoids the implicit clobbering caused by regmasks
688   // from affectings its values. (LiveDebugValues disbelieves calls and
689   // regmasks that claim to clobber SP).
690   Register SP = TLI.getStackPointerRegisterToSaveRestore();
691   if (SP) {
692     unsigned ID = getLocID(SP);
693     (void)lookupOrTrackRegister(ID);
694 
695     for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
696       SPAliases.insert(*RAI);
697   }
698 
699   // Build some common stack positions -- full registers being spilt to the
700   // stack.
701   StackSlotIdxes.insert({{8, 0}, 0});
702   StackSlotIdxes.insert({{16, 0}, 1});
703   StackSlotIdxes.insert({{32, 0}, 2});
704   StackSlotIdxes.insert({{64, 0}, 3});
705   StackSlotIdxes.insert({{128, 0}, 4});
706   StackSlotIdxes.insert({{256, 0}, 5});
707   StackSlotIdxes.insert({{512, 0}, 6});
708 
709   // Traverse all the subregister idxes, and ensure there's an index for them.
710   // Duplicates are no problem: we're interested in their position in the
711   // stack slot, we don't want to type the slot.
712   for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
713     unsigned Size = TRI.getSubRegIdxSize(I);
714     unsigned Offs = TRI.getSubRegIdxOffset(I);
715     unsigned Idx = StackSlotIdxes.size();
716 
717     // Some subregs have -1, -2 and so forth fed into their fields, to mean
718     // special backend things. Ignore those.
719     if (Size > 60000 || Offs > 60000)
720       continue;
721 
722     StackSlotIdxes.insert({{Size, Offs}, Idx});
723   }
724 
725   for (auto &Idx : StackSlotIdxes)
726     StackIdxesToPos[Idx.second] = Idx.first;
727 
728   NumSlotIdxes = StackSlotIdxes.size();
729 }
730 
731 LocIdx MLocTracker::trackRegister(unsigned ID) {
732   assert(ID != 0);
733   LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
734   LocIdxToIDNum.grow(NewIdx);
735   LocIdxToLocID.grow(NewIdx);
736 
737   // Default: it's an mphi.
738   ValueIDNum ValNum = {CurBB, 0, NewIdx};
739   // Was this reg ever touched by a regmask?
740   for (const auto &MaskPair : reverse(Masks)) {
741     if (MaskPair.first->clobbersPhysReg(ID)) {
742       // There was an earlier def we skipped.
743       ValNum = {CurBB, MaskPair.second, NewIdx};
744       break;
745     }
746   }
747 
748   LocIdxToIDNum[NewIdx] = ValNum;
749   LocIdxToLocID[NewIdx] = ID;
750   return NewIdx;
751 }
752 
753 void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
754                                unsigned InstID) {
755   // Def any register we track have that isn't preserved. The regmask
756   // terminates the liveness of a register, meaning its value can't be
757   // relied upon -- we represent this by giving it a new value.
758   for (auto Location : locations()) {
759     unsigned ID = LocIdxToLocID[Location.Idx];
760     // Don't clobber SP, even if the mask says it's clobbered.
761     if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
762       defReg(ID, CurBB, InstID);
763   }
764   Masks.push_back(std::make_pair(MO, InstID));
765 }
766 
767 Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
768   SpillLocationNo SpillID(SpillLocs.idFor(L));
769 
770   if (SpillID.id() == 0) {
771     // If there is no location, and we have reached the limit of how many stack
772     // slots to track, then don't track this one.
773     if (SpillLocs.size() >= StackWorkingSetLimit)
774       return None;
775 
776     // Spill location is untracked: create record for this one, and all
777     // subregister slots too.
778     SpillID = SpillLocationNo(SpillLocs.insert(L));
779     for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
780       unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
781       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
782       LocIdxToIDNum.grow(Idx);
783       LocIdxToLocID.grow(Idx);
784       LocIDToLocIdx.push_back(Idx);
785       LocIdxToLocID[Idx] = L;
786       // Initialize to PHI value; corresponds to the location's live-in value
787       // during transfer function construction.
788       LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
789     }
790   }
791   return SpillID;
792 }
793 
794 std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
795   unsigned ID = LocIdxToLocID[Idx];
796   if (ID >= NumRegs) {
797     StackSlotPos Pos = locIDToSpillIdx(ID);
798     ID -= NumRegs;
799     unsigned Slot = ID / NumSlotIdxes;
800     return Twine("slot ")
801         .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
802         .concat(Twine(" offs ").concat(Twine(Pos.second))))))
803         .str();
804   } else {
805     return TRI.getRegAsmName(ID).str();
806   }
807 }
808 
809 std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
810   std::string DefName = LocIdxToName(Num.getLoc());
811   return Num.asString(DefName);
812 }
813 
814 #ifndef NDEBUG
815 LLVM_DUMP_METHOD void MLocTracker::dump() {
816   for (auto Location : locations()) {
817     std::string MLocName = LocIdxToName(Location.Value.getLoc());
818     std::string DefName = Location.Value.asString(MLocName);
819     dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
820   }
821 }
822 
823 LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
824   for (auto Location : locations()) {
825     std::string foo = LocIdxToName(Location.Idx);
826     dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
827   }
828 }
829 #endif
830 
831 MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc,
832                                          const DebugVariable &Var,
833                                          const DbgValueProperties &Properties) {
834   DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
835                                 Var.getVariable()->getScope(),
836                                 const_cast<DILocation *>(Var.getInlinedAt()));
837   auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
838 
839   const DIExpression *Expr = Properties.DIExpr;
840   if (!MLoc) {
841     // No location -> DBG_VALUE $noreg
842     MIB.addReg(0);
843     MIB.addReg(0);
844   } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
845     unsigned LocID = LocIdxToLocID[*MLoc];
846     SpillLocationNo SpillID = locIDToSpill(LocID);
847     StackSlotPos StackIdx = locIDToSpillIdx(LocID);
848     unsigned short Offset = StackIdx.second;
849 
850     // TODO: support variables that are located in spill slots, with non-zero
851     // offsets from the start of the spill slot. It would require some more
852     // complex DIExpression calculations. This doesn't seem to be produced by
853     // LLVM right now, so don't try and support it.
854     // Accept no-subregister slots and subregisters where the offset is zero.
855     // The consumer should already have type information to work out how large
856     // the variable is.
857     if (Offset == 0) {
858       const SpillLoc &Spill = SpillLocs[SpillID.id()];
859       Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset,
860                                          Spill.SpillOffset);
861       unsigned Base = Spill.SpillBase;
862       MIB.addReg(Base);
863       MIB.addImm(0);
864 
865       // Being on the stack makes this location indirect; if it was _already_
866       // indirect though, we need to add extra indirection. See this test for
867       // a scenario where this happens:
868       //     llvm/test/DebugInfo/X86/spill-nontrivial-param.ll
869       if (Properties.Indirect) {
870         std::vector<uint64_t> Elts = {dwarf::DW_OP_deref};
871         Expr = DIExpression::append(Expr, Elts);
872       }
873     } else {
874       // This is a stack location with a weird subregister offset: emit an undef
875       // DBG_VALUE instead.
876       MIB.addReg(0);
877       MIB.addReg(0);
878     }
879   } else {
880     // Non-empty, non-stack slot, must be a plain register.
881     unsigned LocID = LocIdxToLocID[*MLoc];
882     MIB.addReg(LocID);
883     if (Properties.Indirect)
884       MIB.addImm(0);
885     else
886       MIB.addReg(0);
887   }
888 
889   MIB.addMetadata(Var.getVariable());
890   MIB.addMetadata(Expr);
891   return MIB;
892 }
893 
894 /// Default construct and initialize the pass.
895 InstrRefBasedLDV::InstrRefBasedLDV() = default;
896 
897 bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
898   unsigned Reg = MTracker->LocIdxToLocID[L];
899   for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
900     if (CalleeSavedRegs.test(*RAI))
901       return true;
902   return false;
903 }
904 
905 //===----------------------------------------------------------------------===//
906 //            Debug Range Extension Implementation
907 //===----------------------------------------------------------------------===//
908 
909 #ifndef NDEBUG
910 // Something to restore in the future.
911 // void InstrRefBasedLDV::printVarLocInMBB(..)
912 #endif
913 
914 Optional<SpillLocationNo>
915 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
916   assert(MI.hasOneMemOperand() &&
917          "Spill instruction does not have exactly one memory operand?");
918   auto MMOI = MI.memoperands_begin();
919   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
920   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
921          "Inconsistent memory operand in spill instruction");
922   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
923   const MachineBasicBlock *MBB = MI.getParent();
924   Register Reg;
925   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
926   return MTracker->getOrTrackSpillLoc({Reg, Offset});
927 }
928 
929 Optional<LocIdx>
930 InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
931   Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
932   if (!SpillLoc)
933     return None;
934 
935   // Where in the stack slot is this value defined -- i.e., what size of value
936   // is this? An important question, because it could be loaded into a register
937   // from the stack at some point. Happily the memory operand will tell us
938   // the size written to the stack.
939   auto *MemOperand = *MI.memoperands_begin();
940   unsigned SizeInBits = MemOperand->getSizeInBits();
941 
942   // Find that position in the stack indexes we're tracking.
943   auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0});
944   if (IdxIt == MTracker->StackSlotIdxes.end())
945     // That index is not tracked. This is suprising, and unlikely to ever
946     // occur, but the safe action is to indicate the variable is optimised out.
947     return None;
948 
949   unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second);
950   return MTracker->getSpillMLoc(SpillID);
951 }
952 
953 /// End all previous ranges related to @MI and start a new range from @MI
954 /// if it is a DBG_VALUE instr.
955 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
956   if (!MI.isDebugValue())
957     return false;
958 
959   const DILocalVariable *Var = MI.getDebugVariable();
960   const DIExpression *Expr = MI.getDebugExpression();
961   const DILocation *DebugLoc = MI.getDebugLoc();
962   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
963   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
964          "Expected inlined-at fields to agree");
965 
966   DebugVariable V(Var, Expr, InlinedAt);
967   DbgValueProperties Properties(MI);
968 
969   // If there are no instructions in this lexical scope, do no location tracking
970   // at all, this variable shouldn't get a legitimate location range.
971   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
972   if (Scope == nullptr)
973     return true; // handled it; by doing nothing
974 
975   // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to
976   // contribute to locations in this block, but don't propagate further.
977   // Interpret it like a DBG_VALUE $noreg.
978   if (MI.isDebugValueList()) {
979     if (VTracker)
980       VTracker->defVar(MI, Properties, None);
981     if (TTracker)
982       TTracker->redefVar(MI, Properties, None);
983     return true;
984   }
985 
986   const MachineOperand &MO = MI.getOperand(0);
987 
988   // MLocTracker needs to know that this register is read, even if it's only
989   // read by a debug inst.
990   if (MO.isReg() && MO.getReg() != 0)
991     (void)MTracker->readReg(MO.getReg());
992 
993   // If we're preparing for the second analysis (variables), the machine value
994   // locations are already solved, and we report this DBG_VALUE and the value
995   // it refers to to VLocTracker.
996   if (VTracker) {
997     if (MO.isReg()) {
998       // Feed defVar the new variable location, or if this is a
999       // DBG_VALUE $noreg, feed defVar None.
1000       if (MO.getReg())
1001         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1002       else
1003         VTracker->defVar(MI, Properties, None);
1004     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1005                MI.getOperand(0).isCImm()) {
1006       VTracker->defVar(MI, MI.getOperand(0));
1007     }
1008   }
1009 
1010   // If performing final tracking of transfers, report this variable definition
1011   // to the TransferTracker too.
1012   if (TTracker)
1013     TTracker->redefVar(MI);
1014   return true;
1015 }
1016 
1017 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1018                                              const ValueTable *MLiveOuts,
1019                                              const ValueTable *MLiveIns) {
1020   if (!MI.isDebugRef())
1021     return false;
1022 
1023   // Only handle this instruction when we are building the variable value
1024   // transfer function.
1025   if (!VTracker && !TTracker)
1026     return false;
1027 
1028   unsigned InstNo = MI.getOperand(0).getImm();
1029   unsigned OpNo = MI.getOperand(1).getImm();
1030 
1031   const DILocalVariable *Var = MI.getDebugVariable();
1032   const DIExpression *Expr = MI.getDebugExpression();
1033   const DILocation *DebugLoc = MI.getDebugLoc();
1034   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1035   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1036          "Expected inlined-at fields to agree");
1037 
1038   DebugVariable V(Var, Expr, InlinedAt);
1039 
1040   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1041   if (Scope == nullptr)
1042     return true; // Handled by doing nothing. This variable is never in scope.
1043 
1044   const MachineFunction &MF = *MI.getParent()->getParent();
1045 
1046   // Various optimizations may have happened to the value during codegen,
1047   // recorded in the value substitution table. Apply any substitutions to
1048   // the instruction / operand number in this DBG_INSTR_REF, and collect
1049   // any subregister extractions performed during optimization.
1050 
1051   // Create dummy substitution with Src set, for lookup.
1052   auto SoughtSub =
1053       MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1054 
1055   SmallVector<unsigned, 4> SeenSubregs;
1056   auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1057   while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1058          LowerBoundIt->Src == SoughtSub.Src) {
1059     std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1060     SoughtSub.Src = LowerBoundIt->Dest;
1061     if (unsigned Subreg = LowerBoundIt->Subreg)
1062       SeenSubregs.push_back(Subreg);
1063     LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1064   }
1065 
1066   // Default machine value number is <None> -- if no instruction defines
1067   // the corresponding value, it must have been optimized out.
1068   Optional<ValueIDNum> NewID = None;
1069 
1070   // Try to lookup the instruction number, and find the machine value number
1071   // that it defines. It could be an instruction, or a PHI.
1072   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1073   auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(),
1074                                 DebugPHINumToValue.end(), InstNo);
1075   if (InstrIt != DebugInstrNumToInstr.end()) {
1076     const MachineInstr &TargetInstr = *InstrIt->second.first;
1077     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1078 
1079     // Pick out the designated operand. It might be a memory reference, if
1080     // a register def was folded into a stack store.
1081     if (OpNo == MachineFunction::DebugOperandMemNumber &&
1082         TargetInstr.hasOneMemOperand()) {
1083       Optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1084       if (L)
1085         NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1086     } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
1087       // Permit the debug-info to be completely wrong: identifying a nonexistant
1088       // operand, or one that is not a register definition, means something
1089       // unexpected happened during optimisation. Broken debug-info, however,
1090       // shouldn't crash the compiler -- instead leave the variable value as
1091       // None, which will make it appear "optimised out".
1092       if (OpNo < TargetInstr.getNumOperands()) {
1093         const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1094 
1095         if (MO.isReg() && MO.isDef() && MO.getReg()) {
1096           unsigned LocID = MTracker->getLocID(MO.getReg());
1097           LocIdx L = MTracker->LocIDToLocIdx[LocID];
1098           NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1099         }
1100       }
1101 
1102       if (!NewID) {
1103         LLVM_DEBUG(
1104             { dbgs() << "Seen instruction reference to illegal operand\n"; });
1105       }
1106     }
1107     // else: NewID is left as None.
1108   } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1109     // It's actually a PHI value. Which value it is might not be obvious, use
1110     // the resolver helper to find out.
1111     NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
1112                            MI, InstNo);
1113   }
1114 
1115   // Apply any subregister extractions, in reverse. We might have seen code
1116   // like this:
1117   //    CALL64 @foo, implicit-def $rax
1118   //    %0:gr64 = COPY $rax
1119   //    %1:gr32 = COPY %0.sub_32bit
1120   //    %2:gr16 = COPY %1.sub_16bit
1121   //    %3:gr8  = COPY %2.sub_8bit
1122   // In which case each copy would have been recorded as a substitution with
1123   // a subregister qualifier. Apply those qualifiers now.
1124   if (NewID && !SeenSubregs.empty()) {
1125     unsigned Offset = 0;
1126     unsigned Size = 0;
1127 
1128     // Look at each subregister that we passed through, and progressively
1129     // narrow in, accumulating any offsets that occur. Substitutions should
1130     // only ever be the same or narrower width than what they read from;
1131     // iterate in reverse order so that we go from wide to small.
1132     for (unsigned Subreg : reverse(SeenSubregs)) {
1133       unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1134       unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1135       Offset += ThisOffset;
1136       Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1137     }
1138 
1139     // If that worked, look for an appropriate subregister with the register
1140     // where the define happens. Don't look at values that were defined during
1141     // a stack write: we can't currently express register locations within
1142     // spills.
1143     LocIdx L = NewID->getLoc();
1144     if (NewID && !MTracker->isSpill(L)) {
1145       // Find the register class for the register where this def happened.
1146       // FIXME: no index for this?
1147       Register Reg = MTracker->LocIdxToLocID[L];
1148       const TargetRegisterClass *TRC = nullptr;
1149       for (auto *TRCI : TRI->regclasses())
1150         if (TRCI->contains(Reg))
1151           TRC = TRCI;
1152       assert(TRC && "Couldn't find target register class?");
1153 
1154       // If the register we have isn't the right size or in the right place,
1155       // Try to find a subregister inside it.
1156       unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1157       if (Size != MainRegSize || Offset) {
1158         // Enumerate all subregisters, searching.
1159         Register NewReg = 0;
1160         for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1161           unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1162           unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1163           unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1164           if (SubregSize == Size && SubregOffset == Offset) {
1165             NewReg = *SRI;
1166             break;
1167           }
1168         }
1169 
1170         // If we didn't find anything: there's no way to express our value.
1171         if (!NewReg) {
1172           NewID = None;
1173         } else {
1174           // Re-state the value as being defined within the subregister
1175           // that we found.
1176           LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1177           NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1178         }
1179       }
1180     } else {
1181       // If we can't handle subregisters, unset the new value.
1182       NewID = None;
1183     }
1184   }
1185 
1186   // We, we have a value number or None. Tell the variable value tracker about
1187   // it. The rest of this LiveDebugValues implementation acts exactly the same
1188   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1189   // aren't immediately available).
1190   DbgValueProperties Properties(Expr, false);
1191   if (VTracker)
1192     VTracker->defVar(MI, Properties, NewID);
1193 
1194   // If we're on the final pass through the function, decompose this INSTR_REF
1195   // into a plain DBG_VALUE.
1196   if (!TTracker)
1197     return true;
1198 
1199   // Pick a location for the machine value number, if such a location exists.
1200   // (This information could be stored in TransferTracker to make it faster).
1201   Optional<LocIdx> FoundLoc = None;
1202   for (auto Location : MTracker->locations()) {
1203     LocIdx CurL = Location.Idx;
1204     ValueIDNum ID = MTracker->readMLoc(CurL);
1205     if (NewID && ID == NewID) {
1206       // If this is the first location with that value, pick it. Otherwise,
1207       // consider whether it's a "longer term" location.
1208       if (!FoundLoc) {
1209         FoundLoc = CurL;
1210         continue;
1211       }
1212 
1213       if (MTracker->isSpill(CurL))
1214         FoundLoc = CurL; // Spills are a longer term location.
1215       else if (!MTracker->isSpill(*FoundLoc) &&
1216                !MTracker->isSpill(CurL) &&
1217                !isCalleeSaved(*FoundLoc) &&
1218                isCalleeSaved(CurL))
1219         FoundLoc = CurL; // Callee saved regs are longer term than normal.
1220     }
1221   }
1222 
1223   // Tell transfer tracker that the variable value has changed.
1224   TTracker->redefVar(MI, Properties, FoundLoc);
1225 
1226   // If there was a value with no location; but the value is defined in a
1227   // later instruction in this block, this is a block-local use-before-def.
1228   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1229       NewID->getInst() > CurInst)
1230     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1231 
1232   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1233   // This DBG_VALUE is potentially a $noreg / undefined location, if
1234   // FoundLoc is None.
1235   // (XXX -- could morph the DBG_INSTR_REF in the future).
1236   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1237   TTracker->PendingDbgValues.push_back(DbgMI);
1238   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1239   return true;
1240 }
1241 
1242 bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1243   if (!MI.isDebugPHI())
1244     return false;
1245 
1246   // Analyse these only when solving the machine value location problem.
1247   if (VTracker || TTracker)
1248     return true;
1249 
1250   // First operand is the value location, either a stack slot or register.
1251   // Second is the debug instruction number of the original PHI.
1252   const MachineOperand &MO = MI.getOperand(0);
1253   unsigned InstrNum = MI.getOperand(1).getImm();
1254 
1255   auto EmitBadPHI = [this, &MI, InstrNum](void) -> bool {
1256     // Helper lambda to do any accounting when we fail to find a location for
1257     // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
1258     // dead stack slot, for example.
1259     // Record a DebugPHIRecord with an empty value + location.
1260     DebugPHINumToValue.push_back({InstrNum, MI.getParent(), None, None});
1261     return true;
1262   };
1263 
1264   if (MO.isReg() && MO.getReg()) {
1265     // The value is whatever's currently in the register. Read and record it,
1266     // to be analysed later.
1267     Register Reg = MO.getReg();
1268     ValueIDNum Num = MTracker->readReg(Reg);
1269     auto PHIRec = DebugPHIRecord(
1270         {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1271     DebugPHINumToValue.push_back(PHIRec);
1272 
1273     // Ensure this register is tracked.
1274     for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1275       MTracker->lookupOrTrackRegister(*RAI);
1276   } else if (MO.isFI()) {
1277     // The value is whatever's in this stack slot.
1278     unsigned FI = MO.getIndex();
1279 
1280     // If the stack slot is dead, then this was optimized away.
1281     // FIXME: stack slot colouring should account for slots that get merged.
1282     if (MFI->isDeadObjectIndex(FI))
1283       return EmitBadPHI();
1284 
1285     // Identify this spill slot, ensure it's tracked.
1286     Register Base;
1287     StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1288     SpillLoc SL = {Base, Offs};
1289     Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
1290 
1291     // We might be able to find a value, but have chosen not to, to avoid
1292     // tracking too much stack information.
1293     if (!SpillNo)
1294       return EmitBadPHI();
1295 
1296     // Any stack location DBG_PHI should have an associate bit-size.
1297     assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
1298     unsigned slotBitSize = MI.getOperand(2).getImm();
1299 
1300     unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0});
1301     LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
1302     ValueIDNum Result = MTracker->readMLoc(SpillLoc);
1303 
1304     // Record this DBG_PHI for later analysis.
1305     auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc});
1306     DebugPHINumToValue.push_back(DbgPHI);
1307   } else {
1308     // Else: if the operand is neither a legal register or a stack slot, then
1309     // we're being fed illegal debug-info. Record an empty PHI, so that any
1310     // debug users trying to read this number will be put off trying to
1311     // interpret the value.
1312     LLVM_DEBUG(
1313         { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
1314     return EmitBadPHI();
1315   }
1316 
1317   return true;
1318 }
1319 
1320 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1321   // Meta Instructions do not affect the debug liveness of any register they
1322   // define.
1323   if (MI.isImplicitDef()) {
1324     // Except when there's an implicit def, and the location it's defining has
1325     // no value number. The whole point of an implicit def is to announce that
1326     // the register is live, without be specific about it's value. So define
1327     // a value if there isn't one already.
1328     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1329     // Has a legitimate value -> ignore the implicit def.
1330     if (Num.getLoc() != 0)
1331       return;
1332     // Otherwise, def it here.
1333   } else if (MI.isMetaInstruction())
1334     return;
1335 
1336   // We always ignore SP defines on call instructions, they don't actually
1337   // change the value of the stack pointer... except for win32's _chkstk. This
1338   // is rare: filter quickly for the common case (no stack adjustments, not a
1339   // call, etc). If it is a call that modifies SP, recognise the SP register
1340   // defs.
1341   bool CallChangesSP = false;
1342   if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
1343       !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
1344     CallChangesSP = true;
1345 
1346   // Test whether we should ignore a def of this register due to it being part
1347   // of the stack pointer.
1348   auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
1349     if (CallChangesSP)
1350       return false;
1351     return MI.isCall() && MTracker->SPAliases.count(R);
1352   };
1353 
1354   // Find the regs killed by MI, and find regmasks of preserved regs.
1355   // Max out the number of statically allocated elements in `DeadRegs`, as this
1356   // prevents fallback to std::set::count() operations.
1357   SmallSet<uint32_t, 32> DeadRegs;
1358   SmallVector<const uint32_t *, 4> RegMasks;
1359   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1360   for (const MachineOperand &MO : MI.operands()) {
1361     // Determine whether the operand is a register def.
1362     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1363         Register::isPhysicalRegister(MO.getReg()) &&
1364         !IgnoreSPAlias(MO.getReg())) {
1365       // Remove ranges of all aliased registers.
1366       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1367         // FIXME: Can we break out of this loop early if no insertion occurs?
1368         DeadRegs.insert(*RAI);
1369     } else if (MO.isRegMask()) {
1370       RegMasks.push_back(MO.getRegMask());
1371       RegMaskPtrs.push_back(&MO);
1372     }
1373   }
1374 
1375   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1376   for (uint32_t DeadReg : DeadRegs)
1377     MTracker->defReg(DeadReg, CurBB, CurInst);
1378 
1379   for (auto *MO : RegMaskPtrs)
1380     MTracker->writeRegMask(MO, CurBB, CurInst);
1381 
1382   // If this instruction writes to a spill slot, def that slot.
1383   if (hasFoldedStackStore(MI)) {
1384     if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) {
1385       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1386         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1387         LocIdx L = MTracker->getSpillMLoc(SpillID);
1388         MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1389       }
1390     }
1391   }
1392 
1393   if (!TTracker)
1394     return;
1395 
1396   // When committing variable values to locations: tell transfer tracker that
1397   // we've clobbered things. It may be able to recover the variable from a
1398   // different location.
1399 
1400   // Inform TTracker about any direct clobbers.
1401   for (uint32_t DeadReg : DeadRegs) {
1402     LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
1403     TTracker->clobberMloc(Loc, MI.getIterator(), false);
1404   }
1405 
1406   // Look for any clobbers performed by a register mask. Only test locations
1407   // that are actually being tracked.
1408   if (!RegMaskPtrs.empty()) {
1409     for (auto L : MTracker->locations()) {
1410       // Stack locations can't be clobbered by regmasks.
1411       if (MTracker->isSpill(L.Idx))
1412         continue;
1413 
1414       Register Reg = MTracker->LocIdxToLocID[L.Idx];
1415       if (IgnoreSPAlias(Reg))
1416         continue;
1417 
1418       for (auto *MO : RegMaskPtrs)
1419         if (MO->clobbersPhysReg(Reg))
1420           TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
1421     }
1422   }
1423 
1424   // Tell TTracker about any folded stack store.
1425   if (hasFoldedStackStore(MI)) {
1426     if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) {
1427       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1428         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1429         LocIdx L = MTracker->getSpillMLoc(SpillID);
1430         TTracker->clobberMloc(L, MI.getIterator(), true);
1431       }
1432     }
1433   }
1434 }
1435 
1436 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1437   // In all circumstances, re-def all aliases. It's definitely a new value now.
1438   for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1439     MTracker->defReg(*RAI, CurBB, CurInst);
1440 
1441   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1442   MTracker->setReg(DstRegNum, SrcValue);
1443 
1444   // Copy subregisters from one location to another.
1445   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1446     unsigned SrcSubReg = SRI.getSubReg();
1447     unsigned SubRegIdx = SRI.getSubRegIndex();
1448     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1449     if (!DstSubReg)
1450       continue;
1451 
1452     // Do copy. There are two matching subregisters, the source value should
1453     // have been def'd when the super-reg was, the latter might not be tracked
1454     // yet.
1455     // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1456     // mphi values if it wasn't tracked.
1457     LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1458     LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1459     (void)SrcL;
1460     (void)DstL;
1461     ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1462 
1463     MTracker->setReg(DstSubReg, CpyValue);
1464   }
1465 }
1466 
1467 Optional<SpillLocationNo>
1468 InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1469                                      MachineFunction *MF) {
1470   // TODO: Handle multiple stores folded into one.
1471   if (!MI.hasOneMemOperand())
1472     return None;
1473 
1474   // Reject any memory operand that's aliased -- we can't guarantee its value.
1475   auto MMOI = MI.memoperands_begin();
1476   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1477   if (PVal->isAliased(MFI))
1478     return None;
1479 
1480   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1481     return None; // This is not a spill instruction, since no valid size was
1482                  // returned from either function.
1483 
1484   return extractSpillBaseRegAndOffset(MI);
1485 }
1486 
1487 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1488                                        MachineFunction *MF, unsigned &Reg) {
1489   if (!isSpillInstruction(MI, MF))
1490     return false;
1491 
1492   int FI;
1493   Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1494   return Reg != 0;
1495 }
1496 
1497 Optional<SpillLocationNo>
1498 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1499                                        MachineFunction *MF, unsigned &Reg) {
1500   if (!MI.hasOneMemOperand())
1501     return None;
1502 
1503   // FIXME: Handle folded restore instructions with more than one memory
1504   // operand.
1505   if (MI.getRestoreSize(TII)) {
1506     Reg = MI.getOperand(0).getReg();
1507     return extractSpillBaseRegAndOffset(MI);
1508   }
1509   return None;
1510 }
1511 
1512 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1513   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1514   // limitations under the new model. Therefore, when comparing them, compare
1515   // versions that don't attempt spills or restores at all.
1516   if (EmulateOldLDV)
1517     return false;
1518 
1519   // Strictly limit ourselves to plain loads and stores, not all instructions
1520   // that can access the stack.
1521   int DummyFI = -1;
1522   if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
1523       !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
1524     return false;
1525 
1526   MachineFunction *MF = MI.getMF();
1527   unsigned Reg;
1528 
1529   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1530 
1531   // Strictly limit ourselves to plain loads and stores, not all instructions
1532   // that can access the stack.
1533   int FIDummy;
1534   if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
1535       !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
1536     return false;
1537 
1538   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1539   // written to, terminate that variable location. The value in memory
1540   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
1541   if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
1542     // Un-set this location and clobber, so that earlier locations don't
1543     // continue past this store.
1544     for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
1545       unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
1546       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
1547       if (!MLoc)
1548         continue;
1549 
1550       // We need to over-write the stack slot with something (here, a def at
1551       // this instruction) to ensure no values are preserved in this stack slot
1552       // after the spill. It also prevents TTracker from trying to recover the
1553       // location and re-installing it in the same place.
1554       ValueIDNum Def(CurBB, CurInst, *MLoc);
1555       MTracker->setMLoc(*MLoc, Def);
1556       if (TTracker)
1557         TTracker->clobberMloc(*MLoc, MI.getIterator());
1558     }
1559   }
1560 
1561   // Try to recognise spill and restore instructions that may transfer a value.
1562   if (isLocationSpill(MI, MF, Reg)) {
1563     // isLocationSpill returning true should guarantee we can extract a
1564     // location.
1565     SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
1566 
1567     auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
1568       auto ReadValue = MTracker->readReg(SrcReg);
1569       LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
1570       MTracker->setMLoc(DstLoc, ReadValue);
1571 
1572       if (TTracker) {
1573         LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
1574         TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
1575       }
1576     };
1577 
1578     // Then, transfer subreg bits.
1579     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1580       // Ensure this reg is tracked,
1581       (void)MTracker->lookupOrTrackRegister(*SRI);
1582       unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI);
1583       unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
1584       DoTransfer(*SRI, SpillID);
1585     }
1586 
1587     // Directly lookup size of main source reg, and transfer.
1588     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1589     unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
1590     DoTransfer(Reg, SpillID);
1591   } else {
1592     Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
1593     if (!Loc)
1594       return false;
1595 
1596     // Assumption: we're reading from the base of the stack slot, not some
1597     // offset into it. It seems very unlikely LLVM would ever generate
1598     // restores where this wasn't true. This then becomes a question of what
1599     // subregisters in the destination register line up with positions in the
1600     // stack slot.
1601 
1602     // Def all registers that alias the destination.
1603     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1604       MTracker->defReg(*RAI, CurBB, CurInst);
1605 
1606     // Now find subregisters within the destination register, and load values
1607     // from stack slot positions.
1608     auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
1609       LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
1610       auto ReadValue = MTracker->readMLoc(SrcIdx);
1611       MTracker->setReg(DestReg, ReadValue);
1612     };
1613 
1614     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1615       unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1616       unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
1617       DoTransfer(*SRI, SpillID);
1618     }
1619 
1620     // Directly look up this registers slot idx by size, and transfer.
1621     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1622     unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
1623     DoTransfer(Reg, SpillID);
1624   }
1625   return true;
1626 }
1627 
1628 bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
1629   auto DestSrc = TII->isCopyInstr(MI);
1630   if (!DestSrc)
1631     return false;
1632 
1633   const MachineOperand *DestRegOp = DestSrc->Destination;
1634   const MachineOperand *SrcRegOp = DestSrc->Source;
1635 
1636   auto isCalleeSavedReg = [&](unsigned Reg) {
1637     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1638       if (CalleeSavedRegs.test(*RAI))
1639         return true;
1640     return false;
1641   };
1642 
1643   Register SrcReg = SrcRegOp->getReg();
1644   Register DestReg = DestRegOp->getReg();
1645 
1646   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
1647   if (SrcReg == DestReg)
1648     return true;
1649 
1650   // For emulating VarLocBasedImpl:
1651   // We want to recognize instructions where destination register is callee
1652   // saved register. If register that could be clobbered by the call is
1653   // included, there would be a great chance that it is going to be clobbered
1654   // soon. It is more likely that previous register, which is callee saved, is
1655   // going to stay unclobbered longer, even if it is killed.
1656   //
1657   // For InstrRefBasedImpl, we can track multiple locations per value, so
1658   // ignore this condition.
1659   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
1660     return false;
1661 
1662   // InstrRefBasedImpl only followed killing copies.
1663   if (EmulateOldLDV && !SrcRegOp->isKill())
1664     return false;
1665 
1666   // Copy MTracker info, including subregs if available.
1667   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
1668 
1669   // Only produce a transfer of DBG_VALUE within a block where old LDV
1670   // would have. We might make use of the additional value tracking in some
1671   // other way, later.
1672   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
1673     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
1674                             MTracker->getRegMLoc(DestReg), MI.getIterator());
1675 
1676   // VarLocBasedImpl would quit tracking the old location after copying.
1677   if (EmulateOldLDV && SrcReg != DestReg)
1678     MTracker->defReg(SrcReg, CurBB, CurInst);
1679 
1680   // Finally, the copy might have clobbered variables based on the destination
1681   // register. Tell TTracker about it, in case a backup location exists.
1682   if (TTracker) {
1683     for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
1684       LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
1685       TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false);
1686     }
1687   }
1688 
1689   return true;
1690 }
1691 
1692 /// Accumulate a mapping between each DILocalVariable fragment and other
1693 /// fragments of that DILocalVariable which overlap. This reduces work during
1694 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1695 /// known-to-overlap fragments are present".
1696 /// \param MI A previously unprocessed debug instruction to analyze for
1697 ///           fragment usage.
1698 void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
1699   assert(MI.isDebugValue() || MI.isDebugRef());
1700   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1701                       MI.getDebugLoc()->getInlinedAt());
1702   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1703 
1704   // If this is the first sighting of this variable, then we are guaranteed
1705   // there are currently no overlapping fragments either. Initialize the set
1706   // of seen fragments, record no overlaps for the current one, and return.
1707   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1708   if (SeenIt == SeenFragments.end()) {
1709     SmallSet<FragmentInfo, 4> OneFragment;
1710     OneFragment.insert(ThisFragment);
1711     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1712 
1713     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1714     return;
1715   }
1716 
1717   // If this particular Variable/Fragment pair already exists in the overlap
1718   // map, it has already been accounted for.
1719   auto IsInOLapMap =
1720       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1721   if (!IsInOLapMap.second)
1722     return;
1723 
1724   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1725   auto &AllSeenFragments = SeenIt->second;
1726 
1727   // Otherwise, examine all other seen fragments for this variable, with "this"
1728   // fragment being a previously unseen fragment. Record any pair of
1729   // overlapping fragments.
1730   for (auto &ASeenFragment : AllSeenFragments) {
1731     // Does this previously seen fragment overlap?
1732     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1733       // Yes: Mark the current fragment as being overlapped.
1734       ThisFragmentsOverlaps.push_back(ASeenFragment);
1735       // Mark the previously seen fragment as being overlapped by the current
1736       // one.
1737       auto ASeenFragmentsOverlaps =
1738           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
1739       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
1740              "Previously seen var fragment has no vector of overlaps");
1741       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1742     }
1743   }
1744 
1745   AllSeenFragments.insert(ThisFragment);
1746 }
1747 
1748 void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts,
1749                                const ValueTable *MLiveIns) {
1750   // Try to interpret an MI as a debug or transfer instruction. Only if it's
1751   // none of these should we interpret it's register defs as new value
1752   // definitions.
1753   if (transferDebugValue(MI))
1754     return;
1755   if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
1756     return;
1757   if (transferDebugPHI(MI))
1758     return;
1759   if (transferRegisterCopy(MI))
1760     return;
1761   if (transferSpillOrRestoreInst(MI))
1762     return;
1763   transferRegisterDef(MI);
1764 }
1765 
1766 void InstrRefBasedLDV::produceMLocTransferFunction(
1767     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1768     unsigned MaxNumBlocks) {
1769   // Because we try to optimize around register mask operands by ignoring regs
1770   // that aren't currently tracked, we set up something ugly for later: RegMask
1771   // operands that are seen earlier than the first use of a register, still need
1772   // to clobber that register in the transfer function. But this information
1773   // isn't actively recorded. Instead, we track each RegMask used in each block,
1774   // and accumulated the clobbered but untracked registers in each block into
1775   // the following bitvector. Later, if new values are tracked, we can add
1776   // appropriate clobbers.
1777   SmallVector<BitVector, 32> BlockMasks;
1778   BlockMasks.resize(MaxNumBlocks);
1779 
1780   // Reserve one bit per register for the masks described above.
1781   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
1782   for (auto &BV : BlockMasks)
1783     BV.resize(TRI->getNumRegs(), true);
1784 
1785   // Step through all instructions and inhale the transfer function.
1786   for (auto &MBB : MF) {
1787     // Object fields that are read by trackers to know where we are in the
1788     // function.
1789     CurBB = MBB.getNumber();
1790     CurInst = 1;
1791 
1792     // Set all machine locations to a PHI value. For transfer function
1793     // production only, this signifies the live-in value to the block.
1794     MTracker->reset();
1795     MTracker->setMPhis(CurBB);
1796 
1797     // Step through each instruction in this block.
1798     for (auto &MI : MBB) {
1799       // Pass in an empty unique_ptr for the value tables when accumulating the
1800       // machine transfer function.
1801       process(MI, nullptr, nullptr);
1802 
1803       // Also accumulate fragment map.
1804       if (MI.isDebugValue() || MI.isDebugRef())
1805         accumulateFragmentMap(MI);
1806 
1807       // Create a map from the instruction number (if present) to the
1808       // MachineInstr and its position.
1809       if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
1810         auto InstrAndPos = std::make_pair(&MI, CurInst);
1811         auto InsertResult =
1812             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
1813 
1814         // There should never be duplicate instruction numbers.
1815         assert(InsertResult.second);
1816         (void)InsertResult;
1817       }
1818 
1819       ++CurInst;
1820     }
1821 
1822     // Produce the transfer function, a map of machine location to new value. If
1823     // any machine location has the live-in phi value from the start of the
1824     // block, it's live-through and doesn't need recording in the transfer
1825     // function.
1826     for (auto Location : MTracker->locations()) {
1827       LocIdx Idx = Location.Idx;
1828       ValueIDNum &P = Location.Value;
1829       if (P.isPHI() && P.getLoc() == Idx.asU64())
1830         continue;
1831 
1832       // Insert-or-update.
1833       auto &TransferMap = MLocTransfer[CurBB];
1834       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
1835       if (!Result.second)
1836         Result.first->second = P;
1837     }
1838 
1839     // Accumulate any bitmask operands into the clobberred reg mask for this
1840     // block.
1841     for (auto &P : MTracker->Masks) {
1842       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
1843     }
1844   }
1845 
1846   // Compute a bitvector of all the registers that are tracked in this block.
1847   BitVector UsedRegs(TRI->getNumRegs());
1848   for (auto Location : MTracker->locations()) {
1849     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
1850     // Ignore stack slots, and aliases of the stack pointer.
1851     if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
1852       continue;
1853     UsedRegs.set(ID);
1854   }
1855 
1856   // Check that any regmask-clobber of a register that gets tracked, is not
1857   // live-through in the transfer function. It needs to be clobbered at the
1858   // very least.
1859   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
1860     BitVector &BV = BlockMasks[I];
1861     BV.flip();
1862     BV &= UsedRegs;
1863     // This produces all the bits that we clobber, but also use. Check that
1864     // they're all clobbered or at least set in the designated transfer
1865     // elem.
1866     for (unsigned Bit : BV.set_bits()) {
1867       unsigned ID = MTracker->getLocID(Bit);
1868       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
1869       auto &TransferMap = MLocTransfer[I];
1870 
1871       // Install a value representing the fact that this location is effectively
1872       // written to in this block. As there's no reserved value, instead use
1873       // a value number that is never generated. Pick the value number for the
1874       // first instruction in the block, def'ing this location, which we know
1875       // this block never used anyway.
1876       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
1877       auto Result =
1878         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
1879       if (!Result.second) {
1880         ValueIDNum &ValueID = Result.first->second;
1881         if (ValueID.getBlock() == I && ValueID.isPHI())
1882           // It was left as live-through. Set it to clobbered.
1883           ValueID = NotGeneratedNum;
1884       }
1885     }
1886   }
1887 }
1888 
1889 bool InstrRefBasedLDV::mlocJoin(
1890     MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1891     FuncValueTable &OutLocs, ValueTable &InLocs) {
1892   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1893   bool Changed = false;
1894 
1895   // Handle value-propagation when control flow merges on entry to a block. For
1896   // any location without a PHI already placed, the location has the same value
1897   // as its predecessors. If a PHI is placed, test to see whether it's now a
1898   // redundant PHI that we can eliminate.
1899 
1900   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
1901   for (auto Pred : MBB.predecessors())
1902     BlockOrders.push_back(Pred);
1903 
1904   // Visit predecessors in RPOT order.
1905   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
1906     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
1907   };
1908   llvm::sort(BlockOrders, Cmp);
1909 
1910   // Skip entry block.
1911   if (BlockOrders.size() == 0)
1912     return false;
1913 
1914   // Step through all machine locations, look at each predecessor and test
1915   // whether we can eliminate redundant PHIs.
1916   for (auto Location : MTracker->locations()) {
1917     LocIdx Idx = Location.Idx;
1918 
1919     // Pick out the first predecessors live-out value for this location. It's
1920     // guaranteed to not be a backedge, as we order by RPO.
1921     ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
1922 
1923     // If we've already eliminated a PHI here, do no further checking, just
1924     // propagate the first live-in value into this block.
1925     if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
1926       if (InLocs[Idx.asU64()] != FirstVal) {
1927         InLocs[Idx.asU64()] = FirstVal;
1928         Changed |= true;
1929       }
1930       continue;
1931     }
1932 
1933     // We're now examining a PHI to see whether it's un-necessary. Loop around
1934     // the other live-in values and test whether they're all the same.
1935     bool Disagree = false;
1936     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
1937       const MachineBasicBlock *PredMBB = BlockOrders[I];
1938       const ValueIDNum &PredLiveOut =
1939           OutLocs[PredMBB->getNumber()][Idx.asU64()];
1940 
1941       // Incoming values agree, continue trying to eliminate this PHI.
1942       if (FirstVal == PredLiveOut)
1943         continue;
1944 
1945       // We can also accept a PHI value that feeds back into itself.
1946       if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
1947         continue;
1948 
1949       // Live-out of a predecessor disagrees with the first predecessor.
1950       Disagree = true;
1951     }
1952 
1953     // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
1954     if (!Disagree) {
1955       InLocs[Idx.asU64()] = FirstVal;
1956       Changed |= true;
1957     }
1958   }
1959 
1960   // TODO: Reimplement NumInserted and NumRemoved.
1961   return Changed;
1962 }
1963 
1964 void InstrRefBasedLDV::findStackIndexInterference(
1965     SmallVectorImpl<unsigned> &Slots) {
1966   // We could spend a bit of time finding the exact, minimal, set of stack
1967   // indexes that interfere with each other, much like reg units. Or, we can
1968   // rely on the fact that:
1969   //  * The smallest / lowest index will interfere with everything at zero
1970   //    offset, which will be the largest set of registers,
1971   //  * Most indexes with non-zero offset will end up being interference units
1972   //    anyway.
1973   // So just pick those out and return them.
1974 
1975   // We can rely on a single-byte stack index existing already, because we
1976   // initialize them in MLocTracker.
1977   auto It = MTracker->StackSlotIdxes.find({8, 0});
1978   assert(It != MTracker->StackSlotIdxes.end());
1979   Slots.push_back(It->second);
1980 
1981   // Find anything that has a non-zero offset and add that too.
1982   for (auto &Pair : MTracker->StackSlotIdxes) {
1983     // Is offset zero? If so, ignore.
1984     if (!Pair.first.second)
1985       continue;
1986     Slots.push_back(Pair.second);
1987   }
1988 }
1989 
1990 void InstrRefBasedLDV::placeMLocPHIs(
1991     MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1992     FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
1993   SmallVector<unsigned, 4> StackUnits;
1994   findStackIndexInterference(StackUnits);
1995 
1996   // To avoid repeatedly running the PHI placement algorithm, leverage the
1997   // fact that a def of register MUST also def its register units. Find the
1998   // units for registers, place PHIs for them, and then replicate them for
1999   // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2000   // arguments) don't lead to register units being tracked, just place PHIs for
2001   // those registers directly. Stack slots have their own form of "unit",
2002   // store them to one side.
2003   SmallSet<Register, 32> RegUnitsToPHIUp;
2004   SmallSet<LocIdx, 32> NormalLocsToPHI;
2005   SmallSet<SpillLocationNo, 32> StackSlots;
2006   for (auto Location : MTracker->locations()) {
2007     LocIdx L = Location.Idx;
2008     if (MTracker->isSpill(L)) {
2009       StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
2010       continue;
2011     }
2012 
2013     Register R = MTracker->LocIdxToLocID[L];
2014     SmallSet<Register, 8> FoundRegUnits;
2015     bool AnyIllegal = false;
2016     for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) {
2017       for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){
2018         if (!MTracker->isRegisterTracked(*URoot)) {
2019           // Not all roots were loaded into the tracking map: this register
2020           // isn't actually def'd anywhere, we only read from it. Generate PHIs
2021           // for this reg, but don't iterate units.
2022           AnyIllegal = true;
2023         } else {
2024           FoundRegUnits.insert(*URoot);
2025         }
2026       }
2027     }
2028 
2029     if (AnyIllegal) {
2030       NormalLocsToPHI.insert(L);
2031       continue;
2032     }
2033 
2034     RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
2035   }
2036 
2037   // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2038   // collection.
2039   SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2040   auto CollectPHIsForLoc = [&](LocIdx L) {
2041     // Collect the set of defs.
2042     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2043     for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2044       MachineBasicBlock *MBB = OrderToBB[I];
2045       const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2046       if (TransferFunc.find(L) != TransferFunc.end())
2047         DefBlocks.insert(MBB);
2048     }
2049 
2050     // The entry block defs the location too: it's the live-in / argument value.
2051     // Only insert if there are other defs though; everything is trivially live
2052     // through otherwise.
2053     if (!DefBlocks.empty())
2054       DefBlocks.insert(&*MF.begin());
2055 
2056     // Ask the SSA construction algorithm where we should put PHIs. Clear
2057     // anything that might have been hanging around from earlier.
2058     PHIBlocks.clear();
2059     BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2060   };
2061 
2062   auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2063     for (const MachineBasicBlock *MBB : PHIBlocks)
2064       MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2065   };
2066 
2067   // For locations with no reg units, just place PHIs.
2068   for (LocIdx L : NormalLocsToPHI) {
2069     CollectPHIsForLoc(L);
2070     // Install those PHI values into the live-in value array.
2071     InstallPHIsAtLoc(L);
2072   }
2073 
2074   // For stack slots, calculate PHIs for the equivalent of the units, then
2075   // install for each index.
2076   for (SpillLocationNo Slot : StackSlots) {
2077     for (unsigned Idx : StackUnits) {
2078       unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2079       LocIdx L = MTracker->getSpillMLoc(SpillID);
2080       CollectPHIsForLoc(L);
2081       InstallPHIsAtLoc(L);
2082 
2083       // Find anything that aliases this stack index, install PHIs for it too.
2084       unsigned Size, Offset;
2085       std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2086       for (auto &Pair : MTracker->StackSlotIdxes) {
2087         unsigned ThisSize, ThisOffset;
2088         std::tie(ThisSize, ThisOffset) = Pair.first;
2089         if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2090           continue;
2091 
2092         unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2093         LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2094         InstallPHIsAtLoc(ThisL);
2095       }
2096     }
2097   }
2098 
2099   // For reg units, place PHIs, and then place them for any aliasing registers.
2100   for (Register R : RegUnitsToPHIUp) {
2101     LocIdx L = MTracker->lookupOrTrackRegister(R);
2102     CollectPHIsForLoc(L);
2103 
2104     // Install those PHI values into the live-in value array.
2105     InstallPHIsAtLoc(L);
2106 
2107     // Now find aliases and install PHIs for those.
2108     for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2109       // Super-registers that are "above" the largest register read/written by
2110       // the function will alias, but will not be tracked.
2111       if (!MTracker->isRegisterTracked(*RAI))
2112         continue;
2113 
2114       LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2115       InstallPHIsAtLoc(AliasLoc);
2116     }
2117   }
2118 }
2119 
2120 void InstrRefBasedLDV::buildMLocValueMap(
2121     MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2122     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2123   std::priority_queue<unsigned int, std::vector<unsigned int>,
2124                       std::greater<unsigned int>>
2125       Worklist, Pending;
2126 
2127   // We track what is on the current and pending worklist to avoid inserting
2128   // the same thing twice. We could avoid this with a custom priority queue,
2129   // but this is probably not worth it.
2130   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2131 
2132   // Initialize worklist with every block to be visited. Also produce list of
2133   // all blocks.
2134   SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2135   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2136     Worklist.push(I);
2137     OnWorklist.insert(OrderToBB[I]);
2138     AllBlocks.insert(OrderToBB[I]);
2139   }
2140 
2141   // Initialize entry block to PHIs. These represent arguments.
2142   for (auto Location : MTracker->locations())
2143     MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
2144 
2145   MTracker->reset();
2146 
2147   // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2148   // any machine-location that isn't live-through a block to be def'd in that
2149   // block.
2150   placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2151 
2152   // Propagate values to eliminate redundant PHIs. At the same time, this
2153   // produces the table of Block x Location => Value for the entry to each
2154   // block.
2155   // The kind of PHIs we can eliminate are, for example, where one path in a
2156   // conditional spills and restores a register, and the register still has
2157   // the same value once control flow joins, unbeknowns to the PHI placement
2158   // code. Propagating values allows us to identify such un-necessary PHIs and
2159   // remove them.
2160   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2161   while (!Worklist.empty() || !Pending.empty()) {
2162     // Vector for storing the evaluated block transfer function.
2163     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2164 
2165     while (!Worklist.empty()) {
2166       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2167       CurBB = MBB->getNumber();
2168       Worklist.pop();
2169 
2170       // Join the values in all predecessor blocks.
2171       bool InLocsChanged;
2172       InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2173       InLocsChanged |= Visited.insert(MBB).second;
2174 
2175       // Don't examine transfer function if we've visited this loc at least
2176       // once, and inlocs haven't changed.
2177       if (!InLocsChanged)
2178         continue;
2179 
2180       // Load the current set of live-ins into MLocTracker.
2181       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2182 
2183       // Each element of the transfer function can be a new def, or a read of
2184       // a live-in value. Evaluate each element, and store to "ToRemap".
2185       ToRemap.clear();
2186       for (auto &P : MLocTransfer[CurBB]) {
2187         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2188           // This is a movement of whatever was live in. Read it.
2189           ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2190           ToRemap.push_back(std::make_pair(P.first, NewID));
2191         } else {
2192           // It's a def. Just set it.
2193           assert(P.second.getBlock() == CurBB);
2194           ToRemap.push_back(std::make_pair(P.first, P.second));
2195         }
2196       }
2197 
2198       // Commit the transfer function changes into mloc tracker, which
2199       // transforms the contents of the MLocTracker into the live-outs.
2200       for (auto &P : ToRemap)
2201         MTracker->setMLoc(P.first, P.second);
2202 
2203       // Now copy out-locs from mloc tracker into out-loc vector, checking
2204       // whether changes have occurred. These changes can have come from both
2205       // the transfer function, and mlocJoin.
2206       bool OLChanged = false;
2207       for (auto Location : MTracker->locations()) {
2208         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2209         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2210       }
2211 
2212       MTracker->reset();
2213 
2214       // No need to examine successors again if out-locs didn't change.
2215       if (!OLChanged)
2216         continue;
2217 
2218       // All successors should be visited: put any back-edges on the pending
2219       // list for the next pass-through, and any other successors to be
2220       // visited this pass, if they're not going to be already.
2221       for (auto s : MBB->successors()) {
2222         // Does branching to this successor represent a back-edge?
2223         if (BBToOrder[s] > BBToOrder[MBB]) {
2224           // No: visit it during this dataflow iteration.
2225           if (OnWorklist.insert(s).second)
2226             Worklist.push(BBToOrder[s]);
2227         } else {
2228           // Yes: visit it on the next iteration.
2229           if (OnPending.insert(s).second)
2230             Pending.push(BBToOrder[s]);
2231         }
2232       }
2233     }
2234 
2235     Worklist.swap(Pending);
2236     std::swap(OnPending, OnWorklist);
2237     OnPending.clear();
2238     // At this point, pending must be empty, since it was just the empty
2239     // worklist
2240     assert(Pending.empty() && "Pending should be empty");
2241   }
2242 
2243   // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2244   // redundant PHIs.
2245 }
2246 
2247 void InstrRefBasedLDV::BlockPHIPlacement(
2248     const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2249     const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2250     SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2251   // Apply IDF calculator to the designated set of location defs, storing
2252   // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2253   // InstrRefBasedLDV object.
2254   IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
2255 
2256   IDF.setLiveInBlocks(AllBlocks);
2257   IDF.setDefiningBlocks(DefBlocks);
2258   IDF.calculate(PHIBlocks);
2259 }
2260 
2261 Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc(
2262     const MachineBasicBlock &MBB, const DebugVariable &Var,
2263     const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2264     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2265   // Collect a set of locations from predecessor where its live-out value can
2266   // be found.
2267   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2268   SmallVector<const DbgValueProperties *, 4> Properties;
2269   unsigned NumLocs = MTracker->getNumLocs();
2270 
2271   // No predecessors means no PHIs.
2272   if (BlockOrders.empty())
2273     return None;
2274 
2275   for (auto p : BlockOrders) {
2276     unsigned ThisBBNum = p->getNumber();
2277     auto OutValIt = LiveOuts.find(p);
2278     if (OutValIt == LiveOuts.end())
2279       // If we have a predecessor not in scope, we'll never find a PHI position.
2280       return None;
2281     const DbgValue &OutVal = *OutValIt->second;
2282 
2283     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2284       // Consts and no-values cannot have locations we can join on.
2285       return None;
2286 
2287     Properties.push_back(&OutVal.Properties);
2288 
2289     // Create new empty vector of locations.
2290     Locs.resize(Locs.size() + 1);
2291 
2292     // If the live-in value is a def, find the locations where that value is
2293     // present. Do the same for VPHIs where we know the VPHI value.
2294     if (OutVal.Kind == DbgValue::Def ||
2295         (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2296          OutVal.ID != ValueIDNum::EmptyValue)) {
2297       ValueIDNum ValToLookFor = OutVal.ID;
2298       // Search the live-outs of the predecessor for the specified value.
2299       for (unsigned int I = 0; I < NumLocs; ++I) {
2300         if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2301           Locs.back().push_back(LocIdx(I));
2302       }
2303     } else {
2304       assert(OutVal.Kind == DbgValue::VPHI);
2305       // For VPHIs where we don't know the location, we definitely can't find
2306       // a join loc.
2307       if (OutVal.BlockNo != MBB.getNumber())
2308         return None;
2309 
2310       // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2311       // a value that's live-through the whole loop. (It has to be a backedge,
2312       // because a block can't dominate itself). We can accept as a PHI location
2313       // any location where the other predecessors agree, _and_ the machine
2314       // locations feed back into themselves. Therefore, add all self-looping
2315       // machine-value PHI locations.
2316       for (unsigned int I = 0; I < NumLocs; ++I) {
2317         ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2318         if (MOutLocs[ThisBBNum][I] == MPHI)
2319           Locs.back().push_back(LocIdx(I));
2320       }
2321     }
2322   }
2323 
2324   // We should have found locations for all predecessors, or returned.
2325   assert(Locs.size() == BlockOrders.size());
2326 
2327   // Check that all properties are the same. We can't pick a location if they're
2328   // not.
2329   const DbgValueProperties *Properties0 = Properties[0];
2330   for (auto *Prop : Properties)
2331     if (*Prop != *Properties0)
2332       return None;
2333 
2334   // Starting with the first set of locations, take the intersection with
2335   // subsequent sets.
2336   SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2337   for (unsigned int I = 1; I < Locs.size(); ++I) {
2338     auto &LocVec = Locs[I];
2339     SmallVector<LocIdx, 4> NewCandidates;
2340     std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2341                           LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2342     CandidateLocs = NewCandidates;
2343   }
2344   if (CandidateLocs.empty())
2345     return None;
2346 
2347   // We now have a set of LocIdxes that contain the right output value in
2348   // each of the predecessors. Pick the lowest; if there's a register loc,
2349   // that'll be it.
2350   LocIdx L = *CandidateLocs.begin();
2351 
2352   // Return a PHI-value-number for the found location.
2353   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2354   return PHIVal;
2355 }
2356 
2357 bool InstrRefBasedLDV::vlocJoin(
2358     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2359     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2360     DbgValue &LiveIn) {
2361   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2362   bool Changed = false;
2363 
2364   // Order predecessors by RPOT order, for exploring them in that order.
2365   SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2366 
2367   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2368     return BBToOrder[A] < BBToOrder[B];
2369   };
2370 
2371   llvm::sort(BlockOrders, Cmp);
2372 
2373   unsigned CurBlockRPONum = BBToOrder[&MBB];
2374 
2375   // Collect all the incoming DbgValues for this variable, from predecessor
2376   // live-out values.
2377   SmallVector<InValueT, 8> Values;
2378   bool Bail = false;
2379   int BackEdgesStart = 0;
2380   for (auto p : BlockOrders) {
2381     // If the predecessor isn't in scope / to be explored, we'll never be
2382     // able to join any locations.
2383     if (!BlocksToExplore.contains(p)) {
2384       Bail = true;
2385       break;
2386     }
2387 
2388     // All Live-outs will have been initialized.
2389     DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2390 
2391     // Keep track of where back-edges begin in the Values vector. Relies on
2392     // BlockOrders being sorted by RPO.
2393     unsigned ThisBBRPONum = BBToOrder[p];
2394     if (ThisBBRPONum < CurBlockRPONum)
2395       ++BackEdgesStart;
2396 
2397     Values.push_back(std::make_pair(p, &OutLoc));
2398   }
2399 
2400   // If there were no values, or one of the predecessors couldn't have a
2401   // value, then give up immediately. It's not safe to produce a live-in
2402   // value. Leave as whatever it was before.
2403   if (Bail || Values.size() == 0)
2404     return false;
2405 
2406   // All (non-entry) blocks have at least one non-backedge predecessor.
2407   // Pick the variable value from the first of these, to compare against
2408   // all others.
2409   const DbgValue &FirstVal = *Values[0].second;
2410 
2411   // If the old live-in value is not a PHI then either a) no PHI is needed
2412   // here, or b) we eliminated the PHI that was here. If so, we can just
2413   // propagate in the first parent's incoming value.
2414   if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
2415     Changed = LiveIn != FirstVal;
2416     if (Changed)
2417       LiveIn = FirstVal;
2418     return Changed;
2419   }
2420 
2421   // Scan for variable values that can never be resolved: if they have
2422   // different DIExpressions, different indirectness, or are mixed constants /
2423   // non-constants.
2424   for (auto &V : Values) {
2425     if (V.second->Properties != FirstVal.Properties)
2426       return false;
2427     if (V.second->Kind == DbgValue::NoVal)
2428       return false;
2429     if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
2430       return false;
2431   }
2432 
2433   // Try to eliminate this PHI. Do the incoming values all agree?
2434   bool Disagree = false;
2435   for (auto &V : Values) {
2436     if (*V.second == FirstVal)
2437       continue; // No disagreement.
2438 
2439     // Eliminate if a backedge feeds a VPHI back into itself.
2440     if (V.second->Kind == DbgValue::VPHI &&
2441         V.second->BlockNo == MBB.getNumber() &&
2442         // Is this a backedge?
2443         std::distance(Values.begin(), &V) >= BackEdgesStart)
2444       continue;
2445 
2446     Disagree = true;
2447   }
2448 
2449   // No disagreement -> live-through value.
2450   if (!Disagree) {
2451     Changed = LiveIn != FirstVal;
2452     if (Changed)
2453       LiveIn = FirstVal;
2454     return Changed;
2455   } else {
2456     // Otherwise use a VPHI.
2457     DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
2458     Changed = LiveIn != VPHI;
2459     if (Changed)
2460       LiveIn = VPHI;
2461     return Changed;
2462   }
2463 }
2464 
2465 void InstrRefBasedLDV::getBlocksForScope(
2466     const DILocation *DILoc,
2467     SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
2468     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
2469   // Get the set of "normal" in-lexical-scope blocks.
2470   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
2471 
2472   // VarLoc LiveDebugValues tracks variable locations that are defined in
2473   // blocks not in scope. This is something we could legitimately ignore, but
2474   // lets allow it for now for the sake of coverage.
2475   BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
2476 
2477   // Storage for artificial blocks we intend to add to BlocksToExplore.
2478   DenseSet<const MachineBasicBlock *> ToAdd;
2479 
2480   // To avoid needlessly dropping large volumes of variable locations, propagate
2481   // variables through aritifical blocks, i.e. those that don't have any
2482   // instructions in scope at all. To accurately replicate VarLoc
2483   // LiveDebugValues, this means exploring all artificial successors too.
2484   // Perform a depth-first-search to enumerate those blocks.
2485   for (auto *MBB : BlocksToExplore) {
2486     // Depth-first-search state: each node is a block and which successor
2487     // we're currently exploring.
2488     SmallVector<std::pair<const MachineBasicBlock *,
2489                           MachineBasicBlock::const_succ_iterator>,
2490                 8>
2491         DFS;
2492 
2493     // Find any artificial successors not already tracked.
2494     for (auto *succ : MBB->successors()) {
2495       if (BlocksToExplore.count(succ))
2496         continue;
2497       if (!ArtificialBlocks.count(succ))
2498         continue;
2499       ToAdd.insert(succ);
2500       DFS.push_back({succ, succ->succ_begin()});
2501     }
2502 
2503     // Search all those blocks, depth first.
2504     while (!DFS.empty()) {
2505       const MachineBasicBlock *CurBB = DFS.back().first;
2506       MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
2507       // Walk back if we've explored this blocks successors to the end.
2508       if (CurSucc == CurBB->succ_end()) {
2509         DFS.pop_back();
2510         continue;
2511       }
2512 
2513       // If the current successor is artificial and unexplored, descend into
2514       // it.
2515       if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
2516         ToAdd.insert(*CurSucc);
2517         DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
2518         continue;
2519       }
2520 
2521       ++CurSucc;
2522     }
2523   };
2524 
2525   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
2526 }
2527 
2528 void InstrRefBasedLDV::buildVLocValueMap(
2529     const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2530     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2531     FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
2532     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2533   // This method is much like buildMLocValueMap: but focuses on a single
2534   // LexicalScope at a time. Pick out a set of blocks and variables that are
2535   // to have their value assignments solved, then run our dataflow algorithm
2536   // until a fixedpoint is reached.
2537   std::priority_queue<unsigned int, std::vector<unsigned int>,
2538                       std::greater<unsigned int>>
2539       Worklist, Pending;
2540   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2541 
2542   // The set of blocks we'll be examining.
2543   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2544 
2545   // The order in which to examine them (RPO).
2546   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2547 
2548   // RPO ordering function.
2549   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2550     return BBToOrder[A] < BBToOrder[B];
2551   };
2552 
2553   getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
2554 
2555   // Single block scope: not interesting! No propagation at all. Note that
2556   // this could probably go above ArtificialBlocks without damage, but
2557   // that then produces output differences from original-live-debug-values,
2558   // which propagates from a single block into many artificial ones.
2559   if (BlocksToExplore.size() == 1)
2560     return;
2561 
2562   // Convert a const set to a non-const set. LexicalScopes
2563   // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
2564   // (Neither of them mutate anything).
2565   SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
2566   for (const auto *MBB : BlocksToExplore)
2567     MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
2568 
2569   // Picks out relevants blocks RPO order and sort them.
2570   for (auto *MBB : BlocksToExplore)
2571     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2572 
2573   llvm::sort(BlockOrders, Cmp);
2574   unsigned NumBlocks = BlockOrders.size();
2575 
2576   // Allocate some vectors for storing the live ins and live outs. Large.
2577   SmallVector<DbgValue, 32> LiveIns, LiveOuts;
2578   LiveIns.reserve(NumBlocks);
2579   LiveOuts.reserve(NumBlocks);
2580 
2581   // Initialize all values to start as NoVals. This signifies "it's live
2582   // through, but we don't know what it is".
2583   DbgValueProperties EmptyProperties(EmptyExpr, false);
2584   for (unsigned int I = 0; I < NumBlocks; ++I) {
2585     DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2586     LiveIns.push_back(EmptyDbgValue);
2587     LiveOuts.push_back(EmptyDbgValue);
2588   }
2589 
2590   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
2591   // vlocJoin.
2592   LiveIdxT LiveOutIdx, LiveInIdx;
2593   LiveOutIdx.reserve(NumBlocks);
2594   LiveInIdx.reserve(NumBlocks);
2595   for (unsigned I = 0; I < NumBlocks; ++I) {
2596     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
2597     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
2598   }
2599 
2600   // Loop over each variable and place PHIs for it, then propagate values
2601   // between blocks. This keeps the locality of working on one lexical scope at
2602   // at time, but avoids re-processing variable values because some other
2603   // variable has been assigned.
2604   for (auto &Var : VarsWeCareAbout) {
2605     // Re-initialize live-ins and live-outs, to clear the remains of previous
2606     // variables live-ins / live-outs.
2607     for (unsigned int I = 0; I < NumBlocks; ++I) {
2608       DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2609       LiveIns[I] = EmptyDbgValue;
2610       LiveOuts[I] = EmptyDbgValue;
2611     }
2612 
2613     // Place PHIs for variable values, using the LLVM IDF calculator.
2614     // Collect the set of blocks where variables are def'd.
2615     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2616     for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
2617       auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
2618       if (TransferFunc.find(Var) != TransferFunc.end())
2619         DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
2620     }
2621 
2622     SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2623 
2624     // Request the set of PHIs we should insert for this variable. If there's
2625     // only one value definition, things are very simple.
2626     if (DefBlocks.size() == 1) {
2627       placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
2628                                       AllTheVLocs, Var, Output);
2629       continue;
2630     }
2631 
2632     // Otherwise: we need to place PHIs through SSA and propagate values.
2633     BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
2634 
2635     // Insert PHIs into the per-block live-in tables for this variable.
2636     for (MachineBasicBlock *PHIMBB : PHIBlocks) {
2637       unsigned BlockNo = PHIMBB->getNumber();
2638       DbgValue *LiveIn = LiveInIdx[PHIMBB];
2639       *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
2640     }
2641 
2642     for (auto *MBB : BlockOrders) {
2643       Worklist.push(BBToOrder[MBB]);
2644       OnWorklist.insert(MBB);
2645     }
2646 
2647     // Iterate over all the blocks we selected, propagating the variables value.
2648     // This loop does two things:
2649     //  * Eliminates un-necessary VPHIs in vlocJoin,
2650     //  * Evaluates the blocks transfer function (i.e. variable assignments) and
2651     //    stores the result to the blocks live-outs.
2652     // Always evaluate the transfer function on the first iteration, and when
2653     // the live-ins change thereafter.
2654     bool FirstTrip = true;
2655     while (!Worklist.empty() || !Pending.empty()) {
2656       while (!Worklist.empty()) {
2657         auto *MBB = OrderToBB[Worklist.top()];
2658         CurBB = MBB->getNumber();
2659         Worklist.pop();
2660 
2661         auto LiveInsIt = LiveInIdx.find(MBB);
2662         assert(LiveInsIt != LiveInIdx.end());
2663         DbgValue *LiveIn = LiveInsIt->second;
2664 
2665         // Join values from predecessors. Updates LiveInIdx, and writes output
2666         // into JoinedInLocs.
2667         bool InLocsChanged =
2668             vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
2669 
2670         SmallVector<const MachineBasicBlock *, 8> Preds;
2671         for (const auto *Pred : MBB->predecessors())
2672           Preds.push_back(Pred);
2673 
2674         // If this block's live-in value is a VPHI, try to pick a machine-value
2675         // for it. This makes the machine-value available and propagated
2676         // through all blocks by the time value propagation finishes. We can't
2677         // do this any earlier as it needs to read the block live-outs.
2678         if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
2679           // There's a small possibility that on a preceeding path, a VPHI is
2680           // eliminated and transitions from VPHI-with-location to
2681           // live-through-value. As a result, the selected location of any VPHI
2682           // might change, so we need to re-compute it on each iteration.
2683           Optional<ValueIDNum> ValueNum =
2684               pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds);
2685 
2686           if (ValueNum) {
2687             InLocsChanged |= LiveIn->ID != *ValueNum;
2688             LiveIn->ID = *ValueNum;
2689           }
2690         }
2691 
2692         if (!InLocsChanged && !FirstTrip)
2693           continue;
2694 
2695         DbgValue *LiveOut = LiveOutIdx[MBB];
2696         bool OLChanged = false;
2697 
2698         // Do transfer function.
2699         auto &VTracker = AllTheVLocs[MBB->getNumber()];
2700         auto TransferIt = VTracker.Vars.find(Var);
2701         if (TransferIt != VTracker.Vars.end()) {
2702           // Erase on empty transfer (DBG_VALUE $noreg).
2703           if (TransferIt->second.Kind == DbgValue::Undef) {
2704             DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
2705             if (*LiveOut != NewVal) {
2706               *LiveOut = NewVal;
2707               OLChanged = true;
2708             }
2709           } else {
2710             // Insert new variable value; or overwrite.
2711             if (*LiveOut != TransferIt->second) {
2712               *LiveOut = TransferIt->second;
2713               OLChanged = true;
2714             }
2715           }
2716         } else {
2717           // Just copy live-ins to live-outs, for anything not transferred.
2718           if (*LiveOut != *LiveIn) {
2719             *LiveOut = *LiveIn;
2720             OLChanged = true;
2721           }
2722         }
2723 
2724         // If no live-out value changed, there's no need to explore further.
2725         if (!OLChanged)
2726           continue;
2727 
2728         // We should visit all successors. Ensure we'll visit any non-backedge
2729         // successors during this dataflow iteration; book backedge successors
2730         // to be visited next time around.
2731         for (auto s : MBB->successors()) {
2732           // Ignore out of scope / not-to-be-explored successors.
2733           if (LiveInIdx.find(s) == LiveInIdx.end())
2734             continue;
2735 
2736           if (BBToOrder[s] > BBToOrder[MBB]) {
2737             if (OnWorklist.insert(s).second)
2738               Worklist.push(BBToOrder[s]);
2739           } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
2740             Pending.push(BBToOrder[s]);
2741           }
2742         }
2743       }
2744       Worklist.swap(Pending);
2745       std::swap(OnWorklist, OnPending);
2746       OnPending.clear();
2747       assert(Pending.empty());
2748       FirstTrip = false;
2749     }
2750 
2751     // Save live-ins to output vector. Ignore any that are still marked as being
2752     // VPHIs with no location -- those are variables that we know the value of,
2753     // but are not actually available in the register file.
2754     for (auto *MBB : BlockOrders) {
2755       DbgValue *BlockLiveIn = LiveInIdx[MBB];
2756       if (BlockLiveIn->Kind == DbgValue::NoVal)
2757         continue;
2758       if (BlockLiveIn->Kind == DbgValue::VPHI &&
2759           BlockLiveIn->ID == ValueIDNum::EmptyValue)
2760         continue;
2761       if (BlockLiveIn->Kind == DbgValue::VPHI)
2762         BlockLiveIn->Kind = DbgValue::Def;
2763       assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
2764              Var.getFragment() && "Fragment info missing during value prop");
2765       Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
2766     }
2767   } // Per-variable loop.
2768 
2769   BlockOrders.clear();
2770   BlocksToExplore.clear();
2771 }
2772 
2773 void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
2774     const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
2775     MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
2776     const DebugVariable &Var, LiveInsT &Output) {
2777   // If there is a single definition of the variable, then working out it's
2778   // value everywhere is very simple: it's every block dominated by the
2779   // definition. At the dominance frontier, the usual algorithm would:
2780   //  * Place PHIs,
2781   //  * Propagate values into them,
2782   //  * Find there's no incoming variable value from the other incoming branches
2783   //    of the dominance frontier,
2784   //  * Specify there's no variable value in blocks past the frontier.
2785   // This is a common case, hence it's worth special-casing it.
2786 
2787   // Pick out the variables value from the block transfer function.
2788   VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
2789   auto ValueIt = VLocs.Vars.find(Var);
2790   const DbgValue &Value = ValueIt->second;
2791 
2792   // If it's an explicit assignment of "undef", that means there is no location
2793   // anyway, anywhere.
2794   if (Value.Kind == DbgValue::Undef)
2795     return;
2796 
2797   // Assign the variable value to entry to each dominated block that's in scope.
2798   // Skip the definition block -- it's assigned the variable value in the middle
2799   // of the block somewhere.
2800   for (auto *ScopeBlock : InScopeBlocks) {
2801     if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
2802       continue;
2803 
2804     Output[ScopeBlock->getNumber()].push_back({Var, Value});
2805   }
2806 
2807   // All blocks that aren't dominated have no live-in value, thus no variable
2808   // value will be given to them.
2809 }
2810 
2811 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2812 void InstrRefBasedLDV::dump_mloc_transfer(
2813     const MLocTransferMap &mloc_transfer) const {
2814   for (auto &P : mloc_transfer) {
2815     std::string foo = MTracker->LocIdxToName(P.first);
2816     std::string bar = MTracker->IDAsString(P.second);
2817     dbgs() << "Loc " << foo << " --> " << bar << "\n";
2818   }
2819 }
2820 #endif
2821 
2822 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
2823   // Build some useful data structures.
2824 
2825   LLVMContext &Context = MF.getFunction().getContext();
2826   EmptyExpr = DIExpression::get(Context, {});
2827 
2828   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2829     if (const DebugLoc &DL = MI.getDebugLoc())
2830       return DL.getLine() != 0;
2831     return false;
2832   };
2833   // Collect a set of all the artificial blocks.
2834   for (auto &MBB : MF)
2835     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2836       ArtificialBlocks.insert(&MBB);
2837 
2838   // Compute mappings of block <=> RPO order.
2839   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2840   unsigned int RPONumber = 0;
2841   for (MachineBasicBlock *MBB : RPOT) {
2842     OrderToBB[RPONumber] = MBB;
2843     BBToOrder[MBB] = RPONumber;
2844     BBNumToRPO[MBB->getNumber()] = RPONumber;
2845     ++RPONumber;
2846   }
2847 
2848   // Order value substitutions by their "source" operand pair, for quick lookup.
2849   llvm::sort(MF.DebugValueSubstitutions);
2850 
2851 #ifdef EXPENSIVE_CHECKS
2852   // As an expensive check, test whether there are any duplicate substitution
2853   // sources in the collection.
2854   if (MF.DebugValueSubstitutions.size() > 2) {
2855     for (auto It = MF.DebugValueSubstitutions.begin();
2856          It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
2857       assert(It->Src != std::next(It)->Src && "Duplicate variable location "
2858                                               "substitution seen");
2859     }
2860   }
2861 #endif
2862 }
2863 
2864 // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
2865 // lexical scope it's used in. When exploring in DFS order and we pass that
2866 // scope, the block can be processed and any tracking information freed.
2867 void InstrRefBasedLDV::makeDepthFirstEjectionMap(
2868     SmallVectorImpl<unsigned> &EjectionMap,
2869     const ScopeToDILocT &ScopeToDILocation,
2870     ScopeToAssignBlocksT &ScopeToAssignBlocks) {
2871   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2872   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
2873   auto *TopScope = LS.getCurrentFunctionScope();
2874 
2875   // Unlike lexical scope explorers, we explore in reverse order, to find the
2876   // "last" lexical scope used for each block early.
2877   WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
2878 
2879   while (!WorkStack.empty()) {
2880     auto &ScopePosition = WorkStack.back();
2881     LexicalScope *WS = ScopePosition.first;
2882     ssize_t ChildNum = ScopePosition.second--;
2883 
2884     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
2885     if (ChildNum >= 0) {
2886       // If ChildNum is positive, there are remaining children to explore.
2887       // Push the child and its children-count onto the stack.
2888       auto &ChildScope = Children[ChildNum];
2889       WorkStack.push_back(
2890           std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
2891     } else {
2892       WorkStack.pop_back();
2893 
2894       // We've explored all children and any later blocks: examine all blocks
2895       // in our scope. If they haven't yet had an ejection number set, then
2896       // this scope will be the last to use that block.
2897       auto DILocationIt = ScopeToDILocation.find(WS);
2898       if (DILocationIt != ScopeToDILocation.end()) {
2899         getBlocksForScope(DILocationIt->second, BlocksToExplore,
2900                           ScopeToAssignBlocks.find(WS)->second);
2901         for (auto *MBB : BlocksToExplore) {
2902           unsigned BBNum = MBB->getNumber();
2903           if (EjectionMap[BBNum] == 0)
2904             EjectionMap[BBNum] = WS->getDFSOut();
2905         }
2906 
2907         BlocksToExplore.clear();
2908       }
2909     }
2910   }
2911 }
2912 
2913 bool InstrRefBasedLDV::depthFirstVLocAndEmit(
2914     unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
2915     const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
2916     LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
2917     SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
2918     DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
2919     const TargetPassConfig &TPC) {
2920   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
2921   unsigned NumLocs = MTracker->getNumLocs();
2922   VTracker = nullptr;
2923 
2924   // No scopes? No variable locations.
2925   if (!LS.getCurrentFunctionScope())
2926     return false;
2927 
2928   // Build map from block number to the last scope that uses the block.
2929   SmallVector<unsigned, 16> EjectionMap;
2930   EjectionMap.resize(MaxNumBlocks, 0);
2931   makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
2932                             ScopeToAssignBlocks);
2933 
2934   // Helper lambda for ejecting a block -- if nothing is going to use the block,
2935   // we can translate the variable location information into DBG_VALUEs and then
2936   // free all of InstrRefBasedLDV's data structures.
2937   auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
2938     unsigned BBNum = MBB.getNumber();
2939     AllTheVLocs[BBNum].clear();
2940 
2941     // Prime the transfer-tracker, and then step through all the block
2942     // instructions, installing transfers.
2943     MTracker->reset();
2944     MTracker->loadFromArray(MInLocs[BBNum], BBNum);
2945     TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs);
2946 
2947     CurBB = BBNum;
2948     CurInst = 1;
2949     for (auto &MI : MBB) {
2950       process(MI, MOutLocs.get(), MInLocs.get());
2951       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
2952       ++CurInst;
2953     }
2954 
2955     // Free machine-location tables for this block.
2956     MInLocs[BBNum].reset();
2957     MOutLocs[BBNum].reset();
2958     // We don't need live-in variable values for this block either.
2959     Output[BBNum].clear();
2960     AllTheVLocs[BBNum].clear();
2961   };
2962 
2963   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2964   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
2965   WorkStack.push_back({LS.getCurrentFunctionScope(), 0});
2966   unsigned HighestDFSIn = 0;
2967 
2968   // Proceed to explore in depth first order.
2969   while (!WorkStack.empty()) {
2970     auto &ScopePosition = WorkStack.back();
2971     LexicalScope *WS = ScopePosition.first;
2972     ssize_t ChildNum = ScopePosition.second++;
2973 
2974     // We obesrve scopes with children twice here, once descending in, once
2975     // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
2976     // we don't process a scope twice. Additionally, ignore scopes that don't
2977     // have a DILocation -- by proxy, this means we never tracked any variable
2978     // assignments in that scope.
2979     auto DILocIt = ScopeToDILocation.find(WS);
2980     if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
2981       const DILocation *DILoc = DILocIt->second;
2982       auto &VarsWeCareAbout = ScopeToVars.find(WS)->second;
2983       auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second;
2984 
2985       buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs,
2986                         MInLocs, AllTheVLocs);
2987     }
2988 
2989     HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn());
2990 
2991     // Descend into any scope nests.
2992     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
2993     if (ChildNum < (ssize_t)Children.size()) {
2994       // There are children to explore -- push onto stack and continue.
2995       auto &ChildScope = Children[ChildNum];
2996       WorkStack.push_back(std::make_pair(ChildScope, 0));
2997     } else {
2998       WorkStack.pop_back();
2999 
3000       // We've explored a leaf, or have explored all the children of a scope.
3001       // Try to eject any blocks where this is the last scope it's relevant to.
3002       auto DILocationIt = ScopeToDILocation.find(WS);
3003       if (DILocationIt == ScopeToDILocation.end())
3004         continue;
3005 
3006       getBlocksForScope(DILocationIt->second, BlocksToExplore,
3007                         ScopeToAssignBlocks.find(WS)->second);
3008       for (auto *MBB : BlocksToExplore)
3009         if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
3010           EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
3011 
3012       BlocksToExplore.clear();
3013     }
3014   }
3015 
3016   // Some artificial blocks may not have been ejected, meaning they're not
3017   // connected to an actual legitimate scope. This can technically happen
3018   // with things like the entry block. In theory, we shouldn't need to do
3019   // anything for such out-of-scope blocks, but for the sake of being similar
3020   // to VarLocBasedLDV, eject these too.
3021   for (auto *MBB : ArtificialBlocks)
3022     if (MOutLocs[MBB->getNumber()])
3023       EjectBlock(*MBB);
3024 
3025   return emitTransfers(AllVarsNumbering);
3026 }
3027 
3028 bool InstrRefBasedLDV::emitTransfers(
3029     DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
3030   // Go through all the transfers recorded in the TransferTracker -- this is
3031   // both the live-ins to a block, and any movements of values that happen
3032   // in the middle.
3033   for (const auto &P : TTracker->Transfers) {
3034     // We have to insert DBG_VALUEs in a consistent order, otherwise they
3035     // appear in DWARF in different orders. Use the order that they appear
3036     // when walking through each block / each instruction, stored in
3037     // AllVarsNumbering.
3038     SmallVector<std::pair<unsigned, MachineInstr *>> Insts;
3039     for (MachineInstr *MI : P.Insts) {
3040       DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(),
3041                         MI->getDebugLoc()->getInlinedAt());
3042       Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI);
3043     }
3044     llvm::sort(Insts,
3045                [](const auto &A, const auto &B) { return A.first < B.first; });
3046 
3047     // Insert either before or after the designated point...
3048     if (P.MBB) {
3049       MachineBasicBlock &MBB = *P.MBB;
3050       for (const auto &Pair : Insts)
3051         MBB.insert(P.Pos, Pair.second);
3052     } else {
3053       // Terminators, like tail calls, can clobber things. Don't try and place
3054       // transfers after them.
3055       if (P.Pos->isTerminator())
3056         continue;
3057 
3058       MachineBasicBlock &MBB = *P.Pos->getParent();
3059       for (const auto &Pair : Insts)
3060         MBB.insertAfterBundle(P.Pos, Pair.second);
3061     }
3062   }
3063 
3064   return TTracker->Transfers.size() != 0;
3065 }
3066 
3067 /// Calculate the liveness information for the given machine function and
3068 /// extend ranges across basic blocks.
3069 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3070                                     MachineDominatorTree *DomTree,
3071                                     TargetPassConfig *TPC,
3072                                     unsigned InputBBLimit,
3073                                     unsigned InputDbgValLimit) {
3074   // No subprogram means this function contains no debuginfo.
3075   if (!MF.getFunction().getSubprogram())
3076     return false;
3077 
3078   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3079   this->TPC = TPC;
3080 
3081   this->DomTree = DomTree;
3082   TRI = MF.getSubtarget().getRegisterInfo();
3083   MRI = &MF.getRegInfo();
3084   TII = MF.getSubtarget().getInstrInfo();
3085   TFI = MF.getSubtarget().getFrameLowering();
3086   TFI->getCalleeSaves(MF, CalleeSavedRegs);
3087   MFI = &MF.getFrameInfo();
3088   LS.initialize(MF);
3089 
3090   const auto &STI = MF.getSubtarget();
3091   AdjustsStackInCalls = MFI->adjustsStack() &&
3092                         STI.getFrameLowering()->stackProbeFunctionModifiesSP();
3093   if (AdjustsStackInCalls)
3094     StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
3095 
3096   MTracker =
3097       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3098   VTracker = nullptr;
3099   TTracker = nullptr;
3100 
3101   SmallVector<MLocTransferMap, 32> MLocTransfer;
3102   SmallVector<VLocTracker, 8> vlocs;
3103   LiveInsT SavedLiveIns;
3104 
3105   int MaxNumBlocks = -1;
3106   for (auto &MBB : MF)
3107     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3108   assert(MaxNumBlocks >= 0);
3109   ++MaxNumBlocks;
3110 
3111   MLocTransfer.resize(MaxNumBlocks);
3112   vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr));
3113   SavedLiveIns.resize(MaxNumBlocks);
3114 
3115   initialSetup(MF);
3116 
3117   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3118 
3119   // Allocate and initialize two array-of-arrays for the live-in and live-out
3120   // machine values. The outer dimension is the block number; while the inner
3121   // dimension is a LocIdx from MLocTracker.
3122   FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3123   FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3124   unsigned NumLocs = MTracker->getNumLocs();
3125   for (int i = 0; i < MaxNumBlocks; ++i) {
3126     // These all auto-initialize to ValueIDNum::EmptyValue
3127     MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3128     MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3129   }
3130 
3131   // Solve the machine value dataflow problem using the MLocTransfer function,
3132   // storing the computed live-ins / live-outs into the array-of-arrays. We use
3133   // both live-ins and live-outs for decision making in the variable value
3134   // dataflow problem.
3135   buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3136 
3137   // Patch up debug phi numbers, turning unknown block-live-in values into
3138   // either live-through machine values, or PHIs.
3139   for (auto &DBG_PHI : DebugPHINumToValue) {
3140     // Identify unresolved block-live-ins.
3141     if (!DBG_PHI.ValueRead)
3142       continue;
3143 
3144     ValueIDNum &Num = *DBG_PHI.ValueRead;
3145     if (!Num.isPHI())
3146       continue;
3147 
3148     unsigned BlockNo = Num.getBlock();
3149     LocIdx LocNo = Num.getLoc();
3150     Num = MInLocs[BlockNo][LocNo.asU64()];
3151   }
3152   // Later, we'll be looking up ranges of instruction numbers.
3153   llvm::sort(DebugPHINumToValue);
3154 
3155   // Walk back through each block / instruction, collecting DBG_VALUE
3156   // instructions and recording what machine value their operands refer to.
3157   for (auto &OrderPair : OrderToBB) {
3158     MachineBasicBlock &MBB = *OrderPair.second;
3159     CurBB = MBB.getNumber();
3160     VTracker = &vlocs[CurBB];
3161     VTracker->MBB = &MBB;
3162     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3163     CurInst = 1;
3164     for (auto &MI : MBB) {
3165       process(MI, MOutLocs.get(), MInLocs.get());
3166       ++CurInst;
3167     }
3168     MTracker->reset();
3169   }
3170 
3171   // Number all variables in the order that they appear, to be used as a stable
3172   // insertion order later.
3173   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3174 
3175   // Map from one LexicalScope to all the variables in that scope.
3176   ScopeToVarsT ScopeToVars;
3177 
3178   // Map from One lexical scope to all blocks where assignments happen for
3179   // that scope.
3180   ScopeToAssignBlocksT ScopeToAssignBlocks;
3181 
3182   // Store map of DILocations that describes scopes.
3183   ScopeToDILocT ScopeToDILocation;
3184 
3185   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3186   // the order is unimportant, it just has to be stable.
3187   unsigned VarAssignCount = 0;
3188   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3189     auto *MBB = OrderToBB[I];
3190     auto *VTracker = &vlocs[MBB->getNumber()];
3191     // Collect each variable with a DBG_VALUE in this block.
3192     for (auto &idx : VTracker->Vars) {
3193       const auto &Var = idx.first;
3194       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3195       assert(ScopeLoc != nullptr);
3196       auto *Scope = LS.findLexicalScope(ScopeLoc);
3197 
3198       // No insts in scope -> shouldn't have been recorded.
3199       assert(Scope != nullptr);
3200 
3201       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3202       ScopeToVars[Scope].insert(Var);
3203       ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
3204       ScopeToDILocation[Scope] = ScopeLoc;
3205       ++VarAssignCount;
3206     }
3207   }
3208 
3209   bool Changed = false;
3210 
3211   // If we have an extremely large number of variable assignments and blocks,
3212   // bail out at this point. We've burnt some time doing analysis already,
3213   // however we should cut our losses.
3214   if ((unsigned)MaxNumBlocks > InputBBLimit &&
3215       VarAssignCount > InputDbgValLimit) {
3216     LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3217                       << " has " << MaxNumBlocks << " basic blocks and "
3218                       << VarAssignCount
3219                       << " variable assignments, exceeding limits.\n");
3220   } else {
3221     // Optionally, solve the variable value problem and emit to blocks by using
3222     // a lexical-scope-depth search. It should be functionally identical to
3223     // the "else" block of this condition.
3224     Changed = depthFirstVLocAndEmit(
3225         MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
3226         SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC);
3227   }
3228 
3229   delete MTracker;
3230   delete TTracker;
3231   MTracker = nullptr;
3232   VTracker = nullptr;
3233   TTracker = nullptr;
3234 
3235   ArtificialBlocks.clear();
3236   OrderToBB.clear();
3237   BBToOrder.clear();
3238   BBNumToRPO.clear();
3239   DebugInstrNumToInstr.clear();
3240   DebugPHINumToValue.clear();
3241   OverlapFragments.clear();
3242   SeenFragments.clear();
3243   SeenDbgPHIs.clear();
3244 
3245   return Changed;
3246 }
3247 
3248 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3249   return new InstrRefBasedLDV();
3250 }
3251 
3252 namespace {
3253 class LDVSSABlock;
3254 class LDVSSAUpdater;
3255 
3256 // Pick a type to identify incoming block values as we construct SSA. We
3257 // can't use anything more robust than an integer unfortunately, as SSAUpdater
3258 // expects to zero-initialize the type.
3259 typedef uint64_t BlockValueNum;
3260 
3261 /// Represents an SSA PHI node for the SSA updater class. Contains the block
3262 /// this PHI is in, the value number it would have, and the expected incoming
3263 /// values from parent blocks.
3264 class LDVSSAPhi {
3265 public:
3266   SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3267   LDVSSABlock *ParentBlock;
3268   BlockValueNum PHIValNum;
3269   LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3270       : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3271 
3272   LDVSSABlock *getParent() { return ParentBlock; }
3273 };
3274 
3275 /// Thin wrapper around a block predecessor iterator. Only difference from a
3276 /// normal block iterator is that it dereferences to an LDVSSABlock.
3277 class LDVSSABlockIterator {
3278 public:
3279   MachineBasicBlock::pred_iterator PredIt;
3280   LDVSSAUpdater &Updater;
3281 
3282   LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3283                       LDVSSAUpdater &Updater)
3284       : PredIt(PredIt), Updater(Updater) {}
3285 
3286   bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3287     return OtherIt.PredIt != PredIt;
3288   }
3289 
3290   LDVSSABlockIterator &operator++() {
3291     ++PredIt;
3292     return *this;
3293   }
3294 
3295   LDVSSABlock *operator*();
3296 };
3297 
3298 /// Thin wrapper around a block for SSA Updater interface. Necessary because
3299 /// we need to track the PHI value(s) that we may have observed as necessary
3300 /// in this block.
3301 class LDVSSABlock {
3302 public:
3303   MachineBasicBlock &BB;
3304   LDVSSAUpdater &Updater;
3305   using PHIListT = SmallVector<LDVSSAPhi, 1>;
3306   /// List of PHIs in this block. There should only ever be one.
3307   PHIListT PHIList;
3308 
3309   LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3310       : BB(BB), Updater(Updater) {}
3311 
3312   LDVSSABlockIterator succ_begin() {
3313     return LDVSSABlockIterator(BB.succ_begin(), Updater);
3314   }
3315 
3316   LDVSSABlockIterator succ_end() {
3317     return LDVSSABlockIterator(BB.succ_end(), Updater);
3318   }
3319 
3320   /// SSAUpdater has requested a PHI: create that within this block record.
3321   LDVSSAPhi *newPHI(BlockValueNum Value) {
3322     PHIList.emplace_back(Value, this);
3323     return &PHIList.back();
3324   }
3325 
3326   /// SSAUpdater wishes to know what PHIs already exist in this block.
3327   PHIListT &phis() { return PHIList; }
3328 };
3329 
3330 /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3331 /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3332 // SSAUpdaterTraits<LDVSSAUpdater>.
3333 class LDVSSAUpdater {
3334 public:
3335   /// Map of value numbers to PHI records.
3336   DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3337   /// Map of which blocks generate Undef values -- blocks that are not
3338   /// dominated by any Def.
3339   DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3340   /// Map of machine blocks to our own records of them.
3341   DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3342   /// Machine location where any PHI must occur.
3343   LocIdx Loc;
3344   /// Table of live-in machine value numbers for blocks / locations.
3345   const ValueTable *MLiveIns;
3346 
3347   LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns)
3348       : Loc(L), MLiveIns(MLiveIns) {}
3349 
3350   void reset() {
3351     for (auto &Block : BlockMap)
3352       delete Block.second;
3353 
3354     PHIs.clear();
3355     UndefMap.clear();
3356     BlockMap.clear();
3357   }
3358 
3359   ~LDVSSAUpdater() { reset(); }
3360 
3361   /// For a given MBB, create a wrapper block for it. Stores it in the
3362   /// LDVSSAUpdater block map.
3363   LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3364     auto it = BlockMap.find(BB);
3365     if (it == BlockMap.end()) {
3366       BlockMap[BB] = new LDVSSABlock(*BB, *this);
3367       it = BlockMap.find(BB);
3368     }
3369     return it->second;
3370   }
3371 
3372   /// Find the live-in value number for the given block. Looks up the value at
3373   /// the PHI location on entry.
3374   BlockValueNum getValue(LDVSSABlock *LDVBB) {
3375     return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3376   }
3377 };
3378 
3379 LDVSSABlock *LDVSSABlockIterator::operator*() {
3380   return Updater.getSSALDVBlock(*PredIt);
3381 }
3382 
3383 #ifndef NDEBUG
3384 
3385 raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3386   out << "SSALDVPHI " << PHI.PHIValNum;
3387   return out;
3388 }
3389 
3390 #endif
3391 
3392 } // namespace
3393 
3394 namespace llvm {
3395 
3396 /// Template specialization to give SSAUpdater access to CFG and value
3397 /// information. SSAUpdater calls methods in these traits, passing in the
3398 /// LDVSSAUpdater object, to learn about blocks and the values they define.
3399 /// It also provides methods to create PHI nodes and track them.
3400 template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3401 public:
3402   using BlkT = LDVSSABlock;
3403   using ValT = BlockValueNum;
3404   using PhiT = LDVSSAPhi;
3405   using BlkSucc_iterator = LDVSSABlockIterator;
3406 
3407   // Methods to access block successors -- dereferencing to our wrapper class.
3408   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
3409   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3410 
3411   /// Iterator for PHI operands.
3412   class PHI_iterator {
3413   private:
3414     LDVSSAPhi *PHI;
3415     unsigned Idx;
3416 
3417   public:
3418     explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3419         : PHI(P), Idx(0) {}
3420     PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3421         : PHI(P), Idx(PHI->IncomingValues.size()) {}
3422 
3423     PHI_iterator &operator++() {
3424       Idx++;
3425       return *this;
3426     }
3427     bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
3428     bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3429 
3430     BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
3431 
3432     LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
3433   };
3434 
3435   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
3436 
3437   static inline PHI_iterator PHI_end(PhiT *PHI) {
3438     return PHI_iterator(PHI, true);
3439   }
3440 
3441   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
3442   /// vector.
3443   static void FindPredecessorBlocks(LDVSSABlock *BB,
3444                                     SmallVectorImpl<LDVSSABlock *> *Preds) {
3445     for (MachineBasicBlock *Pred : BB->BB.predecessors())
3446       Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
3447   }
3448 
3449   /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
3450   /// register. For LiveDebugValues, represents a block identified as not having
3451   /// any DBG_PHI predecessors.
3452   static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
3453     // Create a value number for this block -- it needs to be unique and in the
3454     // "undef" collection, so that we know it's not real. Use a number
3455     // representing a PHI into this block.
3456     BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
3457     Updater->UndefMap[&BB->BB] = Num;
3458     return Num;
3459   }
3460 
3461   /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
3462   /// SSAUpdater will populate it with information about incoming values. The
3463   /// value number of this PHI is whatever the  machine value number problem
3464   /// solution determined it to be. This includes non-phi values if SSAUpdater
3465   /// tries to create a PHI where the incoming values are identical.
3466   static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
3467                                    LDVSSAUpdater *Updater) {
3468     BlockValueNum PHIValNum = Updater->getValue(BB);
3469     LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
3470     Updater->PHIs[PHIValNum] = PHI;
3471     return PHIValNum;
3472   }
3473 
3474   /// AddPHIOperand - Add the specified value as an operand of the PHI for
3475   /// the specified predecessor block.
3476   static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
3477     PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
3478   }
3479 
3480   /// ValueIsPHI - Check if the instruction that defines the specified value
3481   /// is a PHI instruction.
3482   static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3483     auto PHIIt = Updater->PHIs.find(Val);
3484     if (PHIIt == Updater->PHIs.end())
3485       return nullptr;
3486     return PHIIt->second;
3487   }
3488 
3489   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
3490   /// operands, i.e., it was just added.
3491   static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3492     LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
3493     if (PHI && PHI->IncomingValues.size() == 0)
3494       return PHI;
3495     return nullptr;
3496   }
3497 
3498   /// GetPHIValue - For the specified PHI instruction, return the value
3499   /// that it defines.
3500   static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
3501 };
3502 
3503 } // end namespace llvm
3504 
3505 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
3506     MachineFunction &MF, const ValueTable *MLiveOuts,
3507     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
3508   assert(MLiveOuts && MLiveIns &&
3509          "Tried to resolve DBG_PHI before location "
3510          "tables allocated?");
3511 
3512   // This function will be called twice per DBG_INSTR_REF, and might end up
3513   // computing lots of SSA information: memoize it.
3514   auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here);
3515   if (SeenDbgPHIIt != SeenDbgPHIs.end())
3516     return SeenDbgPHIIt->second;
3517 
3518   Optional<ValueIDNum> Result =
3519       resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
3520   SeenDbgPHIs.insert({&Here, Result});
3521   return Result;
3522 }
3523 
3524 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
3525     MachineFunction &MF, const ValueTable *MLiveOuts,
3526     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
3527   // Pick out records of DBG_PHI instructions that have been observed. If there
3528   // are none, then we cannot compute a value number.
3529   auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
3530                                     DebugPHINumToValue.end(), InstrNum);
3531   auto LowerIt = RangePair.first;
3532   auto UpperIt = RangePair.second;
3533 
3534   // No DBG_PHI means there can be no location.
3535   if (LowerIt == UpperIt)
3536     return None;
3537 
3538   // If any DBG_PHIs referred to a location we didn't understand, don't try to
3539   // compute a value. There might be scenarios where we could recover a value
3540   // for some range of DBG_INSTR_REFs, but at this point we can have high
3541   // confidence that we've seen a bug.
3542   auto DBGPHIRange = make_range(LowerIt, UpperIt);
3543   for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
3544     if (!DBG_PHI.ValueRead)
3545       return None;
3546 
3547   // If there's only one DBG_PHI, then that is our value number.
3548   if (std::distance(LowerIt, UpperIt) == 1)
3549     return *LowerIt->ValueRead;
3550 
3551   // Pick out the location (physreg, slot) where any PHIs must occur. It's
3552   // technically possible for us to merge values in different registers in each
3553   // block, but highly unlikely that LLVM will generate such code after register
3554   // allocation.
3555   LocIdx Loc = *LowerIt->ReadLoc;
3556 
3557   // We have several DBG_PHIs, and a use position (the Here inst). All each
3558   // DBG_PHI does is identify a value at a program position. We can treat each
3559   // DBG_PHI like it's a Def of a value, and the use position is a Use of a
3560   // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
3561   // determine which Def is used at the Use, and any PHIs that happen along
3562   // the way.
3563   // Adapted LLVM SSA Updater:
3564   LDVSSAUpdater Updater(Loc, MLiveIns);
3565   // Map of which Def or PHI is the current value in each block.
3566   DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
3567   // Set of PHIs that we have created along the way.
3568   SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
3569 
3570   // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
3571   // for the SSAUpdater.
3572   for (const auto &DBG_PHI : DBGPHIRange) {
3573     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3574     const ValueIDNum &Num = *DBG_PHI.ValueRead;
3575     AvailableValues.insert(std::make_pair(Block, Num.asU64()));
3576   }
3577 
3578   LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
3579   const auto &AvailIt = AvailableValues.find(HereBlock);
3580   if (AvailIt != AvailableValues.end()) {
3581     // Actually, we already know what the value is -- the Use is in the same
3582     // block as the Def.
3583     return ValueIDNum::fromU64(AvailIt->second);
3584   }
3585 
3586   // Otherwise, we must use the SSA Updater. It will identify the value number
3587   // that we are to use, and the PHIs that must happen along the way.
3588   SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
3589   BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
3590   ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
3591 
3592   // We have the number for a PHI, or possibly live-through value, to be used
3593   // at this Use. There are a number of things we have to check about it though:
3594   //  * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
3595   //    Use was not completely dominated by DBG_PHIs and we should abort.
3596   //  * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
3597   //    we've left SSA form. Validate that the inputs to each PHI are the
3598   //    expected values.
3599   //  * Is a PHI we've created actually a merging of values, or are all the
3600   //    predecessor values the same, leading to a non-PHI machine value number?
3601   //    (SSAUpdater doesn't know that either). Remap validated PHIs into the
3602   //    the ValidatedValues collection below to sort this out.
3603   DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
3604 
3605   // Define all the input DBG_PHI values in ValidatedValues.
3606   for (const auto &DBG_PHI : DBGPHIRange) {
3607     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3608     const ValueIDNum &Num = *DBG_PHI.ValueRead;
3609     ValidatedValues.insert(std::make_pair(Block, Num));
3610   }
3611 
3612   // Sort PHIs to validate into RPO-order.
3613   SmallVector<LDVSSAPhi *, 8> SortedPHIs;
3614   for (auto &PHI : CreatedPHIs)
3615     SortedPHIs.push_back(PHI);
3616 
3617   std::sort(
3618       SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) {
3619         return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
3620       });
3621 
3622   for (auto &PHI : SortedPHIs) {
3623     ValueIDNum ThisBlockValueNum =
3624         MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
3625 
3626     // Are all these things actually defined?
3627     for (auto &PHIIt : PHI->IncomingValues) {
3628       // Any undef input means DBG_PHIs didn't dominate the use point.
3629       if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
3630         return None;
3631 
3632       ValueIDNum ValueToCheck;
3633       const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
3634 
3635       auto VVal = ValidatedValues.find(PHIIt.first);
3636       if (VVal == ValidatedValues.end()) {
3637         // We cross a loop, and this is a backedge. LLVMs tail duplication
3638         // happens so late that DBG_PHI instructions should not be able to
3639         // migrate into loops -- meaning we can only be live-through this
3640         // loop.
3641         ValueToCheck = ThisBlockValueNum;
3642       } else {
3643         // Does the block have as a live-out, in the location we're examining,
3644         // the value that we expect? If not, it's been moved or clobbered.
3645         ValueToCheck = VVal->second;
3646       }
3647 
3648       if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
3649         return None;
3650     }
3651 
3652     // Record this value as validated.
3653     ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
3654   }
3655 
3656   // All the PHIs are valid: we can return what the SSAUpdater said our value
3657   // number was.
3658   return Result;
3659 }
3660