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