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::findStackIndexInterference(
1888     SmallVectorImpl<unsigned> &Slots) {
1889   // We could spend a bit of time finding the exact, minimal, set of stack
1890   // indexes that interfere with each other, much like reg units. Or, we can
1891   // rely on the fact that:
1892   //  * The smallest / lowest index will interfere with everything at zero
1893   //    offset, which will be the largest set of registers,
1894   //  * Most indexes with non-zero offset will end up being interference units
1895   //    anyway.
1896   // So just pick those out and return them.
1897 
1898   // We can rely on a single-byte stack index existing already, because we
1899   // initialize them in MLocTracker.
1900   auto It = MTracker->StackSlotIdxes.find({8, 0});
1901   assert(It != MTracker->StackSlotIdxes.end());
1902   Slots.push_back(It->second);
1903 
1904   // Find anything that has a non-zero offset and add that too.
1905   for (auto &Pair : MTracker->StackSlotIdxes) {
1906     // Is offset zero? If so, ignore.
1907     if (!Pair.first.second)
1908       continue;
1909     Slots.push_back(Pair.second);
1910   }
1911 }
1912 
1913 void InstrRefBasedLDV::placeMLocPHIs(
1914     MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1915     ValueIDNum **MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
1916   SmallVector<unsigned, 4> StackUnits;
1917   findStackIndexInterference(StackUnits);
1918 
1919   // To avoid repeatedly running the PHI placement algorithm, leverage the
1920   // fact that a def of register MUST also def its register units. Find the
1921   // units for registers, place PHIs for them, and then replicate them for
1922   // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
1923   // arguments) don't lead to register units being tracked, just place PHIs for
1924   // those registers directly. Stack slots have their own form of "unit",
1925   // store them to one side.
1926   SmallSet<Register, 32> RegUnitsToPHIUp;
1927   SmallSet<LocIdx, 32> NormalLocsToPHI;
1928   SmallSet<SpillLocationNo, 32> StackSlots;
1929   for (auto Location : MTracker->locations()) {
1930     LocIdx L = Location.Idx;
1931     if (MTracker->isSpill(L)) {
1932       StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
1933       continue;
1934     }
1935 
1936     Register R = MTracker->LocIdxToLocID[L];
1937     SmallSet<Register, 8> FoundRegUnits;
1938     bool AnyIllegal = false;
1939     for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) {
1940       for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){
1941         if (!MTracker->isRegisterTracked(*URoot)) {
1942           // Not all roots were loaded into the tracking map: this register
1943           // isn't actually def'd anywhere, we only read from it. Generate PHIs
1944           // for this reg, but don't iterate units.
1945           AnyIllegal = true;
1946         } else {
1947           FoundRegUnits.insert(*URoot);
1948         }
1949       }
1950     }
1951 
1952     if (AnyIllegal) {
1953       NormalLocsToPHI.insert(L);
1954       continue;
1955     }
1956 
1957     RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
1958   }
1959 
1960   // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
1961   // collection.
1962   SmallVector<MachineBasicBlock *, 32> PHIBlocks;
1963   auto CollectPHIsForLoc = [&](LocIdx L) {
1964     // Collect the set of defs.
1965     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
1966     for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
1967       MachineBasicBlock *MBB = OrderToBB[I];
1968       const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
1969       if (TransferFunc.find(L) != TransferFunc.end())
1970         DefBlocks.insert(MBB);
1971     }
1972 
1973     // The entry block defs the location too: it's the live-in / argument value.
1974     // Only insert if there are other defs though; everything is trivially live
1975     // through otherwise.
1976     if (!DefBlocks.empty())
1977       DefBlocks.insert(&*MF.begin());
1978 
1979     // Ask the SSA construction algorithm where we should put PHIs. Clear
1980     // anything that might have been hanging around from earlier.
1981     PHIBlocks.clear();
1982     BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
1983   };
1984 
1985   auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
1986     for (const MachineBasicBlock *MBB : PHIBlocks)
1987       MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
1988   };
1989 
1990   // For locations with no reg units, just place PHIs.
1991   for (LocIdx L : NormalLocsToPHI) {
1992     CollectPHIsForLoc(L);
1993     // Install those PHI values into the live-in value array.
1994     InstallPHIsAtLoc(L);
1995   }
1996 
1997   // For stack slots, calculate PHIs for the equivalent of the units, then
1998   // install for each index.
1999   for (SpillLocationNo Slot : StackSlots) {
2000     for (unsigned Idx : StackUnits) {
2001       unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2002       LocIdx L = MTracker->getSpillMLoc(SpillID);
2003       CollectPHIsForLoc(L);
2004       InstallPHIsAtLoc(L);
2005 
2006       // Find anything that aliases this stack index, install PHIs for it too.
2007       unsigned Size, Offset;
2008       std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2009       for (auto &Pair : MTracker->StackSlotIdxes) {
2010         unsigned ThisSize, ThisOffset;
2011         std::tie(ThisSize, ThisOffset) = Pair.first;
2012         if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2013           continue;
2014 
2015         unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2016         LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2017         InstallPHIsAtLoc(ThisL);
2018       }
2019     }
2020   }
2021 
2022   // For reg units, place PHIs, and then place them for any aliasing registers.
2023   for (Register R : RegUnitsToPHIUp) {
2024     LocIdx L = MTracker->lookupOrTrackRegister(R);
2025     CollectPHIsForLoc(L);
2026 
2027     // Install those PHI values into the live-in value array.
2028     InstallPHIsAtLoc(L);
2029 
2030     // Now find aliases and install PHIs for those.
2031     for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2032       // Super-registers that are "above" the largest register read/written by
2033       // the function will alias, but will not be tracked.
2034       if (!MTracker->isRegisterTracked(*RAI))
2035         continue;
2036 
2037       LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2038       InstallPHIsAtLoc(AliasLoc);
2039     }
2040   }
2041 }
2042 
2043 void InstrRefBasedLDV::buildMLocValueMap(
2044     MachineFunction &MF, ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
2045     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2046   std::priority_queue<unsigned int, std::vector<unsigned int>,
2047                       std::greater<unsigned int>>
2048       Worklist, Pending;
2049 
2050   // We track what is on the current and pending worklist to avoid inserting
2051   // the same thing twice. We could avoid this with a custom priority queue,
2052   // but this is probably not worth it.
2053   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2054 
2055   // Initialize worklist with every block to be visited. Also produce list of
2056   // all blocks.
2057   SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2058   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2059     Worklist.push(I);
2060     OnWorklist.insert(OrderToBB[I]);
2061     AllBlocks.insert(OrderToBB[I]);
2062   }
2063 
2064   // Initialize entry block to PHIs. These represent arguments.
2065   for (auto Location : MTracker->locations())
2066     MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
2067 
2068   MTracker->reset();
2069 
2070   // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2071   // any machine-location that isn't live-through a block to be def'd in that
2072   // block.
2073   placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2074 
2075   // Propagate values to eliminate redundant PHIs. At the same time, this
2076   // produces the table of Block x Location => Value for the entry to each
2077   // block.
2078   // The kind of PHIs we can eliminate are, for example, where one path in a
2079   // conditional spills and restores a register, and the register still has
2080   // the same value once control flow joins, unbeknowns to the PHI placement
2081   // code. Propagating values allows us to identify such un-necessary PHIs and
2082   // remove them.
2083   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2084   while (!Worklist.empty() || !Pending.empty()) {
2085     // Vector for storing the evaluated block transfer function.
2086     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2087 
2088     while (!Worklist.empty()) {
2089       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2090       CurBB = MBB->getNumber();
2091       Worklist.pop();
2092 
2093       // Join the values in all predecessor blocks.
2094       bool InLocsChanged;
2095       InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2096       InLocsChanged |= Visited.insert(MBB).second;
2097 
2098       // Don't examine transfer function if we've visited this loc at least
2099       // once, and inlocs haven't changed.
2100       if (!InLocsChanged)
2101         continue;
2102 
2103       // Load the current set of live-ins into MLocTracker.
2104       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2105 
2106       // Each element of the transfer function can be a new def, or a read of
2107       // a live-in value. Evaluate each element, and store to "ToRemap".
2108       ToRemap.clear();
2109       for (auto &P : MLocTransfer[CurBB]) {
2110         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2111           // This is a movement of whatever was live in. Read it.
2112           ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2113           ToRemap.push_back(std::make_pair(P.first, NewID));
2114         } else {
2115           // It's a def. Just set it.
2116           assert(P.second.getBlock() == CurBB);
2117           ToRemap.push_back(std::make_pair(P.first, P.second));
2118         }
2119       }
2120 
2121       // Commit the transfer function changes into mloc tracker, which
2122       // transforms the contents of the MLocTracker into the live-outs.
2123       for (auto &P : ToRemap)
2124         MTracker->setMLoc(P.first, P.second);
2125 
2126       // Now copy out-locs from mloc tracker into out-loc vector, checking
2127       // whether changes have occurred. These changes can have come from both
2128       // the transfer function, and mlocJoin.
2129       bool OLChanged = false;
2130       for (auto Location : MTracker->locations()) {
2131         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2132         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2133       }
2134 
2135       MTracker->reset();
2136 
2137       // No need to examine successors again if out-locs didn't change.
2138       if (!OLChanged)
2139         continue;
2140 
2141       // All successors should be visited: put any back-edges on the pending
2142       // list for the next pass-through, and any other successors to be
2143       // visited this pass, if they're not going to be already.
2144       for (auto s : MBB->successors()) {
2145         // Does branching to this successor represent a back-edge?
2146         if (BBToOrder[s] > BBToOrder[MBB]) {
2147           // No: visit it during this dataflow iteration.
2148           if (OnWorklist.insert(s).second)
2149             Worklist.push(BBToOrder[s]);
2150         } else {
2151           // Yes: visit it on the next iteration.
2152           if (OnPending.insert(s).second)
2153             Pending.push(BBToOrder[s]);
2154         }
2155       }
2156     }
2157 
2158     Worklist.swap(Pending);
2159     std::swap(OnPending, OnWorklist);
2160     OnPending.clear();
2161     // At this point, pending must be empty, since it was just the empty
2162     // worklist
2163     assert(Pending.empty() && "Pending should be empty");
2164   }
2165 
2166   // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2167   // redundant PHIs.
2168 }
2169 
2170 // Boilerplate for feeding MachineBasicBlocks into IDF calculator. Provide
2171 // template specialisations for graph traits and a successor enumerator.
2172 namespace llvm {
2173 template <> struct GraphTraits<MachineBasicBlock> {
2174   using NodeRef = MachineBasicBlock *;
2175   using ChildIteratorType = MachineBasicBlock::succ_iterator;
2176 
2177   static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
2178   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
2179   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
2180 };
2181 
2182 template <> struct GraphTraits<const MachineBasicBlock> {
2183   using NodeRef = const MachineBasicBlock *;
2184   using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
2185 
2186   static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
2187   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
2188   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
2189 };
2190 
2191 using MachineDomTreeBase = DomTreeBase<MachineBasicBlock>::NodeType;
2192 using MachineDomTreeChildGetter =
2193     typename IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false>;
2194 
2195 namespace IDFCalculatorDetail {
2196 template <>
2197 typename MachineDomTreeChildGetter::ChildrenTy
2198 MachineDomTreeChildGetter::get(const NodeRef &N) {
2199   return {N->succ_begin(), N->succ_end()};
2200 }
2201 } // namespace IDFCalculatorDetail
2202 } // namespace llvm
2203 
2204 void InstrRefBasedLDV::BlockPHIPlacement(
2205     const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2206     const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2207     SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2208   // Apply IDF calculator to the designated set of location defs, storing
2209   // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2210   // InstrRefBasedLDV object.
2211   IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false> foo;
2212   IDFCalculatorBase<MachineDomTreeBase, false> IDF(DomTree->getBase(), foo);
2213 
2214   IDF.setLiveInBlocks(AllBlocks);
2215   IDF.setDefiningBlocks(DefBlocks);
2216   IDF.calculate(PHIBlocks);
2217 }
2218 
2219 Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc(
2220     const MachineBasicBlock &MBB, const DebugVariable &Var,
2221     const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
2222     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2223   // Collect a set of locations from predecessor where its live-out value can
2224   // be found.
2225   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2226   SmallVector<const DbgValueProperties *, 4> Properties;
2227   unsigned NumLocs = MTracker->getNumLocs();
2228 
2229   // No predecessors means no PHIs.
2230   if (BlockOrders.empty())
2231     return None;
2232 
2233   for (auto p : BlockOrders) {
2234     unsigned ThisBBNum = p->getNumber();
2235     auto OutValIt = LiveOuts.find(p);
2236     if (OutValIt == LiveOuts.end())
2237       // If we have a predecessor not in scope, we'll never find a PHI position.
2238       return None;
2239     const DbgValue &OutVal = *OutValIt->second;
2240 
2241     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2242       // Consts and no-values cannot have locations we can join on.
2243       return None;
2244 
2245     Properties.push_back(&OutVal.Properties);
2246 
2247     // Create new empty vector of locations.
2248     Locs.resize(Locs.size() + 1);
2249 
2250     // If the live-in value is a def, find the locations where that value is
2251     // present. Do the same for VPHIs where we know the VPHI value.
2252     if (OutVal.Kind == DbgValue::Def ||
2253         (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2254          OutVal.ID != ValueIDNum::EmptyValue)) {
2255       ValueIDNum ValToLookFor = OutVal.ID;
2256       // Search the live-outs of the predecessor for the specified value.
2257       for (unsigned int I = 0; I < NumLocs; ++I) {
2258         if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2259           Locs.back().push_back(LocIdx(I));
2260       }
2261     } else {
2262       assert(OutVal.Kind == DbgValue::VPHI);
2263       // For VPHIs where we don't know the location, we definitely can't find
2264       // a join loc.
2265       if (OutVal.BlockNo != MBB.getNumber())
2266         return None;
2267 
2268       // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2269       // a value that's live-through the whole loop. (It has to be a backedge,
2270       // because a block can't dominate itself). We can accept as a PHI location
2271       // any location where the other predecessors agree, _and_ the machine
2272       // locations feed back into themselves. Therefore, add all self-looping
2273       // machine-value PHI locations.
2274       for (unsigned int I = 0; I < NumLocs; ++I) {
2275         ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2276         if (MOutLocs[ThisBBNum][I] == MPHI)
2277           Locs.back().push_back(LocIdx(I));
2278       }
2279     }
2280   }
2281 
2282   // We should have found locations for all predecessors, or returned.
2283   assert(Locs.size() == BlockOrders.size());
2284 
2285   // Check that all properties are the same. We can't pick a location if they're
2286   // not.
2287   const DbgValueProperties *Properties0 = Properties[0];
2288   for (auto *Prop : Properties)
2289     if (*Prop != *Properties0)
2290       return None;
2291 
2292   // Starting with the first set of locations, take the intersection with
2293   // subsequent sets.
2294   SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2295   for (unsigned int I = 1; I < Locs.size(); ++I) {
2296     auto &LocVec = Locs[I];
2297     SmallVector<LocIdx, 4> NewCandidates;
2298     std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2299                           LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2300     CandidateLocs = NewCandidates;
2301   }
2302   if (CandidateLocs.empty())
2303     return None;
2304 
2305   // We now have a set of LocIdxes that contain the right output value in
2306   // each of the predecessors. Pick the lowest; if there's a register loc,
2307   // that'll be it.
2308   LocIdx L = *CandidateLocs.begin();
2309 
2310   // Return a PHI-value-number for the found location.
2311   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2312   return PHIVal;
2313 }
2314 
2315 bool InstrRefBasedLDV::vlocJoin(
2316     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2317     SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
2318     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2319     DbgValue &LiveIn) {
2320   // To emulate VarLocBasedImpl, process this block if it's not in scope but
2321   // _does_ assign a variable value. No live-ins for this scope are transferred
2322   // in though, so we can return immediately.
2323   if (InScopeBlocks.count(&MBB) == 0 && !ArtificialBlocks.count(&MBB))
2324     return false;
2325 
2326   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2327   bool Changed = false;
2328 
2329   // Order predecessors by RPOT order, for exploring them in that order.
2330   SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2331 
2332   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2333     return BBToOrder[A] < BBToOrder[B];
2334   };
2335 
2336   llvm::sort(BlockOrders, Cmp);
2337 
2338   unsigned CurBlockRPONum = BBToOrder[&MBB];
2339 
2340   // Collect all the incoming DbgValues for this variable, from predecessor
2341   // live-out values.
2342   SmallVector<InValueT, 8> Values;
2343   bool Bail = false;
2344   int BackEdgesStart = 0;
2345   for (auto p : BlockOrders) {
2346     // If the predecessor isn't in scope / to be explored, we'll never be
2347     // able to join any locations.
2348     if (!BlocksToExplore.contains(p)) {
2349       Bail = true;
2350       break;
2351     }
2352 
2353     // All Live-outs will have been initialized.
2354     DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2355 
2356     // Keep track of where back-edges begin in the Values vector. Relies on
2357     // BlockOrders being sorted by RPO.
2358     unsigned ThisBBRPONum = BBToOrder[p];
2359     if (ThisBBRPONum < CurBlockRPONum)
2360       ++BackEdgesStart;
2361 
2362     Values.push_back(std::make_pair(p, &OutLoc));
2363   }
2364 
2365   // If there were no values, or one of the predecessors couldn't have a
2366   // value, then give up immediately. It's not safe to produce a live-in
2367   // value. Leave as whatever it was before.
2368   if (Bail || Values.size() == 0)
2369     return false;
2370 
2371   // All (non-entry) blocks have at least one non-backedge predecessor.
2372   // Pick the variable value from the first of these, to compare against
2373   // all others.
2374   const DbgValue &FirstVal = *Values[0].second;
2375 
2376   // If the old live-in value is not a PHI then either a) no PHI is needed
2377   // here, or b) we eliminated the PHI that was here. If so, we can just
2378   // propagate in the first parent's incoming value.
2379   if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
2380     Changed = LiveIn != FirstVal;
2381     if (Changed)
2382       LiveIn = FirstVal;
2383     return Changed;
2384   }
2385 
2386   // Scan for variable values that can never be resolved: if they have
2387   // different DIExpressions, different indirectness, or are mixed constants /
2388   // non-constants.
2389   for (auto &V : Values) {
2390     if (V.second->Properties != FirstVal.Properties)
2391       return false;
2392     if (V.second->Kind == DbgValue::NoVal)
2393       return false;
2394     if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
2395       return false;
2396   }
2397 
2398   // Try to eliminate this PHI. Do the incoming values all agree?
2399   bool Disagree = false;
2400   for (auto &V : Values) {
2401     if (*V.second == FirstVal)
2402       continue; // No disagreement.
2403 
2404     // Eliminate if a backedge feeds a VPHI back into itself.
2405     if (V.second->Kind == DbgValue::VPHI &&
2406         V.second->BlockNo == MBB.getNumber() &&
2407         // Is this a backedge?
2408         std::distance(Values.begin(), &V) >= BackEdgesStart)
2409       continue;
2410 
2411     Disagree = true;
2412   }
2413 
2414   // No disagreement -> live-through value.
2415   if (!Disagree) {
2416     Changed = LiveIn != FirstVal;
2417     if (Changed)
2418       LiveIn = FirstVal;
2419     return Changed;
2420   } else {
2421     // Otherwise use a VPHI.
2422     DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
2423     Changed = LiveIn != VPHI;
2424     if (Changed)
2425       LiveIn = VPHI;
2426     return Changed;
2427   }
2428 }
2429 
2430 void InstrRefBasedLDV::buildVLocValueMap(const DILocation *DILoc,
2431     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2432     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2433     ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2434     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2435   // This method is much like buildMLocValueMap: but focuses on a single
2436   // LexicalScope at a time. Pick out a set of blocks and variables that are
2437   // to have their value assignments solved, then run our dataflow algorithm
2438   // until a fixedpoint is reached.
2439   std::priority_queue<unsigned int, std::vector<unsigned int>,
2440                       std::greater<unsigned int>>
2441       Worklist, Pending;
2442   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2443 
2444   // The set of blocks we'll be examining.
2445   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2446 
2447   // The order in which to examine them (RPO).
2448   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2449 
2450   // RPO ordering function.
2451   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2452     return BBToOrder[A] < BBToOrder[B];
2453   };
2454 
2455   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
2456 
2457   // A separate container to distinguish "blocks we're exploring" versus
2458   // "blocks that are potentially in scope. See comment at start of vlocJoin.
2459   SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore;
2460 
2461   // Old LiveDebugValues tracks variable locations that come out of blocks
2462   // not in scope, where DBG_VALUEs occur. This is something we could
2463   // legitimately ignore, but lets allow it for now.
2464   if (EmulateOldLDV)
2465     BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
2466 
2467   // We also need to propagate variable values through any artificial blocks
2468   // that immediately follow blocks in scope.
2469   DenseSet<const MachineBasicBlock *> ToAdd;
2470 
2471   // Helper lambda: For a given block in scope, perform a depth first search
2472   // of all the artificial successors, adding them to the ToAdd collection.
2473   auto AccumulateArtificialBlocks =
2474       [this, &ToAdd, &BlocksToExplore,
2475        &InScopeBlocks](const MachineBasicBlock *MBB) {
2476         // Depth-first-search state: each node is a block and which successor
2477         // we're currently exploring.
2478         SmallVector<std::pair<const MachineBasicBlock *,
2479                               MachineBasicBlock::const_succ_iterator>,
2480                     8>
2481             DFS;
2482 
2483         // Find any artificial successors not already tracked.
2484         for (auto *succ : MBB->successors()) {
2485           if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ))
2486             continue;
2487           if (!ArtificialBlocks.count(succ))
2488             continue;
2489           ToAdd.insert(succ);
2490           DFS.push_back(std::make_pair(succ, succ->succ_begin()));
2491         }
2492 
2493         // Search all those blocks, depth first.
2494         while (!DFS.empty()) {
2495           const MachineBasicBlock *CurBB = DFS.back().first;
2496           MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
2497           // Walk back if we've explored this blocks successors to the end.
2498           if (CurSucc == CurBB->succ_end()) {
2499             DFS.pop_back();
2500             continue;
2501           }
2502 
2503           // If the current successor is artificial and unexplored, descend into
2504           // it.
2505           if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
2506             ToAdd.insert(*CurSucc);
2507             DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin()));
2508             continue;
2509           }
2510 
2511           ++CurSucc;
2512         }
2513       };
2514 
2515   // Search in-scope blocks and those containing a DBG_VALUE from this scope
2516   // for artificial successors.
2517   for (auto *MBB : BlocksToExplore)
2518     AccumulateArtificialBlocks(MBB);
2519   for (auto *MBB : InScopeBlocks)
2520     AccumulateArtificialBlocks(MBB);
2521 
2522   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
2523   InScopeBlocks.insert(ToAdd.begin(), ToAdd.end());
2524 
2525   // Single block scope: not interesting! No propagation at all. Note that
2526   // this could probably go above ArtificialBlocks without damage, but
2527   // that then produces output differences from original-live-debug-values,
2528   // which propagates from a single block into many artificial ones.
2529   if (BlocksToExplore.size() == 1)
2530     return;
2531 
2532   // Convert a const set to a non-const set. LexicalScopes
2533   // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
2534   // (Neither of them mutate anything).
2535   SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
2536   for (const auto *MBB : BlocksToExplore)
2537     MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
2538 
2539   // Picks out relevants blocks RPO order and sort them.
2540   for (auto *MBB : BlocksToExplore)
2541     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2542 
2543   llvm::sort(BlockOrders, Cmp);
2544   unsigned NumBlocks = BlockOrders.size();
2545 
2546   // Allocate some vectors for storing the live ins and live outs. Large.
2547   SmallVector<DbgValue, 32> LiveIns, LiveOuts;
2548   LiveIns.reserve(NumBlocks);
2549   LiveOuts.reserve(NumBlocks);
2550 
2551   // Initialize all values to start as NoVals. This signifies "it's live
2552   // through, but we don't know what it is".
2553   DbgValueProperties EmptyProperties(EmptyExpr, false);
2554   for (unsigned int I = 0; I < NumBlocks; ++I) {
2555     DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2556     LiveIns.push_back(EmptyDbgValue);
2557     LiveOuts.push_back(EmptyDbgValue);
2558   }
2559 
2560   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
2561   // vlocJoin.
2562   LiveIdxT LiveOutIdx, LiveInIdx;
2563   LiveOutIdx.reserve(NumBlocks);
2564   LiveInIdx.reserve(NumBlocks);
2565   for (unsigned I = 0; I < NumBlocks; ++I) {
2566     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
2567     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
2568   }
2569 
2570   // Loop over each variable and place PHIs for it, then propagate values
2571   // between blocks. This keeps the locality of working on one lexical scope at
2572   // at time, but avoids re-processing variable values because some other
2573   // variable has been assigned.
2574   for (auto &Var : VarsWeCareAbout) {
2575     // Re-initialize live-ins and live-outs, to clear the remains of previous
2576     // variables live-ins / live-outs.
2577     for (unsigned int I = 0; I < NumBlocks; ++I) {
2578       DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2579       LiveIns[I] = EmptyDbgValue;
2580       LiveOuts[I] = EmptyDbgValue;
2581     }
2582 
2583     // Place PHIs for variable values, using the LLVM IDF calculator.
2584     // Collect the set of blocks where variables are def'd.
2585     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2586     for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
2587       auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
2588       if (TransferFunc.find(Var) != TransferFunc.end())
2589         DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
2590     }
2591 
2592     SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2593 
2594     // Request the set of PHIs we should insert for this variable.
2595     BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
2596 
2597     // Insert PHIs into the per-block live-in tables for this variable.
2598     for (MachineBasicBlock *PHIMBB : PHIBlocks) {
2599       unsigned BlockNo = PHIMBB->getNumber();
2600       DbgValue *LiveIn = LiveInIdx[PHIMBB];
2601       *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
2602     }
2603 
2604     for (auto *MBB : BlockOrders) {
2605       Worklist.push(BBToOrder[MBB]);
2606       OnWorklist.insert(MBB);
2607     }
2608 
2609     // Iterate over all the blocks we selected, propagating the variables value.
2610     // This loop does two things:
2611     //  * Eliminates un-necessary VPHIs in vlocJoin,
2612     //  * Evaluates the blocks transfer function (i.e. variable assignments) and
2613     //    stores the result to the blocks live-outs.
2614     // Always evaluate the transfer function on the first iteration, and when
2615     // the live-ins change thereafter.
2616     bool FirstTrip = true;
2617     while (!Worklist.empty() || !Pending.empty()) {
2618       while (!Worklist.empty()) {
2619         auto *MBB = OrderToBB[Worklist.top()];
2620         CurBB = MBB->getNumber();
2621         Worklist.pop();
2622 
2623         auto LiveInsIt = LiveInIdx.find(MBB);
2624         assert(LiveInsIt != LiveInIdx.end());
2625         DbgValue *LiveIn = LiveInsIt->second;
2626 
2627         // Join values from predecessors. Updates LiveInIdx, and writes output
2628         // into JoinedInLocs.
2629         bool InLocsChanged =
2630             vlocJoin(*MBB, LiveOutIdx, InScopeBlocks, BlocksToExplore, *LiveIn);
2631 
2632         SmallVector<const MachineBasicBlock *, 8> Preds;
2633         for (const auto *Pred : MBB->predecessors())
2634           Preds.push_back(Pred);
2635 
2636         // If this block's live-in value is a VPHI, try to pick a machine-value
2637         // for it. This makes the machine-value available and propagated
2638         // through all blocks by the time value propagation finishes. We can't
2639         // do this any earlier as it needs to read the block live-outs.
2640         if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
2641           // There's a small possibility that on a preceeding path, a VPHI is
2642           // eliminated and transitions from VPHI-with-location to
2643           // live-through-value. As a result, the selected location of any VPHI
2644           // might change, so we need to re-compute it on each iteration.
2645           Optional<ValueIDNum> ValueNum =
2646               pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds);
2647 
2648           if (ValueNum) {
2649             InLocsChanged |= LiveIn->ID != *ValueNum;
2650             LiveIn->ID = *ValueNum;
2651           }
2652         }
2653 
2654         if (!InLocsChanged && !FirstTrip)
2655           continue;
2656 
2657         DbgValue *LiveOut = LiveOutIdx[MBB];
2658         bool OLChanged = false;
2659 
2660         // Do transfer function.
2661         auto &VTracker = AllTheVLocs[MBB->getNumber()];
2662         auto TransferIt = VTracker.Vars.find(Var);
2663         if (TransferIt != VTracker.Vars.end()) {
2664           // Erase on empty transfer (DBG_VALUE $noreg).
2665           if (TransferIt->second.Kind == DbgValue::Undef) {
2666             DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
2667             if (*LiveOut != NewVal) {
2668               *LiveOut = NewVal;
2669               OLChanged = true;
2670             }
2671           } else {
2672             // Insert new variable value; or overwrite.
2673             if (*LiveOut != TransferIt->second) {
2674               *LiveOut = TransferIt->second;
2675               OLChanged = true;
2676             }
2677           }
2678         } else {
2679           // Just copy live-ins to live-outs, for anything not transferred.
2680           if (*LiveOut != *LiveIn) {
2681             *LiveOut = *LiveIn;
2682             OLChanged = true;
2683           }
2684         }
2685 
2686         // If no live-out value changed, there's no need to explore further.
2687         if (!OLChanged)
2688           continue;
2689 
2690         // We should visit all successors. Ensure we'll visit any non-backedge
2691         // successors during this dataflow iteration; book backedge successors
2692         // to be visited next time around.
2693         for (auto s : MBB->successors()) {
2694           // Ignore out of scope / not-to-be-explored successors.
2695           if (LiveInIdx.find(s) == LiveInIdx.end())
2696             continue;
2697 
2698           if (BBToOrder[s] > BBToOrder[MBB]) {
2699             if (OnWorklist.insert(s).second)
2700               Worklist.push(BBToOrder[s]);
2701           } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
2702             Pending.push(BBToOrder[s]);
2703           }
2704         }
2705       }
2706       Worklist.swap(Pending);
2707       std::swap(OnWorklist, OnPending);
2708       OnPending.clear();
2709       assert(Pending.empty());
2710       FirstTrip = false;
2711     }
2712 
2713     // Save live-ins to output vector. Ignore any that are still marked as being
2714     // VPHIs with no location -- those are variables that we know the value of,
2715     // but are not actually available in the register file.
2716     for (auto *MBB : BlockOrders) {
2717       DbgValue *BlockLiveIn = LiveInIdx[MBB];
2718       if (BlockLiveIn->Kind == DbgValue::NoVal)
2719         continue;
2720       if (BlockLiveIn->Kind == DbgValue::VPHI &&
2721           BlockLiveIn->ID == ValueIDNum::EmptyValue)
2722         continue;
2723       if (BlockLiveIn->Kind == DbgValue::VPHI)
2724         BlockLiveIn->Kind = DbgValue::Def;
2725       Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
2726     }
2727   } // Per-variable loop.
2728 
2729   BlockOrders.clear();
2730   BlocksToExplore.clear();
2731 }
2732 
2733 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2734 void InstrRefBasedLDV::dump_mloc_transfer(
2735     const MLocTransferMap &mloc_transfer) const {
2736   for (auto &P : mloc_transfer) {
2737     std::string foo = MTracker->LocIdxToName(P.first);
2738     std::string bar = MTracker->IDAsString(P.second);
2739     dbgs() << "Loc " << foo << " --> " << bar << "\n";
2740   }
2741 }
2742 #endif
2743 
2744 void InstrRefBasedLDV::emitLocations(
2745     MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MOutLocs,
2746     ValueIDNum **MInLocs, DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
2747     const TargetPassConfig &TPC) {
2748   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
2749   unsigned NumLocs = MTracker->getNumLocs();
2750 
2751   // For each block, load in the machine value locations and variable value
2752   // live-ins, then step through each instruction in the block. New DBG_VALUEs
2753   // to be inserted will be created along the way.
2754   for (MachineBasicBlock &MBB : MF) {
2755     unsigned bbnum = MBB.getNumber();
2756     MTracker->reset();
2757     MTracker->loadFromArray(MInLocs[bbnum], bbnum);
2758     TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()],
2759                          NumLocs);
2760 
2761     CurBB = bbnum;
2762     CurInst = 1;
2763     for (auto &MI : MBB) {
2764       process(MI, MOutLocs, MInLocs);
2765       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
2766       ++CurInst;
2767     }
2768   }
2769 
2770   // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer
2771   // in DWARF in different orders. Use the order that they appear when walking
2772   // through each block / each instruction, stored in AllVarsNumbering.
2773   auto OrderDbgValues = [&](const MachineInstr *A,
2774                             const MachineInstr *B) -> bool {
2775     DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(),
2776                        A->getDebugLoc()->getInlinedAt());
2777     DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(),
2778                        B->getDebugLoc()->getInlinedAt());
2779     return AllVarsNumbering.find(VarA)->second <
2780            AllVarsNumbering.find(VarB)->second;
2781   };
2782 
2783   // Go through all the transfers recorded in the TransferTracker -- this is
2784   // both the live-ins to a block, and any movements of values that happen
2785   // in the middle.
2786   for (auto &P : TTracker->Transfers) {
2787     // Sort them according to appearance order.
2788     llvm::sort(P.Insts, OrderDbgValues);
2789     // Insert either before or after the designated point...
2790     if (P.MBB) {
2791       MachineBasicBlock &MBB = *P.MBB;
2792       for (auto *MI : P.Insts) {
2793         MBB.insert(P.Pos, MI);
2794       }
2795     } else {
2796       // Terminators, like tail calls, can clobber things. Don't try and place
2797       // transfers after them.
2798       if (P.Pos->isTerminator())
2799         continue;
2800 
2801       MachineBasicBlock &MBB = *P.Pos->getParent();
2802       for (auto *MI : P.Insts) {
2803         MBB.insertAfterBundle(P.Pos, MI);
2804       }
2805     }
2806   }
2807 }
2808 
2809 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
2810   // Build some useful data structures.
2811 
2812   LLVMContext &Context = MF.getFunction().getContext();
2813   EmptyExpr = DIExpression::get(Context, {});
2814 
2815   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2816     if (const DebugLoc &DL = MI.getDebugLoc())
2817       return DL.getLine() != 0;
2818     return false;
2819   };
2820   // Collect a set of all the artificial blocks.
2821   for (auto &MBB : MF)
2822     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2823       ArtificialBlocks.insert(&MBB);
2824 
2825   // Compute mappings of block <=> RPO order.
2826   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2827   unsigned int RPONumber = 0;
2828   for (MachineBasicBlock *MBB : RPOT) {
2829     OrderToBB[RPONumber] = MBB;
2830     BBToOrder[MBB] = RPONumber;
2831     BBNumToRPO[MBB->getNumber()] = RPONumber;
2832     ++RPONumber;
2833   }
2834 
2835   // Order value substitutions by their "source" operand pair, for quick lookup.
2836   llvm::sort(MF.DebugValueSubstitutions);
2837 
2838 #ifdef EXPENSIVE_CHECKS
2839   // As an expensive check, test whether there are any duplicate substitution
2840   // sources in the collection.
2841   if (MF.DebugValueSubstitutions.size() > 2) {
2842     for (auto It = MF.DebugValueSubstitutions.begin();
2843          It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
2844       assert(It->Src != std::next(It)->Src && "Duplicate variable location "
2845                                               "substitution seen");
2846     }
2847   }
2848 #endif
2849 }
2850 
2851 /// Calculate the liveness information for the given machine function and
2852 /// extend ranges across basic blocks.
2853 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
2854                                     MachineDominatorTree *DomTree,
2855                                     TargetPassConfig *TPC,
2856                                     unsigned InputBBLimit,
2857                                     unsigned InputDbgValLimit) {
2858   // No subprogram means this function contains no debuginfo.
2859   if (!MF.getFunction().getSubprogram())
2860     return false;
2861 
2862   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
2863   this->TPC = TPC;
2864 
2865   this->DomTree = DomTree;
2866   TRI = MF.getSubtarget().getRegisterInfo();
2867   MRI = &MF.getRegInfo();
2868   TII = MF.getSubtarget().getInstrInfo();
2869   TFI = MF.getSubtarget().getFrameLowering();
2870   TFI->getCalleeSaves(MF, CalleeSavedRegs);
2871   MFI = &MF.getFrameInfo();
2872   LS.initialize(MF);
2873 
2874   MTracker =
2875       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
2876   VTracker = nullptr;
2877   TTracker = nullptr;
2878 
2879   SmallVector<MLocTransferMap, 32> MLocTransfer;
2880   SmallVector<VLocTracker, 8> vlocs;
2881   LiveInsT SavedLiveIns;
2882 
2883   int MaxNumBlocks = -1;
2884   for (auto &MBB : MF)
2885     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
2886   assert(MaxNumBlocks >= 0);
2887   ++MaxNumBlocks;
2888 
2889   MLocTransfer.resize(MaxNumBlocks);
2890   vlocs.resize(MaxNumBlocks);
2891   SavedLiveIns.resize(MaxNumBlocks);
2892 
2893   initialSetup(MF);
2894 
2895   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
2896 
2897   // Allocate and initialize two array-of-arrays for the live-in and live-out
2898   // machine values. The outer dimension is the block number; while the inner
2899   // dimension is a LocIdx from MLocTracker.
2900   ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks];
2901   ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks];
2902   unsigned NumLocs = MTracker->getNumLocs();
2903   for (int i = 0; i < MaxNumBlocks; ++i) {
2904     // These all auto-initialize to ValueIDNum::EmptyValue
2905     MOutLocs[i] = new ValueIDNum[NumLocs];
2906     MInLocs[i] = new ValueIDNum[NumLocs];
2907   }
2908 
2909   // Solve the machine value dataflow problem using the MLocTransfer function,
2910   // storing the computed live-ins / live-outs into the array-of-arrays. We use
2911   // both live-ins and live-outs for decision making in the variable value
2912   // dataflow problem.
2913   buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
2914 
2915   // Patch up debug phi numbers, turning unknown block-live-in values into
2916   // either live-through machine values, or PHIs.
2917   for (auto &DBG_PHI : DebugPHINumToValue) {
2918     // Identify unresolved block-live-ins.
2919     ValueIDNum &Num = DBG_PHI.ValueRead;
2920     if (!Num.isPHI())
2921       continue;
2922 
2923     unsigned BlockNo = Num.getBlock();
2924     LocIdx LocNo = Num.getLoc();
2925     Num = MInLocs[BlockNo][LocNo.asU64()];
2926   }
2927   // Later, we'll be looking up ranges of instruction numbers.
2928   llvm::sort(DebugPHINumToValue);
2929 
2930   // Walk back through each block / instruction, collecting DBG_VALUE
2931   // instructions and recording what machine value their operands refer to.
2932   for (auto &OrderPair : OrderToBB) {
2933     MachineBasicBlock &MBB = *OrderPair.second;
2934     CurBB = MBB.getNumber();
2935     VTracker = &vlocs[CurBB];
2936     VTracker->MBB = &MBB;
2937     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2938     CurInst = 1;
2939     for (auto &MI : MBB) {
2940       process(MI, MOutLocs, MInLocs);
2941       ++CurInst;
2942     }
2943     MTracker->reset();
2944   }
2945 
2946   // Number all variables in the order that they appear, to be used as a stable
2947   // insertion order later.
2948   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
2949 
2950   // Map from one LexicalScope to all the variables in that scope.
2951   DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars;
2952 
2953   // Map from One lexical scope to all blocks in that scope.
2954   DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>
2955       ScopeToBlocks;
2956 
2957   // Store a DILocation that describes a scope.
2958   DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation;
2959 
2960   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
2961   // the order is unimportant, it just has to be stable.
2962   unsigned VarAssignCount = 0;
2963   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2964     auto *MBB = OrderToBB[I];
2965     auto *VTracker = &vlocs[MBB->getNumber()];
2966     // Collect each variable with a DBG_VALUE in this block.
2967     for (auto &idx : VTracker->Vars) {
2968       const auto &Var = idx.first;
2969       const DILocation *ScopeLoc = VTracker->Scopes[Var];
2970       assert(ScopeLoc != nullptr);
2971       auto *Scope = LS.findLexicalScope(ScopeLoc);
2972 
2973       // No insts in scope -> shouldn't have been recorded.
2974       assert(Scope != nullptr);
2975 
2976       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
2977       ScopeToVars[Scope].insert(Var);
2978       ScopeToBlocks[Scope].insert(VTracker->MBB);
2979       ScopeToDILocation[Scope] = ScopeLoc;
2980       ++VarAssignCount;
2981     }
2982   }
2983 
2984   bool Changed = false;
2985 
2986   // If we have an extremely large number of variable assignments and blocks,
2987   // bail out at this point. We've burnt some time doing analysis already,
2988   // however we should cut our losses.
2989   if ((unsigned)MaxNumBlocks > InputBBLimit &&
2990       VarAssignCount > InputDbgValLimit) {
2991     LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
2992                       << " has " << MaxNumBlocks << " basic blocks and "
2993                       << VarAssignCount
2994                       << " variable assignments, exceeding limits.\n");
2995   } else {
2996     // Compute the extended ranges, iterating over scopes. There might be
2997     // something to be said for ordering them by size/locality, but that's for
2998     // the future. For each scope, solve the variable value problem, producing
2999     // a map of variables to values in SavedLiveIns.
3000     for (auto &P : ScopeToVars) {
3001       buildVLocValueMap(ScopeToDILocation[P.first], P.second,
3002                    ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs,
3003                    vlocs);
3004     }
3005 
3006     // Using the computed value locations and variable values for each block,
3007     // create the DBG_VALUE instructions representing the extended variable
3008     // locations.
3009     emitLocations(MF, SavedLiveIns, MOutLocs, MInLocs, AllVarsNumbering, *TPC);
3010 
3011     // Did we actually make any changes? If we created any DBG_VALUEs, then yes.
3012     Changed = TTracker->Transfers.size() != 0;
3013   }
3014 
3015   // Common clean-up of memory.
3016   for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) {
3017     delete[] MOutLocs[Idx];
3018     delete[] MInLocs[Idx];
3019   }
3020   delete[] MOutLocs;
3021   delete[] MInLocs;
3022 
3023   delete MTracker;
3024   delete TTracker;
3025   MTracker = nullptr;
3026   VTracker = nullptr;
3027   TTracker = nullptr;
3028 
3029   ArtificialBlocks.clear();
3030   OrderToBB.clear();
3031   BBToOrder.clear();
3032   BBNumToRPO.clear();
3033   DebugInstrNumToInstr.clear();
3034   DebugPHINumToValue.clear();
3035 
3036   return Changed;
3037 }
3038 
3039 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3040   return new InstrRefBasedLDV();
3041 }
3042 
3043 namespace {
3044 class LDVSSABlock;
3045 class LDVSSAUpdater;
3046 
3047 // Pick a type to identify incoming block values as we construct SSA. We
3048 // can't use anything more robust than an integer unfortunately, as SSAUpdater
3049 // expects to zero-initialize the type.
3050 typedef uint64_t BlockValueNum;
3051 
3052 /// Represents an SSA PHI node for the SSA updater class. Contains the block
3053 /// this PHI is in, the value number it would have, and the expected incoming
3054 /// values from parent blocks.
3055 class LDVSSAPhi {
3056 public:
3057   SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3058   LDVSSABlock *ParentBlock;
3059   BlockValueNum PHIValNum;
3060   LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3061       : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3062 
3063   LDVSSABlock *getParent() { return ParentBlock; }
3064 };
3065 
3066 /// Thin wrapper around a block predecessor iterator. Only difference from a
3067 /// normal block iterator is that it dereferences to an LDVSSABlock.
3068 class LDVSSABlockIterator {
3069 public:
3070   MachineBasicBlock::pred_iterator PredIt;
3071   LDVSSAUpdater &Updater;
3072 
3073   LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3074                       LDVSSAUpdater &Updater)
3075       : PredIt(PredIt), Updater(Updater) {}
3076 
3077   bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3078     return OtherIt.PredIt != PredIt;
3079   }
3080 
3081   LDVSSABlockIterator &operator++() {
3082     ++PredIt;
3083     return *this;
3084   }
3085 
3086   LDVSSABlock *operator*();
3087 };
3088 
3089 /// Thin wrapper around a block for SSA Updater interface. Necessary because
3090 /// we need to track the PHI value(s) that we may have observed as necessary
3091 /// in this block.
3092 class LDVSSABlock {
3093 public:
3094   MachineBasicBlock &BB;
3095   LDVSSAUpdater &Updater;
3096   using PHIListT = SmallVector<LDVSSAPhi, 1>;
3097   /// List of PHIs in this block. There should only ever be one.
3098   PHIListT PHIList;
3099 
3100   LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3101       : BB(BB), Updater(Updater) {}
3102 
3103   LDVSSABlockIterator succ_begin() {
3104     return LDVSSABlockIterator(BB.succ_begin(), Updater);
3105   }
3106 
3107   LDVSSABlockIterator succ_end() {
3108     return LDVSSABlockIterator(BB.succ_end(), Updater);
3109   }
3110 
3111   /// SSAUpdater has requested a PHI: create that within this block record.
3112   LDVSSAPhi *newPHI(BlockValueNum Value) {
3113     PHIList.emplace_back(Value, this);
3114     return &PHIList.back();
3115   }
3116 
3117   /// SSAUpdater wishes to know what PHIs already exist in this block.
3118   PHIListT &phis() { return PHIList; }
3119 };
3120 
3121 /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3122 /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3123 // SSAUpdaterTraits<LDVSSAUpdater>.
3124 class LDVSSAUpdater {
3125 public:
3126   /// Map of value numbers to PHI records.
3127   DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3128   /// Map of which blocks generate Undef values -- blocks that are not
3129   /// dominated by any Def.
3130   DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3131   /// Map of machine blocks to our own records of them.
3132   DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3133   /// Machine location where any PHI must occur.
3134   LocIdx Loc;
3135   /// Table of live-in machine value numbers for blocks / locations.
3136   ValueIDNum **MLiveIns;
3137 
3138   LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {}
3139 
3140   void reset() {
3141     for (auto &Block : BlockMap)
3142       delete Block.second;
3143 
3144     PHIs.clear();
3145     UndefMap.clear();
3146     BlockMap.clear();
3147   }
3148 
3149   ~LDVSSAUpdater() { reset(); }
3150 
3151   /// For a given MBB, create a wrapper block for it. Stores it in the
3152   /// LDVSSAUpdater block map.
3153   LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3154     auto it = BlockMap.find(BB);
3155     if (it == BlockMap.end()) {
3156       BlockMap[BB] = new LDVSSABlock(*BB, *this);
3157       it = BlockMap.find(BB);
3158     }
3159     return it->second;
3160   }
3161 
3162   /// Find the live-in value number for the given block. Looks up the value at
3163   /// the PHI location on entry.
3164   BlockValueNum getValue(LDVSSABlock *LDVBB) {
3165     return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3166   }
3167 };
3168 
3169 LDVSSABlock *LDVSSABlockIterator::operator*() {
3170   return Updater.getSSALDVBlock(*PredIt);
3171 }
3172 
3173 #ifndef NDEBUG
3174 
3175 raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3176   out << "SSALDVPHI " << PHI.PHIValNum;
3177   return out;
3178 }
3179 
3180 #endif
3181 
3182 } // namespace
3183 
3184 namespace llvm {
3185 
3186 /// Template specialization to give SSAUpdater access to CFG and value
3187 /// information. SSAUpdater calls methods in these traits, passing in the
3188 /// LDVSSAUpdater object, to learn about blocks and the values they define.
3189 /// It also provides methods to create PHI nodes and track them.
3190 template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3191 public:
3192   using BlkT = LDVSSABlock;
3193   using ValT = BlockValueNum;
3194   using PhiT = LDVSSAPhi;
3195   using BlkSucc_iterator = LDVSSABlockIterator;
3196 
3197   // Methods to access block successors -- dereferencing to our wrapper class.
3198   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
3199   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3200 
3201   /// Iterator for PHI operands.
3202   class PHI_iterator {
3203   private:
3204     LDVSSAPhi *PHI;
3205     unsigned Idx;
3206 
3207   public:
3208     explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3209         : PHI(P), Idx(0) {}
3210     PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3211         : PHI(P), Idx(PHI->IncomingValues.size()) {}
3212 
3213     PHI_iterator &operator++() {
3214       Idx++;
3215       return *this;
3216     }
3217     bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
3218     bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3219 
3220     BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
3221 
3222     LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
3223   };
3224 
3225   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
3226 
3227   static inline PHI_iterator PHI_end(PhiT *PHI) {
3228     return PHI_iterator(PHI, true);
3229   }
3230 
3231   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
3232   /// vector.
3233   static void FindPredecessorBlocks(LDVSSABlock *BB,
3234                                     SmallVectorImpl<LDVSSABlock *> *Preds) {
3235     for (MachineBasicBlock::pred_iterator PI = BB->BB.pred_begin(),
3236                                           E = BB->BB.pred_end();
3237          PI != E; ++PI)
3238       Preds->push_back(BB->Updater.getSSALDVBlock(*PI));
3239   }
3240 
3241   /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
3242   /// register. For LiveDebugValues, represents a block identified as not having
3243   /// any DBG_PHI predecessors.
3244   static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
3245     // Create a value number for this block -- it needs to be unique and in the
3246     // "undef" collection, so that we know it's not real. Use a number
3247     // representing a PHI into this block.
3248     BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
3249     Updater->UndefMap[&BB->BB] = Num;
3250     return Num;
3251   }
3252 
3253   /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
3254   /// SSAUpdater will populate it with information about incoming values. The
3255   /// value number of this PHI is whatever the  machine value number problem
3256   /// solution determined it to be. This includes non-phi values if SSAUpdater
3257   /// tries to create a PHI where the incoming values are identical.
3258   static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
3259                                    LDVSSAUpdater *Updater) {
3260     BlockValueNum PHIValNum = Updater->getValue(BB);
3261     LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
3262     Updater->PHIs[PHIValNum] = PHI;
3263     return PHIValNum;
3264   }
3265 
3266   /// AddPHIOperand - Add the specified value as an operand of the PHI for
3267   /// the specified predecessor block.
3268   static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
3269     PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
3270   }
3271 
3272   /// ValueIsPHI - Check if the instruction that defines the specified value
3273   /// is a PHI instruction.
3274   static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3275     auto PHIIt = Updater->PHIs.find(Val);
3276     if (PHIIt == Updater->PHIs.end())
3277       return nullptr;
3278     return PHIIt->second;
3279   }
3280 
3281   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
3282   /// operands, i.e., it was just added.
3283   static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3284     LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
3285     if (PHI && PHI->IncomingValues.size() == 0)
3286       return PHI;
3287     return nullptr;
3288   }
3289 
3290   /// GetPHIValue - For the specified PHI instruction, return the value
3291   /// that it defines.
3292   static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
3293 };
3294 
3295 } // end namespace llvm
3296 
3297 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF,
3298                                                       ValueIDNum **MLiveOuts,
3299                                                       ValueIDNum **MLiveIns,
3300                                                       MachineInstr &Here,
3301                                                       uint64_t InstrNum) {
3302   // Pick out records of DBG_PHI instructions that have been observed. If there
3303   // are none, then we cannot compute a value number.
3304   auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
3305                                     DebugPHINumToValue.end(), InstrNum);
3306   auto LowerIt = RangePair.first;
3307   auto UpperIt = RangePair.second;
3308 
3309   // No DBG_PHI means there can be no location.
3310   if (LowerIt == UpperIt)
3311     return None;
3312 
3313   // If there's only one DBG_PHI, then that is our value number.
3314   if (std::distance(LowerIt, UpperIt) == 1)
3315     return LowerIt->ValueRead;
3316 
3317   auto DBGPHIRange = make_range(LowerIt, UpperIt);
3318 
3319   // Pick out the location (physreg, slot) where any PHIs must occur. It's
3320   // technically possible for us to merge values in different registers in each
3321   // block, but highly unlikely that LLVM will generate such code after register
3322   // allocation.
3323   LocIdx Loc = LowerIt->ReadLoc;
3324 
3325   // We have several DBG_PHIs, and a use position (the Here inst). All each
3326   // DBG_PHI does is identify a value at a program position. We can treat each
3327   // DBG_PHI like it's a Def of a value, and the use position is a Use of a
3328   // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
3329   // determine which Def is used at the Use, and any PHIs that happen along
3330   // the way.
3331   // Adapted LLVM SSA Updater:
3332   LDVSSAUpdater Updater(Loc, MLiveIns);
3333   // Map of which Def or PHI is the current value in each block.
3334   DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
3335   // Set of PHIs that we have created along the way.
3336   SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
3337 
3338   // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
3339   // for the SSAUpdater.
3340   for (const auto &DBG_PHI : DBGPHIRange) {
3341     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3342     const ValueIDNum &Num = DBG_PHI.ValueRead;
3343     AvailableValues.insert(std::make_pair(Block, Num.asU64()));
3344   }
3345 
3346   LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
3347   const auto &AvailIt = AvailableValues.find(HereBlock);
3348   if (AvailIt != AvailableValues.end()) {
3349     // Actually, we already know what the value is -- the Use is in the same
3350     // block as the Def.
3351     return ValueIDNum::fromU64(AvailIt->second);
3352   }
3353 
3354   // Otherwise, we must use the SSA Updater. It will identify the value number
3355   // that we are to use, and the PHIs that must happen along the way.
3356   SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
3357   BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
3358   ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
3359 
3360   // We have the number for a PHI, or possibly live-through value, to be used
3361   // at this Use. There are a number of things we have to check about it though:
3362   //  * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
3363   //    Use was not completely dominated by DBG_PHIs and we should abort.
3364   //  * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
3365   //    we've left SSA form. Validate that the inputs to each PHI are the
3366   //    expected values.
3367   //  * Is a PHI we've created actually a merging of values, or are all the
3368   //    predecessor values the same, leading to a non-PHI machine value number?
3369   //    (SSAUpdater doesn't know that either). Remap validated PHIs into the
3370   //    the ValidatedValues collection below to sort this out.
3371   DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
3372 
3373   // Define all the input DBG_PHI values in ValidatedValues.
3374   for (const auto &DBG_PHI : DBGPHIRange) {
3375     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3376     const ValueIDNum &Num = DBG_PHI.ValueRead;
3377     ValidatedValues.insert(std::make_pair(Block, Num));
3378   }
3379 
3380   // Sort PHIs to validate into RPO-order.
3381   SmallVector<LDVSSAPhi *, 8> SortedPHIs;
3382   for (auto &PHI : CreatedPHIs)
3383     SortedPHIs.push_back(PHI);
3384 
3385   std::sort(
3386       SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) {
3387         return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
3388       });
3389 
3390   for (auto &PHI : SortedPHIs) {
3391     ValueIDNum ThisBlockValueNum =
3392         MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
3393 
3394     // Are all these things actually defined?
3395     for (auto &PHIIt : PHI->IncomingValues) {
3396       // Any undef input means DBG_PHIs didn't dominate the use point.
3397       if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
3398         return None;
3399 
3400       ValueIDNum ValueToCheck;
3401       ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
3402 
3403       auto VVal = ValidatedValues.find(PHIIt.first);
3404       if (VVal == ValidatedValues.end()) {
3405         // We cross a loop, and this is a backedge. LLVMs tail duplication
3406         // happens so late that DBG_PHI instructions should not be able to
3407         // migrate into loops -- meaning we can only be live-through this
3408         // loop.
3409         ValueToCheck = ThisBlockValueNum;
3410       } else {
3411         // Does the block have as a live-out, in the location we're examining,
3412         // the value that we expect? If not, it's been moved or clobbered.
3413         ValueToCheck = VVal->second;
3414       }
3415 
3416       if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
3417         return None;
3418     }
3419 
3420     // Record this value as validated.
3421     ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
3422   }
3423 
3424   // All the PHIs are valid: we can return what the SSAUpdater said our value
3425   // number was.
3426   return Result;
3427 }
3428