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