xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1e8d8bef9SDimitry Andric //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric /// \file InstrRefBasedImpl.cpp
9e8d8bef9SDimitry Andric ///
10e8d8bef9SDimitry Andric /// This is a separate implementation of LiveDebugValues, see
11e8d8bef9SDimitry Andric /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12e8d8bef9SDimitry Andric ///
13e8d8bef9SDimitry Andric /// This pass propagates variable locations between basic blocks, resolving
14349cc55cSDimitry Andric /// control flow conflicts between them. The problem is SSA construction, where
15349cc55cSDimitry Andric /// each debug instruction assigns the *value* that a variable has, and every
16349cc55cSDimitry Andric /// instruction where the variable is in scope uses that variable. The resulting
17349cc55cSDimitry Andric /// map of instruction-to-value is then translated into a register (or spill)
18349cc55cSDimitry Andric /// location for each variable over each instruction.
19e8d8bef9SDimitry Andric ///
20349cc55cSDimitry Andric /// The primary difference from normal SSA construction is that we cannot
21349cc55cSDimitry Andric /// _create_ PHI values that contain variable values. CodeGen has already
22349cc55cSDimitry Andric /// completed, and we can't alter it just to make debug-info complete. Thus:
23349cc55cSDimitry Andric /// we can identify function positions where we would like a PHI value for a
24349cc55cSDimitry Andric /// variable, but must search the MachineFunction to see whether such a PHI is
25349cc55cSDimitry Andric /// available. If no such PHI exists, the variable location must be dropped.
26e8d8bef9SDimitry Andric ///
27349cc55cSDimitry Andric /// To achieve this, we perform two kinds of analysis. First, we identify
28e8d8bef9SDimitry Andric /// every value defined by every instruction (ignoring those that only move
29349cc55cSDimitry Andric /// another value), then re-compute an SSA-form representation of the
30349cc55cSDimitry Andric /// MachineFunction, using value propagation to eliminate any un-necessary
31349cc55cSDimitry Andric /// PHI values. This gives us a map of every value computed in the function,
32349cc55cSDimitry Andric /// and its location within the register file / stack.
33e8d8bef9SDimitry Andric ///
34349cc55cSDimitry Andric /// Secondly, for each variable we perform the same analysis, where each debug
35349cc55cSDimitry Andric /// instruction is considered a def, and every instruction where the variable
36349cc55cSDimitry Andric /// is in lexical scope as a use. Value propagation is used again to eliminate
37349cc55cSDimitry Andric /// any un-necessary PHIs. This gives us a map of each variable to the value
38349cc55cSDimitry Andric /// it should have in a block.
39e8d8bef9SDimitry Andric ///
40349cc55cSDimitry Andric /// Once both are complete, we have two maps for each block:
41349cc55cSDimitry Andric ///  * Variables to the values they should have,
42349cc55cSDimitry Andric ///  * Values to the register / spill slot they are located in.
43349cc55cSDimitry Andric /// After which we can marry-up variable values with a location, and emit
44349cc55cSDimitry Andric /// DBG_VALUE instructions specifying those locations. Variable locations may
45349cc55cSDimitry Andric /// be dropped in this process due to the desired variable value not being
46349cc55cSDimitry Andric /// resident in any machine location, or because there is no PHI value in any
47349cc55cSDimitry Andric /// location that accurately represents the desired value.  The building of
48349cc55cSDimitry Andric /// location lists for each block is left to DbgEntityHistoryCalculator.
49e8d8bef9SDimitry Andric ///
50349cc55cSDimitry Andric /// This pass is kept efficient because the size of the first SSA problem
51349cc55cSDimitry Andric /// is proportional to the working-set size of the function, which the compiler
52349cc55cSDimitry Andric /// tries to keep small. (It's also proportional to the number of blocks).
53349cc55cSDimitry Andric /// Additionally, we repeatedly perform the second SSA problem analysis with
54349cc55cSDimitry Andric /// only the variables and blocks in a single lexical scope, exploiting their
55349cc55cSDimitry Andric /// locality.
56e8d8bef9SDimitry Andric ///
57e8d8bef9SDimitry Andric /// ### Terminology
58e8d8bef9SDimitry Andric ///
59e8d8bef9SDimitry Andric /// A machine location is a register or spill slot, a value is something that's
60e8d8bef9SDimitry Andric /// defined by an instruction or PHI node, while a variable value is the value
61e8d8bef9SDimitry Andric /// assigned to a variable. A variable location is a machine location, that must
62e8d8bef9SDimitry Andric /// contain the appropriate variable value. A value that is a PHI node is
63e8d8bef9SDimitry Andric /// occasionally called an mphi.
64e8d8bef9SDimitry Andric ///
65349cc55cSDimitry Andric /// The first SSA problem is the "machine value location" problem,
66e8d8bef9SDimitry Andric /// because we're determining which machine locations contain which values.
67e8d8bef9SDimitry Andric /// The "locations" are constant: what's unknown is what value they contain.
68e8d8bef9SDimitry Andric ///
69349cc55cSDimitry Andric /// The second SSA problem (the one for variables) is the "variable value
70e8d8bef9SDimitry Andric /// problem", because it's determining what values a variable has, rather than
71349cc55cSDimitry Andric /// what location those values are placed in.
72e8d8bef9SDimitry Andric ///
73e8d8bef9SDimitry Andric /// TODO:
74e8d8bef9SDimitry Andric ///   Overlapping fragments
75e8d8bef9SDimitry Andric ///   Entry values
76e8d8bef9SDimitry Andric ///   Add back DEBUG statements for debugging this
77e8d8bef9SDimitry Andric ///   Collect statistics
78e8d8bef9SDimitry Andric ///
79e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
80e8d8bef9SDimitry Andric 
81e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h"
82e8d8bef9SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
83fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h"
84e8d8bef9SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
85e8d8bef9SDimitry Andric #include "llvm/ADT/SmallSet.h"
86e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h"
87e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
88349cc55cSDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h"
89e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
90e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
91349cc55cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
92e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
93e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
94e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
95e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
96e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
97fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
98e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
99e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
100e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
101e8d8bef9SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
102e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
103e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
104e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
105e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
106e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
107e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
108e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
109e8d8bef9SDimitry Andric #include "llvm/IR/DIBuilder.h"
110e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
111e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h"
112e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
113e8d8bef9SDimitry Andric #include "llvm/IR/Module.h"
114e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
115e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
116e8d8bef9SDimitry Andric #include "llvm/Pass.h"
117e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h"
118e8d8bef9SDimitry Andric #include "llvm/Support/Compiler.h"
119e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
120e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h"
121e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h"
122fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h"
123fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
124e8d8bef9SDimitry Andric #include <algorithm>
125e8d8bef9SDimitry Andric #include <cassert>
126e8d8bef9SDimitry Andric #include <cstdint>
127e8d8bef9SDimitry Andric #include <functional>
128349cc55cSDimitry Andric #include <limits.h>
129349cc55cSDimitry Andric #include <limits>
130e8d8bef9SDimitry Andric #include <queue>
131e8d8bef9SDimitry Andric #include <tuple>
132e8d8bef9SDimitry Andric #include <utility>
133e8d8bef9SDimitry Andric #include <vector>
134e8d8bef9SDimitry Andric 
135349cc55cSDimitry Andric #include "InstrRefBasedImpl.h"
136e8d8bef9SDimitry Andric #include "LiveDebugValues.h"
137e8d8bef9SDimitry Andric 
138e8d8bef9SDimitry Andric using namespace llvm;
139349cc55cSDimitry Andric using namespace LiveDebugValues;
140e8d8bef9SDimitry Andric 
141fe6060f1SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it.
142fe6060f1SDimitry Andric #undef DEBUG_TYPE
143e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues"
144e8d8bef9SDimitry Andric 
145e8d8bef9SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too
146e8d8bef9SDimitry Andric // far and ignoring some transfers.
147e8d8bef9SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
148e8d8bef9SDimitry Andric                                    cl::desc("Act like old LiveDebugValues did"),
149e8d8bef9SDimitry Andric                                    cl::init(false));
150e8d8bef9SDimitry Andric 
151e8d8bef9SDimitry Andric /// Tracker for converting machine value locations and variable values into
152e8d8bef9SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
153e8d8bef9SDimitry Andric /// specifying block live-in locations and transfers within blocks.
154e8d8bef9SDimitry Andric ///
155e8d8bef9SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
156e8d8bef9SDimitry Andric /// and must be initialized with the set of variable values that are live-in to
157e8d8bef9SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks
158e8d8bef9SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a
159e8d8bef9SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
160e8d8bef9SDimitry Andric /// stepped through, transfers of values between machine locations are
161e8d8bef9SDimitry Andric /// identified and if profitable, a DBG_VALUE created.
162e8d8bef9SDimitry Andric ///
163e8d8bef9SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an
164e8d8bef9SDimitry Andric /// unavailable value could materialize in the middle of a block, when the
165e8d8bef9SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the
166e8d8bef9SDimitry Andric /// variable in a backup location. (XXX these are unimplemented).
167e8d8bef9SDimitry Andric class TransferTracker {
168e8d8bef9SDimitry Andric public:
169e8d8bef9SDimitry Andric   const TargetInstrInfo *TII;
170fe6060f1SDimitry Andric   const TargetLowering *TLI;
171e8d8bef9SDimitry Andric   /// This machine location tracker is assumed to always contain the up-to-date
172e8d8bef9SDimitry Andric   /// value mapping for all machine locations. TransferTracker only reads
173e8d8bef9SDimitry Andric   /// information from it. (XXX make it const?)
174e8d8bef9SDimitry Andric   MLocTracker *MTracker;
175e8d8bef9SDimitry Andric   MachineFunction &MF;
176fe6060f1SDimitry Andric   bool ShouldEmitDebugEntryValues;
177e8d8bef9SDimitry Andric 
178e8d8bef9SDimitry Andric   /// Record of all changes in variable locations at a block position. Awkwardly
179e8d8bef9SDimitry Andric   /// we allow inserting either before or after the point: MBB != nullptr
180e8d8bef9SDimitry Andric   /// indicates it's before, otherwise after.
181e8d8bef9SDimitry Andric   struct Transfer {
182fe6060f1SDimitry Andric     MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
183e8d8bef9SDimitry Andric     MachineBasicBlock *MBB; /// non-null if we should insert after.
184e8d8bef9SDimitry Andric     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
185e8d8bef9SDimitry Andric   };
186e8d8bef9SDimitry Andric 
187fe6060f1SDimitry Andric   struct LocAndProperties {
188e8d8bef9SDimitry Andric     LocIdx Loc;
189e8d8bef9SDimitry Andric     DbgValueProperties Properties;
190fe6060f1SDimitry Andric   };
191e8d8bef9SDimitry Andric 
192e8d8bef9SDimitry Andric   /// Collection of transfers (DBG_VALUEs) to be inserted.
193e8d8bef9SDimitry Andric   SmallVector<Transfer, 32> Transfers;
194e8d8bef9SDimitry Andric 
195e8d8bef9SDimitry Andric   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
196e8d8bef9SDimitry Andric   /// between TransferTrackers view of variable locations and MLocTrackers. For
197e8d8bef9SDimitry Andric   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
198e8d8bef9SDimitry Andric   /// does not.
199349cc55cSDimitry Andric   SmallVector<ValueIDNum, 32> VarLocs;
200e8d8bef9SDimitry Andric 
201e8d8bef9SDimitry Andric   /// Map from LocIdxes to which DebugVariables are based that location.
202e8d8bef9SDimitry Andric   /// Mantained while stepping through the block. Not accurate if
203e8d8bef9SDimitry Andric   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
204349cc55cSDimitry Andric   DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
205e8d8bef9SDimitry Andric 
206e8d8bef9SDimitry Andric   /// Map from DebugVariable to it's current location and qualifying meta
207e8d8bef9SDimitry Andric   /// information. To be used in conjunction with ActiveMLocs to construct
208e8d8bef9SDimitry Andric   /// enough information for the DBG_VALUEs for a particular LocIdx.
209e8d8bef9SDimitry Andric   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
210e8d8bef9SDimitry Andric 
211e8d8bef9SDimitry Andric   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
212e8d8bef9SDimitry Andric   SmallVector<MachineInstr *, 4> PendingDbgValues;
213e8d8bef9SDimitry Andric 
214e8d8bef9SDimitry Andric   /// Record of a use-before-def: created when a value that's live-in to the
215e8d8bef9SDimitry Andric   /// current block isn't available in any machine location, but it will be
216e8d8bef9SDimitry Andric   /// defined in this block.
217e8d8bef9SDimitry Andric   struct UseBeforeDef {
218e8d8bef9SDimitry Andric     /// Value of this variable, def'd in block.
219e8d8bef9SDimitry Andric     ValueIDNum ID;
220e8d8bef9SDimitry Andric     /// Identity of this variable.
221e8d8bef9SDimitry Andric     DebugVariable Var;
222e8d8bef9SDimitry Andric     /// Additional variable properties.
223e8d8bef9SDimitry Andric     DbgValueProperties Properties;
224e8d8bef9SDimitry Andric   };
225e8d8bef9SDimitry Andric 
226e8d8bef9SDimitry Andric   /// Map from instruction index (within the block) to the set of UseBeforeDefs
227e8d8bef9SDimitry Andric   /// that become defined at that instruction.
228e8d8bef9SDimitry Andric   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
229e8d8bef9SDimitry Andric 
230e8d8bef9SDimitry Andric   /// The set of variables that are in UseBeforeDefs and can become a location
231e8d8bef9SDimitry Andric   /// once the relevant value is defined. An element being erased from this
232e8d8bef9SDimitry Andric   /// collection prevents the use-before-def materializing.
233e8d8bef9SDimitry Andric   DenseSet<DebugVariable> UseBeforeDefVariables;
234e8d8bef9SDimitry Andric 
235e8d8bef9SDimitry Andric   const TargetRegisterInfo &TRI;
236e8d8bef9SDimitry Andric   const BitVector &CalleeSavedRegs;
237e8d8bef9SDimitry Andric 
238e8d8bef9SDimitry Andric   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
239e8d8bef9SDimitry Andric                   MachineFunction &MF, const TargetRegisterInfo &TRI,
240fe6060f1SDimitry Andric                   const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
241e8d8bef9SDimitry Andric       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
242fe6060f1SDimitry Andric         CalleeSavedRegs(CalleeSavedRegs) {
243fe6060f1SDimitry Andric     TLI = MF.getSubtarget().getTargetLowering();
244fe6060f1SDimitry Andric     auto &TM = TPC.getTM<TargetMachine>();
245fe6060f1SDimitry Andric     ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
246fe6060f1SDimitry Andric   }
247e8d8bef9SDimitry Andric 
248e8d8bef9SDimitry Andric   /// Load object with live-in variable values. \p mlocs contains the live-in
249e8d8bef9SDimitry Andric   /// values in each machine location, while \p vlocs the live-in variable
250e8d8bef9SDimitry Andric   /// values. This method picks variable locations for the live-in variables,
251e8d8bef9SDimitry Andric   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
252e8d8bef9SDimitry Andric   /// object fields to track variable locations as we step through the block.
253e8d8bef9SDimitry Andric   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
254e8d8bef9SDimitry Andric   void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs,
255e8d8bef9SDimitry Andric                   SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
256e8d8bef9SDimitry Andric                   unsigned NumLocs) {
257e8d8bef9SDimitry Andric     ActiveMLocs.clear();
258e8d8bef9SDimitry Andric     ActiveVLocs.clear();
259e8d8bef9SDimitry Andric     VarLocs.clear();
260e8d8bef9SDimitry Andric     VarLocs.reserve(NumLocs);
261e8d8bef9SDimitry Andric     UseBeforeDefs.clear();
262e8d8bef9SDimitry Andric     UseBeforeDefVariables.clear();
263e8d8bef9SDimitry Andric 
264e8d8bef9SDimitry Andric     auto isCalleeSaved = [&](LocIdx L) {
265e8d8bef9SDimitry Andric       unsigned Reg = MTracker->LocIdxToLocID[L];
266e8d8bef9SDimitry Andric       if (Reg >= MTracker->NumRegs)
267e8d8bef9SDimitry Andric         return false;
268e8d8bef9SDimitry Andric       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
269e8d8bef9SDimitry Andric         if (CalleeSavedRegs.test(*RAI))
270e8d8bef9SDimitry Andric           return true;
271e8d8bef9SDimitry Andric       return false;
272e8d8bef9SDimitry Andric     };
273e8d8bef9SDimitry Andric 
274e8d8bef9SDimitry Andric     // Map of the preferred location for each value.
275e8d8bef9SDimitry Andric     std::map<ValueIDNum, LocIdx> ValueToLoc;
276349cc55cSDimitry Andric     ActiveMLocs.reserve(VLocs.size());
277349cc55cSDimitry Andric     ActiveVLocs.reserve(VLocs.size());
278e8d8bef9SDimitry Andric 
279e8d8bef9SDimitry Andric     // Produce a map of value numbers to the current machine locs they live
280e8d8bef9SDimitry Andric     // in. When emulating VarLocBasedImpl, there should only be one
281e8d8bef9SDimitry Andric     // location; when not, we get to pick.
282e8d8bef9SDimitry Andric     for (auto Location : MTracker->locations()) {
283e8d8bef9SDimitry Andric       LocIdx Idx = Location.Idx;
284e8d8bef9SDimitry Andric       ValueIDNum &VNum = MLocs[Idx.asU64()];
285e8d8bef9SDimitry Andric       VarLocs.push_back(VNum);
286e8d8bef9SDimitry Andric       auto it = ValueToLoc.find(VNum);
287e8d8bef9SDimitry Andric       // In order of preference, pick:
288e8d8bef9SDimitry Andric       //  * Callee saved registers,
289e8d8bef9SDimitry Andric       //  * Other registers,
290e8d8bef9SDimitry Andric       //  * Spill slots.
291e8d8bef9SDimitry Andric       if (it == ValueToLoc.end() || MTracker->isSpill(it->second) ||
292e8d8bef9SDimitry Andric           (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) {
293e8d8bef9SDimitry Andric         // Insert, or overwrite if insertion failed.
294e8d8bef9SDimitry Andric         auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx));
295e8d8bef9SDimitry Andric         if (!PrefLocRes.second)
296e8d8bef9SDimitry Andric           PrefLocRes.first->second = Idx;
297e8d8bef9SDimitry Andric       }
298e8d8bef9SDimitry Andric     }
299e8d8bef9SDimitry Andric 
300e8d8bef9SDimitry Andric     // Now map variables to their picked LocIdxes.
301e8d8bef9SDimitry Andric     for (auto Var : VLocs) {
302e8d8bef9SDimitry Andric       if (Var.second.Kind == DbgValue::Const) {
303e8d8bef9SDimitry Andric         PendingDbgValues.push_back(
304349cc55cSDimitry Andric             emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties));
305e8d8bef9SDimitry Andric         continue;
306e8d8bef9SDimitry Andric       }
307e8d8bef9SDimitry Andric 
308e8d8bef9SDimitry Andric       // If the value has no location, we can't make a variable location.
309e8d8bef9SDimitry Andric       const ValueIDNum &Num = Var.second.ID;
310e8d8bef9SDimitry Andric       auto ValuesPreferredLoc = ValueToLoc.find(Num);
311e8d8bef9SDimitry Andric       if (ValuesPreferredLoc == ValueToLoc.end()) {
312e8d8bef9SDimitry Andric         // If it's a def that occurs in this block, register it as a
313e8d8bef9SDimitry Andric         // use-before-def to be resolved as we step through the block.
314e8d8bef9SDimitry Andric         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
315e8d8bef9SDimitry Andric           addUseBeforeDef(Var.first, Var.second.Properties, Num);
316fe6060f1SDimitry Andric         else
317fe6060f1SDimitry Andric           recoverAsEntryValue(Var.first, Var.second.Properties, Num);
318e8d8bef9SDimitry Andric         continue;
319e8d8bef9SDimitry Andric       }
320e8d8bef9SDimitry Andric 
321e8d8bef9SDimitry Andric       LocIdx M = ValuesPreferredLoc->second;
322e8d8bef9SDimitry Andric       auto NewValue = LocAndProperties{M, Var.second.Properties};
323e8d8bef9SDimitry Andric       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
324e8d8bef9SDimitry Andric       if (!Result.second)
325e8d8bef9SDimitry Andric         Result.first->second = NewValue;
326e8d8bef9SDimitry Andric       ActiveMLocs[M].insert(Var.first);
327e8d8bef9SDimitry Andric       PendingDbgValues.push_back(
328e8d8bef9SDimitry Andric           MTracker->emitLoc(M, Var.first, Var.second.Properties));
329e8d8bef9SDimitry Andric     }
330e8d8bef9SDimitry Andric     flushDbgValues(MBB.begin(), &MBB);
331e8d8bef9SDimitry Andric   }
332e8d8bef9SDimitry Andric 
333e8d8bef9SDimitry Andric   /// Record that \p Var has value \p ID, a value that becomes available
334e8d8bef9SDimitry Andric   /// later in the function.
335e8d8bef9SDimitry Andric   void addUseBeforeDef(const DebugVariable &Var,
336e8d8bef9SDimitry Andric                        const DbgValueProperties &Properties, ValueIDNum ID) {
337e8d8bef9SDimitry Andric     UseBeforeDef UBD = {ID, Var, Properties};
338e8d8bef9SDimitry Andric     UseBeforeDefs[ID.getInst()].push_back(UBD);
339e8d8bef9SDimitry Andric     UseBeforeDefVariables.insert(Var);
340e8d8bef9SDimitry Andric   }
341e8d8bef9SDimitry Andric 
342e8d8bef9SDimitry Andric   /// After the instruction at index \p Inst and position \p pos has been
343e8d8bef9SDimitry Andric   /// processed, check whether it defines a variable value in a use-before-def.
344e8d8bef9SDimitry Andric   /// If so, and the variable value hasn't changed since the start of the
345e8d8bef9SDimitry Andric   /// block, create a DBG_VALUE.
346e8d8bef9SDimitry Andric   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
347e8d8bef9SDimitry Andric     auto MIt = UseBeforeDefs.find(Inst);
348e8d8bef9SDimitry Andric     if (MIt == UseBeforeDefs.end())
349e8d8bef9SDimitry Andric       return;
350e8d8bef9SDimitry Andric 
351e8d8bef9SDimitry Andric     for (auto &Use : MIt->second) {
352e8d8bef9SDimitry Andric       LocIdx L = Use.ID.getLoc();
353e8d8bef9SDimitry Andric 
354e8d8bef9SDimitry Andric       // If something goes very wrong, we might end up labelling a COPY
355e8d8bef9SDimitry Andric       // instruction or similar with an instruction number, where it doesn't
356e8d8bef9SDimitry Andric       // actually define a new value, instead it moves a value. In case this
357e8d8bef9SDimitry Andric       // happens, discard.
358349cc55cSDimitry Andric       if (MTracker->readMLoc(L) != Use.ID)
359e8d8bef9SDimitry Andric         continue;
360e8d8bef9SDimitry Andric 
361e8d8bef9SDimitry Andric       // If a different debug instruction defined the variable value / location
362e8d8bef9SDimitry Andric       // since the start of the block, don't materialize this use-before-def.
363e8d8bef9SDimitry Andric       if (!UseBeforeDefVariables.count(Use.Var))
364e8d8bef9SDimitry Andric         continue;
365e8d8bef9SDimitry Andric 
366e8d8bef9SDimitry Andric       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
367e8d8bef9SDimitry Andric     }
368e8d8bef9SDimitry Andric     flushDbgValues(pos, nullptr);
369e8d8bef9SDimitry Andric   }
370e8d8bef9SDimitry Andric 
371e8d8bef9SDimitry Andric   /// Helper to move created DBG_VALUEs into Transfers collection.
372e8d8bef9SDimitry Andric   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
373fe6060f1SDimitry Andric     if (PendingDbgValues.size() == 0)
374fe6060f1SDimitry Andric       return;
375fe6060f1SDimitry Andric 
376fe6060f1SDimitry Andric     // Pick out the instruction start position.
377fe6060f1SDimitry Andric     MachineBasicBlock::instr_iterator BundleStart;
378fe6060f1SDimitry Andric     if (MBB && Pos == MBB->begin())
379fe6060f1SDimitry Andric       BundleStart = MBB->instr_begin();
380fe6060f1SDimitry Andric     else
381fe6060f1SDimitry Andric       BundleStart = getBundleStart(Pos->getIterator());
382fe6060f1SDimitry Andric 
383fe6060f1SDimitry Andric     Transfers.push_back({BundleStart, MBB, PendingDbgValues});
384e8d8bef9SDimitry Andric     PendingDbgValues.clear();
385e8d8bef9SDimitry Andric   }
386fe6060f1SDimitry Andric 
387fe6060f1SDimitry Andric   bool isEntryValueVariable(const DebugVariable &Var,
388fe6060f1SDimitry Andric                             const DIExpression *Expr) const {
389fe6060f1SDimitry Andric     if (!Var.getVariable()->isParameter())
390fe6060f1SDimitry Andric       return false;
391fe6060f1SDimitry Andric 
392fe6060f1SDimitry Andric     if (Var.getInlinedAt())
393fe6060f1SDimitry Andric       return false;
394fe6060f1SDimitry Andric 
395fe6060f1SDimitry Andric     if (Expr->getNumElements() > 0)
396fe6060f1SDimitry Andric       return false;
397fe6060f1SDimitry Andric 
398fe6060f1SDimitry Andric     return true;
399fe6060f1SDimitry Andric   }
400fe6060f1SDimitry Andric 
401fe6060f1SDimitry Andric   bool isEntryValueValue(const ValueIDNum &Val) const {
402fe6060f1SDimitry Andric     // Must be in entry block (block number zero), and be a PHI / live-in value.
403fe6060f1SDimitry Andric     if (Val.getBlock() || !Val.isPHI())
404fe6060f1SDimitry Andric       return false;
405fe6060f1SDimitry Andric 
406fe6060f1SDimitry Andric     // Entry values must enter in a register.
407fe6060f1SDimitry Andric     if (MTracker->isSpill(Val.getLoc()))
408fe6060f1SDimitry Andric       return false;
409fe6060f1SDimitry Andric 
410fe6060f1SDimitry Andric     Register SP = TLI->getStackPointerRegisterToSaveRestore();
411fe6060f1SDimitry Andric     Register FP = TRI.getFrameRegister(MF);
412fe6060f1SDimitry Andric     Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
413fe6060f1SDimitry Andric     return Reg != SP && Reg != FP;
414fe6060f1SDimitry Andric   }
415fe6060f1SDimitry Andric 
416fe6060f1SDimitry Andric   bool recoverAsEntryValue(const DebugVariable &Var, DbgValueProperties &Prop,
417fe6060f1SDimitry Andric                            const ValueIDNum &Num) {
418fe6060f1SDimitry Andric     // Is this variable location a candidate to be an entry value. First,
419fe6060f1SDimitry Andric     // should we be trying this at all?
420fe6060f1SDimitry Andric     if (!ShouldEmitDebugEntryValues)
421fe6060f1SDimitry Andric       return false;
422fe6060f1SDimitry Andric 
423fe6060f1SDimitry Andric     // Is the variable appropriate for entry values (i.e., is a parameter).
424fe6060f1SDimitry Andric     if (!isEntryValueVariable(Var, Prop.DIExpr))
425fe6060f1SDimitry Andric       return false;
426fe6060f1SDimitry Andric 
427fe6060f1SDimitry Andric     // Is the value assigned to this variable still the entry value?
428fe6060f1SDimitry Andric     if (!isEntryValueValue(Num))
429fe6060f1SDimitry Andric       return false;
430fe6060f1SDimitry Andric 
431fe6060f1SDimitry Andric     // Emit a variable location using an entry value expression.
432fe6060f1SDimitry Andric     DIExpression *NewExpr =
433fe6060f1SDimitry Andric         DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue);
434fe6060f1SDimitry Andric     Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
435fe6060f1SDimitry Andric     MachineOperand MO = MachineOperand::CreateReg(Reg, false);
436fe6060f1SDimitry Andric 
437fe6060f1SDimitry Andric     PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect}));
438fe6060f1SDimitry Andric     return true;
439e8d8bef9SDimitry Andric   }
440e8d8bef9SDimitry Andric 
441e8d8bef9SDimitry Andric   /// Change a variable value after encountering a DBG_VALUE inside a block.
442e8d8bef9SDimitry Andric   void redefVar(const MachineInstr &MI) {
443e8d8bef9SDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
444e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
445e8d8bef9SDimitry Andric     DbgValueProperties Properties(MI);
446e8d8bef9SDimitry Andric 
447e8d8bef9SDimitry Andric     const MachineOperand &MO = MI.getOperand(0);
448e8d8bef9SDimitry Andric 
449e8d8bef9SDimitry Andric     // Ignore non-register locations, we don't transfer those.
450e8d8bef9SDimitry Andric     if (!MO.isReg() || MO.getReg() == 0) {
451e8d8bef9SDimitry Andric       auto It = ActiveVLocs.find(Var);
452e8d8bef9SDimitry Andric       if (It != ActiveVLocs.end()) {
453e8d8bef9SDimitry Andric         ActiveMLocs[It->second.Loc].erase(Var);
454e8d8bef9SDimitry Andric         ActiveVLocs.erase(It);
455e8d8bef9SDimitry Andric      }
456e8d8bef9SDimitry Andric       // Any use-before-defs no longer apply.
457e8d8bef9SDimitry Andric       UseBeforeDefVariables.erase(Var);
458e8d8bef9SDimitry Andric       return;
459e8d8bef9SDimitry Andric     }
460e8d8bef9SDimitry Andric 
461e8d8bef9SDimitry Andric     Register Reg = MO.getReg();
462e8d8bef9SDimitry Andric     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
463e8d8bef9SDimitry Andric     redefVar(MI, Properties, NewLoc);
464e8d8bef9SDimitry Andric   }
465e8d8bef9SDimitry Andric 
466e8d8bef9SDimitry Andric   /// Handle a change in variable location within a block. Terminate the
467e8d8bef9SDimitry Andric   /// variables current location, and record the value it now refers to, so
468e8d8bef9SDimitry Andric   /// that we can detect location transfers later on.
469e8d8bef9SDimitry Andric   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
470e8d8bef9SDimitry Andric                 Optional<LocIdx> OptNewLoc) {
471e8d8bef9SDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
472e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
473e8d8bef9SDimitry Andric     // Any use-before-defs no longer apply.
474e8d8bef9SDimitry Andric     UseBeforeDefVariables.erase(Var);
475e8d8bef9SDimitry Andric 
476e8d8bef9SDimitry Andric     // Erase any previous location,
477e8d8bef9SDimitry Andric     auto It = ActiveVLocs.find(Var);
478e8d8bef9SDimitry Andric     if (It != ActiveVLocs.end())
479e8d8bef9SDimitry Andric       ActiveMLocs[It->second.Loc].erase(Var);
480e8d8bef9SDimitry Andric 
481e8d8bef9SDimitry Andric     // If there _is_ no new location, all we had to do was erase.
482e8d8bef9SDimitry Andric     if (!OptNewLoc)
483e8d8bef9SDimitry Andric       return;
484e8d8bef9SDimitry Andric     LocIdx NewLoc = *OptNewLoc;
485e8d8bef9SDimitry Andric 
486e8d8bef9SDimitry Andric     // Check whether our local copy of values-by-location in #VarLocs is out of
487e8d8bef9SDimitry Andric     // date. Wipe old tracking data for the location if it's been clobbered in
488e8d8bef9SDimitry Andric     // the meantime.
489349cc55cSDimitry Andric     if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
490e8d8bef9SDimitry Andric       for (auto &P : ActiveMLocs[NewLoc]) {
491e8d8bef9SDimitry Andric         ActiveVLocs.erase(P);
492e8d8bef9SDimitry Andric       }
493e8d8bef9SDimitry Andric       ActiveMLocs[NewLoc.asU64()].clear();
494349cc55cSDimitry Andric       VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
495e8d8bef9SDimitry Andric     }
496e8d8bef9SDimitry Andric 
497e8d8bef9SDimitry Andric     ActiveMLocs[NewLoc].insert(Var);
498e8d8bef9SDimitry Andric     if (It == ActiveVLocs.end()) {
499e8d8bef9SDimitry Andric       ActiveVLocs.insert(
500e8d8bef9SDimitry Andric           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
501e8d8bef9SDimitry Andric     } else {
502e8d8bef9SDimitry Andric       It->second.Loc = NewLoc;
503e8d8bef9SDimitry Andric       It->second.Properties = Properties;
504e8d8bef9SDimitry Andric     }
505e8d8bef9SDimitry Andric   }
506e8d8bef9SDimitry Andric 
507fe6060f1SDimitry Andric   /// Account for a location \p mloc being clobbered. Examine the variable
508fe6060f1SDimitry Andric   /// locations that will be terminated: and try to recover them by using
509fe6060f1SDimitry Andric   /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
510fe6060f1SDimitry Andric   /// explicitly terminate a location if it can't be recovered.
511fe6060f1SDimitry Andric   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
512fe6060f1SDimitry Andric                    bool MakeUndef = true) {
513e8d8bef9SDimitry Andric     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
514e8d8bef9SDimitry Andric     if (ActiveMLocIt == ActiveMLocs.end())
515e8d8bef9SDimitry Andric       return;
516e8d8bef9SDimitry Andric 
517fe6060f1SDimitry Andric     // What was the old variable value?
518fe6060f1SDimitry Andric     ValueIDNum OldValue = VarLocs[MLoc.asU64()];
519e8d8bef9SDimitry Andric     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
520e8d8bef9SDimitry Andric 
521fe6060f1SDimitry Andric     // Examine the remaining variable locations: if we can find the same value
522fe6060f1SDimitry Andric     // again, we can recover the location.
523fe6060f1SDimitry Andric     Optional<LocIdx> NewLoc = None;
524fe6060f1SDimitry Andric     for (auto Loc : MTracker->locations())
525fe6060f1SDimitry Andric       if (Loc.Value == OldValue)
526fe6060f1SDimitry Andric         NewLoc = Loc.Idx;
527fe6060f1SDimitry Andric 
528fe6060f1SDimitry Andric     // If there is no location, and we weren't asked to make the variable
529fe6060f1SDimitry Andric     // explicitly undef, then stop here.
530fe6060f1SDimitry Andric     if (!NewLoc && !MakeUndef) {
531fe6060f1SDimitry Andric       // Try and recover a few more locations with entry values.
532fe6060f1SDimitry Andric       for (auto &Var : ActiveMLocIt->second) {
533fe6060f1SDimitry Andric         auto &Prop = ActiveVLocs.find(Var)->second.Properties;
534fe6060f1SDimitry Andric         recoverAsEntryValue(Var, Prop, OldValue);
535fe6060f1SDimitry Andric       }
536fe6060f1SDimitry Andric       flushDbgValues(Pos, nullptr);
537fe6060f1SDimitry Andric       return;
538fe6060f1SDimitry Andric     }
539fe6060f1SDimitry Andric 
540fe6060f1SDimitry Andric     // Examine all the variables based on this location.
541fe6060f1SDimitry Andric     DenseSet<DebugVariable> NewMLocs;
542e8d8bef9SDimitry Andric     for (auto &Var : ActiveMLocIt->second) {
543e8d8bef9SDimitry Andric       auto ActiveVLocIt = ActiveVLocs.find(Var);
544fe6060f1SDimitry Andric       // Re-state the variable location: if there's no replacement then NewLoc
545fe6060f1SDimitry Andric       // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE
546fe6060f1SDimitry Andric       // identifying the alternative location will be emitted.
547*4824e7fdSDimitry Andric       const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
548fe6060f1SDimitry Andric       PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties));
549fe6060f1SDimitry Andric 
550fe6060f1SDimitry Andric       // Update machine locations <=> variable locations maps. Defer updating
551fe6060f1SDimitry Andric       // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator.
552fe6060f1SDimitry Andric       if (!NewLoc) {
553e8d8bef9SDimitry Andric         ActiveVLocs.erase(ActiveVLocIt);
554fe6060f1SDimitry Andric       } else {
555fe6060f1SDimitry Andric         ActiveVLocIt->second.Loc = *NewLoc;
556fe6060f1SDimitry Andric         NewMLocs.insert(Var);
557e8d8bef9SDimitry Andric       }
558fe6060f1SDimitry Andric     }
559fe6060f1SDimitry Andric 
560fe6060f1SDimitry Andric     // Commit any deferred ActiveMLoc changes.
561fe6060f1SDimitry Andric     if (!NewMLocs.empty())
562fe6060f1SDimitry Andric       for (auto &Var : NewMLocs)
563fe6060f1SDimitry Andric         ActiveMLocs[*NewLoc].insert(Var);
564fe6060f1SDimitry Andric 
565fe6060f1SDimitry Andric     // We lazily track what locations have which values; if we've found a new
566fe6060f1SDimitry Andric     // location for the clobbered value, remember it.
567fe6060f1SDimitry Andric     if (NewLoc)
568fe6060f1SDimitry Andric       VarLocs[NewLoc->asU64()] = OldValue;
569fe6060f1SDimitry Andric 
570e8d8bef9SDimitry Andric     flushDbgValues(Pos, nullptr);
571e8d8bef9SDimitry Andric 
572349cc55cSDimitry Andric     // Re-find ActiveMLocIt, iterator could have been invalidated.
573349cc55cSDimitry Andric     ActiveMLocIt = ActiveMLocs.find(MLoc);
574e8d8bef9SDimitry Andric     ActiveMLocIt->second.clear();
575e8d8bef9SDimitry Andric   }
576e8d8bef9SDimitry Andric 
577e8d8bef9SDimitry Andric   /// Transfer variables based on \p Src to be based on \p Dst. This handles
578e8d8bef9SDimitry Andric   /// both register copies as well as spills and restores. Creates DBG_VALUEs
579e8d8bef9SDimitry Andric   /// describing the movement.
580e8d8bef9SDimitry Andric   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
581e8d8bef9SDimitry Andric     // Does Src still contain the value num we expect? If not, it's been
582e8d8bef9SDimitry Andric     // clobbered in the meantime, and our variable locations are stale.
583349cc55cSDimitry Andric     if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
584e8d8bef9SDimitry Andric       return;
585e8d8bef9SDimitry Andric 
586e8d8bef9SDimitry Andric     // assert(ActiveMLocs[Dst].size() == 0);
587e8d8bef9SDimitry Andric     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
588349cc55cSDimitry Andric 
589349cc55cSDimitry Andric     // Move set of active variables from one location to another.
590349cc55cSDimitry Andric     auto MovingVars = ActiveMLocs[Src];
591349cc55cSDimitry Andric     ActiveMLocs[Dst] = MovingVars;
592e8d8bef9SDimitry Andric     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
593e8d8bef9SDimitry Andric 
594e8d8bef9SDimitry Andric     // For each variable based on Src; create a location at Dst.
595349cc55cSDimitry Andric     for (auto &Var : MovingVars) {
596e8d8bef9SDimitry Andric       auto ActiveVLocIt = ActiveVLocs.find(Var);
597e8d8bef9SDimitry Andric       assert(ActiveVLocIt != ActiveVLocs.end());
598e8d8bef9SDimitry Andric       ActiveVLocIt->second.Loc = Dst;
599e8d8bef9SDimitry Andric 
600e8d8bef9SDimitry Andric       MachineInstr *MI =
601e8d8bef9SDimitry Andric           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
602e8d8bef9SDimitry Andric       PendingDbgValues.push_back(MI);
603e8d8bef9SDimitry Andric     }
604e8d8bef9SDimitry Andric     ActiveMLocs[Src].clear();
605e8d8bef9SDimitry Andric     flushDbgValues(Pos, nullptr);
606e8d8bef9SDimitry Andric 
607e8d8bef9SDimitry Andric     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
608e8d8bef9SDimitry Andric     // about the old location.
609e8d8bef9SDimitry Andric     if (EmulateOldLDV)
610e8d8bef9SDimitry Andric       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
611e8d8bef9SDimitry Andric   }
612e8d8bef9SDimitry Andric 
613e8d8bef9SDimitry Andric   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
614e8d8bef9SDimitry Andric                                 const DebugVariable &Var,
615e8d8bef9SDimitry Andric                                 const DbgValueProperties &Properties) {
616e8d8bef9SDimitry Andric     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
617e8d8bef9SDimitry Andric                                   Var.getVariable()->getScope(),
618e8d8bef9SDimitry Andric                                   const_cast<DILocation *>(Var.getInlinedAt()));
619e8d8bef9SDimitry Andric     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
620e8d8bef9SDimitry Andric     MIB.add(MO);
621e8d8bef9SDimitry Andric     if (Properties.Indirect)
622e8d8bef9SDimitry Andric       MIB.addImm(0);
623e8d8bef9SDimitry Andric     else
624e8d8bef9SDimitry Andric       MIB.addReg(0);
625e8d8bef9SDimitry Andric     MIB.addMetadata(Var.getVariable());
626e8d8bef9SDimitry Andric     MIB.addMetadata(Properties.DIExpr);
627e8d8bef9SDimitry Andric     return MIB;
628e8d8bef9SDimitry Andric   }
629e8d8bef9SDimitry Andric };
630e8d8bef9SDimitry Andric 
631349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
632349cc55cSDimitry Andric //            Implementation
633349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
634e8d8bef9SDimitry Andric 
635349cc55cSDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
636349cc55cSDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
637e8d8bef9SDimitry Andric 
638349cc55cSDimitry Andric #ifndef NDEBUG
639349cc55cSDimitry Andric void DbgValue::dump(const MLocTracker *MTrack) const {
640349cc55cSDimitry Andric   if (Kind == Const) {
641349cc55cSDimitry Andric     MO->dump();
642349cc55cSDimitry Andric   } else if (Kind == NoVal) {
643349cc55cSDimitry Andric     dbgs() << "NoVal(" << BlockNo << ")";
644349cc55cSDimitry Andric   } else if (Kind == VPHI) {
645349cc55cSDimitry Andric     dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")";
646349cc55cSDimitry Andric   } else {
647349cc55cSDimitry Andric     assert(Kind == Def);
648349cc55cSDimitry Andric     dbgs() << MTrack->IDAsString(ID);
649349cc55cSDimitry Andric   }
650349cc55cSDimitry Andric   if (Properties.Indirect)
651349cc55cSDimitry Andric     dbgs() << " indir";
652349cc55cSDimitry Andric   if (Properties.DIExpr)
653349cc55cSDimitry Andric     dbgs() << " " << *Properties.DIExpr;
654349cc55cSDimitry Andric }
655349cc55cSDimitry Andric #endif
656e8d8bef9SDimitry Andric 
657349cc55cSDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
658349cc55cSDimitry Andric                          const TargetRegisterInfo &TRI,
659349cc55cSDimitry Andric                          const TargetLowering &TLI)
660349cc55cSDimitry Andric     : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
661349cc55cSDimitry Andric       LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
662349cc55cSDimitry Andric   NumRegs = TRI.getNumRegs();
663349cc55cSDimitry Andric   reset();
664349cc55cSDimitry Andric   LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
665349cc55cSDimitry Andric   assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
666e8d8bef9SDimitry Andric 
667349cc55cSDimitry Andric   // Always track SP. This avoids the implicit clobbering caused by regmasks
668349cc55cSDimitry Andric   // from affectings its values. (LiveDebugValues disbelieves calls and
669349cc55cSDimitry Andric   // regmasks that claim to clobber SP).
670349cc55cSDimitry Andric   Register SP = TLI.getStackPointerRegisterToSaveRestore();
671349cc55cSDimitry Andric   if (SP) {
672349cc55cSDimitry Andric     unsigned ID = getLocID(SP);
673349cc55cSDimitry Andric     (void)lookupOrTrackRegister(ID);
674e8d8bef9SDimitry Andric 
675349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
676349cc55cSDimitry Andric       SPAliases.insert(*RAI);
677349cc55cSDimitry Andric   }
678e8d8bef9SDimitry Andric 
679349cc55cSDimitry Andric   // Build some common stack positions -- full registers being spilt to the
680349cc55cSDimitry Andric   // stack.
681349cc55cSDimitry Andric   StackSlotIdxes.insert({{8, 0}, 0});
682349cc55cSDimitry Andric   StackSlotIdxes.insert({{16, 0}, 1});
683349cc55cSDimitry Andric   StackSlotIdxes.insert({{32, 0}, 2});
684349cc55cSDimitry Andric   StackSlotIdxes.insert({{64, 0}, 3});
685349cc55cSDimitry Andric   StackSlotIdxes.insert({{128, 0}, 4});
686349cc55cSDimitry Andric   StackSlotIdxes.insert({{256, 0}, 5});
687349cc55cSDimitry Andric   StackSlotIdxes.insert({{512, 0}, 6});
688e8d8bef9SDimitry Andric 
689349cc55cSDimitry Andric   // Traverse all the subregister idxes, and ensure there's an index for them.
690349cc55cSDimitry Andric   // Duplicates are no problem: we're interested in their position in the
691349cc55cSDimitry Andric   // stack slot, we don't want to type the slot.
692349cc55cSDimitry Andric   for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
693349cc55cSDimitry Andric     unsigned Size = TRI.getSubRegIdxSize(I);
694349cc55cSDimitry Andric     unsigned Offs = TRI.getSubRegIdxOffset(I);
695349cc55cSDimitry Andric     unsigned Idx = StackSlotIdxes.size();
696e8d8bef9SDimitry Andric 
697349cc55cSDimitry Andric     // Some subregs have -1, -2 and so forth fed into their fields, to mean
698349cc55cSDimitry Andric     // special backend things. Ignore those.
699349cc55cSDimitry Andric     if (Size > 60000 || Offs > 60000)
700349cc55cSDimitry Andric       continue;
701e8d8bef9SDimitry Andric 
702349cc55cSDimitry Andric     StackSlotIdxes.insert({{Size, Offs}, Idx});
703349cc55cSDimitry Andric   }
704e8d8bef9SDimitry Andric 
705349cc55cSDimitry Andric   for (auto &Idx : StackSlotIdxes)
706349cc55cSDimitry Andric     StackIdxesToPos[Idx.second] = Idx.first;
707e8d8bef9SDimitry Andric 
708349cc55cSDimitry Andric   NumSlotIdxes = StackSlotIdxes.size();
709349cc55cSDimitry Andric }
710e8d8bef9SDimitry Andric 
711349cc55cSDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) {
712349cc55cSDimitry Andric   assert(ID != 0);
713349cc55cSDimitry Andric   LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
714349cc55cSDimitry Andric   LocIdxToIDNum.grow(NewIdx);
715349cc55cSDimitry Andric   LocIdxToLocID.grow(NewIdx);
716e8d8bef9SDimitry Andric 
717349cc55cSDimitry Andric   // Default: it's an mphi.
718349cc55cSDimitry Andric   ValueIDNum ValNum = {CurBB, 0, NewIdx};
719349cc55cSDimitry Andric   // Was this reg ever touched by a regmask?
720349cc55cSDimitry Andric   for (const auto &MaskPair : reverse(Masks)) {
721349cc55cSDimitry Andric     if (MaskPair.first->clobbersPhysReg(ID)) {
722349cc55cSDimitry Andric       // There was an earlier def we skipped.
723349cc55cSDimitry Andric       ValNum = {CurBB, MaskPair.second, NewIdx};
724349cc55cSDimitry Andric       break;
725349cc55cSDimitry Andric     }
726349cc55cSDimitry Andric   }
727e8d8bef9SDimitry Andric 
728349cc55cSDimitry Andric   LocIdxToIDNum[NewIdx] = ValNum;
729349cc55cSDimitry Andric   LocIdxToLocID[NewIdx] = ID;
730349cc55cSDimitry Andric   return NewIdx;
731349cc55cSDimitry Andric }
732e8d8bef9SDimitry Andric 
733349cc55cSDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
734349cc55cSDimitry Andric                                unsigned InstID) {
735349cc55cSDimitry Andric   // Def any register we track have that isn't preserved. The regmask
736349cc55cSDimitry Andric   // terminates the liveness of a register, meaning its value can't be
737349cc55cSDimitry Andric   // relied upon -- we represent this by giving it a new value.
738349cc55cSDimitry Andric   for (auto Location : locations()) {
739349cc55cSDimitry Andric     unsigned ID = LocIdxToLocID[Location.Idx];
740349cc55cSDimitry Andric     // Don't clobber SP, even if the mask says it's clobbered.
741349cc55cSDimitry Andric     if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
742349cc55cSDimitry Andric       defReg(ID, CurBB, InstID);
743349cc55cSDimitry Andric   }
744349cc55cSDimitry Andric   Masks.push_back(std::make_pair(MO, InstID));
745349cc55cSDimitry Andric }
746e8d8bef9SDimitry Andric 
747349cc55cSDimitry Andric SpillLocationNo MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
748349cc55cSDimitry Andric   SpillLocationNo SpillID(SpillLocs.idFor(L));
749349cc55cSDimitry Andric   if (SpillID.id() == 0) {
750349cc55cSDimitry Andric     // Spill location is untracked: create record for this one, and all
751349cc55cSDimitry Andric     // subregister slots too.
752349cc55cSDimitry Andric     SpillID = SpillLocationNo(SpillLocs.insert(L));
753349cc55cSDimitry Andric     for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
754349cc55cSDimitry Andric       unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
755349cc55cSDimitry Andric       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
756349cc55cSDimitry Andric       LocIdxToIDNum.grow(Idx);
757349cc55cSDimitry Andric       LocIdxToLocID.grow(Idx);
758349cc55cSDimitry Andric       LocIDToLocIdx.push_back(Idx);
759349cc55cSDimitry Andric       LocIdxToLocID[Idx] = L;
760349cc55cSDimitry Andric       // Initialize to PHI value; corresponds to the location's live-in value
761349cc55cSDimitry Andric       // during transfer function construction.
762349cc55cSDimitry Andric       LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
763349cc55cSDimitry Andric     }
764349cc55cSDimitry Andric   }
765349cc55cSDimitry Andric   return SpillID;
766349cc55cSDimitry Andric }
767fe6060f1SDimitry Andric 
768349cc55cSDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
769349cc55cSDimitry Andric   unsigned ID = LocIdxToLocID[Idx];
770349cc55cSDimitry Andric   if (ID >= NumRegs) {
771349cc55cSDimitry Andric     StackSlotPos Pos = locIDToSpillIdx(ID);
772349cc55cSDimitry Andric     ID -= NumRegs;
773349cc55cSDimitry Andric     unsigned Slot = ID / NumSlotIdxes;
774349cc55cSDimitry Andric     return Twine("slot ")
775349cc55cSDimitry Andric         .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
776349cc55cSDimitry Andric         .concat(Twine(" offs ").concat(Twine(Pos.second))))))
777349cc55cSDimitry Andric         .str();
778349cc55cSDimitry Andric   } else {
779349cc55cSDimitry Andric     return TRI.getRegAsmName(ID).str();
780349cc55cSDimitry Andric   }
781349cc55cSDimitry Andric }
782fe6060f1SDimitry Andric 
783349cc55cSDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
784349cc55cSDimitry Andric   std::string DefName = LocIdxToName(Num.getLoc());
785349cc55cSDimitry Andric   return Num.asString(DefName);
786349cc55cSDimitry Andric }
787fe6060f1SDimitry Andric 
788349cc55cSDimitry Andric #ifndef NDEBUG
789349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() {
790349cc55cSDimitry Andric   for (auto Location : locations()) {
791349cc55cSDimitry Andric     std::string MLocName = LocIdxToName(Location.Value.getLoc());
792349cc55cSDimitry Andric     std::string DefName = Location.Value.asString(MLocName);
793349cc55cSDimitry Andric     dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
794349cc55cSDimitry Andric   }
795349cc55cSDimitry Andric }
796e8d8bef9SDimitry Andric 
797349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
798349cc55cSDimitry Andric   for (auto Location : locations()) {
799349cc55cSDimitry Andric     std::string foo = LocIdxToName(Location.Idx);
800349cc55cSDimitry Andric     dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
801349cc55cSDimitry Andric   }
802349cc55cSDimitry Andric }
803349cc55cSDimitry Andric #endif
804e8d8bef9SDimitry Andric 
805349cc55cSDimitry Andric MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc,
806349cc55cSDimitry Andric                                          const DebugVariable &Var,
807349cc55cSDimitry Andric                                          const DbgValueProperties &Properties) {
808349cc55cSDimitry Andric   DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
809349cc55cSDimitry Andric                                 Var.getVariable()->getScope(),
810349cc55cSDimitry Andric                                 const_cast<DILocation *>(Var.getInlinedAt()));
811349cc55cSDimitry Andric   auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
812e8d8bef9SDimitry Andric 
813349cc55cSDimitry Andric   const DIExpression *Expr = Properties.DIExpr;
814349cc55cSDimitry Andric   if (!MLoc) {
815349cc55cSDimitry Andric     // No location -> DBG_VALUE $noreg
816349cc55cSDimitry Andric     MIB.addReg(0);
817349cc55cSDimitry Andric     MIB.addReg(0);
818349cc55cSDimitry Andric   } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
819349cc55cSDimitry Andric     unsigned LocID = LocIdxToLocID[*MLoc];
820349cc55cSDimitry Andric     SpillLocationNo SpillID = locIDToSpill(LocID);
821349cc55cSDimitry Andric     StackSlotPos StackIdx = locIDToSpillIdx(LocID);
822349cc55cSDimitry Andric     unsigned short Offset = StackIdx.second;
823e8d8bef9SDimitry Andric 
824349cc55cSDimitry Andric     // TODO: support variables that are located in spill slots, with non-zero
825349cc55cSDimitry Andric     // offsets from the start of the spill slot. It would require some more
826349cc55cSDimitry Andric     // complex DIExpression calculations. This doesn't seem to be produced by
827349cc55cSDimitry Andric     // LLVM right now, so don't try and support it.
828349cc55cSDimitry Andric     // Accept no-subregister slots and subregisters where the offset is zero.
829349cc55cSDimitry Andric     // The consumer should already have type information to work out how large
830349cc55cSDimitry Andric     // the variable is.
831349cc55cSDimitry Andric     if (Offset == 0) {
832349cc55cSDimitry Andric       const SpillLoc &Spill = SpillLocs[SpillID.id()];
833349cc55cSDimitry Andric       Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset,
834349cc55cSDimitry Andric                                          Spill.SpillOffset);
835349cc55cSDimitry Andric       unsigned Base = Spill.SpillBase;
836349cc55cSDimitry Andric       MIB.addReg(Base);
837349cc55cSDimitry Andric       MIB.addImm(0);
838*4824e7fdSDimitry Andric 
839*4824e7fdSDimitry Andric       // Being on the stack makes this location indirect; if it was _already_
840*4824e7fdSDimitry Andric       // indirect though, we need to add extra indirection. See this test for
841*4824e7fdSDimitry Andric       // a scenario where this happens:
842*4824e7fdSDimitry Andric       //     llvm/test/DebugInfo/X86/spill-nontrivial-param.ll
843*4824e7fdSDimitry Andric       if (Properties.Indirect) {
844*4824e7fdSDimitry Andric         std::vector<uint64_t> Elts = {dwarf::DW_OP_deref};
845*4824e7fdSDimitry Andric         Expr = DIExpression::append(Expr, Elts);
846*4824e7fdSDimitry Andric       }
847349cc55cSDimitry Andric     } else {
848349cc55cSDimitry Andric       // This is a stack location with a weird subregister offset: emit an undef
849349cc55cSDimitry Andric       // DBG_VALUE instead.
850349cc55cSDimitry Andric       MIB.addReg(0);
851349cc55cSDimitry Andric       MIB.addReg(0);
852349cc55cSDimitry Andric     }
853349cc55cSDimitry Andric   } else {
854349cc55cSDimitry Andric     // Non-empty, non-stack slot, must be a plain register.
855349cc55cSDimitry Andric     unsigned LocID = LocIdxToLocID[*MLoc];
856349cc55cSDimitry Andric     MIB.addReg(LocID);
857349cc55cSDimitry Andric     if (Properties.Indirect)
858349cc55cSDimitry Andric       MIB.addImm(0);
859349cc55cSDimitry Andric     else
860349cc55cSDimitry Andric       MIB.addReg(0);
861349cc55cSDimitry Andric   }
862e8d8bef9SDimitry Andric 
863349cc55cSDimitry Andric   MIB.addMetadata(Var.getVariable());
864349cc55cSDimitry Andric   MIB.addMetadata(Expr);
865349cc55cSDimitry Andric   return MIB;
866349cc55cSDimitry Andric }
867e8d8bef9SDimitry Andric 
868e8d8bef9SDimitry Andric /// Default construct and initialize the pass.
869349cc55cSDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() {}
870e8d8bef9SDimitry Andric 
871349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
872e8d8bef9SDimitry Andric   unsigned Reg = MTracker->LocIdxToLocID[L];
873e8d8bef9SDimitry Andric   for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
874e8d8bef9SDimitry Andric     if (CalleeSavedRegs.test(*RAI))
875e8d8bef9SDimitry Andric       return true;
876e8d8bef9SDimitry Andric   return false;
877e8d8bef9SDimitry Andric }
878e8d8bef9SDimitry Andric 
879e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
880e8d8bef9SDimitry Andric //            Debug Range Extension Implementation
881e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
882e8d8bef9SDimitry Andric 
883e8d8bef9SDimitry Andric #ifndef NDEBUG
884e8d8bef9SDimitry Andric // Something to restore in the future.
885e8d8bef9SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..)
886e8d8bef9SDimitry Andric #endif
887e8d8bef9SDimitry Andric 
888349cc55cSDimitry Andric SpillLocationNo
889e8d8bef9SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
890e8d8bef9SDimitry Andric   assert(MI.hasOneMemOperand() &&
891e8d8bef9SDimitry Andric          "Spill instruction does not have exactly one memory operand?");
892e8d8bef9SDimitry Andric   auto MMOI = MI.memoperands_begin();
893e8d8bef9SDimitry Andric   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
894e8d8bef9SDimitry Andric   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
895e8d8bef9SDimitry Andric          "Inconsistent memory operand in spill instruction");
896e8d8bef9SDimitry Andric   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
897e8d8bef9SDimitry Andric   const MachineBasicBlock *MBB = MI.getParent();
898e8d8bef9SDimitry Andric   Register Reg;
899e8d8bef9SDimitry Andric   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
900349cc55cSDimitry Andric   return MTracker->getOrTrackSpillLoc({Reg, Offset});
901349cc55cSDimitry Andric }
902349cc55cSDimitry Andric 
903349cc55cSDimitry Andric Optional<LocIdx> InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
904349cc55cSDimitry Andric   SpillLocationNo SpillLoc =  extractSpillBaseRegAndOffset(MI);
905349cc55cSDimitry Andric 
906349cc55cSDimitry Andric   // Where in the stack slot is this value defined -- i.e., what size of value
907349cc55cSDimitry Andric   // is this? An important question, because it could be loaded into a register
908349cc55cSDimitry Andric   // from the stack at some point. Happily the memory operand will tell us
909349cc55cSDimitry Andric   // the size written to the stack.
910349cc55cSDimitry Andric   auto *MemOperand = *MI.memoperands_begin();
911349cc55cSDimitry Andric   unsigned SizeInBits = MemOperand->getSizeInBits();
912349cc55cSDimitry Andric 
913349cc55cSDimitry Andric   // Find that position in the stack indexes we're tracking.
914349cc55cSDimitry Andric   auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0});
915349cc55cSDimitry Andric   if (IdxIt == MTracker->StackSlotIdxes.end())
916349cc55cSDimitry Andric     // That index is not tracked. This is suprising, and unlikely to ever
917349cc55cSDimitry Andric     // occur, but the safe action is to indicate the variable is optimised out.
918349cc55cSDimitry Andric     return None;
919349cc55cSDimitry Andric 
920349cc55cSDimitry Andric   unsigned SpillID = MTracker->getSpillIDWithIdx(SpillLoc, IdxIt->second);
921349cc55cSDimitry Andric   return MTracker->getSpillMLoc(SpillID);
922e8d8bef9SDimitry Andric }
923e8d8bef9SDimitry Andric 
924e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI
925e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr.
926e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
927e8d8bef9SDimitry Andric   if (!MI.isDebugValue())
928e8d8bef9SDimitry Andric     return false;
929e8d8bef9SDimitry Andric 
930e8d8bef9SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
931e8d8bef9SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
932e8d8bef9SDimitry Andric   const DILocation *DebugLoc = MI.getDebugLoc();
933e8d8bef9SDimitry Andric   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
934e8d8bef9SDimitry Andric   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
935e8d8bef9SDimitry Andric          "Expected inlined-at fields to agree");
936e8d8bef9SDimitry Andric 
937e8d8bef9SDimitry Andric   DebugVariable V(Var, Expr, InlinedAt);
938e8d8bef9SDimitry Andric   DbgValueProperties Properties(MI);
939e8d8bef9SDimitry Andric 
940e8d8bef9SDimitry Andric   // If there are no instructions in this lexical scope, do no location tracking
941e8d8bef9SDimitry Andric   // at all, this variable shouldn't get a legitimate location range.
942e8d8bef9SDimitry Andric   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
943e8d8bef9SDimitry Andric   if (Scope == nullptr)
944e8d8bef9SDimitry Andric     return true; // handled it; by doing nothing
945e8d8bef9SDimitry Andric 
946349cc55cSDimitry Andric   // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to
947349cc55cSDimitry Andric   // contribute to locations in this block, but don't propagate further.
948349cc55cSDimitry Andric   // Interpret it like a DBG_VALUE $noreg.
949349cc55cSDimitry Andric   if (MI.isDebugValueList()) {
950349cc55cSDimitry Andric     if (VTracker)
951349cc55cSDimitry Andric       VTracker->defVar(MI, Properties, None);
952349cc55cSDimitry Andric     if (TTracker)
953349cc55cSDimitry Andric       TTracker->redefVar(MI, Properties, None);
954349cc55cSDimitry Andric     return true;
955349cc55cSDimitry Andric   }
956349cc55cSDimitry Andric 
957e8d8bef9SDimitry Andric   const MachineOperand &MO = MI.getOperand(0);
958e8d8bef9SDimitry Andric 
959e8d8bef9SDimitry Andric   // MLocTracker needs to know that this register is read, even if it's only
960e8d8bef9SDimitry Andric   // read by a debug inst.
961e8d8bef9SDimitry Andric   if (MO.isReg() && MO.getReg() != 0)
962e8d8bef9SDimitry Andric     (void)MTracker->readReg(MO.getReg());
963e8d8bef9SDimitry Andric 
964e8d8bef9SDimitry Andric   // If we're preparing for the second analysis (variables), the machine value
965e8d8bef9SDimitry Andric   // locations are already solved, and we report this DBG_VALUE and the value
966e8d8bef9SDimitry Andric   // it refers to to VLocTracker.
967e8d8bef9SDimitry Andric   if (VTracker) {
968e8d8bef9SDimitry Andric     if (MO.isReg()) {
969e8d8bef9SDimitry Andric       // Feed defVar the new variable location, or if this is a
970e8d8bef9SDimitry Andric       // DBG_VALUE $noreg, feed defVar None.
971e8d8bef9SDimitry Andric       if (MO.getReg())
972e8d8bef9SDimitry Andric         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
973e8d8bef9SDimitry Andric       else
974e8d8bef9SDimitry Andric         VTracker->defVar(MI, Properties, None);
975e8d8bef9SDimitry Andric     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
976e8d8bef9SDimitry Andric                MI.getOperand(0).isCImm()) {
977e8d8bef9SDimitry Andric       VTracker->defVar(MI, MI.getOperand(0));
978e8d8bef9SDimitry Andric     }
979e8d8bef9SDimitry Andric   }
980e8d8bef9SDimitry Andric 
981e8d8bef9SDimitry Andric   // If performing final tracking of transfers, report this variable definition
982e8d8bef9SDimitry Andric   // to the TransferTracker too.
983e8d8bef9SDimitry Andric   if (TTracker)
984e8d8bef9SDimitry Andric     TTracker->redefVar(MI);
985e8d8bef9SDimitry Andric   return true;
986e8d8bef9SDimitry Andric }
987e8d8bef9SDimitry Andric 
988fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
989fe6060f1SDimitry Andric                                              ValueIDNum **MLiveOuts,
990fe6060f1SDimitry Andric                                              ValueIDNum **MLiveIns) {
991e8d8bef9SDimitry Andric   if (!MI.isDebugRef())
992e8d8bef9SDimitry Andric     return false;
993e8d8bef9SDimitry Andric 
994e8d8bef9SDimitry Andric   // Only handle this instruction when we are building the variable value
995e8d8bef9SDimitry Andric   // transfer function.
996e8d8bef9SDimitry Andric   if (!VTracker)
997e8d8bef9SDimitry Andric     return false;
998e8d8bef9SDimitry Andric 
999e8d8bef9SDimitry Andric   unsigned InstNo = MI.getOperand(0).getImm();
1000e8d8bef9SDimitry Andric   unsigned OpNo = MI.getOperand(1).getImm();
1001e8d8bef9SDimitry Andric 
1002e8d8bef9SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
1003e8d8bef9SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
1004e8d8bef9SDimitry Andric   const DILocation *DebugLoc = MI.getDebugLoc();
1005e8d8bef9SDimitry Andric   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1006e8d8bef9SDimitry Andric   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1007e8d8bef9SDimitry Andric          "Expected inlined-at fields to agree");
1008e8d8bef9SDimitry Andric 
1009e8d8bef9SDimitry Andric   DebugVariable V(Var, Expr, InlinedAt);
1010e8d8bef9SDimitry Andric 
1011e8d8bef9SDimitry Andric   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1012e8d8bef9SDimitry Andric   if (Scope == nullptr)
1013e8d8bef9SDimitry Andric     return true; // Handled by doing nothing. This variable is never in scope.
1014e8d8bef9SDimitry Andric 
1015e8d8bef9SDimitry Andric   const MachineFunction &MF = *MI.getParent()->getParent();
1016e8d8bef9SDimitry Andric 
1017e8d8bef9SDimitry Andric   // Various optimizations may have happened to the value during codegen,
1018e8d8bef9SDimitry Andric   // recorded in the value substitution table. Apply any substitutions to
1019fe6060f1SDimitry Andric   // the instruction / operand number in this DBG_INSTR_REF, and collect
1020fe6060f1SDimitry Andric   // any subregister extractions performed during optimization.
1021fe6060f1SDimitry Andric 
1022fe6060f1SDimitry Andric   // Create dummy substitution with Src set, for lookup.
1023fe6060f1SDimitry Andric   auto SoughtSub =
1024fe6060f1SDimitry Andric       MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1025fe6060f1SDimitry Andric 
1026fe6060f1SDimitry Andric   SmallVector<unsigned, 4> SeenSubregs;
1027fe6060f1SDimitry Andric   auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1028fe6060f1SDimitry Andric   while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1029fe6060f1SDimitry Andric          LowerBoundIt->Src == SoughtSub.Src) {
1030fe6060f1SDimitry Andric     std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1031fe6060f1SDimitry Andric     SoughtSub.Src = LowerBoundIt->Dest;
1032fe6060f1SDimitry Andric     if (unsigned Subreg = LowerBoundIt->Subreg)
1033fe6060f1SDimitry Andric       SeenSubregs.push_back(Subreg);
1034fe6060f1SDimitry Andric     LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1035e8d8bef9SDimitry Andric   }
1036e8d8bef9SDimitry Andric 
1037e8d8bef9SDimitry Andric   // Default machine value number is <None> -- if no instruction defines
1038e8d8bef9SDimitry Andric   // the corresponding value, it must have been optimized out.
1039e8d8bef9SDimitry Andric   Optional<ValueIDNum> NewID = None;
1040e8d8bef9SDimitry Andric 
1041e8d8bef9SDimitry Andric   // Try to lookup the instruction number, and find the machine value number
1042fe6060f1SDimitry Andric   // that it defines. It could be an instruction, or a PHI.
1043e8d8bef9SDimitry Andric   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1044fe6060f1SDimitry Andric   auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(),
1045fe6060f1SDimitry Andric                                 DebugPHINumToValue.end(), InstNo);
1046e8d8bef9SDimitry Andric   if (InstrIt != DebugInstrNumToInstr.end()) {
1047e8d8bef9SDimitry Andric     const MachineInstr &TargetInstr = *InstrIt->second.first;
1048e8d8bef9SDimitry Andric     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1049e8d8bef9SDimitry Andric 
1050349cc55cSDimitry Andric     // Pick out the designated operand. It might be a memory reference, if
1051349cc55cSDimitry Andric     // a register def was folded into a stack store.
1052349cc55cSDimitry Andric     if (OpNo == MachineFunction::DebugOperandMemNumber &&
1053349cc55cSDimitry Andric         TargetInstr.hasOneMemOperand()) {
1054349cc55cSDimitry Andric       Optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1055349cc55cSDimitry Andric       if (L)
1056349cc55cSDimitry Andric         NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1057349cc55cSDimitry Andric     } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
1058e8d8bef9SDimitry Andric       assert(OpNo < TargetInstr.getNumOperands());
1059e8d8bef9SDimitry Andric       const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1060e8d8bef9SDimitry Andric 
1061e8d8bef9SDimitry Andric       // Today, this can only be a register.
1062e8d8bef9SDimitry Andric       assert(MO.isReg() && MO.isDef());
1063e8d8bef9SDimitry Andric 
1064349cc55cSDimitry Andric       unsigned LocID = MTracker->getLocID(MO.getReg());
1065e8d8bef9SDimitry Andric       LocIdx L = MTracker->LocIDToLocIdx[LocID];
1066e8d8bef9SDimitry Andric       NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1067349cc55cSDimitry Andric     }
1068349cc55cSDimitry Andric     // else: NewID is left as None.
1069fe6060f1SDimitry Andric   } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1070fe6060f1SDimitry Andric     // It's actually a PHI value. Which value it is might not be obvious, use
1071fe6060f1SDimitry Andric     // the resolver helper to find out.
1072fe6060f1SDimitry Andric     NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
1073fe6060f1SDimitry Andric                            MI, InstNo);
1074fe6060f1SDimitry Andric   }
1075fe6060f1SDimitry Andric 
1076fe6060f1SDimitry Andric   // Apply any subregister extractions, in reverse. We might have seen code
1077fe6060f1SDimitry Andric   // like this:
1078fe6060f1SDimitry Andric   //    CALL64 @foo, implicit-def $rax
1079fe6060f1SDimitry Andric   //    %0:gr64 = COPY $rax
1080fe6060f1SDimitry Andric   //    %1:gr32 = COPY %0.sub_32bit
1081fe6060f1SDimitry Andric   //    %2:gr16 = COPY %1.sub_16bit
1082fe6060f1SDimitry Andric   //    %3:gr8  = COPY %2.sub_8bit
1083fe6060f1SDimitry Andric   // In which case each copy would have been recorded as a substitution with
1084fe6060f1SDimitry Andric   // a subregister qualifier. Apply those qualifiers now.
1085fe6060f1SDimitry Andric   if (NewID && !SeenSubregs.empty()) {
1086fe6060f1SDimitry Andric     unsigned Offset = 0;
1087fe6060f1SDimitry Andric     unsigned Size = 0;
1088fe6060f1SDimitry Andric 
1089fe6060f1SDimitry Andric     // Look at each subregister that we passed through, and progressively
1090fe6060f1SDimitry Andric     // narrow in, accumulating any offsets that occur. Substitutions should
1091fe6060f1SDimitry Andric     // only ever be the same or narrower width than what they read from;
1092fe6060f1SDimitry Andric     // iterate in reverse order so that we go from wide to small.
1093fe6060f1SDimitry Andric     for (unsigned Subreg : reverse(SeenSubregs)) {
1094fe6060f1SDimitry Andric       unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1095fe6060f1SDimitry Andric       unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1096fe6060f1SDimitry Andric       Offset += ThisOffset;
1097fe6060f1SDimitry Andric       Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1098fe6060f1SDimitry Andric     }
1099fe6060f1SDimitry Andric 
1100fe6060f1SDimitry Andric     // If that worked, look for an appropriate subregister with the register
1101fe6060f1SDimitry Andric     // where the define happens. Don't look at values that were defined during
1102fe6060f1SDimitry Andric     // a stack write: we can't currently express register locations within
1103fe6060f1SDimitry Andric     // spills.
1104fe6060f1SDimitry Andric     LocIdx L = NewID->getLoc();
1105fe6060f1SDimitry Andric     if (NewID && !MTracker->isSpill(L)) {
1106fe6060f1SDimitry Andric       // Find the register class for the register where this def happened.
1107fe6060f1SDimitry Andric       // FIXME: no index for this?
1108fe6060f1SDimitry Andric       Register Reg = MTracker->LocIdxToLocID[L];
1109fe6060f1SDimitry Andric       const TargetRegisterClass *TRC = nullptr;
1110fe6060f1SDimitry Andric       for (auto *TRCI : TRI->regclasses())
1111fe6060f1SDimitry Andric         if (TRCI->contains(Reg))
1112fe6060f1SDimitry Andric           TRC = TRCI;
1113fe6060f1SDimitry Andric       assert(TRC && "Couldn't find target register class?");
1114fe6060f1SDimitry Andric 
1115fe6060f1SDimitry Andric       // If the register we have isn't the right size or in the right place,
1116fe6060f1SDimitry Andric       // Try to find a subregister inside it.
1117fe6060f1SDimitry Andric       unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1118fe6060f1SDimitry Andric       if (Size != MainRegSize || Offset) {
1119fe6060f1SDimitry Andric         // Enumerate all subregisters, searching.
1120fe6060f1SDimitry Andric         Register NewReg = 0;
1121fe6060f1SDimitry Andric         for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1122fe6060f1SDimitry Andric           unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1123fe6060f1SDimitry Andric           unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1124fe6060f1SDimitry Andric           unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1125fe6060f1SDimitry Andric           if (SubregSize == Size && SubregOffset == Offset) {
1126fe6060f1SDimitry Andric             NewReg = *SRI;
1127fe6060f1SDimitry Andric             break;
1128fe6060f1SDimitry Andric           }
1129fe6060f1SDimitry Andric         }
1130fe6060f1SDimitry Andric 
1131fe6060f1SDimitry Andric         // If we didn't find anything: there's no way to express our value.
1132fe6060f1SDimitry Andric         if (!NewReg) {
1133fe6060f1SDimitry Andric           NewID = None;
1134fe6060f1SDimitry Andric         } else {
1135fe6060f1SDimitry Andric           // Re-state the value as being defined within the subregister
1136fe6060f1SDimitry Andric           // that we found.
1137fe6060f1SDimitry Andric           LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1138fe6060f1SDimitry Andric           NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1139fe6060f1SDimitry Andric         }
1140fe6060f1SDimitry Andric       }
1141fe6060f1SDimitry Andric     } else {
1142fe6060f1SDimitry Andric       // If we can't handle subregisters, unset the new value.
1143fe6060f1SDimitry Andric       NewID = None;
1144fe6060f1SDimitry Andric     }
1145e8d8bef9SDimitry Andric   }
1146e8d8bef9SDimitry Andric 
1147e8d8bef9SDimitry Andric   // We, we have a value number or None. Tell the variable value tracker about
1148e8d8bef9SDimitry Andric   // it. The rest of this LiveDebugValues implementation acts exactly the same
1149e8d8bef9SDimitry Andric   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1150e8d8bef9SDimitry Andric   // aren't immediately available).
1151e8d8bef9SDimitry Andric   DbgValueProperties Properties(Expr, false);
1152e8d8bef9SDimitry Andric   VTracker->defVar(MI, Properties, NewID);
1153e8d8bef9SDimitry Andric 
1154e8d8bef9SDimitry Andric   // If we're on the final pass through the function, decompose this INSTR_REF
1155e8d8bef9SDimitry Andric   // into a plain DBG_VALUE.
1156e8d8bef9SDimitry Andric   if (!TTracker)
1157e8d8bef9SDimitry Andric     return true;
1158e8d8bef9SDimitry Andric 
1159e8d8bef9SDimitry Andric   // Pick a location for the machine value number, if such a location exists.
1160e8d8bef9SDimitry Andric   // (This information could be stored in TransferTracker to make it faster).
1161e8d8bef9SDimitry Andric   Optional<LocIdx> FoundLoc = None;
1162e8d8bef9SDimitry Andric   for (auto Location : MTracker->locations()) {
1163e8d8bef9SDimitry Andric     LocIdx CurL = Location.Idx;
1164349cc55cSDimitry Andric     ValueIDNum ID = MTracker->readMLoc(CurL);
1165e8d8bef9SDimitry Andric     if (NewID && ID == NewID) {
1166e8d8bef9SDimitry Andric       // If this is the first location with that value, pick it. Otherwise,
1167e8d8bef9SDimitry Andric       // consider whether it's a "longer term" location.
1168e8d8bef9SDimitry Andric       if (!FoundLoc) {
1169e8d8bef9SDimitry Andric         FoundLoc = CurL;
1170e8d8bef9SDimitry Andric         continue;
1171e8d8bef9SDimitry Andric       }
1172e8d8bef9SDimitry Andric 
1173e8d8bef9SDimitry Andric       if (MTracker->isSpill(CurL))
1174e8d8bef9SDimitry Andric         FoundLoc = CurL; // Spills are a longer term location.
1175e8d8bef9SDimitry Andric       else if (!MTracker->isSpill(*FoundLoc) &&
1176e8d8bef9SDimitry Andric                !MTracker->isSpill(CurL) &&
1177e8d8bef9SDimitry Andric                !isCalleeSaved(*FoundLoc) &&
1178e8d8bef9SDimitry Andric                isCalleeSaved(CurL))
1179e8d8bef9SDimitry Andric         FoundLoc = CurL; // Callee saved regs are longer term than normal.
1180e8d8bef9SDimitry Andric     }
1181e8d8bef9SDimitry Andric   }
1182e8d8bef9SDimitry Andric 
1183e8d8bef9SDimitry Andric   // Tell transfer tracker that the variable value has changed.
1184e8d8bef9SDimitry Andric   TTracker->redefVar(MI, Properties, FoundLoc);
1185e8d8bef9SDimitry Andric 
1186e8d8bef9SDimitry Andric   // If there was a value with no location; but the value is defined in a
1187e8d8bef9SDimitry Andric   // later instruction in this block, this is a block-local use-before-def.
1188e8d8bef9SDimitry Andric   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1189e8d8bef9SDimitry Andric       NewID->getInst() > CurInst)
1190e8d8bef9SDimitry Andric     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1191e8d8bef9SDimitry Andric 
1192e8d8bef9SDimitry Andric   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1193e8d8bef9SDimitry Andric   // This DBG_VALUE is potentially a $noreg / undefined location, if
1194e8d8bef9SDimitry Andric   // FoundLoc is None.
1195e8d8bef9SDimitry Andric   // (XXX -- could morph the DBG_INSTR_REF in the future).
1196e8d8bef9SDimitry Andric   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1197e8d8bef9SDimitry Andric   TTracker->PendingDbgValues.push_back(DbgMI);
1198e8d8bef9SDimitry Andric   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1199fe6060f1SDimitry Andric   return true;
1200fe6060f1SDimitry Andric }
1201fe6060f1SDimitry Andric 
1202fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1203fe6060f1SDimitry Andric   if (!MI.isDebugPHI())
1204fe6060f1SDimitry Andric     return false;
1205fe6060f1SDimitry Andric 
1206fe6060f1SDimitry Andric   // Analyse these only when solving the machine value location problem.
1207fe6060f1SDimitry Andric   if (VTracker || TTracker)
1208fe6060f1SDimitry Andric     return true;
1209fe6060f1SDimitry Andric 
1210fe6060f1SDimitry Andric   // First operand is the value location, either a stack slot or register.
1211fe6060f1SDimitry Andric   // Second is the debug instruction number of the original PHI.
1212fe6060f1SDimitry Andric   const MachineOperand &MO = MI.getOperand(0);
1213fe6060f1SDimitry Andric   unsigned InstrNum = MI.getOperand(1).getImm();
1214fe6060f1SDimitry Andric 
1215fe6060f1SDimitry Andric   if (MO.isReg()) {
1216fe6060f1SDimitry Andric     // The value is whatever's currently in the register. Read and record it,
1217fe6060f1SDimitry Andric     // to be analysed later.
1218fe6060f1SDimitry Andric     Register Reg = MO.getReg();
1219fe6060f1SDimitry Andric     ValueIDNum Num = MTracker->readReg(Reg);
1220fe6060f1SDimitry Andric     auto PHIRec = DebugPHIRecord(
1221fe6060f1SDimitry Andric         {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1222fe6060f1SDimitry Andric     DebugPHINumToValue.push_back(PHIRec);
1223349cc55cSDimitry Andric 
1224349cc55cSDimitry Andric     // Ensure this register is tracked.
1225349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1226349cc55cSDimitry Andric       MTracker->lookupOrTrackRegister(*RAI);
1227fe6060f1SDimitry Andric   } else {
1228fe6060f1SDimitry Andric     // The value is whatever's in this stack slot.
1229fe6060f1SDimitry Andric     assert(MO.isFI());
1230fe6060f1SDimitry Andric     unsigned FI = MO.getIndex();
1231fe6060f1SDimitry Andric 
1232fe6060f1SDimitry Andric     // If the stack slot is dead, then this was optimized away.
1233fe6060f1SDimitry Andric     // FIXME: stack slot colouring should account for slots that get merged.
1234fe6060f1SDimitry Andric     if (MFI->isDeadObjectIndex(FI))
1235fe6060f1SDimitry Andric       return true;
1236fe6060f1SDimitry Andric 
1237349cc55cSDimitry Andric     // Identify this spill slot, ensure it's tracked.
1238fe6060f1SDimitry Andric     Register Base;
1239fe6060f1SDimitry Andric     StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1240fe6060f1SDimitry Andric     SpillLoc SL = {Base, Offs};
1241349cc55cSDimitry Andric     SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(SL);
1242fe6060f1SDimitry Andric 
1243349cc55cSDimitry Andric     // Problem: what value should we extract from the stack? LLVM does not
1244349cc55cSDimitry Andric     // record what size the last store to the slot was, and it would become
1245349cc55cSDimitry Andric     // sketchy after stack slot colouring anyway. Take a look at what values
1246349cc55cSDimitry Andric     // are stored on the stack, and pick the largest one that wasn't def'd
1247349cc55cSDimitry Andric     // by a spill (i.e., the value most likely to have been def'd in a register
1248349cc55cSDimitry Andric     // and then spilt.
1249349cc55cSDimitry Andric     std::array<unsigned, 4> CandidateSizes = {64, 32, 16, 8};
1250349cc55cSDimitry Andric     Optional<ValueIDNum> Result = None;
1251349cc55cSDimitry Andric     Optional<LocIdx> SpillLoc = None;
1252349cc55cSDimitry Andric     for (unsigned int I = 0; I < CandidateSizes.size(); ++I) {
1253349cc55cSDimitry Andric       unsigned SpillID = MTracker->getLocID(SpillNo, {CandidateSizes[I], 0});
1254349cc55cSDimitry Andric       SpillLoc = MTracker->getSpillMLoc(SpillID);
1255349cc55cSDimitry Andric       ValueIDNum Val = MTracker->readMLoc(*SpillLoc);
1256349cc55cSDimitry Andric       // If this value was defined in it's own position, then it was probably
1257349cc55cSDimitry Andric       // an aliasing index of a small value that was spilt.
1258349cc55cSDimitry Andric       if (Val.getLoc() != SpillLoc->asU64()) {
1259349cc55cSDimitry Andric         Result = Val;
1260349cc55cSDimitry Andric         break;
1261349cc55cSDimitry Andric       }
1262349cc55cSDimitry Andric     }
1263349cc55cSDimitry Andric 
1264349cc55cSDimitry Andric     // If we didn't find anything, we're probably looking at a PHI, or a memory
1265349cc55cSDimitry Andric     // store folded into an instruction. FIXME: Take a guess that's it's 64
1266349cc55cSDimitry Andric     // bits. This isn't ideal, but tracking the size that the spill is
1267349cc55cSDimitry Andric     // "supposed" to be is more complex, and benefits a small number of
1268349cc55cSDimitry Andric     // locations.
1269349cc55cSDimitry Andric     if (!Result) {
1270349cc55cSDimitry Andric       unsigned SpillID = MTracker->getLocID(SpillNo, {64, 0});
1271349cc55cSDimitry Andric       SpillLoc = MTracker->getSpillMLoc(SpillID);
1272349cc55cSDimitry Andric       Result = MTracker->readMLoc(*SpillLoc);
1273349cc55cSDimitry Andric     }
1274fe6060f1SDimitry Andric 
1275fe6060f1SDimitry Andric     // Record this DBG_PHI for later analysis.
1276349cc55cSDimitry Andric     auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), *Result, *SpillLoc});
1277fe6060f1SDimitry Andric     DebugPHINumToValue.push_back(DbgPHI);
1278fe6060f1SDimitry Andric   }
1279e8d8bef9SDimitry Andric 
1280e8d8bef9SDimitry Andric   return true;
1281e8d8bef9SDimitry Andric }
1282e8d8bef9SDimitry Andric 
1283e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1284e8d8bef9SDimitry Andric   // Meta Instructions do not affect the debug liveness of any register they
1285e8d8bef9SDimitry Andric   // define.
1286e8d8bef9SDimitry Andric   if (MI.isImplicitDef()) {
1287e8d8bef9SDimitry Andric     // Except when there's an implicit def, and the location it's defining has
1288e8d8bef9SDimitry Andric     // no value number. The whole point of an implicit def is to announce that
1289e8d8bef9SDimitry Andric     // the register is live, without be specific about it's value. So define
1290e8d8bef9SDimitry Andric     // a value if there isn't one already.
1291e8d8bef9SDimitry Andric     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1292e8d8bef9SDimitry Andric     // Has a legitimate value -> ignore the implicit def.
1293e8d8bef9SDimitry Andric     if (Num.getLoc() != 0)
1294e8d8bef9SDimitry Andric       return;
1295e8d8bef9SDimitry Andric     // Otherwise, def it here.
1296e8d8bef9SDimitry Andric   } else if (MI.isMetaInstruction())
1297e8d8bef9SDimitry Andric     return;
1298e8d8bef9SDimitry Andric 
1299*4824e7fdSDimitry Andric   // We always ignore SP defines on call instructions, they don't actually
1300*4824e7fdSDimitry Andric   // change the value of the stack pointer... except for win32's _chkstk. This
1301*4824e7fdSDimitry Andric   // is rare: filter quickly for the common case (no stack adjustments, not a
1302*4824e7fdSDimitry Andric   // call, etc). If it is a call that modifies SP, recognise the SP register
1303*4824e7fdSDimitry Andric   // defs.
1304*4824e7fdSDimitry Andric   bool CallChangesSP = false;
1305*4824e7fdSDimitry Andric   if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
1306*4824e7fdSDimitry Andric       !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
1307*4824e7fdSDimitry Andric     CallChangesSP = true;
1308*4824e7fdSDimitry Andric 
1309*4824e7fdSDimitry Andric   // Test whether we should ignore a def of this register due to it being part
1310*4824e7fdSDimitry Andric   // of the stack pointer.
1311*4824e7fdSDimitry Andric   auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
1312*4824e7fdSDimitry Andric     if (CallChangesSP)
1313*4824e7fdSDimitry Andric       return false;
1314*4824e7fdSDimitry Andric     return MI.isCall() && MTracker->SPAliases.count(R);
1315*4824e7fdSDimitry Andric   };
1316*4824e7fdSDimitry Andric 
1317e8d8bef9SDimitry Andric   // Find the regs killed by MI, and find regmasks of preserved regs.
1318e8d8bef9SDimitry Andric   // Max out the number of statically allocated elements in `DeadRegs`, as this
1319e8d8bef9SDimitry Andric   // prevents fallback to std::set::count() operations.
1320e8d8bef9SDimitry Andric   SmallSet<uint32_t, 32> DeadRegs;
1321e8d8bef9SDimitry Andric   SmallVector<const uint32_t *, 4> RegMasks;
1322e8d8bef9SDimitry Andric   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1323e8d8bef9SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1324e8d8bef9SDimitry Andric     // Determine whether the operand is a register def.
1325e8d8bef9SDimitry Andric     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1326e8d8bef9SDimitry Andric         Register::isPhysicalRegister(MO.getReg()) &&
1327*4824e7fdSDimitry Andric         !IgnoreSPAlias(MO.getReg())) {
1328e8d8bef9SDimitry Andric       // Remove ranges of all aliased registers.
1329e8d8bef9SDimitry Andric       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1330e8d8bef9SDimitry Andric         // FIXME: Can we break out of this loop early if no insertion occurs?
1331e8d8bef9SDimitry Andric         DeadRegs.insert(*RAI);
1332e8d8bef9SDimitry Andric     } else if (MO.isRegMask()) {
1333e8d8bef9SDimitry Andric       RegMasks.push_back(MO.getRegMask());
1334e8d8bef9SDimitry Andric       RegMaskPtrs.push_back(&MO);
1335e8d8bef9SDimitry Andric     }
1336e8d8bef9SDimitry Andric   }
1337e8d8bef9SDimitry Andric 
1338e8d8bef9SDimitry Andric   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1339e8d8bef9SDimitry Andric   for (uint32_t DeadReg : DeadRegs)
1340e8d8bef9SDimitry Andric     MTracker->defReg(DeadReg, CurBB, CurInst);
1341e8d8bef9SDimitry Andric 
1342e8d8bef9SDimitry Andric   for (auto *MO : RegMaskPtrs)
1343e8d8bef9SDimitry Andric     MTracker->writeRegMask(MO, CurBB, CurInst);
1344fe6060f1SDimitry Andric 
1345349cc55cSDimitry Andric   // If this instruction writes to a spill slot, def that slot.
1346349cc55cSDimitry Andric   if (hasFoldedStackStore(MI)) {
1347349cc55cSDimitry Andric     SpillLocationNo SpillNo = extractSpillBaseRegAndOffset(MI);
1348349cc55cSDimitry Andric     for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1349349cc55cSDimitry Andric       unsigned SpillID = MTracker->getSpillIDWithIdx(SpillNo, I);
1350349cc55cSDimitry Andric       LocIdx L = MTracker->getSpillMLoc(SpillID);
1351349cc55cSDimitry Andric       MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1352349cc55cSDimitry Andric     }
1353349cc55cSDimitry Andric   }
1354349cc55cSDimitry Andric 
1355fe6060f1SDimitry Andric   if (!TTracker)
1356fe6060f1SDimitry Andric     return;
1357fe6060f1SDimitry Andric 
1358fe6060f1SDimitry Andric   // When committing variable values to locations: tell transfer tracker that
1359fe6060f1SDimitry Andric   // we've clobbered things. It may be able to recover the variable from a
1360fe6060f1SDimitry Andric   // different location.
1361fe6060f1SDimitry Andric 
1362fe6060f1SDimitry Andric   // Inform TTracker about any direct clobbers.
1363fe6060f1SDimitry Andric   for (uint32_t DeadReg : DeadRegs) {
1364fe6060f1SDimitry Andric     LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
1365fe6060f1SDimitry Andric     TTracker->clobberMloc(Loc, MI.getIterator(), false);
1366fe6060f1SDimitry Andric   }
1367fe6060f1SDimitry Andric 
1368fe6060f1SDimitry Andric   // Look for any clobbers performed by a register mask. Only test locations
1369fe6060f1SDimitry Andric   // that are actually being tracked.
1370fe6060f1SDimitry Andric   for (auto L : MTracker->locations()) {
1371fe6060f1SDimitry Andric     // Stack locations can't be clobbered by regmasks.
1372fe6060f1SDimitry Andric     if (MTracker->isSpill(L.Idx))
1373fe6060f1SDimitry Andric       continue;
1374fe6060f1SDimitry Andric 
1375fe6060f1SDimitry Andric     Register Reg = MTracker->LocIdxToLocID[L.Idx];
1376*4824e7fdSDimitry Andric     if (IgnoreSPAlias(Reg))
1377*4824e7fdSDimitry Andric       continue;
1378*4824e7fdSDimitry Andric 
1379fe6060f1SDimitry Andric     for (auto *MO : RegMaskPtrs)
1380fe6060f1SDimitry Andric       if (MO->clobbersPhysReg(Reg))
1381fe6060f1SDimitry Andric         TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
1382fe6060f1SDimitry Andric   }
1383349cc55cSDimitry Andric 
1384349cc55cSDimitry Andric   // Tell TTracker about any folded stack store.
1385349cc55cSDimitry Andric   if (hasFoldedStackStore(MI)) {
1386349cc55cSDimitry Andric     SpillLocationNo SpillNo = extractSpillBaseRegAndOffset(MI);
1387349cc55cSDimitry Andric     for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1388349cc55cSDimitry Andric       unsigned SpillID = MTracker->getSpillIDWithIdx(SpillNo, I);
1389349cc55cSDimitry Andric       LocIdx L = MTracker->getSpillMLoc(SpillID);
1390349cc55cSDimitry Andric       TTracker->clobberMloc(L, MI.getIterator(), true);
1391349cc55cSDimitry Andric     }
1392349cc55cSDimitry Andric   }
1393e8d8bef9SDimitry Andric }
1394e8d8bef9SDimitry Andric 
1395e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1396349cc55cSDimitry Andric   // In all circumstances, re-def all aliases. It's definitely a new value now.
1397349cc55cSDimitry Andric   for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1398349cc55cSDimitry Andric     MTracker->defReg(*RAI, CurBB, CurInst);
1399e8d8bef9SDimitry Andric 
1400349cc55cSDimitry Andric   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1401e8d8bef9SDimitry Andric   MTracker->setReg(DstRegNum, SrcValue);
1402e8d8bef9SDimitry Andric 
1403349cc55cSDimitry Andric   // Copy subregisters from one location to another.
1404e8d8bef9SDimitry Andric   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1405e8d8bef9SDimitry Andric     unsigned SrcSubReg = SRI.getSubReg();
1406e8d8bef9SDimitry Andric     unsigned SubRegIdx = SRI.getSubRegIndex();
1407e8d8bef9SDimitry Andric     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1408e8d8bef9SDimitry Andric     if (!DstSubReg)
1409e8d8bef9SDimitry Andric       continue;
1410e8d8bef9SDimitry Andric 
1411e8d8bef9SDimitry Andric     // Do copy. There are two matching subregisters, the source value should
1412e8d8bef9SDimitry Andric     // have been def'd when the super-reg was, the latter might not be tracked
1413e8d8bef9SDimitry Andric     // yet.
1414349cc55cSDimitry Andric     // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1415349cc55cSDimitry Andric     // mphi values if it wasn't tracked.
1416349cc55cSDimitry Andric     LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1417349cc55cSDimitry Andric     LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1418349cc55cSDimitry Andric     (void)SrcL;
1419e8d8bef9SDimitry Andric     (void)DstL;
1420349cc55cSDimitry Andric     ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1421e8d8bef9SDimitry Andric 
1422e8d8bef9SDimitry Andric     MTracker->setReg(DstSubReg, CpyValue);
1423e8d8bef9SDimitry Andric   }
1424e8d8bef9SDimitry Andric }
1425e8d8bef9SDimitry Andric 
1426e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1427e8d8bef9SDimitry Andric                                           MachineFunction *MF) {
1428e8d8bef9SDimitry Andric   // TODO: Handle multiple stores folded into one.
1429e8d8bef9SDimitry Andric   if (!MI.hasOneMemOperand())
1430e8d8bef9SDimitry Andric     return false;
1431e8d8bef9SDimitry Andric 
1432349cc55cSDimitry Andric   // Reject any memory operand that's aliased -- we can't guarantee its value.
1433349cc55cSDimitry Andric   auto MMOI = MI.memoperands_begin();
1434349cc55cSDimitry Andric   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1435349cc55cSDimitry Andric   if (PVal->isAliased(MFI))
1436349cc55cSDimitry Andric     return false;
1437349cc55cSDimitry Andric 
1438e8d8bef9SDimitry Andric   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1439e8d8bef9SDimitry Andric     return false; // This is not a spill instruction, since no valid size was
1440e8d8bef9SDimitry Andric                   // returned from either function.
1441e8d8bef9SDimitry Andric 
1442e8d8bef9SDimitry Andric   return true;
1443e8d8bef9SDimitry Andric }
1444e8d8bef9SDimitry Andric 
1445e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1446e8d8bef9SDimitry Andric                                        MachineFunction *MF, unsigned &Reg) {
1447e8d8bef9SDimitry Andric   if (!isSpillInstruction(MI, MF))
1448e8d8bef9SDimitry Andric     return false;
1449e8d8bef9SDimitry Andric 
1450e8d8bef9SDimitry Andric   int FI;
1451e8d8bef9SDimitry Andric   Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1452e8d8bef9SDimitry Andric   return Reg != 0;
1453e8d8bef9SDimitry Andric }
1454e8d8bef9SDimitry Andric 
1455349cc55cSDimitry Andric Optional<SpillLocationNo>
1456e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1457e8d8bef9SDimitry Andric                                        MachineFunction *MF, unsigned &Reg) {
1458e8d8bef9SDimitry Andric   if (!MI.hasOneMemOperand())
1459e8d8bef9SDimitry Andric     return None;
1460e8d8bef9SDimitry Andric 
1461e8d8bef9SDimitry Andric   // FIXME: Handle folded restore instructions with more than one memory
1462e8d8bef9SDimitry Andric   // operand.
1463e8d8bef9SDimitry Andric   if (MI.getRestoreSize(TII)) {
1464e8d8bef9SDimitry Andric     Reg = MI.getOperand(0).getReg();
1465e8d8bef9SDimitry Andric     return extractSpillBaseRegAndOffset(MI);
1466e8d8bef9SDimitry Andric   }
1467e8d8bef9SDimitry Andric   return None;
1468e8d8bef9SDimitry Andric }
1469e8d8bef9SDimitry Andric 
1470e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1471e8d8bef9SDimitry Andric   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1472e8d8bef9SDimitry Andric   // limitations under the new model. Therefore, when comparing them, compare
1473e8d8bef9SDimitry Andric   // versions that don't attempt spills or restores at all.
1474e8d8bef9SDimitry Andric   if (EmulateOldLDV)
1475e8d8bef9SDimitry Andric     return false;
1476e8d8bef9SDimitry Andric 
1477349cc55cSDimitry Andric   // Strictly limit ourselves to plain loads and stores, not all instructions
1478349cc55cSDimitry Andric   // that can access the stack.
1479349cc55cSDimitry Andric   int DummyFI = -1;
1480349cc55cSDimitry Andric   if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
1481349cc55cSDimitry Andric       !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
1482349cc55cSDimitry Andric     return false;
1483349cc55cSDimitry Andric 
1484e8d8bef9SDimitry Andric   MachineFunction *MF = MI.getMF();
1485e8d8bef9SDimitry Andric   unsigned Reg;
1486e8d8bef9SDimitry Andric 
1487e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1488e8d8bef9SDimitry Andric 
1489349cc55cSDimitry Andric   // Strictly limit ourselves to plain loads and stores, not all instructions
1490349cc55cSDimitry Andric   // that can access the stack.
1491349cc55cSDimitry Andric   int FIDummy;
1492349cc55cSDimitry Andric   if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
1493349cc55cSDimitry Andric       !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
1494349cc55cSDimitry Andric     return false;
1495349cc55cSDimitry Andric 
1496e8d8bef9SDimitry Andric   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1497e8d8bef9SDimitry Andric   // written to, terminate that variable location. The value in memory
1498e8d8bef9SDimitry Andric   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
1499e8d8bef9SDimitry Andric   if (isSpillInstruction(MI, MF)) {
1500349cc55cSDimitry Andric     SpillLocationNo Loc = extractSpillBaseRegAndOffset(MI);
1501e8d8bef9SDimitry Andric 
1502349cc55cSDimitry Andric     // Un-set this location and clobber, so that earlier locations don't
1503349cc55cSDimitry Andric     // continue past this store.
1504349cc55cSDimitry Andric     for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
1505349cc55cSDimitry Andric       unsigned SpillID = MTracker->getSpillIDWithIdx(Loc, SlotIdx);
1506349cc55cSDimitry Andric       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
1507349cc55cSDimitry Andric       if (!MLoc)
1508349cc55cSDimitry Andric         continue;
1509349cc55cSDimitry Andric 
1510349cc55cSDimitry Andric       // We need to over-write the stack slot with something (here, a def at
1511349cc55cSDimitry Andric       // this instruction) to ensure no values are preserved in this stack slot
1512349cc55cSDimitry Andric       // after the spill. It also prevents TTracker from trying to recover the
1513349cc55cSDimitry Andric       // location and re-installing it in the same place.
1514349cc55cSDimitry Andric       ValueIDNum Def(CurBB, CurInst, *MLoc);
1515349cc55cSDimitry Andric       MTracker->setMLoc(*MLoc, Def);
1516349cc55cSDimitry Andric       if (TTracker)
1517e8d8bef9SDimitry Andric         TTracker->clobberMloc(*MLoc, MI.getIterator());
1518e8d8bef9SDimitry Andric     }
1519e8d8bef9SDimitry Andric   }
1520e8d8bef9SDimitry Andric 
1521e8d8bef9SDimitry Andric   // Try to recognise spill and restore instructions that may transfer a value.
1522e8d8bef9SDimitry Andric   if (isLocationSpill(MI, MF, Reg)) {
1523349cc55cSDimitry Andric     SpillLocationNo Loc = extractSpillBaseRegAndOffset(MI);
1524e8d8bef9SDimitry Andric 
1525349cc55cSDimitry Andric     auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
1526349cc55cSDimitry Andric       auto ReadValue = MTracker->readReg(SrcReg);
1527349cc55cSDimitry Andric       LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
1528349cc55cSDimitry Andric       MTracker->setMLoc(DstLoc, ReadValue);
1529e8d8bef9SDimitry Andric 
1530349cc55cSDimitry Andric       if (TTracker) {
1531349cc55cSDimitry Andric         LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
1532349cc55cSDimitry Andric         TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
1533e8d8bef9SDimitry Andric       }
1534349cc55cSDimitry Andric     };
1535349cc55cSDimitry Andric 
1536349cc55cSDimitry Andric     // Then, transfer subreg bits.
1537349cc55cSDimitry Andric     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1538349cc55cSDimitry Andric       // Ensure this reg is tracked,
1539349cc55cSDimitry Andric       (void)MTracker->lookupOrTrackRegister(*SRI);
1540349cc55cSDimitry Andric       unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI);
1541349cc55cSDimitry Andric       unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
1542349cc55cSDimitry Andric       DoTransfer(*SRI, SpillID);
1543349cc55cSDimitry Andric     }
1544349cc55cSDimitry Andric 
1545349cc55cSDimitry Andric     // Directly lookup size of main source reg, and transfer.
1546349cc55cSDimitry Andric     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1547349cc55cSDimitry Andric     unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
1548349cc55cSDimitry Andric     DoTransfer(Reg, SpillID);
1549349cc55cSDimitry Andric   } else {
1550349cc55cSDimitry Andric     Optional<SpillLocationNo> OptLoc = isRestoreInstruction(MI, MF, Reg);
1551349cc55cSDimitry Andric     if (!OptLoc)
1552349cc55cSDimitry Andric       return false;
1553349cc55cSDimitry Andric     SpillLocationNo Loc = *OptLoc;
1554349cc55cSDimitry Andric 
1555349cc55cSDimitry Andric     // Assumption: we're reading from the base of the stack slot, not some
1556349cc55cSDimitry Andric     // offset into it. It seems very unlikely LLVM would ever generate
1557349cc55cSDimitry Andric     // restores where this wasn't true. This then becomes a question of what
1558349cc55cSDimitry Andric     // subregisters in the destination register line up with positions in the
1559349cc55cSDimitry Andric     // stack slot.
1560349cc55cSDimitry Andric 
1561349cc55cSDimitry Andric     // Def all registers that alias the destination.
1562349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1563349cc55cSDimitry Andric       MTracker->defReg(*RAI, CurBB, CurInst);
1564349cc55cSDimitry Andric 
1565349cc55cSDimitry Andric     // Now find subregisters within the destination register, and load values
1566349cc55cSDimitry Andric     // from stack slot positions.
1567349cc55cSDimitry Andric     auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
1568349cc55cSDimitry Andric       LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
1569349cc55cSDimitry Andric       auto ReadValue = MTracker->readMLoc(SrcIdx);
1570349cc55cSDimitry Andric       MTracker->setReg(DestReg, ReadValue);
1571349cc55cSDimitry Andric 
1572349cc55cSDimitry Andric       if (TTracker) {
1573349cc55cSDimitry Andric         LocIdx DstLoc = MTracker->getRegMLoc(DestReg);
1574349cc55cSDimitry Andric         TTracker->transferMlocs(SrcIdx, DstLoc, MI.getIterator());
1575349cc55cSDimitry Andric       }
1576349cc55cSDimitry Andric     };
1577349cc55cSDimitry Andric 
1578349cc55cSDimitry Andric     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1579349cc55cSDimitry Andric       unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1580349cc55cSDimitry Andric       unsigned SpillID = MTracker->getLocID(Loc, Subreg);
1581349cc55cSDimitry Andric       DoTransfer(*SRI, SpillID);
1582349cc55cSDimitry Andric     }
1583349cc55cSDimitry Andric 
1584349cc55cSDimitry Andric     // Directly look up this registers slot idx by size, and transfer.
1585349cc55cSDimitry Andric     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1586349cc55cSDimitry Andric     unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
1587349cc55cSDimitry Andric     DoTransfer(Reg, SpillID);
1588e8d8bef9SDimitry Andric   }
1589e8d8bef9SDimitry Andric   return true;
1590e8d8bef9SDimitry Andric }
1591e8d8bef9SDimitry Andric 
1592e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
1593e8d8bef9SDimitry Andric   auto DestSrc = TII->isCopyInstr(MI);
1594e8d8bef9SDimitry Andric   if (!DestSrc)
1595e8d8bef9SDimitry Andric     return false;
1596e8d8bef9SDimitry Andric 
1597e8d8bef9SDimitry Andric   const MachineOperand *DestRegOp = DestSrc->Destination;
1598e8d8bef9SDimitry Andric   const MachineOperand *SrcRegOp = DestSrc->Source;
1599e8d8bef9SDimitry Andric 
1600e8d8bef9SDimitry Andric   auto isCalleeSavedReg = [&](unsigned Reg) {
1601e8d8bef9SDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1602e8d8bef9SDimitry Andric       if (CalleeSavedRegs.test(*RAI))
1603e8d8bef9SDimitry Andric         return true;
1604e8d8bef9SDimitry Andric     return false;
1605e8d8bef9SDimitry Andric   };
1606e8d8bef9SDimitry Andric 
1607e8d8bef9SDimitry Andric   Register SrcReg = SrcRegOp->getReg();
1608e8d8bef9SDimitry Andric   Register DestReg = DestRegOp->getReg();
1609e8d8bef9SDimitry Andric 
1610e8d8bef9SDimitry Andric   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
1611e8d8bef9SDimitry Andric   if (SrcReg == DestReg)
1612e8d8bef9SDimitry Andric     return true;
1613e8d8bef9SDimitry Andric 
1614e8d8bef9SDimitry Andric   // For emulating VarLocBasedImpl:
1615e8d8bef9SDimitry Andric   // We want to recognize instructions where destination register is callee
1616e8d8bef9SDimitry Andric   // saved register. If register that could be clobbered by the call is
1617e8d8bef9SDimitry Andric   // included, there would be a great chance that it is going to be clobbered
1618e8d8bef9SDimitry Andric   // soon. It is more likely that previous register, which is callee saved, is
1619e8d8bef9SDimitry Andric   // going to stay unclobbered longer, even if it is killed.
1620e8d8bef9SDimitry Andric   //
1621e8d8bef9SDimitry Andric   // For InstrRefBasedImpl, we can track multiple locations per value, so
1622e8d8bef9SDimitry Andric   // ignore this condition.
1623e8d8bef9SDimitry Andric   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
1624e8d8bef9SDimitry Andric     return false;
1625e8d8bef9SDimitry Andric 
1626e8d8bef9SDimitry Andric   // InstrRefBasedImpl only followed killing copies.
1627e8d8bef9SDimitry Andric   if (EmulateOldLDV && !SrcRegOp->isKill())
1628e8d8bef9SDimitry Andric     return false;
1629e8d8bef9SDimitry Andric 
1630e8d8bef9SDimitry Andric   // Copy MTracker info, including subregs if available.
1631e8d8bef9SDimitry Andric   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
1632e8d8bef9SDimitry Andric 
1633e8d8bef9SDimitry Andric   // Only produce a transfer of DBG_VALUE within a block where old LDV
1634e8d8bef9SDimitry Andric   // would have. We might make use of the additional value tracking in some
1635e8d8bef9SDimitry Andric   // other way, later.
1636e8d8bef9SDimitry Andric   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
1637e8d8bef9SDimitry Andric     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
1638e8d8bef9SDimitry Andric                             MTracker->getRegMLoc(DestReg), MI.getIterator());
1639e8d8bef9SDimitry Andric 
1640e8d8bef9SDimitry Andric   // VarLocBasedImpl would quit tracking the old location after copying.
1641e8d8bef9SDimitry Andric   if (EmulateOldLDV && SrcReg != DestReg)
1642e8d8bef9SDimitry Andric     MTracker->defReg(SrcReg, CurBB, CurInst);
1643e8d8bef9SDimitry Andric 
1644fe6060f1SDimitry Andric   // Finally, the copy might have clobbered variables based on the destination
1645fe6060f1SDimitry Andric   // register. Tell TTracker about it, in case a backup location exists.
1646fe6060f1SDimitry Andric   if (TTracker) {
1647fe6060f1SDimitry Andric     for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
1648fe6060f1SDimitry Andric       LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
1649fe6060f1SDimitry Andric       TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false);
1650fe6060f1SDimitry Andric     }
1651fe6060f1SDimitry Andric   }
1652fe6060f1SDimitry Andric 
1653e8d8bef9SDimitry Andric   return true;
1654e8d8bef9SDimitry Andric }
1655e8d8bef9SDimitry Andric 
1656e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
1657e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
1658e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1659e8d8bef9SDimitry Andric /// known-to-overlap fragments are present".
1660*4824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for
1661e8d8bef9SDimitry Andric ///           fragment usage.
1662e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
1663*4824e7fdSDimitry Andric   assert(MI.isDebugValue() || MI.isDebugRef());
1664e8d8bef9SDimitry Andric   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1665e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
1666e8d8bef9SDimitry Andric   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1667e8d8bef9SDimitry Andric 
1668e8d8bef9SDimitry Andric   // If this is the first sighting of this variable, then we are guaranteed
1669e8d8bef9SDimitry Andric   // there are currently no overlapping fragments either. Initialize the set
1670e8d8bef9SDimitry Andric   // of seen fragments, record no overlaps for the current one, and return.
1671e8d8bef9SDimitry Andric   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1672e8d8bef9SDimitry Andric   if (SeenIt == SeenFragments.end()) {
1673e8d8bef9SDimitry Andric     SmallSet<FragmentInfo, 4> OneFragment;
1674e8d8bef9SDimitry Andric     OneFragment.insert(ThisFragment);
1675e8d8bef9SDimitry Andric     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1676e8d8bef9SDimitry Andric 
1677e8d8bef9SDimitry Andric     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1678e8d8bef9SDimitry Andric     return;
1679e8d8bef9SDimitry Andric   }
1680e8d8bef9SDimitry Andric 
1681e8d8bef9SDimitry Andric   // If this particular Variable/Fragment pair already exists in the overlap
1682e8d8bef9SDimitry Andric   // map, it has already been accounted for.
1683e8d8bef9SDimitry Andric   auto IsInOLapMap =
1684e8d8bef9SDimitry Andric       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1685e8d8bef9SDimitry Andric   if (!IsInOLapMap.second)
1686e8d8bef9SDimitry Andric     return;
1687e8d8bef9SDimitry Andric 
1688e8d8bef9SDimitry Andric   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1689e8d8bef9SDimitry Andric   auto &AllSeenFragments = SeenIt->second;
1690e8d8bef9SDimitry Andric 
1691e8d8bef9SDimitry Andric   // Otherwise, examine all other seen fragments for this variable, with "this"
1692e8d8bef9SDimitry Andric   // fragment being a previously unseen fragment. Record any pair of
1693e8d8bef9SDimitry Andric   // overlapping fragments.
1694e8d8bef9SDimitry Andric   for (auto &ASeenFragment : AllSeenFragments) {
1695e8d8bef9SDimitry Andric     // Does this previously seen fragment overlap?
1696e8d8bef9SDimitry Andric     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1697e8d8bef9SDimitry Andric       // Yes: Mark the current fragment as being overlapped.
1698e8d8bef9SDimitry Andric       ThisFragmentsOverlaps.push_back(ASeenFragment);
1699e8d8bef9SDimitry Andric       // Mark the previously seen fragment as being overlapped by the current
1700e8d8bef9SDimitry Andric       // one.
1701e8d8bef9SDimitry Andric       auto ASeenFragmentsOverlaps =
1702e8d8bef9SDimitry Andric           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
1703e8d8bef9SDimitry Andric       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
1704e8d8bef9SDimitry Andric              "Previously seen var fragment has no vector of overlaps");
1705e8d8bef9SDimitry Andric       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1706e8d8bef9SDimitry Andric     }
1707e8d8bef9SDimitry Andric   }
1708e8d8bef9SDimitry Andric 
1709e8d8bef9SDimitry Andric   AllSeenFragments.insert(ThisFragment);
1710e8d8bef9SDimitry Andric }
1711e8d8bef9SDimitry Andric 
1712fe6060f1SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, ValueIDNum **MLiveOuts,
1713fe6060f1SDimitry Andric                                ValueIDNum **MLiveIns) {
1714e8d8bef9SDimitry Andric   // Try to interpret an MI as a debug or transfer instruction. Only if it's
1715e8d8bef9SDimitry Andric   // none of these should we interpret it's register defs as new value
1716e8d8bef9SDimitry Andric   // definitions.
1717e8d8bef9SDimitry Andric   if (transferDebugValue(MI))
1718e8d8bef9SDimitry Andric     return;
1719fe6060f1SDimitry Andric   if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
1720fe6060f1SDimitry Andric     return;
1721fe6060f1SDimitry Andric   if (transferDebugPHI(MI))
1722e8d8bef9SDimitry Andric     return;
1723e8d8bef9SDimitry Andric   if (transferRegisterCopy(MI))
1724e8d8bef9SDimitry Andric     return;
1725e8d8bef9SDimitry Andric   if (transferSpillOrRestoreInst(MI))
1726e8d8bef9SDimitry Andric     return;
1727e8d8bef9SDimitry Andric   transferRegisterDef(MI);
1728e8d8bef9SDimitry Andric }
1729e8d8bef9SDimitry Andric 
1730e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction(
1731e8d8bef9SDimitry Andric     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1732e8d8bef9SDimitry Andric     unsigned MaxNumBlocks) {
1733e8d8bef9SDimitry Andric   // Because we try to optimize around register mask operands by ignoring regs
1734e8d8bef9SDimitry Andric   // that aren't currently tracked, we set up something ugly for later: RegMask
1735e8d8bef9SDimitry Andric   // operands that are seen earlier than the first use of a register, still need
1736e8d8bef9SDimitry Andric   // to clobber that register in the transfer function. But this information
1737e8d8bef9SDimitry Andric   // isn't actively recorded. Instead, we track each RegMask used in each block,
1738e8d8bef9SDimitry Andric   // and accumulated the clobbered but untracked registers in each block into
1739e8d8bef9SDimitry Andric   // the following bitvector. Later, if new values are tracked, we can add
1740e8d8bef9SDimitry Andric   // appropriate clobbers.
1741e8d8bef9SDimitry Andric   SmallVector<BitVector, 32> BlockMasks;
1742e8d8bef9SDimitry Andric   BlockMasks.resize(MaxNumBlocks);
1743e8d8bef9SDimitry Andric 
1744e8d8bef9SDimitry Andric   // Reserve one bit per register for the masks described above.
1745e8d8bef9SDimitry Andric   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
1746e8d8bef9SDimitry Andric   for (auto &BV : BlockMasks)
1747e8d8bef9SDimitry Andric     BV.resize(TRI->getNumRegs(), true);
1748e8d8bef9SDimitry Andric 
1749e8d8bef9SDimitry Andric   // Step through all instructions and inhale the transfer function.
1750e8d8bef9SDimitry Andric   for (auto &MBB : MF) {
1751e8d8bef9SDimitry Andric     // Object fields that are read by trackers to know where we are in the
1752e8d8bef9SDimitry Andric     // function.
1753e8d8bef9SDimitry Andric     CurBB = MBB.getNumber();
1754e8d8bef9SDimitry Andric     CurInst = 1;
1755e8d8bef9SDimitry Andric 
1756e8d8bef9SDimitry Andric     // Set all machine locations to a PHI value. For transfer function
1757e8d8bef9SDimitry Andric     // production only, this signifies the live-in value to the block.
1758e8d8bef9SDimitry Andric     MTracker->reset();
1759e8d8bef9SDimitry Andric     MTracker->setMPhis(CurBB);
1760e8d8bef9SDimitry Andric 
1761e8d8bef9SDimitry Andric     // Step through each instruction in this block.
1762e8d8bef9SDimitry Andric     for (auto &MI : MBB) {
1763e8d8bef9SDimitry Andric       process(MI);
1764e8d8bef9SDimitry Andric       // Also accumulate fragment map.
1765*4824e7fdSDimitry Andric       if (MI.isDebugValue() || MI.isDebugRef())
1766e8d8bef9SDimitry Andric         accumulateFragmentMap(MI);
1767e8d8bef9SDimitry Andric 
1768e8d8bef9SDimitry Andric       // Create a map from the instruction number (if present) to the
1769e8d8bef9SDimitry Andric       // MachineInstr and its position.
1770e8d8bef9SDimitry Andric       if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
1771e8d8bef9SDimitry Andric         auto InstrAndPos = std::make_pair(&MI, CurInst);
1772e8d8bef9SDimitry Andric         auto InsertResult =
1773e8d8bef9SDimitry Andric             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
1774e8d8bef9SDimitry Andric 
1775e8d8bef9SDimitry Andric         // There should never be duplicate instruction numbers.
1776e8d8bef9SDimitry Andric         assert(InsertResult.second);
1777e8d8bef9SDimitry Andric         (void)InsertResult;
1778e8d8bef9SDimitry Andric       }
1779e8d8bef9SDimitry Andric 
1780e8d8bef9SDimitry Andric       ++CurInst;
1781e8d8bef9SDimitry Andric     }
1782e8d8bef9SDimitry Andric 
1783e8d8bef9SDimitry Andric     // Produce the transfer function, a map of machine location to new value. If
1784e8d8bef9SDimitry Andric     // any machine location has the live-in phi value from the start of the
1785e8d8bef9SDimitry Andric     // block, it's live-through and doesn't need recording in the transfer
1786e8d8bef9SDimitry Andric     // function.
1787e8d8bef9SDimitry Andric     for (auto Location : MTracker->locations()) {
1788e8d8bef9SDimitry Andric       LocIdx Idx = Location.Idx;
1789e8d8bef9SDimitry Andric       ValueIDNum &P = Location.Value;
1790e8d8bef9SDimitry Andric       if (P.isPHI() && P.getLoc() == Idx.asU64())
1791e8d8bef9SDimitry Andric         continue;
1792e8d8bef9SDimitry Andric 
1793e8d8bef9SDimitry Andric       // Insert-or-update.
1794e8d8bef9SDimitry Andric       auto &TransferMap = MLocTransfer[CurBB];
1795e8d8bef9SDimitry Andric       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
1796e8d8bef9SDimitry Andric       if (!Result.second)
1797e8d8bef9SDimitry Andric         Result.first->second = P;
1798e8d8bef9SDimitry Andric     }
1799e8d8bef9SDimitry Andric 
1800e8d8bef9SDimitry Andric     // Accumulate any bitmask operands into the clobberred reg mask for this
1801e8d8bef9SDimitry Andric     // block.
1802e8d8bef9SDimitry Andric     for (auto &P : MTracker->Masks) {
1803e8d8bef9SDimitry Andric       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
1804e8d8bef9SDimitry Andric     }
1805e8d8bef9SDimitry Andric   }
1806e8d8bef9SDimitry Andric 
1807e8d8bef9SDimitry Andric   // Compute a bitvector of all the registers that are tracked in this block.
1808e8d8bef9SDimitry Andric   BitVector UsedRegs(TRI->getNumRegs());
1809e8d8bef9SDimitry Andric   for (auto Location : MTracker->locations()) {
1810e8d8bef9SDimitry Andric     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
1811349cc55cSDimitry Andric     // Ignore stack slots, and aliases of the stack pointer.
1812349cc55cSDimitry Andric     if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
1813e8d8bef9SDimitry Andric       continue;
1814e8d8bef9SDimitry Andric     UsedRegs.set(ID);
1815e8d8bef9SDimitry Andric   }
1816e8d8bef9SDimitry Andric 
1817e8d8bef9SDimitry Andric   // Check that any regmask-clobber of a register that gets tracked, is not
1818e8d8bef9SDimitry Andric   // live-through in the transfer function. It needs to be clobbered at the
1819e8d8bef9SDimitry Andric   // very least.
1820e8d8bef9SDimitry Andric   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
1821e8d8bef9SDimitry Andric     BitVector &BV = BlockMasks[I];
1822e8d8bef9SDimitry Andric     BV.flip();
1823e8d8bef9SDimitry Andric     BV &= UsedRegs;
1824e8d8bef9SDimitry Andric     // This produces all the bits that we clobber, but also use. Check that
1825e8d8bef9SDimitry Andric     // they're all clobbered or at least set in the designated transfer
1826e8d8bef9SDimitry Andric     // elem.
1827e8d8bef9SDimitry Andric     for (unsigned Bit : BV.set_bits()) {
1828349cc55cSDimitry Andric       unsigned ID = MTracker->getLocID(Bit);
1829e8d8bef9SDimitry Andric       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
1830e8d8bef9SDimitry Andric       auto &TransferMap = MLocTransfer[I];
1831e8d8bef9SDimitry Andric 
1832e8d8bef9SDimitry Andric       // Install a value representing the fact that this location is effectively
1833e8d8bef9SDimitry Andric       // written to in this block. As there's no reserved value, instead use
1834e8d8bef9SDimitry Andric       // a value number that is never generated. Pick the value number for the
1835e8d8bef9SDimitry Andric       // first instruction in the block, def'ing this location, which we know
1836e8d8bef9SDimitry Andric       // this block never used anyway.
1837e8d8bef9SDimitry Andric       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
1838e8d8bef9SDimitry Andric       auto Result =
1839e8d8bef9SDimitry Andric         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
1840e8d8bef9SDimitry Andric       if (!Result.second) {
1841e8d8bef9SDimitry Andric         ValueIDNum &ValueID = Result.first->second;
1842e8d8bef9SDimitry Andric         if (ValueID.getBlock() == I && ValueID.isPHI())
1843e8d8bef9SDimitry Andric           // It was left as live-through. Set it to clobbered.
1844e8d8bef9SDimitry Andric           ValueID = NotGeneratedNum;
1845e8d8bef9SDimitry Andric       }
1846e8d8bef9SDimitry Andric     }
1847e8d8bef9SDimitry Andric   }
1848e8d8bef9SDimitry Andric }
1849e8d8bef9SDimitry Andric 
1850349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin(
1851349cc55cSDimitry Andric     MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1852e8d8bef9SDimitry Andric     ValueIDNum **OutLocs, ValueIDNum *InLocs) {
1853e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1854e8d8bef9SDimitry Andric   bool Changed = false;
1855e8d8bef9SDimitry Andric 
1856349cc55cSDimitry Andric   // Handle value-propagation when control flow merges on entry to a block. For
1857349cc55cSDimitry Andric   // any location without a PHI already placed, the location has the same value
1858349cc55cSDimitry Andric   // as its predecessors. If a PHI is placed, test to see whether it's now a
1859349cc55cSDimitry Andric   // redundant PHI that we can eliminate.
1860349cc55cSDimitry Andric 
1861e8d8bef9SDimitry Andric   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
1862349cc55cSDimitry Andric   for (auto Pred : MBB.predecessors())
1863e8d8bef9SDimitry Andric     BlockOrders.push_back(Pred);
1864e8d8bef9SDimitry Andric 
1865e8d8bef9SDimitry Andric   // Visit predecessors in RPOT order.
1866e8d8bef9SDimitry Andric   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
1867e8d8bef9SDimitry Andric     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
1868e8d8bef9SDimitry Andric   };
1869e8d8bef9SDimitry Andric   llvm::sort(BlockOrders, Cmp);
1870e8d8bef9SDimitry Andric 
1871e8d8bef9SDimitry Andric   // Skip entry block.
1872e8d8bef9SDimitry Andric   if (BlockOrders.size() == 0)
1873349cc55cSDimitry Andric     return false;
1874e8d8bef9SDimitry Andric 
1875349cc55cSDimitry Andric   // Step through all machine locations, look at each predecessor and test
1876349cc55cSDimitry Andric   // whether we can eliminate redundant PHIs.
1877e8d8bef9SDimitry Andric   for (auto Location : MTracker->locations()) {
1878e8d8bef9SDimitry Andric     LocIdx Idx = Location.Idx;
1879349cc55cSDimitry Andric 
1880e8d8bef9SDimitry Andric     // Pick out the first predecessors live-out value for this location. It's
1881349cc55cSDimitry Andric     // guaranteed to not be a backedge, as we order by RPO.
1882349cc55cSDimitry Andric     ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
1883e8d8bef9SDimitry Andric 
1884349cc55cSDimitry Andric     // If we've already eliminated a PHI here, do no further checking, just
1885349cc55cSDimitry Andric     // propagate the first live-in value into this block.
1886349cc55cSDimitry Andric     if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
1887349cc55cSDimitry Andric       if (InLocs[Idx.asU64()] != FirstVal) {
1888349cc55cSDimitry Andric         InLocs[Idx.asU64()] = FirstVal;
1889349cc55cSDimitry Andric         Changed |= true;
1890349cc55cSDimitry Andric       }
1891349cc55cSDimitry Andric       continue;
1892349cc55cSDimitry Andric     }
1893349cc55cSDimitry Andric 
1894349cc55cSDimitry Andric     // We're now examining a PHI to see whether it's un-necessary. Loop around
1895349cc55cSDimitry Andric     // the other live-in values and test whether they're all the same.
1896e8d8bef9SDimitry Andric     bool Disagree = false;
1897e8d8bef9SDimitry Andric     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
1898349cc55cSDimitry Andric       const MachineBasicBlock *PredMBB = BlockOrders[I];
1899349cc55cSDimitry Andric       const ValueIDNum &PredLiveOut =
1900349cc55cSDimitry Andric           OutLocs[PredMBB->getNumber()][Idx.asU64()];
1901349cc55cSDimitry Andric 
1902349cc55cSDimitry Andric       // Incoming values agree, continue trying to eliminate this PHI.
1903349cc55cSDimitry Andric       if (FirstVal == PredLiveOut)
1904349cc55cSDimitry Andric         continue;
1905349cc55cSDimitry Andric 
1906349cc55cSDimitry Andric       // We can also accept a PHI value that feeds back into itself.
1907349cc55cSDimitry Andric       if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
1908349cc55cSDimitry Andric         continue;
1909349cc55cSDimitry Andric 
1910e8d8bef9SDimitry Andric       // Live-out of a predecessor disagrees with the first predecessor.
1911e8d8bef9SDimitry Andric       Disagree = true;
1912e8d8bef9SDimitry Andric     }
1913e8d8bef9SDimitry Andric 
1914349cc55cSDimitry Andric     // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
1915349cc55cSDimitry Andric     if (!Disagree) {
1916349cc55cSDimitry Andric       InLocs[Idx.asU64()] = FirstVal;
1917e8d8bef9SDimitry Andric       Changed |= true;
1918e8d8bef9SDimitry Andric     }
1919e8d8bef9SDimitry Andric   }
1920e8d8bef9SDimitry Andric 
1921e8d8bef9SDimitry Andric   // TODO: Reimplement NumInserted and NumRemoved.
1922349cc55cSDimitry Andric   return Changed;
1923e8d8bef9SDimitry Andric }
1924e8d8bef9SDimitry Andric 
1925349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference(
1926349cc55cSDimitry Andric     SmallVectorImpl<unsigned> &Slots) {
1927349cc55cSDimitry Andric   // We could spend a bit of time finding the exact, minimal, set of stack
1928349cc55cSDimitry Andric   // indexes that interfere with each other, much like reg units. Or, we can
1929349cc55cSDimitry Andric   // rely on the fact that:
1930349cc55cSDimitry Andric   //  * The smallest / lowest index will interfere with everything at zero
1931349cc55cSDimitry Andric   //    offset, which will be the largest set of registers,
1932349cc55cSDimitry Andric   //  * Most indexes with non-zero offset will end up being interference units
1933349cc55cSDimitry Andric   //    anyway.
1934349cc55cSDimitry Andric   // So just pick those out and return them.
1935349cc55cSDimitry Andric 
1936349cc55cSDimitry Andric   // We can rely on a single-byte stack index existing already, because we
1937349cc55cSDimitry Andric   // initialize them in MLocTracker.
1938349cc55cSDimitry Andric   auto It = MTracker->StackSlotIdxes.find({8, 0});
1939349cc55cSDimitry Andric   assert(It != MTracker->StackSlotIdxes.end());
1940349cc55cSDimitry Andric   Slots.push_back(It->second);
1941349cc55cSDimitry Andric 
1942349cc55cSDimitry Andric   // Find anything that has a non-zero offset and add that too.
1943349cc55cSDimitry Andric   for (auto &Pair : MTracker->StackSlotIdxes) {
1944349cc55cSDimitry Andric     // Is offset zero? If so, ignore.
1945349cc55cSDimitry Andric     if (!Pair.first.second)
1946349cc55cSDimitry Andric       continue;
1947349cc55cSDimitry Andric     Slots.push_back(Pair.second);
1948349cc55cSDimitry Andric   }
1949349cc55cSDimitry Andric }
1950349cc55cSDimitry Andric 
1951349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs(
1952349cc55cSDimitry Andric     MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
1953349cc55cSDimitry Andric     ValueIDNum **MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
1954349cc55cSDimitry Andric   SmallVector<unsigned, 4> StackUnits;
1955349cc55cSDimitry Andric   findStackIndexInterference(StackUnits);
1956349cc55cSDimitry Andric 
1957349cc55cSDimitry Andric   // To avoid repeatedly running the PHI placement algorithm, leverage the
1958349cc55cSDimitry Andric   // fact that a def of register MUST also def its register units. Find the
1959349cc55cSDimitry Andric   // units for registers, place PHIs for them, and then replicate them for
1960349cc55cSDimitry Andric   // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
1961349cc55cSDimitry Andric   // arguments) don't lead to register units being tracked, just place PHIs for
1962349cc55cSDimitry Andric   // those registers directly. Stack slots have their own form of "unit",
1963349cc55cSDimitry Andric   // store them to one side.
1964349cc55cSDimitry Andric   SmallSet<Register, 32> RegUnitsToPHIUp;
1965349cc55cSDimitry Andric   SmallSet<LocIdx, 32> NormalLocsToPHI;
1966349cc55cSDimitry Andric   SmallSet<SpillLocationNo, 32> StackSlots;
1967349cc55cSDimitry Andric   for (auto Location : MTracker->locations()) {
1968349cc55cSDimitry Andric     LocIdx L = Location.Idx;
1969349cc55cSDimitry Andric     if (MTracker->isSpill(L)) {
1970349cc55cSDimitry Andric       StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
1971349cc55cSDimitry Andric       continue;
1972349cc55cSDimitry Andric     }
1973349cc55cSDimitry Andric 
1974349cc55cSDimitry Andric     Register R = MTracker->LocIdxToLocID[L];
1975349cc55cSDimitry Andric     SmallSet<Register, 8> FoundRegUnits;
1976349cc55cSDimitry Andric     bool AnyIllegal = false;
1977349cc55cSDimitry Andric     for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) {
1978349cc55cSDimitry Andric       for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){
1979349cc55cSDimitry Andric         if (!MTracker->isRegisterTracked(*URoot)) {
1980349cc55cSDimitry Andric           // Not all roots were loaded into the tracking map: this register
1981349cc55cSDimitry Andric           // isn't actually def'd anywhere, we only read from it. Generate PHIs
1982349cc55cSDimitry Andric           // for this reg, but don't iterate units.
1983349cc55cSDimitry Andric           AnyIllegal = true;
1984349cc55cSDimitry Andric         } else {
1985349cc55cSDimitry Andric           FoundRegUnits.insert(*URoot);
1986349cc55cSDimitry Andric         }
1987349cc55cSDimitry Andric       }
1988349cc55cSDimitry Andric     }
1989349cc55cSDimitry Andric 
1990349cc55cSDimitry Andric     if (AnyIllegal) {
1991349cc55cSDimitry Andric       NormalLocsToPHI.insert(L);
1992349cc55cSDimitry Andric       continue;
1993349cc55cSDimitry Andric     }
1994349cc55cSDimitry Andric 
1995349cc55cSDimitry Andric     RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
1996349cc55cSDimitry Andric   }
1997349cc55cSDimitry Andric 
1998349cc55cSDimitry Andric   // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
1999349cc55cSDimitry Andric   // collection.
2000349cc55cSDimitry Andric   SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2001349cc55cSDimitry Andric   auto CollectPHIsForLoc = [&](LocIdx L) {
2002349cc55cSDimitry Andric     // Collect the set of defs.
2003349cc55cSDimitry Andric     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2004349cc55cSDimitry Andric     for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2005349cc55cSDimitry Andric       MachineBasicBlock *MBB = OrderToBB[I];
2006349cc55cSDimitry Andric       const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2007349cc55cSDimitry Andric       if (TransferFunc.find(L) != TransferFunc.end())
2008349cc55cSDimitry Andric         DefBlocks.insert(MBB);
2009349cc55cSDimitry Andric     }
2010349cc55cSDimitry Andric 
2011349cc55cSDimitry Andric     // The entry block defs the location too: it's the live-in / argument value.
2012349cc55cSDimitry Andric     // Only insert if there are other defs though; everything is trivially live
2013349cc55cSDimitry Andric     // through otherwise.
2014349cc55cSDimitry Andric     if (!DefBlocks.empty())
2015349cc55cSDimitry Andric       DefBlocks.insert(&*MF.begin());
2016349cc55cSDimitry Andric 
2017349cc55cSDimitry Andric     // Ask the SSA construction algorithm where we should put PHIs. Clear
2018349cc55cSDimitry Andric     // anything that might have been hanging around from earlier.
2019349cc55cSDimitry Andric     PHIBlocks.clear();
2020349cc55cSDimitry Andric     BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2021349cc55cSDimitry Andric   };
2022349cc55cSDimitry Andric 
2023349cc55cSDimitry Andric   auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2024349cc55cSDimitry Andric     for (const MachineBasicBlock *MBB : PHIBlocks)
2025349cc55cSDimitry Andric       MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2026349cc55cSDimitry Andric   };
2027349cc55cSDimitry Andric 
2028349cc55cSDimitry Andric   // For locations with no reg units, just place PHIs.
2029349cc55cSDimitry Andric   for (LocIdx L : NormalLocsToPHI) {
2030349cc55cSDimitry Andric     CollectPHIsForLoc(L);
2031349cc55cSDimitry Andric     // Install those PHI values into the live-in value array.
2032349cc55cSDimitry Andric     InstallPHIsAtLoc(L);
2033349cc55cSDimitry Andric   }
2034349cc55cSDimitry Andric 
2035349cc55cSDimitry Andric   // For stack slots, calculate PHIs for the equivalent of the units, then
2036349cc55cSDimitry Andric   // install for each index.
2037349cc55cSDimitry Andric   for (SpillLocationNo Slot : StackSlots) {
2038349cc55cSDimitry Andric     for (unsigned Idx : StackUnits) {
2039349cc55cSDimitry Andric       unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2040349cc55cSDimitry Andric       LocIdx L = MTracker->getSpillMLoc(SpillID);
2041349cc55cSDimitry Andric       CollectPHIsForLoc(L);
2042349cc55cSDimitry Andric       InstallPHIsAtLoc(L);
2043349cc55cSDimitry Andric 
2044349cc55cSDimitry Andric       // Find anything that aliases this stack index, install PHIs for it too.
2045349cc55cSDimitry Andric       unsigned Size, Offset;
2046349cc55cSDimitry Andric       std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2047349cc55cSDimitry Andric       for (auto &Pair : MTracker->StackSlotIdxes) {
2048349cc55cSDimitry Andric         unsigned ThisSize, ThisOffset;
2049349cc55cSDimitry Andric         std::tie(ThisSize, ThisOffset) = Pair.first;
2050349cc55cSDimitry Andric         if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2051349cc55cSDimitry Andric           continue;
2052349cc55cSDimitry Andric 
2053349cc55cSDimitry Andric         unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2054349cc55cSDimitry Andric         LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2055349cc55cSDimitry Andric         InstallPHIsAtLoc(ThisL);
2056349cc55cSDimitry Andric       }
2057349cc55cSDimitry Andric     }
2058349cc55cSDimitry Andric   }
2059349cc55cSDimitry Andric 
2060349cc55cSDimitry Andric   // For reg units, place PHIs, and then place them for any aliasing registers.
2061349cc55cSDimitry Andric   for (Register R : RegUnitsToPHIUp) {
2062349cc55cSDimitry Andric     LocIdx L = MTracker->lookupOrTrackRegister(R);
2063349cc55cSDimitry Andric     CollectPHIsForLoc(L);
2064349cc55cSDimitry Andric 
2065349cc55cSDimitry Andric     // Install those PHI values into the live-in value array.
2066349cc55cSDimitry Andric     InstallPHIsAtLoc(L);
2067349cc55cSDimitry Andric 
2068349cc55cSDimitry Andric     // Now find aliases and install PHIs for those.
2069349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2070349cc55cSDimitry Andric       // Super-registers that are "above" the largest register read/written by
2071349cc55cSDimitry Andric       // the function will alias, but will not be tracked.
2072349cc55cSDimitry Andric       if (!MTracker->isRegisterTracked(*RAI))
2073349cc55cSDimitry Andric         continue;
2074349cc55cSDimitry Andric 
2075349cc55cSDimitry Andric       LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2076349cc55cSDimitry Andric       InstallPHIsAtLoc(AliasLoc);
2077349cc55cSDimitry Andric     }
2078349cc55cSDimitry Andric   }
2079349cc55cSDimitry Andric }
2080349cc55cSDimitry Andric 
2081349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap(
2082349cc55cSDimitry Andric     MachineFunction &MF, ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
2083e8d8bef9SDimitry Andric     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2084e8d8bef9SDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
2085e8d8bef9SDimitry Andric                       std::greater<unsigned int>>
2086e8d8bef9SDimitry Andric       Worklist, Pending;
2087e8d8bef9SDimitry Andric 
2088e8d8bef9SDimitry Andric   // We track what is on the current and pending worklist to avoid inserting
2089e8d8bef9SDimitry Andric   // the same thing twice. We could avoid this with a custom priority queue,
2090e8d8bef9SDimitry Andric   // but this is probably not worth it.
2091e8d8bef9SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2092e8d8bef9SDimitry Andric 
2093349cc55cSDimitry Andric   // Initialize worklist with every block to be visited. Also produce list of
2094349cc55cSDimitry Andric   // all blocks.
2095349cc55cSDimitry Andric   SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2096e8d8bef9SDimitry Andric   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2097e8d8bef9SDimitry Andric     Worklist.push(I);
2098e8d8bef9SDimitry Andric     OnWorklist.insert(OrderToBB[I]);
2099349cc55cSDimitry Andric     AllBlocks.insert(OrderToBB[I]);
2100e8d8bef9SDimitry Andric   }
2101e8d8bef9SDimitry Andric 
2102349cc55cSDimitry Andric   // Initialize entry block to PHIs. These represent arguments.
2103349cc55cSDimitry Andric   for (auto Location : MTracker->locations())
2104349cc55cSDimitry Andric     MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
2105349cc55cSDimitry Andric 
2106e8d8bef9SDimitry Andric   MTracker->reset();
2107e8d8bef9SDimitry Andric 
2108349cc55cSDimitry Andric   // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2109349cc55cSDimitry Andric   // any machine-location that isn't live-through a block to be def'd in that
2110349cc55cSDimitry Andric   // block.
2111349cc55cSDimitry Andric   placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2112e8d8bef9SDimitry Andric 
2113349cc55cSDimitry Andric   // Propagate values to eliminate redundant PHIs. At the same time, this
2114349cc55cSDimitry Andric   // produces the table of Block x Location => Value for the entry to each
2115349cc55cSDimitry Andric   // block.
2116349cc55cSDimitry Andric   // The kind of PHIs we can eliminate are, for example, where one path in a
2117349cc55cSDimitry Andric   // conditional spills and restores a register, and the register still has
2118349cc55cSDimitry Andric   // the same value once control flow joins, unbeknowns to the PHI placement
2119349cc55cSDimitry Andric   // code. Propagating values allows us to identify such un-necessary PHIs and
2120349cc55cSDimitry Andric   // remove them.
2121e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2122e8d8bef9SDimitry Andric   while (!Worklist.empty() || !Pending.empty()) {
2123e8d8bef9SDimitry Andric     // Vector for storing the evaluated block transfer function.
2124e8d8bef9SDimitry Andric     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2125e8d8bef9SDimitry Andric 
2126e8d8bef9SDimitry Andric     while (!Worklist.empty()) {
2127e8d8bef9SDimitry Andric       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2128e8d8bef9SDimitry Andric       CurBB = MBB->getNumber();
2129e8d8bef9SDimitry Andric       Worklist.pop();
2130e8d8bef9SDimitry Andric 
2131e8d8bef9SDimitry Andric       // Join the values in all predecessor blocks.
2132349cc55cSDimitry Andric       bool InLocsChanged;
2133349cc55cSDimitry Andric       InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2134e8d8bef9SDimitry Andric       InLocsChanged |= Visited.insert(MBB).second;
2135e8d8bef9SDimitry Andric 
2136e8d8bef9SDimitry Andric       // Don't examine transfer function if we've visited this loc at least
2137e8d8bef9SDimitry Andric       // once, and inlocs haven't changed.
2138e8d8bef9SDimitry Andric       if (!InLocsChanged)
2139e8d8bef9SDimitry Andric         continue;
2140e8d8bef9SDimitry Andric 
2141e8d8bef9SDimitry Andric       // Load the current set of live-ins into MLocTracker.
2142e8d8bef9SDimitry Andric       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2143e8d8bef9SDimitry Andric 
2144e8d8bef9SDimitry Andric       // Each element of the transfer function can be a new def, or a read of
2145e8d8bef9SDimitry Andric       // a live-in value. Evaluate each element, and store to "ToRemap".
2146e8d8bef9SDimitry Andric       ToRemap.clear();
2147e8d8bef9SDimitry Andric       for (auto &P : MLocTransfer[CurBB]) {
2148e8d8bef9SDimitry Andric         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2149e8d8bef9SDimitry Andric           // This is a movement of whatever was live in. Read it.
2150349cc55cSDimitry Andric           ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2151e8d8bef9SDimitry Andric           ToRemap.push_back(std::make_pair(P.first, NewID));
2152e8d8bef9SDimitry Andric         } else {
2153e8d8bef9SDimitry Andric           // It's a def. Just set it.
2154e8d8bef9SDimitry Andric           assert(P.second.getBlock() == CurBB);
2155e8d8bef9SDimitry Andric           ToRemap.push_back(std::make_pair(P.first, P.second));
2156e8d8bef9SDimitry Andric         }
2157e8d8bef9SDimitry Andric       }
2158e8d8bef9SDimitry Andric 
2159e8d8bef9SDimitry Andric       // Commit the transfer function changes into mloc tracker, which
2160e8d8bef9SDimitry Andric       // transforms the contents of the MLocTracker into the live-outs.
2161e8d8bef9SDimitry Andric       for (auto &P : ToRemap)
2162e8d8bef9SDimitry Andric         MTracker->setMLoc(P.first, P.second);
2163e8d8bef9SDimitry Andric 
2164e8d8bef9SDimitry Andric       // Now copy out-locs from mloc tracker into out-loc vector, checking
2165e8d8bef9SDimitry Andric       // whether changes have occurred. These changes can have come from both
2166e8d8bef9SDimitry Andric       // the transfer function, and mlocJoin.
2167e8d8bef9SDimitry Andric       bool OLChanged = false;
2168e8d8bef9SDimitry Andric       for (auto Location : MTracker->locations()) {
2169e8d8bef9SDimitry Andric         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2170e8d8bef9SDimitry Andric         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2171e8d8bef9SDimitry Andric       }
2172e8d8bef9SDimitry Andric 
2173e8d8bef9SDimitry Andric       MTracker->reset();
2174e8d8bef9SDimitry Andric 
2175e8d8bef9SDimitry Andric       // No need to examine successors again if out-locs didn't change.
2176e8d8bef9SDimitry Andric       if (!OLChanged)
2177e8d8bef9SDimitry Andric         continue;
2178e8d8bef9SDimitry Andric 
2179e8d8bef9SDimitry Andric       // All successors should be visited: put any back-edges on the pending
2180349cc55cSDimitry Andric       // list for the next pass-through, and any other successors to be
2181349cc55cSDimitry Andric       // visited this pass, if they're not going to be already.
2182e8d8bef9SDimitry Andric       for (auto s : MBB->successors()) {
2183e8d8bef9SDimitry Andric         // Does branching to this successor represent a back-edge?
2184e8d8bef9SDimitry Andric         if (BBToOrder[s] > BBToOrder[MBB]) {
2185e8d8bef9SDimitry Andric           // No: visit it during this dataflow iteration.
2186e8d8bef9SDimitry Andric           if (OnWorklist.insert(s).second)
2187e8d8bef9SDimitry Andric             Worklist.push(BBToOrder[s]);
2188e8d8bef9SDimitry Andric         } else {
2189e8d8bef9SDimitry Andric           // Yes: visit it on the next iteration.
2190e8d8bef9SDimitry Andric           if (OnPending.insert(s).second)
2191e8d8bef9SDimitry Andric             Pending.push(BBToOrder[s]);
2192e8d8bef9SDimitry Andric         }
2193e8d8bef9SDimitry Andric       }
2194e8d8bef9SDimitry Andric     }
2195e8d8bef9SDimitry Andric 
2196e8d8bef9SDimitry Andric     Worklist.swap(Pending);
2197e8d8bef9SDimitry Andric     std::swap(OnPending, OnWorklist);
2198e8d8bef9SDimitry Andric     OnPending.clear();
2199e8d8bef9SDimitry Andric     // At this point, pending must be empty, since it was just the empty
2200e8d8bef9SDimitry Andric     // worklist
2201e8d8bef9SDimitry Andric     assert(Pending.empty() && "Pending should be empty");
2202e8d8bef9SDimitry Andric   }
2203e8d8bef9SDimitry Andric 
2204349cc55cSDimitry Andric   // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2205349cc55cSDimitry Andric   // redundant PHIs.
2206e8d8bef9SDimitry Andric }
2207e8d8bef9SDimitry Andric 
2208349cc55cSDimitry Andric // Boilerplate for feeding MachineBasicBlocks into IDF calculator. Provide
2209349cc55cSDimitry Andric // template specialisations for graph traits and a successor enumerator.
2210349cc55cSDimitry Andric namespace llvm {
2211349cc55cSDimitry Andric template <> struct GraphTraits<MachineBasicBlock> {
2212349cc55cSDimitry Andric   using NodeRef = MachineBasicBlock *;
2213349cc55cSDimitry Andric   using ChildIteratorType = MachineBasicBlock::succ_iterator;
2214e8d8bef9SDimitry Andric 
2215349cc55cSDimitry Andric   static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
2216349cc55cSDimitry Andric   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
2217349cc55cSDimitry Andric   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
2218349cc55cSDimitry Andric };
2219349cc55cSDimitry Andric 
2220349cc55cSDimitry Andric template <> struct GraphTraits<const MachineBasicBlock> {
2221349cc55cSDimitry Andric   using NodeRef = const MachineBasicBlock *;
2222349cc55cSDimitry Andric   using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
2223349cc55cSDimitry Andric 
2224349cc55cSDimitry Andric   static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
2225349cc55cSDimitry Andric   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
2226349cc55cSDimitry Andric   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
2227349cc55cSDimitry Andric };
2228349cc55cSDimitry Andric 
2229349cc55cSDimitry Andric using MachineDomTreeBase = DomTreeBase<MachineBasicBlock>::NodeType;
2230349cc55cSDimitry Andric using MachineDomTreeChildGetter =
2231349cc55cSDimitry Andric     typename IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false>;
2232349cc55cSDimitry Andric 
2233349cc55cSDimitry Andric namespace IDFCalculatorDetail {
2234349cc55cSDimitry Andric template <>
2235349cc55cSDimitry Andric typename MachineDomTreeChildGetter::ChildrenTy
2236349cc55cSDimitry Andric MachineDomTreeChildGetter::get(const NodeRef &N) {
2237349cc55cSDimitry Andric   return {N->succ_begin(), N->succ_end()};
2238349cc55cSDimitry Andric }
2239349cc55cSDimitry Andric } // namespace IDFCalculatorDetail
2240349cc55cSDimitry Andric } // namespace llvm
2241349cc55cSDimitry Andric 
2242349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement(
2243349cc55cSDimitry Andric     const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2244349cc55cSDimitry Andric     const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2245349cc55cSDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2246349cc55cSDimitry Andric   // Apply IDF calculator to the designated set of location defs, storing
2247349cc55cSDimitry Andric   // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2248349cc55cSDimitry Andric   // InstrRefBasedLDV object.
2249349cc55cSDimitry Andric   IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false> foo;
2250349cc55cSDimitry Andric   IDFCalculatorBase<MachineDomTreeBase, false> IDF(DomTree->getBase(), foo);
2251349cc55cSDimitry Andric 
2252349cc55cSDimitry Andric   IDF.setLiveInBlocks(AllBlocks);
2253349cc55cSDimitry Andric   IDF.setDefiningBlocks(DefBlocks);
2254349cc55cSDimitry Andric   IDF.calculate(PHIBlocks);
2255e8d8bef9SDimitry Andric }
2256e8d8bef9SDimitry Andric 
2257349cc55cSDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc(
2258349cc55cSDimitry Andric     const MachineBasicBlock &MBB, const DebugVariable &Var,
2259349cc55cSDimitry Andric     const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
2260349cc55cSDimitry Andric     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2261e8d8bef9SDimitry Andric   // Collect a set of locations from predecessor where its live-out value can
2262e8d8bef9SDimitry Andric   // be found.
2263e8d8bef9SDimitry Andric   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2264349cc55cSDimitry Andric   SmallVector<const DbgValueProperties *, 4> Properties;
2265e8d8bef9SDimitry Andric   unsigned NumLocs = MTracker->getNumLocs();
2266349cc55cSDimitry Andric 
2267349cc55cSDimitry Andric   // No predecessors means no PHIs.
2268349cc55cSDimitry Andric   if (BlockOrders.empty())
2269349cc55cSDimitry Andric     return None;
2270e8d8bef9SDimitry Andric 
2271e8d8bef9SDimitry Andric   for (auto p : BlockOrders) {
2272e8d8bef9SDimitry Andric     unsigned ThisBBNum = p->getNumber();
2273349cc55cSDimitry Andric     auto OutValIt = LiveOuts.find(p);
2274349cc55cSDimitry Andric     if (OutValIt == LiveOuts.end())
2275349cc55cSDimitry Andric       // If we have a predecessor not in scope, we'll never find a PHI position.
2276349cc55cSDimitry Andric       return None;
2277349cc55cSDimitry Andric     const DbgValue &OutVal = *OutValIt->second;
2278e8d8bef9SDimitry Andric 
2279e8d8bef9SDimitry Andric     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2280e8d8bef9SDimitry Andric       // Consts and no-values cannot have locations we can join on.
2281349cc55cSDimitry Andric       return None;
2282e8d8bef9SDimitry Andric 
2283349cc55cSDimitry Andric     Properties.push_back(&OutVal.Properties);
2284349cc55cSDimitry Andric 
2285349cc55cSDimitry Andric     // Create new empty vector of locations.
2286349cc55cSDimitry Andric     Locs.resize(Locs.size() + 1);
2287349cc55cSDimitry Andric 
2288349cc55cSDimitry Andric     // If the live-in value is a def, find the locations where that value is
2289349cc55cSDimitry Andric     // present. Do the same for VPHIs where we know the VPHI value.
2290349cc55cSDimitry Andric     if (OutVal.Kind == DbgValue::Def ||
2291349cc55cSDimitry Andric         (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2292349cc55cSDimitry Andric          OutVal.ID != ValueIDNum::EmptyValue)) {
2293e8d8bef9SDimitry Andric       ValueIDNum ValToLookFor = OutVal.ID;
2294e8d8bef9SDimitry Andric       // Search the live-outs of the predecessor for the specified value.
2295e8d8bef9SDimitry Andric       for (unsigned int I = 0; I < NumLocs; ++I) {
2296e8d8bef9SDimitry Andric         if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2297e8d8bef9SDimitry Andric           Locs.back().push_back(LocIdx(I));
2298e8d8bef9SDimitry Andric       }
2299349cc55cSDimitry Andric     } else {
2300349cc55cSDimitry Andric       assert(OutVal.Kind == DbgValue::VPHI);
2301349cc55cSDimitry Andric       // For VPHIs where we don't know the location, we definitely can't find
2302349cc55cSDimitry Andric       // a join loc.
2303349cc55cSDimitry Andric       if (OutVal.BlockNo != MBB.getNumber())
2304349cc55cSDimitry Andric         return None;
2305349cc55cSDimitry Andric 
2306349cc55cSDimitry Andric       // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2307349cc55cSDimitry Andric       // a value that's live-through the whole loop. (It has to be a backedge,
2308349cc55cSDimitry Andric       // because a block can't dominate itself). We can accept as a PHI location
2309349cc55cSDimitry Andric       // any location where the other predecessors agree, _and_ the machine
2310349cc55cSDimitry Andric       // locations feed back into themselves. Therefore, add all self-looping
2311349cc55cSDimitry Andric       // machine-value PHI locations.
2312349cc55cSDimitry Andric       for (unsigned int I = 0; I < NumLocs; ++I) {
2313349cc55cSDimitry Andric         ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2314349cc55cSDimitry Andric         if (MOutLocs[ThisBBNum][I] == MPHI)
2315349cc55cSDimitry Andric           Locs.back().push_back(LocIdx(I));
2316349cc55cSDimitry Andric       }
2317349cc55cSDimitry Andric     }
2318e8d8bef9SDimitry Andric   }
2319e8d8bef9SDimitry Andric 
2320349cc55cSDimitry Andric   // We should have found locations for all predecessors, or returned.
2321349cc55cSDimitry Andric   assert(Locs.size() == BlockOrders.size());
2322e8d8bef9SDimitry Andric 
2323349cc55cSDimitry Andric   // Check that all properties are the same. We can't pick a location if they're
2324349cc55cSDimitry Andric   // not.
2325349cc55cSDimitry Andric   const DbgValueProperties *Properties0 = Properties[0];
2326349cc55cSDimitry Andric   for (auto *Prop : Properties)
2327349cc55cSDimitry Andric     if (*Prop != *Properties0)
2328349cc55cSDimitry Andric       return None;
2329349cc55cSDimitry Andric 
2330e8d8bef9SDimitry Andric   // Starting with the first set of locations, take the intersection with
2331e8d8bef9SDimitry Andric   // subsequent sets.
2332349cc55cSDimitry Andric   SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2333349cc55cSDimitry Andric   for (unsigned int I = 1; I < Locs.size(); ++I) {
2334349cc55cSDimitry Andric     auto &LocVec = Locs[I];
2335349cc55cSDimitry Andric     SmallVector<LocIdx, 4> NewCandidates;
2336349cc55cSDimitry Andric     std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2337349cc55cSDimitry Andric                           LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2338349cc55cSDimitry Andric     CandidateLocs = NewCandidates;
2339e8d8bef9SDimitry Andric   }
2340349cc55cSDimitry Andric   if (CandidateLocs.empty())
2341e8d8bef9SDimitry Andric     return None;
2342e8d8bef9SDimitry Andric 
2343e8d8bef9SDimitry Andric   // We now have a set of LocIdxes that contain the right output value in
2344e8d8bef9SDimitry Andric   // each of the predecessors. Pick the lowest; if there's a register loc,
2345e8d8bef9SDimitry Andric   // that'll be it.
2346349cc55cSDimitry Andric   LocIdx L = *CandidateLocs.begin();
2347e8d8bef9SDimitry Andric 
2348e8d8bef9SDimitry Andric   // Return a PHI-value-number for the found location.
2349e8d8bef9SDimitry Andric   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2350349cc55cSDimitry Andric   return PHIVal;
2351e8d8bef9SDimitry Andric }
2352e8d8bef9SDimitry Andric 
2353349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin(
2354349cc55cSDimitry Andric     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2355e8d8bef9SDimitry Andric     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2356349cc55cSDimitry Andric     DbgValue &LiveIn) {
2357e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2358e8d8bef9SDimitry Andric   bool Changed = false;
2359e8d8bef9SDimitry Andric 
2360e8d8bef9SDimitry Andric   // Order predecessors by RPOT order, for exploring them in that order.
2361fe6060f1SDimitry Andric   SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2362e8d8bef9SDimitry Andric 
2363e8d8bef9SDimitry Andric   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2364e8d8bef9SDimitry Andric     return BBToOrder[A] < BBToOrder[B];
2365e8d8bef9SDimitry Andric   };
2366e8d8bef9SDimitry Andric 
2367e8d8bef9SDimitry Andric   llvm::sort(BlockOrders, Cmp);
2368e8d8bef9SDimitry Andric 
2369e8d8bef9SDimitry Andric   unsigned CurBlockRPONum = BBToOrder[&MBB];
2370e8d8bef9SDimitry Andric 
2371349cc55cSDimitry Andric   // Collect all the incoming DbgValues for this variable, from predecessor
2372349cc55cSDimitry Andric   // live-out values.
2373e8d8bef9SDimitry Andric   SmallVector<InValueT, 8> Values;
2374e8d8bef9SDimitry Andric   bool Bail = false;
2375349cc55cSDimitry Andric   int BackEdgesStart = 0;
2376e8d8bef9SDimitry Andric   for (auto p : BlockOrders) {
2377e8d8bef9SDimitry Andric     // If the predecessor isn't in scope / to be explored, we'll never be
2378e8d8bef9SDimitry Andric     // able to join any locations.
2379e8d8bef9SDimitry Andric     if (!BlocksToExplore.contains(p)) {
2380e8d8bef9SDimitry Andric       Bail = true;
2381e8d8bef9SDimitry Andric       break;
2382e8d8bef9SDimitry Andric     }
2383e8d8bef9SDimitry Andric 
2384349cc55cSDimitry Andric     // All Live-outs will have been initialized.
2385349cc55cSDimitry Andric     DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2386e8d8bef9SDimitry Andric 
2387e8d8bef9SDimitry Andric     // Keep track of where back-edges begin in the Values vector. Relies on
2388e8d8bef9SDimitry Andric     // BlockOrders being sorted by RPO.
2389e8d8bef9SDimitry Andric     unsigned ThisBBRPONum = BBToOrder[p];
2390e8d8bef9SDimitry Andric     if (ThisBBRPONum < CurBlockRPONum)
2391e8d8bef9SDimitry Andric       ++BackEdgesStart;
2392e8d8bef9SDimitry Andric 
2393349cc55cSDimitry Andric     Values.push_back(std::make_pair(p, &OutLoc));
2394e8d8bef9SDimitry Andric   }
2395e8d8bef9SDimitry Andric 
2396e8d8bef9SDimitry Andric   // If there were no values, or one of the predecessors couldn't have a
2397e8d8bef9SDimitry Andric   // value, then give up immediately. It's not safe to produce a live-in
2398349cc55cSDimitry Andric   // value. Leave as whatever it was before.
2399e8d8bef9SDimitry Andric   if (Bail || Values.size() == 0)
2400349cc55cSDimitry Andric     return false;
2401e8d8bef9SDimitry Andric 
2402e8d8bef9SDimitry Andric   // All (non-entry) blocks have at least one non-backedge predecessor.
2403e8d8bef9SDimitry Andric   // Pick the variable value from the first of these, to compare against
2404e8d8bef9SDimitry Andric   // all others.
2405e8d8bef9SDimitry Andric   const DbgValue &FirstVal = *Values[0].second;
2406e8d8bef9SDimitry Andric 
2407349cc55cSDimitry Andric   // If the old live-in value is not a PHI then either a) no PHI is needed
2408349cc55cSDimitry Andric   // here, or b) we eliminated the PHI that was here. If so, we can just
2409349cc55cSDimitry Andric   // propagate in the first parent's incoming value.
2410349cc55cSDimitry Andric   if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
2411349cc55cSDimitry Andric     Changed = LiveIn != FirstVal;
2412349cc55cSDimitry Andric     if (Changed)
2413349cc55cSDimitry Andric       LiveIn = FirstVal;
2414349cc55cSDimitry Andric     return Changed;
2415349cc55cSDimitry Andric   }
2416349cc55cSDimitry Andric 
2417349cc55cSDimitry Andric   // Scan for variable values that can never be resolved: if they have
2418349cc55cSDimitry Andric   // different DIExpressions, different indirectness, or are mixed constants /
2419e8d8bef9SDimitry Andric   // non-constants.
2420e8d8bef9SDimitry Andric   for (auto &V : Values) {
2421e8d8bef9SDimitry Andric     if (V.second->Properties != FirstVal.Properties)
2422349cc55cSDimitry Andric       return false;
2423349cc55cSDimitry Andric     if (V.second->Kind == DbgValue::NoVal)
2424349cc55cSDimitry Andric       return false;
2425e8d8bef9SDimitry Andric     if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
2426349cc55cSDimitry Andric       return false;
2427e8d8bef9SDimitry Andric   }
2428e8d8bef9SDimitry Andric 
2429349cc55cSDimitry Andric   // Try to eliminate this PHI. Do the incoming values all agree?
2430e8d8bef9SDimitry Andric   bool Disagree = false;
2431e8d8bef9SDimitry Andric   for (auto &V : Values) {
2432e8d8bef9SDimitry Andric     if (*V.second == FirstVal)
2433e8d8bef9SDimitry Andric       continue; // No disagreement.
2434e8d8bef9SDimitry Andric 
2435349cc55cSDimitry Andric     // Eliminate if a backedge feeds a VPHI back into itself.
2436349cc55cSDimitry Andric     if (V.second->Kind == DbgValue::VPHI &&
2437349cc55cSDimitry Andric         V.second->BlockNo == MBB.getNumber() &&
2438349cc55cSDimitry Andric         // Is this a backedge?
2439349cc55cSDimitry Andric         std::distance(Values.begin(), &V) >= BackEdgesStart)
2440349cc55cSDimitry Andric       continue;
2441349cc55cSDimitry Andric 
2442e8d8bef9SDimitry Andric     Disagree = true;
2443e8d8bef9SDimitry Andric   }
2444e8d8bef9SDimitry Andric 
2445349cc55cSDimitry Andric   // No disagreement -> live-through value.
2446349cc55cSDimitry Andric   if (!Disagree) {
2447349cc55cSDimitry Andric     Changed = LiveIn != FirstVal;
2448e8d8bef9SDimitry Andric     if (Changed)
2449349cc55cSDimitry Andric       LiveIn = FirstVal;
2450349cc55cSDimitry Andric     return Changed;
2451349cc55cSDimitry Andric   } else {
2452349cc55cSDimitry Andric     // Otherwise use a VPHI.
2453349cc55cSDimitry Andric     DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
2454349cc55cSDimitry Andric     Changed = LiveIn != VPHI;
2455349cc55cSDimitry Andric     if (Changed)
2456349cc55cSDimitry Andric       LiveIn = VPHI;
2457349cc55cSDimitry Andric     return Changed;
2458349cc55cSDimitry Andric   }
2459e8d8bef9SDimitry Andric }
2460e8d8bef9SDimitry Andric 
2461349cc55cSDimitry Andric void InstrRefBasedLDV::buildVLocValueMap(const DILocation *DILoc,
2462e8d8bef9SDimitry Andric     const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2463e8d8bef9SDimitry Andric     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2464e8d8bef9SDimitry Andric     ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2465e8d8bef9SDimitry Andric     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2466349cc55cSDimitry Andric   // This method is much like buildMLocValueMap: but focuses on a single
2467e8d8bef9SDimitry Andric   // LexicalScope at a time. Pick out a set of blocks and variables that are
2468e8d8bef9SDimitry Andric   // to have their value assignments solved, then run our dataflow algorithm
2469e8d8bef9SDimitry Andric   // until a fixedpoint is reached.
2470e8d8bef9SDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
2471e8d8bef9SDimitry Andric                       std::greater<unsigned int>>
2472e8d8bef9SDimitry Andric       Worklist, Pending;
2473e8d8bef9SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2474e8d8bef9SDimitry Andric 
2475e8d8bef9SDimitry Andric   // The set of blocks we'll be examining.
2476e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2477e8d8bef9SDimitry Andric 
2478e8d8bef9SDimitry Andric   // The order in which to examine them (RPO).
2479e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2480e8d8bef9SDimitry Andric 
2481e8d8bef9SDimitry Andric   // RPO ordering function.
2482e8d8bef9SDimitry Andric   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2483e8d8bef9SDimitry Andric     return BBToOrder[A] < BBToOrder[B];
2484e8d8bef9SDimitry Andric   };
2485e8d8bef9SDimitry Andric 
2486e8d8bef9SDimitry Andric   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
2487e8d8bef9SDimitry Andric 
2488e8d8bef9SDimitry Andric   // A separate container to distinguish "blocks we're exploring" versus
2489e8d8bef9SDimitry Andric   // "blocks that are potentially in scope. See comment at start of vlocJoin.
2490e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore;
2491e8d8bef9SDimitry Andric 
2492*4824e7fdSDimitry Andric   // VarLoc LiveDebugValues tracks variable locations that are defined in
2493*4824e7fdSDimitry Andric   // blocks not in scope. This is something we could legitimately ignore, but
2494*4824e7fdSDimitry Andric   // lets allow it for now for the sake of coverage.
2495e8d8bef9SDimitry Andric   BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
2496e8d8bef9SDimitry Andric 
2497e8d8bef9SDimitry Andric   // We also need to propagate variable values through any artificial blocks
2498e8d8bef9SDimitry Andric   // that immediately follow blocks in scope.
2499e8d8bef9SDimitry Andric   DenseSet<const MachineBasicBlock *> ToAdd;
2500e8d8bef9SDimitry Andric 
2501e8d8bef9SDimitry Andric   // Helper lambda: For a given block in scope, perform a depth first search
2502e8d8bef9SDimitry Andric   // of all the artificial successors, adding them to the ToAdd collection.
2503e8d8bef9SDimitry Andric   auto AccumulateArtificialBlocks =
2504e8d8bef9SDimitry Andric       [this, &ToAdd, &BlocksToExplore,
2505e8d8bef9SDimitry Andric        &InScopeBlocks](const MachineBasicBlock *MBB) {
2506e8d8bef9SDimitry Andric         // Depth-first-search state: each node is a block and which successor
2507e8d8bef9SDimitry Andric         // we're currently exploring.
2508e8d8bef9SDimitry Andric         SmallVector<std::pair<const MachineBasicBlock *,
2509e8d8bef9SDimitry Andric                               MachineBasicBlock::const_succ_iterator>,
2510e8d8bef9SDimitry Andric                     8>
2511e8d8bef9SDimitry Andric             DFS;
2512e8d8bef9SDimitry Andric 
2513e8d8bef9SDimitry Andric         // Find any artificial successors not already tracked.
2514e8d8bef9SDimitry Andric         for (auto *succ : MBB->successors()) {
2515e8d8bef9SDimitry Andric           if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ))
2516e8d8bef9SDimitry Andric             continue;
2517e8d8bef9SDimitry Andric           if (!ArtificialBlocks.count(succ))
2518e8d8bef9SDimitry Andric             continue;
2519e8d8bef9SDimitry Andric           ToAdd.insert(succ);
2520349cc55cSDimitry Andric           DFS.push_back(std::make_pair(succ, succ->succ_begin()));
2521e8d8bef9SDimitry Andric         }
2522e8d8bef9SDimitry Andric 
2523e8d8bef9SDimitry Andric         // Search all those blocks, depth first.
2524e8d8bef9SDimitry Andric         while (!DFS.empty()) {
2525e8d8bef9SDimitry Andric           const MachineBasicBlock *CurBB = DFS.back().first;
2526e8d8bef9SDimitry Andric           MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
2527e8d8bef9SDimitry Andric           // Walk back if we've explored this blocks successors to the end.
2528e8d8bef9SDimitry Andric           if (CurSucc == CurBB->succ_end()) {
2529e8d8bef9SDimitry Andric             DFS.pop_back();
2530e8d8bef9SDimitry Andric             continue;
2531e8d8bef9SDimitry Andric           }
2532e8d8bef9SDimitry Andric 
2533e8d8bef9SDimitry Andric           // If the current successor is artificial and unexplored, descend into
2534e8d8bef9SDimitry Andric           // it.
2535e8d8bef9SDimitry Andric           if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
2536e8d8bef9SDimitry Andric             ToAdd.insert(*CurSucc);
2537349cc55cSDimitry Andric             DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin()));
2538e8d8bef9SDimitry Andric             continue;
2539e8d8bef9SDimitry Andric           }
2540e8d8bef9SDimitry Andric 
2541e8d8bef9SDimitry Andric           ++CurSucc;
2542e8d8bef9SDimitry Andric         }
2543e8d8bef9SDimitry Andric       };
2544e8d8bef9SDimitry Andric 
2545e8d8bef9SDimitry Andric   // Search in-scope blocks and those containing a DBG_VALUE from this scope
2546e8d8bef9SDimitry Andric   // for artificial successors.
2547e8d8bef9SDimitry Andric   for (auto *MBB : BlocksToExplore)
2548e8d8bef9SDimitry Andric     AccumulateArtificialBlocks(MBB);
2549e8d8bef9SDimitry Andric   for (auto *MBB : InScopeBlocks)
2550e8d8bef9SDimitry Andric     AccumulateArtificialBlocks(MBB);
2551e8d8bef9SDimitry Andric 
2552e8d8bef9SDimitry Andric   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
2553e8d8bef9SDimitry Andric   InScopeBlocks.insert(ToAdd.begin(), ToAdd.end());
2554e8d8bef9SDimitry Andric 
2555e8d8bef9SDimitry Andric   // Single block scope: not interesting! No propagation at all. Note that
2556e8d8bef9SDimitry Andric   // this could probably go above ArtificialBlocks without damage, but
2557e8d8bef9SDimitry Andric   // that then produces output differences from original-live-debug-values,
2558e8d8bef9SDimitry Andric   // which propagates from a single block into many artificial ones.
2559e8d8bef9SDimitry Andric   if (BlocksToExplore.size() == 1)
2560e8d8bef9SDimitry Andric     return;
2561e8d8bef9SDimitry Andric 
2562349cc55cSDimitry Andric   // Convert a const set to a non-const set. LexicalScopes
2563349cc55cSDimitry Andric   // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
2564349cc55cSDimitry Andric   // (Neither of them mutate anything).
2565349cc55cSDimitry Andric   SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
2566349cc55cSDimitry Andric   for (const auto *MBB : BlocksToExplore)
2567349cc55cSDimitry Andric     MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
2568349cc55cSDimitry Andric 
2569e8d8bef9SDimitry Andric   // Picks out relevants blocks RPO order and sort them.
2570e8d8bef9SDimitry Andric   for (auto *MBB : BlocksToExplore)
2571e8d8bef9SDimitry Andric     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2572e8d8bef9SDimitry Andric 
2573e8d8bef9SDimitry Andric   llvm::sort(BlockOrders, Cmp);
2574e8d8bef9SDimitry Andric   unsigned NumBlocks = BlockOrders.size();
2575e8d8bef9SDimitry Andric 
2576e8d8bef9SDimitry Andric   // Allocate some vectors for storing the live ins and live outs. Large.
2577349cc55cSDimitry Andric   SmallVector<DbgValue, 32> LiveIns, LiveOuts;
2578349cc55cSDimitry Andric   LiveIns.reserve(NumBlocks);
2579349cc55cSDimitry Andric   LiveOuts.reserve(NumBlocks);
2580349cc55cSDimitry Andric 
2581349cc55cSDimitry Andric   // Initialize all values to start as NoVals. This signifies "it's live
2582349cc55cSDimitry Andric   // through, but we don't know what it is".
2583349cc55cSDimitry Andric   DbgValueProperties EmptyProperties(EmptyExpr, false);
2584349cc55cSDimitry Andric   for (unsigned int I = 0; I < NumBlocks; ++I) {
2585349cc55cSDimitry Andric     DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2586349cc55cSDimitry Andric     LiveIns.push_back(EmptyDbgValue);
2587349cc55cSDimitry Andric     LiveOuts.push_back(EmptyDbgValue);
2588349cc55cSDimitry Andric   }
2589e8d8bef9SDimitry Andric 
2590e8d8bef9SDimitry Andric   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
2591e8d8bef9SDimitry Andric   // vlocJoin.
2592e8d8bef9SDimitry Andric   LiveIdxT LiveOutIdx, LiveInIdx;
2593e8d8bef9SDimitry Andric   LiveOutIdx.reserve(NumBlocks);
2594e8d8bef9SDimitry Andric   LiveInIdx.reserve(NumBlocks);
2595e8d8bef9SDimitry Andric   for (unsigned I = 0; I < NumBlocks; ++I) {
2596e8d8bef9SDimitry Andric     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
2597e8d8bef9SDimitry Andric     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
2598e8d8bef9SDimitry Andric   }
2599e8d8bef9SDimitry Andric 
2600349cc55cSDimitry Andric   // Loop over each variable and place PHIs for it, then propagate values
2601349cc55cSDimitry Andric   // between blocks. This keeps the locality of working on one lexical scope at
2602349cc55cSDimitry Andric   // at time, but avoids re-processing variable values because some other
2603349cc55cSDimitry Andric   // variable has been assigned.
2604349cc55cSDimitry Andric   for (auto &Var : VarsWeCareAbout) {
2605349cc55cSDimitry Andric     // Re-initialize live-ins and live-outs, to clear the remains of previous
2606349cc55cSDimitry Andric     // variables live-ins / live-outs.
2607349cc55cSDimitry Andric     for (unsigned int I = 0; I < NumBlocks; ++I) {
2608349cc55cSDimitry Andric       DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2609349cc55cSDimitry Andric       LiveIns[I] = EmptyDbgValue;
2610349cc55cSDimitry Andric       LiveOuts[I] = EmptyDbgValue;
2611349cc55cSDimitry Andric     }
2612349cc55cSDimitry Andric 
2613349cc55cSDimitry Andric     // Place PHIs for variable values, using the LLVM IDF calculator.
2614349cc55cSDimitry Andric     // Collect the set of blocks where variables are def'd.
2615349cc55cSDimitry Andric     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2616349cc55cSDimitry Andric     for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
2617349cc55cSDimitry Andric       auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
2618349cc55cSDimitry Andric       if (TransferFunc.find(Var) != TransferFunc.end())
2619349cc55cSDimitry Andric         DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
2620349cc55cSDimitry Andric     }
2621349cc55cSDimitry Andric 
2622349cc55cSDimitry Andric     SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2623349cc55cSDimitry Andric 
2624349cc55cSDimitry Andric     // Request the set of PHIs we should insert for this variable.
2625349cc55cSDimitry Andric     BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
2626349cc55cSDimitry Andric 
2627349cc55cSDimitry Andric     // Insert PHIs into the per-block live-in tables for this variable.
2628349cc55cSDimitry Andric     for (MachineBasicBlock *PHIMBB : PHIBlocks) {
2629349cc55cSDimitry Andric       unsigned BlockNo = PHIMBB->getNumber();
2630349cc55cSDimitry Andric       DbgValue *LiveIn = LiveInIdx[PHIMBB];
2631349cc55cSDimitry Andric       *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
2632349cc55cSDimitry Andric     }
2633349cc55cSDimitry Andric 
2634e8d8bef9SDimitry Andric     for (auto *MBB : BlockOrders) {
2635e8d8bef9SDimitry Andric       Worklist.push(BBToOrder[MBB]);
2636e8d8bef9SDimitry Andric       OnWorklist.insert(MBB);
2637e8d8bef9SDimitry Andric     }
2638e8d8bef9SDimitry Andric 
2639349cc55cSDimitry Andric     // Iterate over all the blocks we selected, propagating the variables value.
2640349cc55cSDimitry Andric     // This loop does two things:
2641349cc55cSDimitry Andric     //  * Eliminates un-necessary VPHIs in vlocJoin,
2642349cc55cSDimitry Andric     //  * Evaluates the blocks transfer function (i.e. variable assignments) and
2643349cc55cSDimitry Andric     //    stores the result to the blocks live-outs.
2644349cc55cSDimitry Andric     // Always evaluate the transfer function on the first iteration, and when
2645349cc55cSDimitry Andric     // the live-ins change thereafter.
2646e8d8bef9SDimitry Andric     bool FirstTrip = true;
2647e8d8bef9SDimitry Andric     while (!Worklist.empty() || !Pending.empty()) {
2648e8d8bef9SDimitry Andric       while (!Worklist.empty()) {
2649e8d8bef9SDimitry Andric         auto *MBB = OrderToBB[Worklist.top()];
2650e8d8bef9SDimitry Andric         CurBB = MBB->getNumber();
2651e8d8bef9SDimitry Andric         Worklist.pop();
2652e8d8bef9SDimitry Andric 
2653349cc55cSDimitry Andric         auto LiveInsIt = LiveInIdx.find(MBB);
2654349cc55cSDimitry Andric         assert(LiveInsIt != LiveInIdx.end());
2655349cc55cSDimitry Andric         DbgValue *LiveIn = LiveInsIt->second;
2656e8d8bef9SDimitry Andric 
2657e8d8bef9SDimitry Andric         // Join values from predecessors. Updates LiveInIdx, and writes output
2658e8d8bef9SDimitry Andric         // into JoinedInLocs.
2659349cc55cSDimitry Andric         bool InLocsChanged =
2660*4824e7fdSDimitry Andric             vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
2661e8d8bef9SDimitry Andric 
2662349cc55cSDimitry Andric         SmallVector<const MachineBasicBlock *, 8> Preds;
2663349cc55cSDimitry Andric         for (const auto *Pred : MBB->predecessors())
2664349cc55cSDimitry Andric           Preds.push_back(Pred);
2665e8d8bef9SDimitry Andric 
2666349cc55cSDimitry Andric         // If this block's live-in value is a VPHI, try to pick a machine-value
2667349cc55cSDimitry Andric         // for it. This makes the machine-value available and propagated
2668349cc55cSDimitry Andric         // through all blocks by the time value propagation finishes. We can't
2669349cc55cSDimitry Andric         // do this any earlier as it needs to read the block live-outs.
2670349cc55cSDimitry Andric         if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
2671349cc55cSDimitry Andric           // There's a small possibility that on a preceeding path, a VPHI is
2672349cc55cSDimitry Andric           // eliminated and transitions from VPHI-with-location to
2673349cc55cSDimitry Andric           // live-through-value. As a result, the selected location of any VPHI
2674349cc55cSDimitry Andric           // might change, so we need to re-compute it on each iteration.
2675349cc55cSDimitry Andric           Optional<ValueIDNum> ValueNum =
2676349cc55cSDimitry Andric               pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds);
2677e8d8bef9SDimitry Andric 
2678349cc55cSDimitry Andric           if (ValueNum) {
2679349cc55cSDimitry Andric             InLocsChanged |= LiveIn->ID != *ValueNum;
2680349cc55cSDimitry Andric             LiveIn->ID = *ValueNum;
2681349cc55cSDimitry Andric           }
2682349cc55cSDimitry Andric         }
2683e8d8bef9SDimitry Andric 
2684349cc55cSDimitry Andric         if (!InLocsChanged && !FirstTrip)
2685e8d8bef9SDimitry Andric           continue;
2686e8d8bef9SDimitry Andric 
2687349cc55cSDimitry Andric         DbgValue *LiveOut = LiveOutIdx[MBB];
2688349cc55cSDimitry Andric         bool OLChanged = false;
2689349cc55cSDimitry Andric 
2690e8d8bef9SDimitry Andric         // Do transfer function.
2691e8d8bef9SDimitry Andric         auto &VTracker = AllTheVLocs[MBB->getNumber()];
2692349cc55cSDimitry Andric         auto TransferIt = VTracker.Vars.find(Var);
2693349cc55cSDimitry Andric         if (TransferIt != VTracker.Vars.end()) {
2694e8d8bef9SDimitry Andric           // Erase on empty transfer (DBG_VALUE $noreg).
2695349cc55cSDimitry Andric           if (TransferIt->second.Kind == DbgValue::Undef) {
2696349cc55cSDimitry Andric             DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
2697349cc55cSDimitry Andric             if (*LiveOut != NewVal) {
2698349cc55cSDimitry Andric               *LiveOut = NewVal;
2699349cc55cSDimitry Andric               OLChanged = true;
2700349cc55cSDimitry Andric             }
2701e8d8bef9SDimitry Andric           } else {
2702e8d8bef9SDimitry Andric             // Insert new variable value; or overwrite.
2703349cc55cSDimitry Andric             if (*LiveOut != TransferIt->second) {
2704349cc55cSDimitry Andric               *LiveOut = TransferIt->second;
2705349cc55cSDimitry Andric               OLChanged = true;
2706e8d8bef9SDimitry Andric             }
2707e8d8bef9SDimitry Andric           }
2708349cc55cSDimitry Andric         } else {
2709349cc55cSDimitry Andric           // Just copy live-ins to live-outs, for anything not transferred.
2710349cc55cSDimitry Andric           if (*LiveOut != *LiveIn) {
2711349cc55cSDimitry Andric             *LiveOut = *LiveIn;
2712349cc55cSDimitry Andric             OLChanged = true;
2713349cc55cSDimitry Andric           }
2714e8d8bef9SDimitry Andric         }
2715e8d8bef9SDimitry Andric 
2716349cc55cSDimitry Andric         // If no live-out value changed, there's no need to explore further.
2717e8d8bef9SDimitry Andric         if (!OLChanged)
2718e8d8bef9SDimitry Andric           continue;
2719e8d8bef9SDimitry Andric 
2720e8d8bef9SDimitry Andric         // We should visit all successors. Ensure we'll visit any non-backedge
2721e8d8bef9SDimitry Andric         // successors during this dataflow iteration; book backedge successors
2722e8d8bef9SDimitry Andric         // to be visited next time around.
2723e8d8bef9SDimitry Andric         for (auto s : MBB->successors()) {
2724e8d8bef9SDimitry Andric           // Ignore out of scope / not-to-be-explored successors.
2725e8d8bef9SDimitry Andric           if (LiveInIdx.find(s) == LiveInIdx.end())
2726e8d8bef9SDimitry Andric             continue;
2727e8d8bef9SDimitry Andric 
2728e8d8bef9SDimitry Andric           if (BBToOrder[s] > BBToOrder[MBB]) {
2729e8d8bef9SDimitry Andric             if (OnWorklist.insert(s).second)
2730e8d8bef9SDimitry Andric               Worklist.push(BBToOrder[s]);
2731e8d8bef9SDimitry Andric           } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
2732e8d8bef9SDimitry Andric             Pending.push(BBToOrder[s]);
2733e8d8bef9SDimitry Andric           }
2734e8d8bef9SDimitry Andric         }
2735e8d8bef9SDimitry Andric       }
2736e8d8bef9SDimitry Andric       Worklist.swap(Pending);
2737e8d8bef9SDimitry Andric       std::swap(OnWorklist, OnPending);
2738e8d8bef9SDimitry Andric       OnPending.clear();
2739e8d8bef9SDimitry Andric       assert(Pending.empty());
2740e8d8bef9SDimitry Andric       FirstTrip = false;
2741e8d8bef9SDimitry Andric     }
2742e8d8bef9SDimitry Andric 
2743349cc55cSDimitry Andric     // Save live-ins to output vector. Ignore any that are still marked as being
2744349cc55cSDimitry Andric     // VPHIs with no location -- those are variables that we know the value of,
2745349cc55cSDimitry Andric     // but are not actually available in the register file.
2746e8d8bef9SDimitry Andric     for (auto *MBB : BlockOrders) {
2747349cc55cSDimitry Andric       DbgValue *BlockLiveIn = LiveInIdx[MBB];
2748349cc55cSDimitry Andric       if (BlockLiveIn->Kind == DbgValue::NoVal)
2749e8d8bef9SDimitry Andric         continue;
2750349cc55cSDimitry Andric       if (BlockLiveIn->Kind == DbgValue::VPHI &&
2751349cc55cSDimitry Andric           BlockLiveIn->ID == ValueIDNum::EmptyValue)
2752349cc55cSDimitry Andric         continue;
2753349cc55cSDimitry Andric       if (BlockLiveIn->Kind == DbgValue::VPHI)
2754349cc55cSDimitry Andric         BlockLiveIn->Kind = DbgValue::Def;
2755*4824e7fdSDimitry Andric       assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
2756*4824e7fdSDimitry Andric              Var.getFragment() && "Fragment info missing during value prop");
2757349cc55cSDimitry Andric       Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
2758e8d8bef9SDimitry Andric     }
2759349cc55cSDimitry Andric   } // Per-variable loop.
2760e8d8bef9SDimitry Andric 
2761e8d8bef9SDimitry Andric   BlockOrders.clear();
2762e8d8bef9SDimitry Andric   BlocksToExplore.clear();
2763e8d8bef9SDimitry Andric }
2764e8d8bef9SDimitry Andric 
2765e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2766e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer(
2767e8d8bef9SDimitry Andric     const MLocTransferMap &mloc_transfer) const {
2768e8d8bef9SDimitry Andric   for (auto &P : mloc_transfer) {
2769e8d8bef9SDimitry Andric     std::string foo = MTracker->LocIdxToName(P.first);
2770e8d8bef9SDimitry Andric     std::string bar = MTracker->IDAsString(P.second);
2771e8d8bef9SDimitry Andric     dbgs() << "Loc " << foo << " --> " << bar << "\n";
2772e8d8bef9SDimitry Andric   }
2773e8d8bef9SDimitry Andric }
2774e8d8bef9SDimitry Andric #endif
2775e8d8bef9SDimitry Andric 
2776e8d8bef9SDimitry Andric void InstrRefBasedLDV::emitLocations(
2777fe6060f1SDimitry Andric     MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MOutLocs,
2778fe6060f1SDimitry Andric     ValueIDNum **MInLocs, DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
2779fe6060f1SDimitry Andric     const TargetPassConfig &TPC) {
2780fe6060f1SDimitry Andric   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
2781e8d8bef9SDimitry Andric   unsigned NumLocs = MTracker->getNumLocs();
2782e8d8bef9SDimitry Andric 
2783e8d8bef9SDimitry Andric   // For each block, load in the machine value locations and variable value
2784e8d8bef9SDimitry Andric   // live-ins, then step through each instruction in the block. New DBG_VALUEs
2785e8d8bef9SDimitry Andric   // to be inserted will be created along the way.
2786e8d8bef9SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
2787e8d8bef9SDimitry Andric     unsigned bbnum = MBB.getNumber();
2788e8d8bef9SDimitry Andric     MTracker->reset();
2789e8d8bef9SDimitry Andric     MTracker->loadFromArray(MInLocs[bbnum], bbnum);
2790e8d8bef9SDimitry Andric     TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()],
2791e8d8bef9SDimitry Andric                          NumLocs);
2792e8d8bef9SDimitry Andric 
2793e8d8bef9SDimitry Andric     CurBB = bbnum;
2794e8d8bef9SDimitry Andric     CurInst = 1;
2795e8d8bef9SDimitry Andric     for (auto &MI : MBB) {
2796fe6060f1SDimitry Andric       process(MI, MOutLocs, MInLocs);
2797e8d8bef9SDimitry Andric       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
2798e8d8bef9SDimitry Andric       ++CurInst;
2799e8d8bef9SDimitry Andric     }
2800e8d8bef9SDimitry Andric   }
2801e8d8bef9SDimitry Andric 
2802e8d8bef9SDimitry Andric   // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer
2803e8d8bef9SDimitry Andric   // in DWARF in different orders. Use the order that they appear when walking
2804e8d8bef9SDimitry Andric   // through each block / each instruction, stored in AllVarsNumbering.
2805e8d8bef9SDimitry Andric   auto OrderDbgValues = [&](const MachineInstr *A,
2806e8d8bef9SDimitry Andric                             const MachineInstr *B) -> bool {
2807e8d8bef9SDimitry Andric     DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(),
2808e8d8bef9SDimitry Andric                        A->getDebugLoc()->getInlinedAt());
2809e8d8bef9SDimitry Andric     DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(),
2810e8d8bef9SDimitry Andric                        B->getDebugLoc()->getInlinedAt());
2811e8d8bef9SDimitry Andric     return AllVarsNumbering.find(VarA)->second <
2812e8d8bef9SDimitry Andric            AllVarsNumbering.find(VarB)->second;
2813e8d8bef9SDimitry Andric   };
2814e8d8bef9SDimitry Andric 
2815e8d8bef9SDimitry Andric   // Go through all the transfers recorded in the TransferTracker -- this is
2816e8d8bef9SDimitry Andric   // both the live-ins to a block, and any movements of values that happen
2817e8d8bef9SDimitry Andric   // in the middle.
2818e8d8bef9SDimitry Andric   for (auto &P : TTracker->Transfers) {
2819e8d8bef9SDimitry Andric     // Sort them according to appearance order.
2820e8d8bef9SDimitry Andric     llvm::sort(P.Insts, OrderDbgValues);
2821e8d8bef9SDimitry Andric     // Insert either before or after the designated point...
2822e8d8bef9SDimitry Andric     if (P.MBB) {
2823e8d8bef9SDimitry Andric       MachineBasicBlock &MBB = *P.MBB;
2824e8d8bef9SDimitry Andric       for (auto *MI : P.Insts) {
2825e8d8bef9SDimitry Andric         MBB.insert(P.Pos, MI);
2826e8d8bef9SDimitry Andric       }
2827e8d8bef9SDimitry Andric     } else {
2828fe6060f1SDimitry Andric       // Terminators, like tail calls, can clobber things. Don't try and place
2829fe6060f1SDimitry Andric       // transfers after them.
2830fe6060f1SDimitry Andric       if (P.Pos->isTerminator())
2831fe6060f1SDimitry Andric         continue;
2832fe6060f1SDimitry Andric 
2833e8d8bef9SDimitry Andric       MachineBasicBlock &MBB = *P.Pos->getParent();
2834e8d8bef9SDimitry Andric       for (auto *MI : P.Insts) {
2835fe6060f1SDimitry Andric         MBB.insertAfterBundle(P.Pos, MI);
2836e8d8bef9SDimitry Andric       }
2837e8d8bef9SDimitry Andric     }
2838e8d8bef9SDimitry Andric   }
2839e8d8bef9SDimitry Andric }
2840e8d8bef9SDimitry Andric 
2841e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
2842e8d8bef9SDimitry Andric   // Build some useful data structures.
2843349cc55cSDimitry Andric 
2844349cc55cSDimitry Andric   LLVMContext &Context = MF.getFunction().getContext();
2845349cc55cSDimitry Andric   EmptyExpr = DIExpression::get(Context, {});
2846349cc55cSDimitry Andric 
2847e8d8bef9SDimitry Andric   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2848e8d8bef9SDimitry Andric     if (const DebugLoc &DL = MI.getDebugLoc())
2849e8d8bef9SDimitry Andric       return DL.getLine() != 0;
2850e8d8bef9SDimitry Andric     return false;
2851e8d8bef9SDimitry Andric   };
2852e8d8bef9SDimitry Andric   // Collect a set of all the artificial blocks.
2853e8d8bef9SDimitry Andric   for (auto &MBB : MF)
2854e8d8bef9SDimitry Andric     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2855e8d8bef9SDimitry Andric       ArtificialBlocks.insert(&MBB);
2856e8d8bef9SDimitry Andric 
2857e8d8bef9SDimitry Andric   // Compute mappings of block <=> RPO order.
2858e8d8bef9SDimitry Andric   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2859e8d8bef9SDimitry Andric   unsigned int RPONumber = 0;
2860fe6060f1SDimitry Andric   for (MachineBasicBlock *MBB : RPOT) {
2861fe6060f1SDimitry Andric     OrderToBB[RPONumber] = MBB;
2862fe6060f1SDimitry Andric     BBToOrder[MBB] = RPONumber;
2863fe6060f1SDimitry Andric     BBNumToRPO[MBB->getNumber()] = RPONumber;
2864e8d8bef9SDimitry Andric     ++RPONumber;
2865e8d8bef9SDimitry Andric   }
2866fe6060f1SDimitry Andric 
2867fe6060f1SDimitry Andric   // Order value substitutions by their "source" operand pair, for quick lookup.
2868fe6060f1SDimitry Andric   llvm::sort(MF.DebugValueSubstitutions);
2869fe6060f1SDimitry Andric 
2870fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS
2871fe6060f1SDimitry Andric   // As an expensive check, test whether there are any duplicate substitution
2872fe6060f1SDimitry Andric   // sources in the collection.
2873fe6060f1SDimitry Andric   if (MF.DebugValueSubstitutions.size() > 2) {
2874fe6060f1SDimitry Andric     for (auto It = MF.DebugValueSubstitutions.begin();
2875fe6060f1SDimitry Andric          It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
2876fe6060f1SDimitry Andric       assert(It->Src != std::next(It)->Src && "Duplicate variable location "
2877fe6060f1SDimitry Andric                                               "substitution seen");
2878fe6060f1SDimitry Andric     }
2879fe6060f1SDimitry Andric   }
2880fe6060f1SDimitry Andric #endif
2881e8d8bef9SDimitry Andric }
2882e8d8bef9SDimitry Andric 
2883e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and
2884e8d8bef9SDimitry Andric /// extend ranges across basic blocks.
2885e8d8bef9SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
2886349cc55cSDimitry Andric                                     MachineDominatorTree *DomTree,
2887349cc55cSDimitry Andric                                     TargetPassConfig *TPC,
2888349cc55cSDimitry Andric                                     unsigned InputBBLimit,
2889349cc55cSDimitry Andric                                     unsigned InputDbgValLimit) {
2890e8d8bef9SDimitry Andric   // No subprogram means this function contains no debuginfo.
2891e8d8bef9SDimitry Andric   if (!MF.getFunction().getSubprogram())
2892e8d8bef9SDimitry Andric     return false;
2893e8d8bef9SDimitry Andric 
2894e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
2895e8d8bef9SDimitry Andric   this->TPC = TPC;
2896e8d8bef9SDimitry Andric 
2897349cc55cSDimitry Andric   this->DomTree = DomTree;
2898e8d8bef9SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
2899349cc55cSDimitry Andric   MRI = &MF.getRegInfo();
2900e8d8bef9SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
2901e8d8bef9SDimitry Andric   TFI = MF.getSubtarget().getFrameLowering();
2902e8d8bef9SDimitry Andric   TFI->getCalleeSaves(MF, CalleeSavedRegs);
2903fe6060f1SDimitry Andric   MFI = &MF.getFrameInfo();
2904e8d8bef9SDimitry Andric   LS.initialize(MF);
2905e8d8bef9SDimitry Andric 
2906*4824e7fdSDimitry Andric   const auto &STI = MF.getSubtarget();
2907*4824e7fdSDimitry Andric   AdjustsStackInCalls = MFI->adjustsStack() &&
2908*4824e7fdSDimitry Andric                         STI.getFrameLowering()->stackProbeFunctionModifiesSP();
2909*4824e7fdSDimitry Andric   if (AdjustsStackInCalls)
2910*4824e7fdSDimitry Andric     StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
2911*4824e7fdSDimitry Andric 
2912e8d8bef9SDimitry Andric   MTracker =
2913e8d8bef9SDimitry Andric       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
2914e8d8bef9SDimitry Andric   VTracker = nullptr;
2915e8d8bef9SDimitry Andric   TTracker = nullptr;
2916e8d8bef9SDimitry Andric 
2917e8d8bef9SDimitry Andric   SmallVector<MLocTransferMap, 32> MLocTransfer;
2918e8d8bef9SDimitry Andric   SmallVector<VLocTracker, 8> vlocs;
2919e8d8bef9SDimitry Andric   LiveInsT SavedLiveIns;
2920e8d8bef9SDimitry Andric 
2921e8d8bef9SDimitry Andric   int MaxNumBlocks = -1;
2922e8d8bef9SDimitry Andric   for (auto &MBB : MF)
2923e8d8bef9SDimitry Andric     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
2924e8d8bef9SDimitry Andric   assert(MaxNumBlocks >= 0);
2925e8d8bef9SDimitry Andric   ++MaxNumBlocks;
2926e8d8bef9SDimitry Andric 
2927e8d8bef9SDimitry Andric   MLocTransfer.resize(MaxNumBlocks);
2928*4824e7fdSDimitry Andric   vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr));
2929e8d8bef9SDimitry Andric   SavedLiveIns.resize(MaxNumBlocks);
2930e8d8bef9SDimitry Andric 
2931e8d8bef9SDimitry Andric   initialSetup(MF);
2932e8d8bef9SDimitry Andric 
2933e8d8bef9SDimitry Andric   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
2934e8d8bef9SDimitry Andric 
2935e8d8bef9SDimitry Andric   // Allocate and initialize two array-of-arrays for the live-in and live-out
2936e8d8bef9SDimitry Andric   // machine values. The outer dimension is the block number; while the inner
2937e8d8bef9SDimitry Andric   // dimension is a LocIdx from MLocTracker.
2938e8d8bef9SDimitry Andric   ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks];
2939e8d8bef9SDimitry Andric   ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks];
2940e8d8bef9SDimitry Andric   unsigned NumLocs = MTracker->getNumLocs();
2941e8d8bef9SDimitry Andric   for (int i = 0; i < MaxNumBlocks; ++i) {
2942349cc55cSDimitry Andric     // These all auto-initialize to ValueIDNum::EmptyValue
2943e8d8bef9SDimitry Andric     MOutLocs[i] = new ValueIDNum[NumLocs];
2944e8d8bef9SDimitry Andric     MInLocs[i] = new ValueIDNum[NumLocs];
2945e8d8bef9SDimitry Andric   }
2946e8d8bef9SDimitry Andric 
2947e8d8bef9SDimitry Andric   // Solve the machine value dataflow problem using the MLocTransfer function,
2948e8d8bef9SDimitry Andric   // storing the computed live-ins / live-outs into the array-of-arrays. We use
2949e8d8bef9SDimitry Andric   // both live-ins and live-outs for decision making in the variable value
2950e8d8bef9SDimitry Andric   // dataflow problem.
2951349cc55cSDimitry Andric   buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
2952e8d8bef9SDimitry Andric 
2953fe6060f1SDimitry Andric   // Patch up debug phi numbers, turning unknown block-live-in values into
2954fe6060f1SDimitry Andric   // either live-through machine values, or PHIs.
2955fe6060f1SDimitry Andric   for (auto &DBG_PHI : DebugPHINumToValue) {
2956fe6060f1SDimitry Andric     // Identify unresolved block-live-ins.
2957fe6060f1SDimitry Andric     ValueIDNum &Num = DBG_PHI.ValueRead;
2958fe6060f1SDimitry Andric     if (!Num.isPHI())
2959fe6060f1SDimitry Andric       continue;
2960fe6060f1SDimitry Andric 
2961fe6060f1SDimitry Andric     unsigned BlockNo = Num.getBlock();
2962fe6060f1SDimitry Andric     LocIdx LocNo = Num.getLoc();
2963fe6060f1SDimitry Andric     Num = MInLocs[BlockNo][LocNo.asU64()];
2964fe6060f1SDimitry Andric   }
2965fe6060f1SDimitry Andric   // Later, we'll be looking up ranges of instruction numbers.
2966fe6060f1SDimitry Andric   llvm::sort(DebugPHINumToValue);
2967fe6060f1SDimitry Andric 
2968e8d8bef9SDimitry Andric   // Walk back through each block / instruction, collecting DBG_VALUE
2969e8d8bef9SDimitry Andric   // instructions and recording what machine value their operands refer to.
2970e8d8bef9SDimitry Andric   for (auto &OrderPair : OrderToBB) {
2971e8d8bef9SDimitry Andric     MachineBasicBlock &MBB = *OrderPair.second;
2972e8d8bef9SDimitry Andric     CurBB = MBB.getNumber();
2973e8d8bef9SDimitry Andric     VTracker = &vlocs[CurBB];
2974e8d8bef9SDimitry Andric     VTracker->MBB = &MBB;
2975e8d8bef9SDimitry Andric     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2976e8d8bef9SDimitry Andric     CurInst = 1;
2977e8d8bef9SDimitry Andric     for (auto &MI : MBB) {
2978fe6060f1SDimitry Andric       process(MI, MOutLocs, MInLocs);
2979e8d8bef9SDimitry Andric       ++CurInst;
2980e8d8bef9SDimitry Andric     }
2981e8d8bef9SDimitry Andric     MTracker->reset();
2982e8d8bef9SDimitry Andric   }
2983e8d8bef9SDimitry Andric 
2984e8d8bef9SDimitry Andric   // Number all variables in the order that they appear, to be used as a stable
2985e8d8bef9SDimitry Andric   // insertion order later.
2986e8d8bef9SDimitry Andric   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
2987e8d8bef9SDimitry Andric 
2988e8d8bef9SDimitry Andric   // Map from one LexicalScope to all the variables in that scope.
2989e8d8bef9SDimitry Andric   DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars;
2990e8d8bef9SDimitry Andric 
2991e8d8bef9SDimitry Andric   // Map from One lexical scope to all blocks in that scope.
2992e8d8bef9SDimitry Andric   DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>
2993e8d8bef9SDimitry Andric       ScopeToBlocks;
2994e8d8bef9SDimitry Andric 
2995e8d8bef9SDimitry Andric   // Store a DILocation that describes a scope.
2996e8d8bef9SDimitry Andric   DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation;
2997e8d8bef9SDimitry Andric 
2998e8d8bef9SDimitry Andric   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
2999e8d8bef9SDimitry Andric   // the order is unimportant, it just has to be stable.
3000349cc55cSDimitry Andric   unsigned VarAssignCount = 0;
3001e8d8bef9SDimitry Andric   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3002e8d8bef9SDimitry Andric     auto *MBB = OrderToBB[I];
3003e8d8bef9SDimitry Andric     auto *VTracker = &vlocs[MBB->getNumber()];
3004e8d8bef9SDimitry Andric     // Collect each variable with a DBG_VALUE in this block.
3005e8d8bef9SDimitry Andric     for (auto &idx : VTracker->Vars) {
3006e8d8bef9SDimitry Andric       const auto &Var = idx.first;
3007e8d8bef9SDimitry Andric       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3008e8d8bef9SDimitry Andric       assert(ScopeLoc != nullptr);
3009e8d8bef9SDimitry Andric       auto *Scope = LS.findLexicalScope(ScopeLoc);
3010e8d8bef9SDimitry Andric 
3011e8d8bef9SDimitry Andric       // No insts in scope -> shouldn't have been recorded.
3012e8d8bef9SDimitry Andric       assert(Scope != nullptr);
3013e8d8bef9SDimitry Andric 
3014e8d8bef9SDimitry Andric       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3015e8d8bef9SDimitry Andric       ScopeToVars[Scope].insert(Var);
3016e8d8bef9SDimitry Andric       ScopeToBlocks[Scope].insert(VTracker->MBB);
3017e8d8bef9SDimitry Andric       ScopeToDILocation[Scope] = ScopeLoc;
3018349cc55cSDimitry Andric       ++VarAssignCount;
3019e8d8bef9SDimitry Andric     }
3020e8d8bef9SDimitry Andric   }
3021e8d8bef9SDimitry Andric 
3022349cc55cSDimitry Andric   bool Changed = false;
3023349cc55cSDimitry Andric 
3024349cc55cSDimitry Andric   // If we have an extremely large number of variable assignments and blocks,
3025349cc55cSDimitry Andric   // bail out at this point. We've burnt some time doing analysis already,
3026349cc55cSDimitry Andric   // however we should cut our losses.
3027349cc55cSDimitry Andric   if ((unsigned)MaxNumBlocks > InputBBLimit &&
3028349cc55cSDimitry Andric       VarAssignCount > InputDbgValLimit) {
3029349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3030349cc55cSDimitry Andric                       << " has " << MaxNumBlocks << " basic blocks and "
3031349cc55cSDimitry Andric                       << VarAssignCount
3032349cc55cSDimitry Andric                       << " variable assignments, exceeding limits.\n");
3033349cc55cSDimitry Andric   } else {
3034349cc55cSDimitry Andric     // Compute the extended ranges, iterating over scopes. There might be
3035349cc55cSDimitry Andric     // something to be said for ordering them by size/locality, but that's for
3036349cc55cSDimitry Andric     // the future. For each scope, solve the variable value problem, producing
3037349cc55cSDimitry Andric     // a map of variables to values in SavedLiveIns.
3038e8d8bef9SDimitry Andric     for (auto &P : ScopeToVars) {
3039349cc55cSDimitry Andric       buildVLocValueMap(ScopeToDILocation[P.first], P.second,
3040e8d8bef9SDimitry Andric                    ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs,
3041e8d8bef9SDimitry Andric                    vlocs);
3042e8d8bef9SDimitry Andric     }
3043e8d8bef9SDimitry Andric 
3044e8d8bef9SDimitry Andric     // Using the computed value locations and variable values for each block,
3045e8d8bef9SDimitry Andric     // create the DBG_VALUE instructions representing the extended variable
3046e8d8bef9SDimitry Andric     // locations.
3047fe6060f1SDimitry Andric     emitLocations(MF, SavedLiveIns, MOutLocs, MInLocs, AllVarsNumbering, *TPC);
3048e8d8bef9SDimitry Andric 
3049349cc55cSDimitry Andric     // Did we actually make any changes? If we created any DBG_VALUEs, then yes.
3050349cc55cSDimitry Andric     Changed = TTracker->Transfers.size() != 0;
3051349cc55cSDimitry Andric   }
3052349cc55cSDimitry Andric 
3053349cc55cSDimitry Andric   // Common clean-up of memory.
3054e8d8bef9SDimitry Andric   for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) {
3055e8d8bef9SDimitry Andric     delete[] MOutLocs[Idx];
3056e8d8bef9SDimitry Andric     delete[] MInLocs[Idx];
3057e8d8bef9SDimitry Andric   }
3058e8d8bef9SDimitry Andric   delete[] MOutLocs;
3059e8d8bef9SDimitry Andric   delete[] MInLocs;
3060e8d8bef9SDimitry Andric 
3061e8d8bef9SDimitry Andric   delete MTracker;
3062e8d8bef9SDimitry Andric   delete TTracker;
3063e8d8bef9SDimitry Andric   MTracker = nullptr;
3064e8d8bef9SDimitry Andric   VTracker = nullptr;
3065e8d8bef9SDimitry Andric   TTracker = nullptr;
3066e8d8bef9SDimitry Andric 
3067e8d8bef9SDimitry Andric   ArtificialBlocks.clear();
3068e8d8bef9SDimitry Andric   OrderToBB.clear();
3069e8d8bef9SDimitry Andric   BBToOrder.clear();
3070e8d8bef9SDimitry Andric   BBNumToRPO.clear();
3071e8d8bef9SDimitry Andric   DebugInstrNumToInstr.clear();
3072fe6060f1SDimitry Andric   DebugPHINumToValue.clear();
3073*4824e7fdSDimitry Andric   OverlapFragments.clear();
3074*4824e7fdSDimitry Andric   SeenFragments.clear();
3075e8d8bef9SDimitry Andric 
3076e8d8bef9SDimitry Andric   return Changed;
3077e8d8bef9SDimitry Andric }
3078e8d8bef9SDimitry Andric 
3079e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3080e8d8bef9SDimitry Andric   return new InstrRefBasedLDV();
3081e8d8bef9SDimitry Andric }
3082fe6060f1SDimitry Andric 
3083fe6060f1SDimitry Andric namespace {
3084fe6060f1SDimitry Andric class LDVSSABlock;
3085fe6060f1SDimitry Andric class LDVSSAUpdater;
3086fe6060f1SDimitry Andric 
3087fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We
3088fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater
3089fe6060f1SDimitry Andric // expects to zero-initialize the type.
3090fe6060f1SDimitry Andric typedef uint64_t BlockValueNum;
3091fe6060f1SDimitry Andric 
3092fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block
3093fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming
3094fe6060f1SDimitry Andric /// values from parent blocks.
3095fe6060f1SDimitry Andric class LDVSSAPhi {
3096fe6060f1SDimitry Andric public:
3097fe6060f1SDimitry Andric   SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3098fe6060f1SDimitry Andric   LDVSSABlock *ParentBlock;
3099fe6060f1SDimitry Andric   BlockValueNum PHIValNum;
3100fe6060f1SDimitry Andric   LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3101fe6060f1SDimitry Andric       : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3102fe6060f1SDimitry Andric 
3103fe6060f1SDimitry Andric   LDVSSABlock *getParent() { return ParentBlock; }
3104fe6060f1SDimitry Andric };
3105fe6060f1SDimitry Andric 
3106fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a
3107fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock.
3108fe6060f1SDimitry Andric class LDVSSABlockIterator {
3109fe6060f1SDimitry Andric public:
3110fe6060f1SDimitry Andric   MachineBasicBlock::pred_iterator PredIt;
3111fe6060f1SDimitry Andric   LDVSSAUpdater &Updater;
3112fe6060f1SDimitry Andric 
3113fe6060f1SDimitry Andric   LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3114fe6060f1SDimitry Andric                       LDVSSAUpdater &Updater)
3115fe6060f1SDimitry Andric       : PredIt(PredIt), Updater(Updater) {}
3116fe6060f1SDimitry Andric 
3117fe6060f1SDimitry Andric   bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3118fe6060f1SDimitry Andric     return OtherIt.PredIt != PredIt;
3119fe6060f1SDimitry Andric   }
3120fe6060f1SDimitry Andric 
3121fe6060f1SDimitry Andric   LDVSSABlockIterator &operator++() {
3122fe6060f1SDimitry Andric     ++PredIt;
3123fe6060f1SDimitry Andric     return *this;
3124fe6060f1SDimitry Andric   }
3125fe6060f1SDimitry Andric 
3126fe6060f1SDimitry Andric   LDVSSABlock *operator*();
3127fe6060f1SDimitry Andric };
3128fe6060f1SDimitry Andric 
3129fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because
3130fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary
3131fe6060f1SDimitry Andric /// in this block.
3132fe6060f1SDimitry Andric class LDVSSABlock {
3133fe6060f1SDimitry Andric public:
3134fe6060f1SDimitry Andric   MachineBasicBlock &BB;
3135fe6060f1SDimitry Andric   LDVSSAUpdater &Updater;
3136fe6060f1SDimitry Andric   using PHIListT = SmallVector<LDVSSAPhi, 1>;
3137fe6060f1SDimitry Andric   /// List of PHIs in this block. There should only ever be one.
3138fe6060f1SDimitry Andric   PHIListT PHIList;
3139fe6060f1SDimitry Andric 
3140fe6060f1SDimitry Andric   LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3141fe6060f1SDimitry Andric       : BB(BB), Updater(Updater) {}
3142fe6060f1SDimitry Andric 
3143fe6060f1SDimitry Andric   LDVSSABlockIterator succ_begin() {
3144fe6060f1SDimitry Andric     return LDVSSABlockIterator(BB.succ_begin(), Updater);
3145fe6060f1SDimitry Andric   }
3146fe6060f1SDimitry Andric 
3147fe6060f1SDimitry Andric   LDVSSABlockIterator succ_end() {
3148fe6060f1SDimitry Andric     return LDVSSABlockIterator(BB.succ_end(), Updater);
3149fe6060f1SDimitry Andric   }
3150fe6060f1SDimitry Andric 
3151fe6060f1SDimitry Andric   /// SSAUpdater has requested a PHI: create that within this block record.
3152fe6060f1SDimitry Andric   LDVSSAPhi *newPHI(BlockValueNum Value) {
3153fe6060f1SDimitry Andric     PHIList.emplace_back(Value, this);
3154fe6060f1SDimitry Andric     return &PHIList.back();
3155fe6060f1SDimitry Andric   }
3156fe6060f1SDimitry Andric 
3157fe6060f1SDimitry Andric   /// SSAUpdater wishes to know what PHIs already exist in this block.
3158fe6060f1SDimitry Andric   PHIListT &phis() { return PHIList; }
3159fe6060f1SDimitry Andric };
3160fe6060f1SDimitry Andric 
3161fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3162fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3163fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>.
3164fe6060f1SDimitry Andric class LDVSSAUpdater {
3165fe6060f1SDimitry Andric public:
3166fe6060f1SDimitry Andric   /// Map of value numbers to PHI records.
3167fe6060f1SDimitry Andric   DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3168fe6060f1SDimitry Andric   /// Map of which blocks generate Undef values -- blocks that are not
3169fe6060f1SDimitry Andric   /// dominated by any Def.
3170fe6060f1SDimitry Andric   DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3171fe6060f1SDimitry Andric   /// Map of machine blocks to our own records of them.
3172fe6060f1SDimitry Andric   DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3173fe6060f1SDimitry Andric   /// Machine location where any PHI must occur.
3174fe6060f1SDimitry Andric   LocIdx Loc;
3175fe6060f1SDimitry Andric   /// Table of live-in machine value numbers for blocks / locations.
3176fe6060f1SDimitry Andric   ValueIDNum **MLiveIns;
3177fe6060f1SDimitry Andric 
3178fe6060f1SDimitry Andric   LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {}
3179fe6060f1SDimitry Andric 
3180fe6060f1SDimitry Andric   void reset() {
3181fe6060f1SDimitry Andric     for (auto &Block : BlockMap)
3182fe6060f1SDimitry Andric       delete Block.second;
3183fe6060f1SDimitry Andric 
3184fe6060f1SDimitry Andric     PHIs.clear();
3185fe6060f1SDimitry Andric     UndefMap.clear();
3186fe6060f1SDimitry Andric     BlockMap.clear();
3187fe6060f1SDimitry Andric   }
3188fe6060f1SDimitry Andric 
3189fe6060f1SDimitry Andric   ~LDVSSAUpdater() { reset(); }
3190fe6060f1SDimitry Andric 
3191fe6060f1SDimitry Andric   /// For a given MBB, create a wrapper block for it. Stores it in the
3192fe6060f1SDimitry Andric   /// LDVSSAUpdater block map.
3193fe6060f1SDimitry Andric   LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3194fe6060f1SDimitry Andric     auto it = BlockMap.find(BB);
3195fe6060f1SDimitry Andric     if (it == BlockMap.end()) {
3196fe6060f1SDimitry Andric       BlockMap[BB] = new LDVSSABlock(*BB, *this);
3197fe6060f1SDimitry Andric       it = BlockMap.find(BB);
3198fe6060f1SDimitry Andric     }
3199fe6060f1SDimitry Andric     return it->second;
3200fe6060f1SDimitry Andric   }
3201fe6060f1SDimitry Andric 
3202fe6060f1SDimitry Andric   /// Find the live-in value number for the given block. Looks up the value at
3203fe6060f1SDimitry Andric   /// the PHI location on entry.
3204fe6060f1SDimitry Andric   BlockValueNum getValue(LDVSSABlock *LDVBB) {
3205fe6060f1SDimitry Andric     return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3206fe6060f1SDimitry Andric   }
3207fe6060f1SDimitry Andric };
3208fe6060f1SDimitry Andric 
3209fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() {
3210fe6060f1SDimitry Andric   return Updater.getSSALDVBlock(*PredIt);
3211fe6060f1SDimitry Andric }
3212fe6060f1SDimitry Andric 
3213fe6060f1SDimitry Andric #ifndef NDEBUG
3214fe6060f1SDimitry Andric 
3215fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3216fe6060f1SDimitry Andric   out << "SSALDVPHI " << PHI.PHIValNum;
3217fe6060f1SDimitry Andric   return out;
3218fe6060f1SDimitry Andric }
3219fe6060f1SDimitry Andric 
3220fe6060f1SDimitry Andric #endif
3221fe6060f1SDimitry Andric 
3222fe6060f1SDimitry Andric } // namespace
3223fe6060f1SDimitry Andric 
3224fe6060f1SDimitry Andric namespace llvm {
3225fe6060f1SDimitry Andric 
3226fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value
3227fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the
3228fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define.
3229fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them.
3230fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3231fe6060f1SDimitry Andric public:
3232fe6060f1SDimitry Andric   using BlkT = LDVSSABlock;
3233fe6060f1SDimitry Andric   using ValT = BlockValueNum;
3234fe6060f1SDimitry Andric   using PhiT = LDVSSAPhi;
3235fe6060f1SDimitry Andric   using BlkSucc_iterator = LDVSSABlockIterator;
3236fe6060f1SDimitry Andric 
3237fe6060f1SDimitry Andric   // Methods to access block successors -- dereferencing to our wrapper class.
3238fe6060f1SDimitry Andric   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
3239fe6060f1SDimitry Andric   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3240fe6060f1SDimitry Andric 
3241fe6060f1SDimitry Andric   /// Iterator for PHI operands.
3242fe6060f1SDimitry Andric   class PHI_iterator {
3243fe6060f1SDimitry Andric   private:
3244fe6060f1SDimitry Andric     LDVSSAPhi *PHI;
3245fe6060f1SDimitry Andric     unsigned Idx;
3246fe6060f1SDimitry Andric 
3247fe6060f1SDimitry Andric   public:
3248fe6060f1SDimitry Andric     explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3249fe6060f1SDimitry Andric         : PHI(P), Idx(0) {}
3250fe6060f1SDimitry Andric     PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3251fe6060f1SDimitry Andric         : PHI(P), Idx(PHI->IncomingValues.size()) {}
3252fe6060f1SDimitry Andric 
3253fe6060f1SDimitry Andric     PHI_iterator &operator++() {
3254fe6060f1SDimitry Andric       Idx++;
3255fe6060f1SDimitry Andric       return *this;
3256fe6060f1SDimitry Andric     }
3257fe6060f1SDimitry Andric     bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
3258fe6060f1SDimitry Andric     bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3259fe6060f1SDimitry Andric 
3260fe6060f1SDimitry Andric     BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
3261fe6060f1SDimitry Andric 
3262fe6060f1SDimitry Andric     LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
3263fe6060f1SDimitry Andric   };
3264fe6060f1SDimitry Andric 
3265fe6060f1SDimitry Andric   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
3266fe6060f1SDimitry Andric 
3267fe6060f1SDimitry Andric   static inline PHI_iterator PHI_end(PhiT *PHI) {
3268fe6060f1SDimitry Andric     return PHI_iterator(PHI, true);
3269fe6060f1SDimitry Andric   }
3270fe6060f1SDimitry Andric 
3271fe6060f1SDimitry Andric   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
3272fe6060f1SDimitry Andric   /// vector.
3273fe6060f1SDimitry Andric   static void FindPredecessorBlocks(LDVSSABlock *BB,
3274fe6060f1SDimitry Andric                                     SmallVectorImpl<LDVSSABlock *> *Preds) {
3275349cc55cSDimitry Andric     for (MachineBasicBlock *Pred : BB->BB.predecessors())
3276349cc55cSDimitry Andric       Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
3277fe6060f1SDimitry Andric   }
3278fe6060f1SDimitry Andric 
3279fe6060f1SDimitry Andric   /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
3280fe6060f1SDimitry Andric   /// register. For LiveDebugValues, represents a block identified as not having
3281fe6060f1SDimitry Andric   /// any DBG_PHI predecessors.
3282fe6060f1SDimitry Andric   static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
3283fe6060f1SDimitry Andric     // Create a value number for this block -- it needs to be unique and in the
3284fe6060f1SDimitry Andric     // "undef" collection, so that we know it's not real. Use a number
3285fe6060f1SDimitry Andric     // representing a PHI into this block.
3286fe6060f1SDimitry Andric     BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
3287fe6060f1SDimitry Andric     Updater->UndefMap[&BB->BB] = Num;
3288fe6060f1SDimitry Andric     return Num;
3289fe6060f1SDimitry Andric   }
3290fe6060f1SDimitry Andric 
3291fe6060f1SDimitry Andric   /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
3292fe6060f1SDimitry Andric   /// SSAUpdater will populate it with information about incoming values. The
3293fe6060f1SDimitry Andric   /// value number of this PHI is whatever the  machine value number problem
3294fe6060f1SDimitry Andric   /// solution determined it to be. This includes non-phi values if SSAUpdater
3295fe6060f1SDimitry Andric   /// tries to create a PHI where the incoming values are identical.
3296fe6060f1SDimitry Andric   static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
3297fe6060f1SDimitry Andric                                    LDVSSAUpdater *Updater) {
3298fe6060f1SDimitry Andric     BlockValueNum PHIValNum = Updater->getValue(BB);
3299fe6060f1SDimitry Andric     LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
3300fe6060f1SDimitry Andric     Updater->PHIs[PHIValNum] = PHI;
3301fe6060f1SDimitry Andric     return PHIValNum;
3302fe6060f1SDimitry Andric   }
3303fe6060f1SDimitry Andric 
3304fe6060f1SDimitry Andric   /// AddPHIOperand - Add the specified value as an operand of the PHI for
3305fe6060f1SDimitry Andric   /// the specified predecessor block.
3306fe6060f1SDimitry Andric   static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
3307fe6060f1SDimitry Andric     PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
3308fe6060f1SDimitry Andric   }
3309fe6060f1SDimitry Andric 
3310fe6060f1SDimitry Andric   /// ValueIsPHI - Check if the instruction that defines the specified value
3311fe6060f1SDimitry Andric   /// is a PHI instruction.
3312fe6060f1SDimitry Andric   static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3313fe6060f1SDimitry Andric     auto PHIIt = Updater->PHIs.find(Val);
3314fe6060f1SDimitry Andric     if (PHIIt == Updater->PHIs.end())
3315fe6060f1SDimitry Andric       return nullptr;
3316fe6060f1SDimitry Andric     return PHIIt->second;
3317fe6060f1SDimitry Andric   }
3318fe6060f1SDimitry Andric 
3319fe6060f1SDimitry Andric   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
3320fe6060f1SDimitry Andric   /// operands, i.e., it was just added.
3321fe6060f1SDimitry Andric   static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3322fe6060f1SDimitry Andric     LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
3323fe6060f1SDimitry Andric     if (PHI && PHI->IncomingValues.size() == 0)
3324fe6060f1SDimitry Andric       return PHI;
3325fe6060f1SDimitry Andric     return nullptr;
3326fe6060f1SDimitry Andric   }
3327fe6060f1SDimitry Andric 
3328fe6060f1SDimitry Andric   /// GetPHIValue - For the specified PHI instruction, return the value
3329fe6060f1SDimitry Andric   /// that it defines.
3330fe6060f1SDimitry Andric   static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
3331fe6060f1SDimitry Andric };
3332fe6060f1SDimitry Andric 
3333fe6060f1SDimitry Andric } // end namespace llvm
3334fe6060f1SDimitry Andric 
3335fe6060f1SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF,
3336fe6060f1SDimitry Andric                                                       ValueIDNum **MLiveOuts,
3337fe6060f1SDimitry Andric                                                       ValueIDNum **MLiveIns,
3338fe6060f1SDimitry Andric                                                       MachineInstr &Here,
3339fe6060f1SDimitry Andric                                                       uint64_t InstrNum) {
3340fe6060f1SDimitry Andric   // Pick out records of DBG_PHI instructions that have been observed. If there
3341fe6060f1SDimitry Andric   // are none, then we cannot compute a value number.
3342fe6060f1SDimitry Andric   auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
3343fe6060f1SDimitry Andric                                     DebugPHINumToValue.end(), InstrNum);
3344fe6060f1SDimitry Andric   auto LowerIt = RangePair.first;
3345fe6060f1SDimitry Andric   auto UpperIt = RangePair.second;
3346fe6060f1SDimitry Andric 
3347fe6060f1SDimitry Andric   // No DBG_PHI means there can be no location.
3348fe6060f1SDimitry Andric   if (LowerIt == UpperIt)
3349fe6060f1SDimitry Andric     return None;
3350fe6060f1SDimitry Andric 
3351fe6060f1SDimitry Andric   // If there's only one DBG_PHI, then that is our value number.
3352fe6060f1SDimitry Andric   if (std::distance(LowerIt, UpperIt) == 1)
3353fe6060f1SDimitry Andric     return LowerIt->ValueRead;
3354fe6060f1SDimitry Andric 
3355fe6060f1SDimitry Andric   auto DBGPHIRange = make_range(LowerIt, UpperIt);
3356fe6060f1SDimitry Andric 
3357fe6060f1SDimitry Andric   // Pick out the location (physreg, slot) where any PHIs must occur. It's
3358fe6060f1SDimitry Andric   // technically possible for us to merge values in different registers in each
3359fe6060f1SDimitry Andric   // block, but highly unlikely that LLVM will generate such code after register
3360fe6060f1SDimitry Andric   // allocation.
3361fe6060f1SDimitry Andric   LocIdx Loc = LowerIt->ReadLoc;
3362fe6060f1SDimitry Andric 
3363fe6060f1SDimitry Andric   // We have several DBG_PHIs, and a use position (the Here inst). All each
3364fe6060f1SDimitry Andric   // DBG_PHI does is identify a value at a program position. We can treat each
3365fe6060f1SDimitry Andric   // DBG_PHI like it's a Def of a value, and the use position is a Use of a
3366fe6060f1SDimitry Andric   // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
3367fe6060f1SDimitry Andric   // determine which Def is used at the Use, and any PHIs that happen along
3368fe6060f1SDimitry Andric   // the way.
3369fe6060f1SDimitry Andric   // Adapted LLVM SSA Updater:
3370fe6060f1SDimitry Andric   LDVSSAUpdater Updater(Loc, MLiveIns);
3371fe6060f1SDimitry Andric   // Map of which Def or PHI is the current value in each block.
3372fe6060f1SDimitry Andric   DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
3373fe6060f1SDimitry Andric   // Set of PHIs that we have created along the way.
3374fe6060f1SDimitry Andric   SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
3375fe6060f1SDimitry Andric 
3376fe6060f1SDimitry Andric   // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
3377fe6060f1SDimitry Andric   // for the SSAUpdater.
3378fe6060f1SDimitry Andric   for (const auto &DBG_PHI : DBGPHIRange) {
3379fe6060f1SDimitry Andric     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3380fe6060f1SDimitry Andric     const ValueIDNum &Num = DBG_PHI.ValueRead;
3381fe6060f1SDimitry Andric     AvailableValues.insert(std::make_pair(Block, Num.asU64()));
3382fe6060f1SDimitry Andric   }
3383fe6060f1SDimitry Andric 
3384fe6060f1SDimitry Andric   LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
3385fe6060f1SDimitry Andric   const auto &AvailIt = AvailableValues.find(HereBlock);
3386fe6060f1SDimitry Andric   if (AvailIt != AvailableValues.end()) {
3387fe6060f1SDimitry Andric     // Actually, we already know what the value is -- the Use is in the same
3388fe6060f1SDimitry Andric     // block as the Def.
3389fe6060f1SDimitry Andric     return ValueIDNum::fromU64(AvailIt->second);
3390fe6060f1SDimitry Andric   }
3391fe6060f1SDimitry Andric 
3392fe6060f1SDimitry Andric   // Otherwise, we must use the SSA Updater. It will identify the value number
3393fe6060f1SDimitry Andric   // that we are to use, and the PHIs that must happen along the way.
3394fe6060f1SDimitry Andric   SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
3395fe6060f1SDimitry Andric   BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
3396fe6060f1SDimitry Andric   ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
3397fe6060f1SDimitry Andric 
3398fe6060f1SDimitry Andric   // We have the number for a PHI, or possibly live-through value, to be used
3399fe6060f1SDimitry Andric   // at this Use. There are a number of things we have to check about it though:
3400fe6060f1SDimitry Andric   //  * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
3401fe6060f1SDimitry Andric   //    Use was not completely dominated by DBG_PHIs and we should abort.
3402fe6060f1SDimitry Andric   //  * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
3403fe6060f1SDimitry Andric   //    we've left SSA form. Validate that the inputs to each PHI are the
3404fe6060f1SDimitry Andric   //    expected values.
3405fe6060f1SDimitry Andric   //  * Is a PHI we've created actually a merging of values, or are all the
3406fe6060f1SDimitry Andric   //    predecessor values the same, leading to a non-PHI machine value number?
3407fe6060f1SDimitry Andric   //    (SSAUpdater doesn't know that either). Remap validated PHIs into the
3408fe6060f1SDimitry Andric   //    the ValidatedValues collection below to sort this out.
3409fe6060f1SDimitry Andric   DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
3410fe6060f1SDimitry Andric 
3411fe6060f1SDimitry Andric   // Define all the input DBG_PHI values in ValidatedValues.
3412fe6060f1SDimitry Andric   for (const auto &DBG_PHI : DBGPHIRange) {
3413fe6060f1SDimitry Andric     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3414fe6060f1SDimitry Andric     const ValueIDNum &Num = DBG_PHI.ValueRead;
3415fe6060f1SDimitry Andric     ValidatedValues.insert(std::make_pair(Block, Num));
3416fe6060f1SDimitry Andric   }
3417fe6060f1SDimitry Andric 
3418fe6060f1SDimitry Andric   // Sort PHIs to validate into RPO-order.
3419fe6060f1SDimitry Andric   SmallVector<LDVSSAPhi *, 8> SortedPHIs;
3420fe6060f1SDimitry Andric   for (auto &PHI : CreatedPHIs)
3421fe6060f1SDimitry Andric     SortedPHIs.push_back(PHI);
3422fe6060f1SDimitry Andric 
3423fe6060f1SDimitry Andric   std::sort(
3424fe6060f1SDimitry Andric       SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) {
3425fe6060f1SDimitry Andric         return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
3426fe6060f1SDimitry Andric       });
3427fe6060f1SDimitry Andric 
3428fe6060f1SDimitry Andric   for (auto &PHI : SortedPHIs) {
3429fe6060f1SDimitry Andric     ValueIDNum ThisBlockValueNum =
3430fe6060f1SDimitry Andric         MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
3431fe6060f1SDimitry Andric 
3432fe6060f1SDimitry Andric     // Are all these things actually defined?
3433fe6060f1SDimitry Andric     for (auto &PHIIt : PHI->IncomingValues) {
3434fe6060f1SDimitry Andric       // Any undef input means DBG_PHIs didn't dominate the use point.
3435fe6060f1SDimitry Andric       if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
3436fe6060f1SDimitry Andric         return None;
3437fe6060f1SDimitry Andric 
3438fe6060f1SDimitry Andric       ValueIDNum ValueToCheck;
3439fe6060f1SDimitry Andric       ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
3440fe6060f1SDimitry Andric 
3441fe6060f1SDimitry Andric       auto VVal = ValidatedValues.find(PHIIt.first);
3442fe6060f1SDimitry Andric       if (VVal == ValidatedValues.end()) {
3443fe6060f1SDimitry Andric         // We cross a loop, and this is a backedge. LLVMs tail duplication
3444fe6060f1SDimitry Andric         // happens so late that DBG_PHI instructions should not be able to
3445fe6060f1SDimitry Andric         // migrate into loops -- meaning we can only be live-through this
3446fe6060f1SDimitry Andric         // loop.
3447fe6060f1SDimitry Andric         ValueToCheck = ThisBlockValueNum;
3448fe6060f1SDimitry Andric       } else {
3449fe6060f1SDimitry Andric         // Does the block have as a live-out, in the location we're examining,
3450fe6060f1SDimitry Andric         // the value that we expect? If not, it's been moved or clobbered.
3451fe6060f1SDimitry Andric         ValueToCheck = VVal->second;
3452fe6060f1SDimitry Andric       }
3453fe6060f1SDimitry Andric 
3454fe6060f1SDimitry Andric       if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
3455fe6060f1SDimitry Andric         return None;
3456fe6060f1SDimitry Andric     }
3457fe6060f1SDimitry Andric 
3458fe6060f1SDimitry Andric     // Record this value as validated.
3459fe6060f1SDimitry Andric     ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
3460fe6060f1SDimitry Andric   }
3461fe6060f1SDimitry Andric 
3462fe6060f1SDimitry Andric   // All the PHIs are valid: we can return what the SSAUpdater said our value
3463fe6060f1SDimitry Andric   // number was.
3464fe6060f1SDimitry Andric   return Result;
3465fe6060f1SDimitry Andric }
3466