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