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