xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
8781ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
88e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
89e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
90349cc55cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
91e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
92e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
93e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
94e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
95fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
96e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
97e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
98e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
99e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
100e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
101e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
102e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
103e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
104e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
105e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
106e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
107e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h"
108e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
109e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
110e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h"
111e8d8bef9SDimitry Andric #include "llvm/Support/Compiler.h"
112e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
11381ad6265SDimitry Andric #include "llvm/Support/GenericIteratedDominanceFrontier.h"
114e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h"
115e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h"
116fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h"
117fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
118e8d8bef9SDimitry Andric #include <algorithm>
119e8d8bef9SDimitry Andric #include <cassert>
12081ad6265SDimitry Andric #include <climits>
121e8d8bef9SDimitry Andric #include <cstdint>
122e8d8bef9SDimitry Andric #include <functional>
123e8d8bef9SDimitry Andric #include <queue>
124e8d8bef9SDimitry Andric #include <tuple>
125e8d8bef9SDimitry Andric #include <utility>
126e8d8bef9SDimitry Andric #include <vector>
127e8d8bef9SDimitry Andric 
128349cc55cSDimitry Andric #include "InstrRefBasedImpl.h"
129e8d8bef9SDimitry Andric #include "LiveDebugValues.h"
130bdd1243dSDimitry Andric #include <optional>
131e8d8bef9SDimitry Andric 
132e8d8bef9SDimitry Andric using namespace llvm;
133349cc55cSDimitry Andric using namespace LiveDebugValues;
134e8d8bef9SDimitry Andric 
135fe6060f1SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it.
136fe6060f1SDimitry Andric #undef DEBUG_TYPE
137e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues"
138e8d8bef9SDimitry Andric 
139e8d8bef9SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too
140e8d8bef9SDimitry Andric // far and ignoring some transfers.
141e8d8bef9SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
142e8d8bef9SDimitry Andric                                    cl::desc("Act like old LiveDebugValues did"),
143e8d8bef9SDimitry Andric                                    cl::init(false));
144e8d8bef9SDimitry Andric 
145d56accc7SDimitry Andric // Limit for the maximum number of stack slots we should track, past which we
146d56accc7SDimitry Andric // will ignore any spills. InstrRefBasedLDV gathers detailed information on all
147d56accc7SDimitry Andric // stack slots which leads to high memory consumption, and in some scenarios
148d56accc7SDimitry Andric // (such as asan with very many locals) the working set of the function can be
149d56accc7SDimitry Andric // very large, causing many spills. In these scenarios, it is very unlikely that
150d56accc7SDimitry Andric // the developer has hundreds of variables live at the same time that they're
151d56accc7SDimitry Andric // carefully thinking about -- instead, they probably autogenerated the code.
152d56accc7SDimitry Andric // When this happens, gracefully stop tracking excess spill slots, rather than
153d56accc7SDimitry Andric // consuming all the developer's memory.
154d56accc7SDimitry Andric static cl::opt<unsigned>
155d56accc7SDimitry Andric     StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
156d56accc7SDimitry Andric                          cl::desc("livedebugvalues-stack-ws-limit"),
157d56accc7SDimitry Andric                          cl::init(250));
158d56accc7SDimitry Andric 
159bdd1243dSDimitry Andric DbgOpID DbgOpID::UndefID = DbgOpID(0xffffffff);
160bdd1243dSDimitry Andric 
161e8d8bef9SDimitry Andric /// Tracker for converting machine value locations and variable values into
162e8d8bef9SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
163e8d8bef9SDimitry Andric /// specifying block live-in locations and transfers within blocks.
164e8d8bef9SDimitry Andric ///
165e8d8bef9SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
166e8d8bef9SDimitry Andric /// and must be initialized with the set of variable values that are live-in to
167e8d8bef9SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks
168e8d8bef9SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a
169e8d8bef9SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
170e8d8bef9SDimitry Andric /// stepped through, transfers of values between machine locations are
171e8d8bef9SDimitry Andric /// identified and if profitable, a DBG_VALUE created.
172e8d8bef9SDimitry Andric ///
173e8d8bef9SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an
174e8d8bef9SDimitry Andric /// unavailable value could materialize in the middle of a block, when the
175e8d8bef9SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the
176e8d8bef9SDimitry Andric /// variable in a backup location. (XXX these are unimplemented).
177e8d8bef9SDimitry Andric class TransferTracker {
178e8d8bef9SDimitry Andric public:
179e8d8bef9SDimitry Andric   const TargetInstrInfo *TII;
180fe6060f1SDimitry Andric   const TargetLowering *TLI;
181e8d8bef9SDimitry Andric   /// This machine location tracker is assumed to always contain the up-to-date
182e8d8bef9SDimitry Andric   /// value mapping for all machine locations. TransferTracker only reads
183e8d8bef9SDimitry Andric   /// information from it. (XXX make it const?)
184e8d8bef9SDimitry Andric   MLocTracker *MTracker;
185e8d8bef9SDimitry Andric   MachineFunction &MF;
186fe6060f1SDimitry Andric   bool ShouldEmitDebugEntryValues;
187e8d8bef9SDimitry Andric 
188e8d8bef9SDimitry Andric   /// Record of all changes in variable locations at a block position. Awkwardly
189e8d8bef9SDimitry Andric   /// we allow inserting either before or after the point: MBB != nullptr
190e8d8bef9SDimitry Andric   /// indicates it's before, otherwise after.
191e8d8bef9SDimitry Andric   struct Transfer {
192fe6060f1SDimitry Andric     MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
193e8d8bef9SDimitry Andric     MachineBasicBlock *MBB; /// non-null if we should insert after.
194e8d8bef9SDimitry Andric     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
195e8d8bef9SDimitry Andric   };
196e8d8bef9SDimitry Andric 
197bdd1243dSDimitry Andric   /// Stores the resolved operands (machine locations and constants) and
198bdd1243dSDimitry Andric   /// qualifying meta-information needed to construct a concrete DBG_VALUE-like
199bdd1243dSDimitry Andric   /// instruction.
200bdd1243dSDimitry Andric   struct ResolvedDbgValue {
201bdd1243dSDimitry Andric     SmallVector<ResolvedDbgOp> Ops;
202e8d8bef9SDimitry Andric     DbgValueProperties Properties;
203bdd1243dSDimitry Andric 
204bdd1243dSDimitry Andric     ResolvedDbgValue(SmallVectorImpl<ResolvedDbgOp> &Ops,
205bdd1243dSDimitry Andric                      DbgValueProperties Properties)
206bdd1243dSDimitry Andric         : Ops(Ops.begin(), Ops.end()), Properties(Properties) {}
207bdd1243dSDimitry Andric 
208bdd1243dSDimitry Andric     /// Returns all the LocIdx values used in this struct, in the order in which
209bdd1243dSDimitry Andric     /// they appear as operands in the debug value; may contain duplicates.
210bdd1243dSDimitry Andric     auto loc_indices() const {
211bdd1243dSDimitry Andric       return map_range(
212bdd1243dSDimitry Andric           make_filter_range(
213bdd1243dSDimitry Andric               Ops, [](const ResolvedDbgOp &Op) { return !Op.IsConst; }),
214bdd1243dSDimitry Andric           [](const ResolvedDbgOp &Op) { return Op.Loc; });
215bdd1243dSDimitry Andric     }
216fe6060f1SDimitry Andric   };
217e8d8bef9SDimitry Andric 
218e8d8bef9SDimitry Andric   /// Collection of transfers (DBG_VALUEs) to be inserted.
219e8d8bef9SDimitry Andric   SmallVector<Transfer, 32> Transfers;
220e8d8bef9SDimitry Andric 
221e8d8bef9SDimitry Andric   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
222e8d8bef9SDimitry Andric   /// between TransferTrackers view of variable locations and MLocTrackers. For
223e8d8bef9SDimitry Andric   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
224e8d8bef9SDimitry Andric   /// does not.
225349cc55cSDimitry Andric   SmallVector<ValueIDNum, 32> VarLocs;
226e8d8bef9SDimitry Andric 
227e8d8bef9SDimitry Andric   /// Map from LocIdxes to which DebugVariables are based that location.
228e8d8bef9SDimitry Andric   /// Mantained while stepping through the block. Not accurate if
229e8d8bef9SDimitry Andric   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
230349cc55cSDimitry Andric   DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
231e8d8bef9SDimitry Andric 
232e8d8bef9SDimitry Andric   /// Map from DebugVariable to it's current location and qualifying meta
233e8d8bef9SDimitry Andric   /// information. To be used in conjunction with ActiveMLocs to construct
234e8d8bef9SDimitry Andric   /// enough information for the DBG_VALUEs for a particular LocIdx.
235bdd1243dSDimitry Andric   DenseMap<DebugVariable, ResolvedDbgValue> ActiveVLocs;
236e8d8bef9SDimitry Andric 
237e8d8bef9SDimitry Andric   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
238e8d8bef9SDimitry Andric   SmallVector<MachineInstr *, 4> PendingDbgValues;
239e8d8bef9SDimitry Andric 
240e8d8bef9SDimitry Andric   /// Record of a use-before-def: created when a value that's live-in to the
241e8d8bef9SDimitry Andric   /// current block isn't available in any machine location, but it will be
242e8d8bef9SDimitry Andric   /// defined in this block.
243e8d8bef9SDimitry Andric   struct UseBeforeDef {
244e8d8bef9SDimitry Andric     /// Value of this variable, def'd in block.
245bdd1243dSDimitry Andric     SmallVector<DbgOp> Values;
246e8d8bef9SDimitry Andric     /// Identity of this variable.
247e8d8bef9SDimitry Andric     DebugVariable Var;
248e8d8bef9SDimitry Andric     /// Additional variable properties.
249e8d8bef9SDimitry Andric     DbgValueProperties Properties;
250bdd1243dSDimitry Andric     UseBeforeDef(ArrayRef<DbgOp> Values, const DebugVariable &Var,
251bdd1243dSDimitry Andric                  const DbgValueProperties &Properties)
252bdd1243dSDimitry Andric         : Values(Values.begin(), Values.end()), Var(Var),
253bdd1243dSDimitry Andric           Properties(Properties) {}
254e8d8bef9SDimitry Andric   };
255e8d8bef9SDimitry Andric 
256e8d8bef9SDimitry Andric   /// Map from instruction index (within the block) to the set of UseBeforeDefs
257e8d8bef9SDimitry Andric   /// that become defined at that instruction.
258e8d8bef9SDimitry Andric   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
259e8d8bef9SDimitry Andric 
260e8d8bef9SDimitry Andric   /// The set of variables that are in UseBeforeDefs and can become a location
261e8d8bef9SDimitry Andric   /// once the relevant value is defined. An element being erased from this
262e8d8bef9SDimitry Andric   /// collection prevents the use-before-def materializing.
263e8d8bef9SDimitry Andric   DenseSet<DebugVariable> UseBeforeDefVariables;
264e8d8bef9SDimitry Andric 
265e8d8bef9SDimitry Andric   const TargetRegisterInfo &TRI;
266e8d8bef9SDimitry Andric   const BitVector &CalleeSavedRegs;
267e8d8bef9SDimitry Andric 
268e8d8bef9SDimitry Andric   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
269e8d8bef9SDimitry Andric                   MachineFunction &MF, const TargetRegisterInfo &TRI,
270fe6060f1SDimitry Andric                   const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
271e8d8bef9SDimitry Andric       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
272fe6060f1SDimitry Andric         CalleeSavedRegs(CalleeSavedRegs) {
273fe6060f1SDimitry Andric     TLI = MF.getSubtarget().getTargetLowering();
274fe6060f1SDimitry Andric     auto &TM = TPC.getTM<TargetMachine>();
275fe6060f1SDimitry Andric     ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
276fe6060f1SDimitry Andric   }
277e8d8bef9SDimitry Andric 
278bdd1243dSDimitry Andric   bool isCalleeSaved(LocIdx L) const {
279e8d8bef9SDimitry Andric     unsigned Reg = MTracker->LocIdxToLocID[L];
280e8d8bef9SDimitry Andric     if (Reg >= MTracker->NumRegs)
281e8d8bef9SDimitry Andric       return false;
282e8d8bef9SDimitry Andric     for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
283e8d8bef9SDimitry Andric       if (CalleeSavedRegs.test(*RAI))
284e8d8bef9SDimitry Andric         return true;
285e8d8bef9SDimitry Andric     return false;
286e8d8bef9SDimitry Andric   };
287e8d8bef9SDimitry Andric 
288bdd1243dSDimitry Andric   // An estimate of the expected lifespan of values at a machine location, with
289bdd1243dSDimitry Andric   // a greater value corresponding to a longer expected lifespan, i.e. spill
290bdd1243dSDimitry Andric   // slots generally live longer than callee-saved registers which generally
291bdd1243dSDimitry Andric   // live longer than non-callee-saved registers. The minimum value of 0
292bdd1243dSDimitry Andric   // corresponds to an illegal location that cannot have a "lifespan" at all.
293bdd1243dSDimitry Andric   enum class LocationQuality : unsigned char {
294bdd1243dSDimitry Andric     Illegal = 0,
295bdd1243dSDimitry Andric     Register,
296bdd1243dSDimitry Andric     CalleeSavedRegister,
297bdd1243dSDimitry Andric     SpillSlot,
298bdd1243dSDimitry Andric     Best = SpillSlot
299bdd1243dSDimitry Andric   };
300bdd1243dSDimitry Andric 
301bdd1243dSDimitry Andric   class LocationAndQuality {
302bdd1243dSDimitry Andric     unsigned Location : 24;
303bdd1243dSDimitry Andric     unsigned Quality : 8;
304bdd1243dSDimitry Andric 
305bdd1243dSDimitry Andric   public:
306bdd1243dSDimitry Andric     LocationAndQuality() : Location(0), Quality(0) {}
307bdd1243dSDimitry Andric     LocationAndQuality(LocIdx L, LocationQuality Q)
308bdd1243dSDimitry Andric         : Location(L.asU64()), Quality(static_cast<unsigned>(Q)) {}
309bdd1243dSDimitry Andric     LocIdx getLoc() const {
310bdd1243dSDimitry Andric       if (!Quality)
311bdd1243dSDimitry Andric         return LocIdx::MakeIllegalLoc();
312bdd1243dSDimitry Andric       return LocIdx(Location);
313bdd1243dSDimitry Andric     }
314bdd1243dSDimitry Andric     LocationQuality getQuality() const { return LocationQuality(Quality); }
315bdd1243dSDimitry Andric     bool isIllegal() const { return !Quality; }
316bdd1243dSDimitry Andric     bool isBest() const { return getQuality() == LocationQuality::Best; }
317bdd1243dSDimitry Andric   };
318bdd1243dSDimitry Andric 
319bdd1243dSDimitry Andric   // Returns the LocationQuality for the location L iff the quality of L is
320bdd1243dSDimitry Andric   // is strictly greater than the provided minimum quality.
321bdd1243dSDimitry Andric   std::optional<LocationQuality>
322bdd1243dSDimitry Andric   getLocQualityIfBetter(LocIdx L, LocationQuality Min) const {
323bdd1243dSDimitry Andric     if (L.isIllegal())
324bdd1243dSDimitry Andric       return std::nullopt;
325bdd1243dSDimitry Andric     if (Min >= LocationQuality::SpillSlot)
326bdd1243dSDimitry Andric       return std::nullopt;
327bdd1243dSDimitry Andric     if (MTracker->isSpill(L))
328bdd1243dSDimitry Andric       return LocationQuality::SpillSlot;
329bdd1243dSDimitry Andric     if (Min >= LocationQuality::CalleeSavedRegister)
330bdd1243dSDimitry Andric       return std::nullopt;
331bdd1243dSDimitry Andric     if (isCalleeSaved(L))
332bdd1243dSDimitry Andric       return LocationQuality::CalleeSavedRegister;
333bdd1243dSDimitry Andric     if (Min >= LocationQuality::Register)
334bdd1243dSDimitry Andric       return std::nullopt;
335bdd1243dSDimitry Andric     return LocationQuality::Register;
336bdd1243dSDimitry Andric   }
337bdd1243dSDimitry Andric 
338bdd1243dSDimitry Andric   /// For a variable \p Var with the live-in value \p Value, attempts to resolve
339bdd1243dSDimitry Andric   /// the DbgValue to a concrete DBG_VALUE, emitting that value and loading the
340bdd1243dSDimitry Andric   /// tracking information to track Var throughout the block.
341bdd1243dSDimitry Andric   /// \p ValueToLoc is a map containing the best known location for every
342bdd1243dSDimitry Andric   ///    ValueIDNum that Value may use.
343bdd1243dSDimitry Andric   /// \p MBB is the basic block that we are loading the live-in value for.
344bdd1243dSDimitry Andric   /// \p DbgOpStore is the map containing the DbgOpID->DbgOp mapping needed to
345bdd1243dSDimitry Andric   ///    determine the values used by Value.
346bdd1243dSDimitry Andric   void loadVarInloc(MachineBasicBlock &MBB, DbgOpIDMap &DbgOpStore,
347bdd1243dSDimitry Andric                     const DenseMap<ValueIDNum, LocationAndQuality> &ValueToLoc,
348bdd1243dSDimitry Andric                     DebugVariable Var, DbgValue Value) {
349bdd1243dSDimitry Andric     SmallVector<DbgOp> DbgOps;
350bdd1243dSDimitry Andric     SmallVector<ResolvedDbgOp> ResolvedDbgOps;
351bdd1243dSDimitry Andric     bool IsValueValid = true;
352bdd1243dSDimitry Andric     unsigned LastUseBeforeDef = 0;
353bdd1243dSDimitry Andric 
354bdd1243dSDimitry Andric     // If every value used by the incoming DbgValue is available at block
355bdd1243dSDimitry Andric     // entry, ResolvedDbgOps will contain the machine locations/constants for
356bdd1243dSDimitry Andric     // those values and will be used to emit a debug location.
357bdd1243dSDimitry Andric     // If one or more values are not yet available, but will all be defined in
358bdd1243dSDimitry Andric     // this block, then LastUseBeforeDef will track the instruction index in
359bdd1243dSDimitry Andric     // this BB at which the last of those values is defined, DbgOps will
360bdd1243dSDimitry Andric     // contain the values that we will emit when we reach that instruction.
361bdd1243dSDimitry Andric     // If one or more values are undef or not available throughout this block,
362bdd1243dSDimitry Andric     // and we can't recover as an entry value, we set IsValueValid=false and
363bdd1243dSDimitry Andric     // skip this variable.
364bdd1243dSDimitry Andric     for (DbgOpID ID : Value.getDbgOpIDs()) {
365bdd1243dSDimitry Andric       DbgOp Op = DbgOpStore.find(ID);
366bdd1243dSDimitry Andric       DbgOps.push_back(Op);
367bdd1243dSDimitry Andric       if (ID.isUndef()) {
368bdd1243dSDimitry Andric         IsValueValid = false;
369bdd1243dSDimitry Andric         break;
370bdd1243dSDimitry Andric       }
371bdd1243dSDimitry Andric       if (ID.isConst()) {
372bdd1243dSDimitry Andric         ResolvedDbgOps.push_back(Op.MO);
373bdd1243dSDimitry Andric         continue;
374bdd1243dSDimitry Andric       }
375bdd1243dSDimitry Andric 
376bdd1243dSDimitry Andric       // If the value has no location, we can't make a variable location.
377bdd1243dSDimitry Andric       const ValueIDNum &Num = Op.ID;
378bdd1243dSDimitry Andric       auto ValuesPreferredLoc = ValueToLoc.find(Num);
379bdd1243dSDimitry Andric       if (ValuesPreferredLoc->second.isIllegal()) {
380bdd1243dSDimitry Andric         // If it's a def that occurs in this block, register it as a
381bdd1243dSDimitry Andric         // use-before-def to be resolved as we step through the block.
382bdd1243dSDimitry Andric         // Continue processing values so that we add any other UseBeforeDef
383bdd1243dSDimitry Andric         // entries needed for later.
384bdd1243dSDimitry Andric         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) {
385bdd1243dSDimitry Andric           LastUseBeforeDef = std::max(LastUseBeforeDef,
386bdd1243dSDimitry Andric                                       static_cast<unsigned>(Num.getInst()));
387bdd1243dSDimitry Andric           continue;
388bdd1243dSDimitry Andric         }
389bdd1243dSDimitry Andric         recoverAsEntryValue(Var, Value.Properties, Num);
390bdd1243dSDimitry Andric         IsValueValid = false;
391bdd1243dSDimitry Andric         break;
392bdd1243dSDimitry Andric       }
393bdd1243dSDimitry Andric 
394bdd1243dSDimitry Andric       // Defer modifying ActiveVLocs until after we've confirmed we have a
395bdd1243dSDimitry Andric       // live range.
396bdd1243dSDimitry Andric       LocIdx M = ValuesPreferredLoc->second.getLoc();
397bdd1243dSDimitry Andric       ResolvedDbgOps.push_back(M);
398bdd1243dSDimitry Andric     }
399bdd1243dSDimitry Andric 
400bdd1243dSDimitry Andric     // If we cannot produce a valid value for the LiveIn value within this
401bdd1243dSDimitry Andric     // block, skip this variable.
402bdd1243dSDimitry Andric     if (!IsValueValid)
403bdd1243dSDimitry Andric       return;
404bdd1243dSDimitry Andric 
405bdd1243dSDimitry Andric     // Add UseBeforeDef entry for the last value to be defined in this block.
406bdd1243dSDimitry Andric     if (LastUseBeforeDef) {
407bdd1243dSDimitry Andric       addUseBeforeDef(Var, Value.Properties, DbgOps,
408bdd1243dSDimitry Andric                       LastUseBeforeDef);
409bdd1243dSDimitry Andric       return;
410bdd1243dSDimitry Andric     }
411bdd1243dSDimitry Andric 
412bdd1243dSDimitry Andric     // The LiveIn value is available at block entry, begin tracking and record
413bdd1243dSDimitry Andric     // the transfer.
414bdd1243dSDimitry Andric     for (const ResolvedDbgOp &Op : ResolvedDbgOps)
415bdd1243dSDimitry Andric       if (!Op.IsConst)
416bdd1243dSDimitry Andric         ActiveMLocs[Op.Loc].insert(Var);
417bdd1243dSDimitry Andric     auto NewValue = ResolvedDbgValue{ResolvedDbgOps, Value.Properties};
418bdd1243dSDimitry Andric     auto Result = ActiveVLocs.insert(std::make_pair(Var, NewValue));
419bdd1243dSDimitry Andric     if (!Result.second)
420bdd1243dSDimitry Andric       Result.first->second = NewValue;
421bdd1243dSDimitry Andric     PendingDbgValues.push_back(
422bdd1243dSDimitry Andric         MTracker->emitLoc(ResolvedDbgOps, Var, Value.Properties));
423bdd1243dSDimitry Andric   }
424bdd1243dSDimitry Andric 
425bdd1243dSDimitry Andric   /// Load object with live-in variable values. \p mlocs contains the live-in
426bdd1243dSDimitry Andric   /// values in each machine location, while \p vlocs the live-in variable
427bdd1243dSDimitry Andric   /// values. This method picks variable locations for the live-in variables,
428bdd1243dSDimitry Andric   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
429bdd1243dSDimitry Andric   /// object fields to track variable locations as we step through the block.
430bdd1243dSDimitry Andric   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
431bdd1243dSDimitry Andric   void
432bdd1243dSDimitry Andric   loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, DbgOpIDMap &DbgOpStore,
433bdd1243dSDimitry Andric              const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
434bdd1243dSDimitry Andric              unsigned NumLocs) {
435bdd1243dSDimitry Andric     ActiveMLocs.clear();
436bdd1243dSDimitry Andric     ActiveVLocs.clear();
437bdd1243dSDimitry Andric     VarLocs.clear();
438bdd1243dSDimitry Andric     VarLocs.reserve(NumLocs);
439bdd1243dSDimitry Andric     UseBeforeDefs.clear();
440bdd1243dSDimitry Andric     UseBeforeDefVariables.clear();
441bdd1243dSDimitry Andric 
442e8d8bef9SDimitry Andric     // Map of the preferred location for each value.
443bdd1243dSDimitry Andric     DenseMap<ValueIDNum, LocationAndQuality> ValueToLoc;
4441fd87a68SDimitry Andric 
4451fd87a68SDimitry Andric     // Initialized the preferred-location map with illegal locations, to be
4461fd87a68SDimitry Andric     // filled in later.
447fcaf7f86SDimitry Andric     for (const auto &VLoc : VLocs)
4481fd87a68SDimitry Andric       if (VLoc.second.Kind == DbgValue::Def)
449bdd1243dSDimitry Andric         for (DbgOpID OpID : VLoc.second.getDbgOpIDs())
450bdd1243dSDimitry Andric           if (!OpID.ID.IsConst)
451bdd1243dSDimitry Andric             ValueToLoc.insert({DbgOpStore.find(OpID).ID, LocationAndQuality()});
4521fd87a68SDimitry Andric 
453349cc55cSDimitry Andric     ActiveMLocs.reserve(VLocs.size());
454349cc55cSDimitry Andric     ActiveVLocs.reserve(VLocs.size());
455e8d8bef9SDimitry Andric 
456e8d8bef9SDimitry Andric     // Produce a map of value numbers to the current machine locs they live
457e8d8bef9SDimitry Andric     // in. When emulating VarLocBasedImpl, there should only be one
458e8d8bef9SDimitry Andric     // location; when not, we get to pick.
459e8d8bef9SDimitry Andric     for (auto Location : MTracker->locations()) {
460e8d8bef9SDimitry Andric       LocIdx Idx = Location.Idx;
461e8d8bef9SDimitry Andric       ValueIDNum &VNum = MLocs[Idx.asU64()];
462bdd1243dSDimitry Andric       if (VNum == ValueIDNum::EmptyValue)
463bdd1243dSDimitry Andric         continue;
464e8d8bef9SDimitry Andric       VarLocs.push_back(VNum);
46504eeddc0SDimitry Andric 
4661fd87a68SDimitry Andric       // Is there a variable that wants a location for this value? If not, skip.
4671fd87a68SDimitry Andric       auto VIt = ValueToLoc.find(VNum);
4681fd87a68SDimitry Andric       if (VIt == ValueToLoc.end())
46904eeddc0SDimitry Andric         continue;
47004eeddc0SDimitry Andric 
471bdd1243dSDimitry Andric       auto &Previous = VIt->second;
472bdd1243dSDimitry Andric       // If this is the first location with that value, pick it. Otherwise,
473bdd1243dSDimitry Andric       // consider whether it's a "longer term" location.
474bdd1243dSDimitry Andric       std::optional<LocationQuality> ReplacementQuality =
475bdd1243dSDimitry Andric           getLocQualityIfBetter(Idx, Previous.getQuality());
476bdd1243dSDimitry Andric       if (ReplacementQuality)
477bdd1243dSDimitry Andric         Previous = LocationAndQuality(Idx, *ReplacementQuality);
478e8d8bef9SDimitry Andric     }
479e8d8bef9SDimitry Andric 
480e8d8bef9SDimitry Andric     // Now map variables to their picked LocIdxes.
48104eeddc0SDimitry Andric     for (const auto &Var : VLocs) {
482bdd1243dSDimitry Andric       loadVarInloc(MBB, DbgOpStore, ValueToLoc, Var.first, Var.second);
483e8d8bef9SDimitry Andric     }
484e8d8bef9SDimitry Andric     flushDbgValues(MBB.begin(), &MBB);
485e8d8bef9SDimitry Andric   }
486e8d8bef9SDimitry Andric 
487e8d8bef9SDimitry Andric   /// Record that \p Var has value \p ID, a value that becomes available
488e8d8bef9SDimitry Andric   /// later in the function.
489e8d8bef9SDimitry Andric   void addUseBeforeDef(const DebugVariable &Var,
490bdd1243dSDimitry Andric                        const DbgValueProperties &Properties,
491bdd1243dSDimitry Andric                        const SmallVectorImpl<DbgOp> &DbgOps, unsigned Inst) {
492bdd1243dSDimitry Andric     UseBeforeDefs[Inst].emplace_back(DbgOps, Var, Properties);
493e8d8bef9SDimitry Andric     UseBeforeDefVariables.insert(Var);
494e8d8bef9SDimitry Andric   }
495e8d8bef9SDimitry Andric 
496e8d8bef9SDimitry Andric   /// After the instruction at index \p Inst and position \p pos has been
497e8d8bef9SDimitry Andric   /// processed, check whether it defines a variable value in a use-before-def.
498e8d8bef9SDimitry Andric   /// If so, and the variable value hasn't changed since the start of the
499e8d8bef9SDimitry Andric   /// block, create a DBG_VALUE.
500e8d8bef9SDimitry Andric   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
501e8d8bef9SDimitry Andric     auto MIt = UseBeforeDefs.find(Inst);
502e8d8bef9SDimitry Andric     if (MIt == UseBeforeDefs.end())
503e8d8bef9SDimitry Andric       return;
504e8d8bef9SDimitry Andric 
505bdd1243dSDimitry Andric     // Map of values to the locations that store them for every value used by
506bdd1243dSDimitry Andric     // the variables that may have become available.
507bdd1243dSDimitry Andric     SmallDenseMap<ValueIDNum, LocationAndQuality> ValueToLoc;
508bdd1243dSDimitry Andric 
509bdd1243dSDimitry Andric     // Populate ValueToLoc with illegal default mappings for every value used by
510bdd1243dSDimitry Andric     // any UseBeforeDef variables for this instruction.
511e8d8bef9SDimitry Andric     for (auto &Use : MIt->second) {
512e8d8bef9SDimitry Andric       if (!UseBeforeDefVariables.count(Use.Var))
513e8d8bef9SDimitry Andric         continue;
514e8d8bef9SDimitry Andric 
515bdd1243dSDimitry Andric       for (DbgOp &Op : Use.Values) {
516bdd1243dSDimitry Andric         assert(!Op.isUndef() && "UseBeforeDef erroneously created for a "
517bdd1243dSDimitry Andric                                 "DbgValue with undef values.");
518bdd1243dSDimitry Andric         if (Op.IsConst)
519bdd1243dSDimitry Andric           continue;
520bdd1243dSDimitry Andric 
521bdd1243dSDimitry Andric         ValueToLoc.insert({Op.ID, LocationAndQuality()});
522bdd1243dSDimitry Andric       }
523bdd1243dSDimitry Andric     }
524bdd1243dSDimitry Andric 
525bdd1243dSDimitry Andric     // Exit early if we have no DbgValues to produce.
526bdd1243dSDimitry Andric     if (ValueToLoc.empty())
527bdd1243dSDimitry Andric       return;
528bdd1243dSDimitry Andric 
529bdd1243dSDimitry Andric     // Determine the best location for each desired value.
530bdd1243dSDimitry Andric     for (auto Location : MTracker->locations()) {
531bdd1243dSDimitry Andric       LocIdx Idx = Location.Idx;
532bdd1243dSDimitry Andric       ValueIDNum &LocValueID = Location.Value;
533bdd1243dSDimitry Andric 
534bdd1243dSDimitry Andric       // Is there a variable that wants a location for this value? If not, skip.
535bdd1243dSDimitry Andric       auto VIt = ValueToLoc.find(LocValueID);
536bdd1243dSDimitry Andric       if (VIt == ValueToLoc.end())
537bdd1243dSDimitry Andric         continue;
538bdd1243dSDimitry Andric 
539bdd1243dSDimitry Andric       auto &Previous = VIt->second;
540bdd1243dSDimitry Andric       // If this is the first location with that value, pick it. Otherwise,
541bdd1243dSDimitry Andric       // consider whether it's a "longer term" location.
542bdd1243dSDimitry Andric       std::optional<LocationQuality> ReplacementQuality =
543bdd1243dSDimitry Andric           getLocQualityIfBetter(Idx, Previous.getQuality());
544bdd1243dSDimitry Andric       if (ReplacementQuality)
545bdd1243dSDimitry Andric         Previous = LocationAndQuality(Idx, *ReplacementQuality);
546bdd1243dSDimitry Andric     }
547bdd1243dSDimitry Andric 
548bdd1243dSDimitry Andric     // Using the map of values to locations, produce a final set of values for
549bdd1243dSDimitry Andric     // this variable.
550bdd1243dSDimitry Andric     for (auto &Use : MIt->second) {
551bdd1243dSDimitry Andric       if (!UseBeforeDefVariables.count(Use.Var))
552bdd1243dSDimitry Andric         continue;
553bdd1243dSDimitry Andric 
554bdd1243dSDimitry Andric       SmallVector<ResolvedDbgOp> DbgOps;
555bdd1243dSDimitry Andric 
556bdd1243dSDimitry Andric       for (DbgOp &Op : Use.Values) {
557bdd1243dSDimitry Andric         if (Op.IsConst) {
558bdd1243dSDimitry Andric           DbgOps.push_back(Op.MO);
559bdd1243dSDimitry Andric           continue;
560bdd1243dSDimitry Andric         }
561bdd1243dSDimitry Andric         LocIdx NewLoc = ValueToLoc.find(Op.ID)->second.getLoc();
562bdd1243dSDimitry Andric         if (NewLoc.isIllegal())
563bdd1243dSDimitry Andric           break;
564bdd1243dSDimitry Andric         DbgOps.push_back(NewLoc);
565bdd1243dSDimitry Andric       }
566bdd1243dSDimitry Andric 
567bdd1243dSDimitry Andric       // If at least one value used by this debug value is no longer available,
568bdd1243dSDimitry Andric       // i.e. one of the values was killed before we finished defining all of
569bdd1243dSDimitry Andric       // the values used by this variable, discard.
570bdd1243dSDimitry Andric       if (DbgOps.size() != Use.Values.size())
571bdd1243dSDimitry Andric         continue;
572bdd1243dSDimitry Andric 
573bdd1243dSDimitry Andric       // Otherwise, we're good to go.
574bdd1243dSDimitry Andric       PendingDbgValues.push_back(
575bdd1243dSDimitry Andric           MTracker->emitLoc(DbgOps, Use.Var, Use.Properties));
576e8d8bef9SDimitry Andric     }
577e8d8bef9SDimitry Andric     flushDbgValues(pos, nullptr);
578e8d8bef9SDimitry Andric   }
579e8d8bef9SDimitry Andric 
580e8d8bef9SDimitry Andric   /// Helper to move created DBG_VALUEs into Transfers collection.
581e8d8bef9SDimitry Andric   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
582fe6060f1SDimitry Andric     if (PendingDbgValues.size() == 0)
583fe6060f1SDimitry Andric       return;
584fe6060f1SDimitry Andric 
585fe6060f1SDimitry Andric     // Pick out the instruction start position.
586fe6060f1SDimitry Andric     MachineBasicBlock::instr_iterator BundleStart;
587fe6060f1SDimitry Andric     if (MBB && Pos == MBB->begin())
588fe6060f1SDimitry Andric       BundleStart = MBB->instr_begin();
589fe6060f1SDimitry Andric     else
590fe6060f1SDimitry Andric       BundleStart = getBundleStart(Pos->getIterator());
591fe6060f1SDimitry Andric 
592fe6060f1SDimitry Andric     Transfers.push_back({BundleStart, MBB, PendingDbgValues});
593e8d8bef9SDimitry Andric     PendingDbgValues.clear();
594e8d8bef9SDimitry Andric   }
595fe6060f1SDimitry Andric 
596fe6060f1SDimitry Andric   bool isEntryValueVariable(const DebugVariable &Var,
597fe6060f1SDimitry Andric                             const DIExpression *Expr) const {
598fe6060f1SDimitry Andric     if (!Var.getVariable()->isParameter())
599fe6060f1SDimitry Andric       return false;
600fe6060f1SDimitry Andric 
601fe6060f1SDimitry Andric     if (Var.getInlinedAt())
602fe6060f1SDimitry Andric       return false;
603fe6060f1SDimitry Andric 
604*06c3fb27SDimitry Andric     if (Expr->getNumElements() > 0 && !Expr->isDeref())
605fe6060f1SDimitry Andric       return false;
606fe6060f1SDimitry Andric 
607fe6060f1SDimitry Andric     return true;
608fe6060f1SDimitry Andric   }
609fe6060f1SDimitry Andric 
610fe6060f1SDimitry Andric   bool isEntryValueValue(const ValueIDNum &Val) const {
611fe6060f1SDimitry Andric     // Must be in entry block (block number zero), and be a PHI / live-in value.
612fe6060f1SDimitry Andric     if (Val.getBlock() || !Val.isPHI())
613fe6060f1SDimitry Andric       return false;
614fe6060f1SDimitry Andric 
615fe6060f1SDimitry Andric     // Entry values must enter in a register.
616fe6060f1SDimitry Andric     if (MTracker->isSpill(Val.getLoc()))
617fe6060f1SDimitry Andric       return false;
618fe6060f1SDimitry Andric 
619fe6060f1SDimitry Andric     Register SP = TLI->getStackPointerRegisterToSaveRestore();
620fe6060f1SDimitry Andric     Register FP = TRI.getFrameRegister(MF);
621fe6060f1SDimitry Andric     Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
622fe6060f1SDimitry Andric     return Reg != SP && Reg != FP;
623fe6060f1SDimitry Andric   }
624fe6060f1SDimitry Andric 
62504eeddc0SDimitry Andric   bool recoverAsEntryValue(const DebugVariable &Var,
62604eeddc0SDimitry Andric                            const DbgValueProperties &Prop,
627fe6060f1SDimitry Andric                            const ValueIDNum &Num) {
628fe6060f1SDimitry Andric     // Is this variable location a candidate to be an entry value. First,
629fe6060f1SDimitry Andric     // should we be trying this at all?
630fe6060f1SDimitry Andric     if (!ShouldEmitDebugEntryValues)
631fe6060f1SDimitry Andric       return false;
632fe6060f1SDimitry Andric 
633bdd1243dSDimitry Andric     const DIExpression *DIExpr = Prop.DIExpr;
634bdd1243dSDimitry Andric 
635bdd1243dSDimitry Andric     // We don't currently emit entry values for DBG_VALUE_LISTs.
636bdd1243dSDimitry Andric     if (Prop.IsVariadic) {
637bdd1243dSDimitry Andric       // If this debug value can be converted to be non-variadic, then do so;
638bdd1243dSDimitry Andric       // otherwise give up.
639bdd1243dSDimitry Andric       auto NonVariadicExpression =
640bdd1243dSDimitry Andric           DIExpression::convertToNonVariadicExpression(DIExpr);
641bdd1243dSDimitry Andric       if (!NonVariadicExpression)
642bdd1243dSDimitry Andric         return false;
643bdd1243dSDimitry Andric       DIExpr = *NonVariadicExpression;
644bdd1243dSDimitry Andric     }
645bdd1243dSDimitry Andric 
646fe6060f1SDimitry Andric     // Is the variable appropriate for entry values (i.e., is a parameter).
647bdd1243dSDimitry Andric     if (!isEntryValueVariable(Var, DIExpr))
648fe6060f1SDimitry Andric       return false;
649fe6060f1SDimitry Andric 
650fe6060f1SDimitry Andric     // Is the value assigned to this variable still the entry value?
651fe6060f1SDimitry Andric     if (!isEntryValueValue(Num))
652fe6060f1SDimitry Andric       return false;
653fe6060f1SDimitry Andric 
654fe6060f1SDimitry Andric     // Emit a variable location using an entry value expression.
655fe6060f1SDimitry Andric     DIExpression *NewExpr =
656bdd1243dSDimitry Andric         DIExpression::prepend(DIExpr, DIExpression::EntryValue);
657fe6060f1SDimitry Andric     Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
658fe6060f1SDimitry Andric     MachineOperand MO = MachineOperand::CreateReg(Reg, false);
659fe6060f1SDimitry Andric 
660bdd1243dSDimitry Andric     PendingDbgValues.push_back(
661bdd1243dSDimitry Andric         emitMOLoc(MO, Var, {NewExpr, Prop.Indirect, false}));
662fe6060f1SDimitry Andric     return true;
663e8d8bef9SDimitry Andric   }
664e8d8bef9SDimitry Andric 
665e8d8bef9SDimitry Andric   /// Change a variable value after encountering a DBG_VALUE inside a block.
666e8d8bef9SDimitry Andric   void redefVar(const MachineInstr &MI) {
667e8d8bef9SDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
668e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
669e8d8bef9SDimitry Andric     DbgValueProperties Properties(MI);
670e8d8bef9SDimitry Andric 
671e8d8bef9SDimitry Andric     // Ignore non-register locations, we don't transfer those.
672bdd1243dSDimitry Andric     if (MI.isUndefDebugValue() ||
673bdd1243dSDimitry Andric         all_of(MI.debug_operands(),
674bdd1243dSDimitry Andric                [](const MachineOperand &MO) { return !MO.isReg(); })) {
675e8d8bef9SDimitry Andric       auto It = ActiveVLocs.find(Var);
676e8d8bef9SDimitry Andric       if (It != ActiveVLocs.end()) {
677bdd1243dSDimitry Andric         for (LocIdx Loc : It->second.loc_indices())
678bdd1243dSDimitry Andric           ActiveMLocs[Loc].erase(Var);
679e8d8bef9SDimitry Andric         ActiveVLocs.erase(It);
680e8d8bef9SDimitry Andric       }
681e8d8bef9SDimitry Andric       // Any use-before-defs no longer apply.
682e8d8bef9SDimitry Andric       UseBeforeDefVariables.erase(Var);
683e8d8bef9SDimitry Andric       return;
684e8d8bef9SDimitry Andric     }
685e8d8bef9SDimitry Andric 
686bdd1243dSDimitry Andric     SmallVector<ResolvedDbgOp> NewLocs;
687bdd1243dSDimitry Andric     for (const MachineOperand &MO : MI.debug_operands()) {
688bdd1243dSDimitry Andric       if (MO.isReg()) {
689bdd1243dSDimitry Andric         // Any undef regs have already been filtered out above.
690e8d8bef9SDimitry Andric         Register Reg = MO.getReg();
691e8d8bef9SDimitry Andric         LocIdx NewLoc = MTracker->getRegMLoc(Reg);
692bdd1243dSDimitry Andric         NewLocs.push_back(NewLoc);
693bdd1243dSDimitry Andric       } else {
694bdd1243dSDimitry Andric         NewLocs.push_back(MO);
695bdd1243dSDimitry Andric       }
696bdd1243dSDimitry Andric     }
697bdd1243dSDimitry Andric 
698bdd1243dSDimitry Andric     redefVar(MI, Properties, NewLocs);
699e8d8bef9SDimitry Andric   }
700e8d8bef9SDimitry Andric 
701e8d8bef9SDimitry Andric   /// Handle a change in variable location within a block. Terminate the
702e8d8bef9SDimitry Andric   /// variables current location, and record the value it now refers to, so
703e8d8bef9SDimitry Andric   /// that we can detect location transfers later on.
704e8d8bef9SDimitry Andric   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
705bdd1243dSDimitry Andric                 SmallVectorImpl<ResolvedDbgOp> &NewLocs) {
706e8d8bef9SDimitry Andric     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
707e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
708e8d8bef9SDimitry Andric     // Any use-before-defs no longer apply.
709e8d8bef9SDimitry Andric     UseBeforeDefVariables.erase(Var);
710e8d8bef9SDimitry Andric 
711bdd1243dSDimitry Andric     // Erase any previous location.
712e8d8bef9SDimitry Andric     auto It = ActiveVLocs.find(Var);
713bdd1243dSDimitry Andric     if (It != ActiveVLocs.end()) {
714bdd1243dSDimitry Andric       for (LocIdx Loc : It->second.loc_indices())
715bdd1243dSDimitry Andric         ActiveMLocs[Loc].erase(Var);
716bdd1243dSDimitry Andric     }
717e8d8bef9SDimitry Andric 
718e8d8bef9SDimitry Andric     // If there _is_ no new location, all we had to do was erase.
719bdd1243dSDimitry Andric     if (NewLocs.empty()) {
720bdd1243dSDimitry Andric       if (It != ActiveVLocs.end())
721bdd1243dSDimitry Andric         ActiveVLocs.erase(It);
722e8d8bef9SDimitry Andric       return;
723bdd1243dSDimitry Andric     }
724e8d8bef9SDimitry Andric 
725bdd1243dSDimitry Andric     SmallVector<std::pair<LocIdx, DebugVariable>> LostMLocs;
726bdd1243dSDimitry Andric     for (ResolvedDbgOp &Op : NewLocs) {
727bdd1243dSDimitry Andric       if (Op.IsConst)
728bdd1243dSDimitry Andric         continue;
729bdd1243dSDimitry Andric 
730bdd1243dSDimitry Andric       LocIdx NewLoc = Op.Loc;
731bdd1243dSDimitry Andric 
732bdd1243dSDimitry Andric       // Check whether our local copy of values-by-location in #VarLocs is out
733bdd1243dSDimitry Andric       // of date. Wipe old tracking data for the location if it's been clobbered
734bdd1243dSDimitry Andric       // in the meantime.
735349cc55cSDimitry Andric       if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
736fcaf7f86SDimitry Andric         for (const auto &P : ActiveMLocs[NewLoc]) {
737bdd1243dSDimitry Andric           auto LostVLocIt = ActiveVLocs.find(P);
738bdd1243dSDimitry Andric           if (LostVLocIt != ActiveVLocs.end()) {
739bdd1243dSDimitry Andric             for (LocIdx Loc : LostVLocIt->second.loc_indices()) {
740bdd1243dSDimitry Andric               // Every active variable mapping for NewLoc will be cleared, no
741bdd1243dSDimitry Andric               // need to track individual variables.
742bdd1243dSDimitry Andric               if (Loc == NewLoc)
743bdd1243dSDimitry Andric                 continue;
744bdd1243dSDimitry Andric               LostMLocs.emplace_back(Loc, P);
745bdd1243dSDimitry Andric             }
746bdd1243dSDimitry Andric           }
747e8d8bef9SDimitry Andric           ActiveVLocs.erase(P);
748e8d8bef9SDimitry Andric         }
749bdd1243dSDimitry Andric         for (const auto &LostMLoc : LostMLocs)
750bdd1243dSDimitry Andric           ActiveMLocs[LostMLoc.first].erase(LostMLoc.second);
751bdd1243dSDimitry Andric         LostMLocs.clear();
752bdd1243dSDimitry Andric         It = ActiveVLocs.find(Var);
753e8d8bef9SDimitry Andric         ActiveMLocs[NewLoc.asU64()].clear();
754349cc55cSDimitry Andric         VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
755e8d8bef9SDimitry Andric       }
756e8d8bef9SDimitry Andric 
757e8d8bef9SDimitry Andric       ActiveMLocs[NewLoc].insert(Var);
758bdd1243dSDimitry Andric     }
759bdd1243dSDimitry Andric 
760e8d8bef9SDimitry Andric     if (It == ActiveVLocs.end()) {
761e8d8bef9SDimitry Andric       ActiveVLocs.insert(
762bdd1243dSDimitry Andric           std::make_pair(Var, ResolvedDbgValue(NewLocs, Properties)));
763e8d8bef9SDimitry Andric     } else {
764bdd1243dSDimitry Andric       It->second.Ops.assign(NewLocs);
765e8d8bef9SDimitry Andric       It->second.Properties = Properties;
766e8d8bef9SDimitry Andric     }
767e8d8bef9SDimitry Andric   }
768e8d8bef9SDimitry Andric 
769fe6060f1SDimitry Andric   /// Account for a location \p mloc being clobbered. Examine the variable
770fe6060f1SDimitry Andric   /// locations that will be terminated: and try to recover them by using
771fe6060f1SDimitry Andric   /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
772fe6060f1SDimitry Andric   /// explicitly terminate a location if it can't be recovered.
773fe6060f1SDimitry Andric   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
774fe6060f1SDimitry Andric                    bool MakeUndef = true) {
775e8d8bef9SDimitry Andric     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
776e8d8bef9SDimitry Andric     if (ActiveMLocIt == ActiveMLocs.end())
777e8d8bef9SDimitry Andric       return;
778e8d8bef9SDimitry Andric 
779fe6060f1SDimitry Andric     // What was the old variable value?
780fe6060f1SDimitry Andric     ValueIDNum OldValue = VarLocs[MLoc.asU64()];
781753f127fSDimitry Andric     clobberMloc(MLoc, OldValue, Pos, MakeUndef);
782753f127fSDimitry Andric   }
783753f127fSDimitry Andric   /// Overload that takes an explicit value \p OldValue for when the value in
784753f127fSDimitry Andric   /// \p MLoc has changed and the TransferTracker's locations have not been
785753f127fSDimitry Andric   /// updated yet.
786753f127fSDimitry Andric   void clobberMloc(LocIdx MLoc, ValueIDNum OldValue,
787753f127fSDimitry Andric                    MachineBasicBlock::iterator Pos, bool MakeUndef = true) {
788753f127fSDimitry Andric     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
789753f127fSDimitry Andric     if (ActiveMLocIt == ActiveMLocs.end())
790753f127fSDimitry Andric       return;
791753f127fSDimitry Andric 
792e8d8bef9SDimitry Andric     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
793e8d8bef9SDimitry Andric 
794fe6060f1SDimitry Andric     // Examine the remaining variable locations: if we can find the same value
795fe6060f1SDimitry Andric     // again, we can recover the location.
796bdd1243dSDimitry Andric     std::optional<LocIdx> NewLoc;
797fe6060f1SDimitry Andric     for (auto Loc : MTracker->locations())
798fe6060f1SDimitry Andric       if (Loc.Value == OldValue)
799fe6060f1SDimitry Andric         NewLoc = Loc.Idx;
800fe6060f1SDimitry Andric 
801fe6060f1SDimitry Andric     // If there is no location, and we weren't asked to make the variable
802fe6060f1SDimitry Andric     // explicitly undef, then stop here.
803fe6060f1SDimitry Andric     if (!NewLoc && !MakeUndef) {
804fe6060f1SDimitry Andric       // Try and recover a few more locations with entry values.
805fcaf7f86SDimitry Andric       for (const auto &Var : ActiveMLocIt->second) {
806fe6060f1SDimitry Andric         auto &Prop = ActiveVLocs.find(Var)->second.Properties;
807fe6060f1SDimitry Andric         recoverAsEntryValue(Var, Prop, OldValue);
808fe6060f1SDimitry Andric       }
809fe6060f1SDimitry Andric       flushDbgValues(Pos, nullptr);
810fe6060f1SDimitry Andric       return;
811fe6060f1SDimitry Andric     }
812fe6060f1SDimitry Andric 
813fe6060f1SDimitry Andric     // Examine all the variables based on this location.
814fe6060f1SDimitry Andric     DenseSet<DebugVariable> NewMLocs;
815bdd1243dSDimitry Andric     // If no new location has been found, every variable that depends on this
816bdd1243dSDimitry Andric     // MLoc is dead, so end their existing MLoc->Var mappings as well.
817bdd1243dSDimitry Andric     SmallVector<std::pair<LocIdx, DebugVariable>> LostMLocs;
818fcaf7f86SDimitry Andric     for (const auto &Var : ActiveMLocIt->second) {
819e8d8bef9SDimitry Andric       auto ActiveVLocIt = ActiveVLocs.find(Var);
820fe6060f1SDimitry Andric       // Re-state the variable location: if there's no replacement then NewLoc
821bdd1243dSDimitry Andric       // is std::nullopt and a $noreg DBG_VALUE will be created. Otherwise, a
822bdd1243dSDimitry Andric       // DBG_VALUE identifying the alternative location will be emitted.
8234824e7fdSDimitry Andric       const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
824bdd1243dSDimitry Andric 
825bdd1243dSDimitry Andric       // Produce the new list of debug ops - an empty list if no new location
826bdd1243dSDimitry Andric       // was found, or the existing list with the substitution MLoc -> NewLoc
827bdd1243dSDimitry Andric       // otherwise.
828bdd1243dSDimitry Andric       SmallVector<ResolvedDbgOp> DbgOps;
829bdd1243dSDimitry Andric       if (NewLoc) {
830bdd1243dSDimitry Andric         ResolvedDbgOp OldOp(MLoc);
831bdd1243dSDimitry Andric         ResolvedDbgOp NewOp(*NewLoc);
832bdd1243dSDimitry Andric         // Insert illegal ops to overwrite afterwards.
833bdd1243dSDimitry Andric         DbgOps.insert(DbgOps.begin(), ActiveVLocIt->second.Ops.size(),
834bdd1243dSDimitry Andric                       ResolvedDbgOp(LocIdx::MakeIllegalLoc()));
835bdd1243dSDimitry Andric         replace_copy(ActiveVLocIt->second.Ops, DbgOps.begin(), OldOp, NewOp);
836bdd1243dSDimitry Andric       }
837bdd1243dSDimitry Andric 
838bdd1243dSDimitry Andric       PendingDbgValues.push_back(MTracker->emitLoc(DbgOps, Var, Properties));
839fe6060f1SDimitry Andric 
840fe6060f1SDimitry Andric       // Update machine locations <=> variable locations maps. Defer updating
841bdd1243dSDimitry Andric       // ActiveMLocs to avoid invalidating the ActiveMLocIt iterator.
842fe6060f1SDimitry Andric       if (!NewLoc) {
843bdd1243dSDimitry Andric         for (LocIdx Loc : ActiveVLocIt->second.loc_indices()) {
844bdd1243dSDimitry Andric           if (Loc != MLoc)
845bdd1243dSDimitry Andric             LostMLocs.emplace_back(Loc, Var);
846bdd1243dSDimitry Andric         }
847e8d8bef9SDimitry Andric         ActiveVLocs.erase(ActiveVLocIt);
848fe6060f1SDimitry Andric       } else {
849bdd1243dSDimitry Andric         ActiveVLocIt->second.Ops = DbgOps;
850fe6060f1SDimitry Andric         NewMLocs.insert(Var);
851e8d8bef9SDimitry Andric       }
852fe6060f1SDimitry Andric     }
853fe6060f1SDimitry Andric 
854bdd1243dSDimitry Andric     // Remove variables from ActiveMLocs if they no longer use any other MLocs
855bdd1243dSDimitry Andric     // due to being killed by this clobber.
856bdd1243dSDimitry Andric     for (auto &LocVarIt : LostMLocs) {
857bdd1243dSDimitry Andric       auto LostMLocIt = ActiveMLocs.find(LocVarIt.first);
858bdd1243dSDimitry Andric       assert(LostMLocIt != ActiveMLocs.end() &&
859bdd1243dSDimitry Andric              "Variable was using this MLoc, but ActiveMLocs[MLoc] has no "
860bdd1243dSDimitry Andric              "entries?");
861bdd1243dSDimitry Andric       LostMLocIt->second.erase(LocVarIt.second);
862bdd1243dSDimitry Andric     }
863fe6060f1SDimitry Andric 
864fe6060f1SDimitry Andric     // We lazily track what locations have which values; if we've found a new
865fe6060f1SDimitry Andric     // location for the clobbered value, remember it.
866fe6060f1SDimitry Andric     if (NewLoc)
867fe6060f1SDimitry Andric       VarLocs[NewLoc->asU64()] = OldValue;
868fe6060f1SDimitry Andric 
869e8d8bef9SDimitry Andric     flushDbgValues(Pos, nullptr);
870e8d8bef9SDimitry Andric 
871bdd1243dSDimitry Andric     // Commit ActiveMLoc changes.
872e8d8bef9SDimitry Andric     ActiveMLocIt->second.clear();
873bdd1243dSDimitry Andric     if (!NewMLocs.empty())
874bdd1243dSDimitry Andric       for (auto &Var : NewMLocs)
875bdd1243dSDimitry Andric         ActiveMLocs[*NewLoc].insert(Var);
876e8d8bef9SDimitry Andric   }
877e8d8bef9SDimitry Andric 
878e8d8bef9SDimitry Andric   /// Transfer variables based on \p Src to be based on \p Dst. This handles
879e8d8bef9SDimitry Andric   /// both register copies as well as spills and restores. Creates DBG_VALUEs
880e8d8bef9SDimitry Andric   /// describing the movement.
881e8d8bef9SDimitry Andric   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
882e8d8bef9SDimitry Andric     // Does Src still contain the value num we expect? If not, it's been
883e8d8bef9SDimitry Andric     // clobbered in the meantime, and our variable locations are stale.
884349cc55cSDimitry Andric     if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
885e8d8bef9SDimitry Andric       return;
886e8d8bef9SDimitry Andric 
887e8d8bef9SDimitry Andric     // assert(ActiveMLocs[Dst].size() == 0);
888e8d8bef9SDimitry Andric     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
889349cc55cSDimitry Andric 
890349cc55cSDimitry Andric     // Move set of active variables from one location to another.
891349cc55cSDimitry Andric     auto MovingVars = ActiveMLocs[Src];
892bdd1243dSDimitry Andric     ActiveMLocs[Dst].insert(MovingVars.begin(), MovingVars.end());
893e8d8bef9SDimitry Andric     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
894e8d8bef9SDimitry Andric 
895e8d8bef9SDimitry Andric     // For each variable based on Src; create a location at Dst.
896bdd1243dSDimitry Andric     ResolvedDbgOp SrcOp(Src);
897bdd1243dSDimitry Andric     ResolvedDbgOp DstOp(Dst);
898fcaf7f86SDimitry Andric     for (const auto &Var : MovingVars) {
899e8d8bef9SDimitry Andric       auto ActiveVLocIt = ActiveVLocs.find(Var);
900e8d8bef9SDimitry Andric       assert(ActiveVLocIt != ActiveVLocs.end());
901e8d8bef9SDimitry Andric 
902bdd1243dSDimitry Andric       // Update all instances of Src in the variable's tracked values to Dst.
903bdd1243dSDimitry Andric       std::replace(ActiveVLocIt->second.Ops.begin(),
904bdd1243dSDimitry Andric                    ActiveVLocIt->second.Ops.end(), SrcOp, DstOp);
905bdd1243dSDimitry Andric 
906bdd1243dSDimitry Andric       MachineInstr *MI = MTracker->emitLoc(ActiveVLocIt->second.Ops, Var,
907bdd1243dSDimitry Andric                                            ActiveVLocIt->second.Properties);
908e8d8bef9SDimitry Andric       PendingDbgValues.push_back(MI);
909e8d8bef9SDimitry Andric     }
910e8d8bef9SDimitry Andric     ActiveMLocs[Src].clear();
911e8d8bef9SDimitry Andric     flushDbgValues(Pos, nullptr);
912e8d8bef9SDimitry Andric 
913e8d8bef9SDimitry Andric     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
914e8d8bef9SDimitry Andric     // about the old location.
915e8d8bef9SDimitry Andric     if (EmulateOldLDV)
916e8d8bef9SDimitry Andric       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
917e8d8bef9SDimitry Andric   }
918e8d8bef9SDimitry Andric 
919e8d8bef9SDimitry Andric   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
920e8d8bef9SDimitry Andric                                 const DebugVariable &Var,
921e8d8bef9SDimitry Andric                                 const DbgValueProperties &Properties) {
922e8d8bef9SDimitry Andric     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
923e8d8bef9SDimitry Andric                                   Var.getVariable()->getScope(),
924e8d8bef9SDimitry Andric                                   const_cast<DILocation *>(Var.getInlinedAt()));
925e8d8bef9SDimitry Andric     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
926e8d8bef9SDimitry Andric     MIB.add(MO);
927e8d8bef9SDimitry Andric     if (Properties.Indirect)
928e8d8bef9SDimitry Andric       MIB.addImm(0);
929e8d8bef9SDimitry Andric     else
930e8d8bef9SDimitry Andric       MIB.addReg(0);
931e8d8bef9SDimitry Andric     MIB.addMetadata(Var.getVariable());
932e8d8bef9SDimitry Andric     MIB.addMetadata(Properties.DIExpr);
933e8d8bef9SDimitry Andric     return MIB;
934e8d8bef9SDimitry Andric   }
935e8d8bef9SDimitry Andric };
936e8d8bef9SDimitry Andric 
937349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
938349cc55cSDimitry Andric //            Implementation
939349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
940e8d8bef9SDimitry Andric 
941349cc55cSDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
942349cc55cSDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
943e8d8bef9SDimitry Andric 
944349cc55cSDimitry Andric #ifndef NDEBUG
945bdd1243dSDimitry Andric void ResolvedDbgOp::dump(const MLocTracker *MTrack) const {
946bdd1243dSDimitry Andric   if (IsConst) {
947bdd1243dSDimitry Andric     dbgs() << MO;
948349cc55cSDimitry Andric   } else {
949bdd1243dSDimitry Andric     dbgs() << MTrack->LocIdxToName(Loc);
950bdd1243dSDimitry Andric   }
951bdd1243dSDimitry Andric }
952bdd1243dSDimitry Andric void DbgOp::dump(const MLocTracker *MTrack) const {
953bdd1243dSDimitry Andric   if (IsConst) {
954bdd1243dSDimitry Andric     dbgs() << MO;
955bdd1243dSDimitry Andric   } else if (!isUndef()) {
956349cc55cSDimitry Andric     dbgs() << MTrack->IDAsString(ID);
957349cc55cSDimitry Andric   }
958bdd1243dSDimitry Andric }
959bdd1243dSDimitry Andric void DbgOpID::dump(const MLocTracker *MTrack, const DbgOpIDMap *OpStore) const {
960bdd1243dSDimitry Andric   if (!OpStore) {
961bdd1243dSDimitry Andric     dbgs() << "ID(" << asU32() << ")";
962bdd1243dSDimitry Andric   } else {
963bdd1243dSDimitry Andric     OpStore->find(*this).dump(MTrack);
964bdd1243dSDimitry Andric   }
965bdd1243dSDimitry Andric }
966bdd1243dSDimitry Andric void DbgValue::dump(const MLocTracker *MTrack,
967bdd1243dSDimitry Andric                     const DbgOpIDMap *OpStore) const {
968bdd1243dSDimitry Andric   if (Kind == NoVal) {
969bdd1243dSDimitry Andric     dbgs() << "NoVal(" << BlockNo << ")";
970bdd1243dSDimitry Andric   } else if (Kind == VPHI || Kind == Def) {
971bdd1243dSDimitry Andric     if (Kind == VPHI)
972bdd1243dSDimitry Andric       dbgs() << "VPHI(" << BlockNo << ",";
973bdd1243dSDimitry Andric     else
974bdd1243dSDimitry Andric       dbgs() << "Def(";
975bdd1243dSDimitry Andric     for (unsigned Idx = 0; Idx < getDbgOpIDs().size(); ++Idx) {
976bdd1243dSDimitry Andric       getDbgOpID(Idx).dump(MTrack, OpStore);
977bdd1243dSDimitry Andric       if (Idx != 0)
978bdd1243dSDimitry Andric         dbgs() << ",";
979bdd1243dSDimitry Andric     }
980bdd1243dSDimitry Andric     dbgs() << ")";
981bdd1243dSDimitry Andric   }
982349cc55cSDimitry Andric   if (Properties.Indirect)
983349cc55cSDimitry Andric     dbgs() << " indir";
984349cc55cSDimitry Andric   if (Properties.DIExpr)
985349cc55cSDimitry Andric     dbgs() << " " << *Properties.DIExpr;
986349cc55cSDimitry Andric }
987349cc55cSDimitry Andric #endif
988e8d8bef9SDimitry Andric 
989349cc55cSDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
990349cc55cSDimitry Andric                          const TargetRegisterInfo &TRI,
991349cc55cSDimitry Andric                          const TargetLowering &TLI)
992349cc55cSDimitry Andric     : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
993349cc55cSDimitry Andric       LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
994349cc55cSDimitry Andric   NumRegs = TRI.getNumRegs();
995349cc55cSDimitry Andric   reset();
996349cc55cSDimitry Andric   LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
997349cc55cSDimitry Andric   assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
998e8d8bef9SDimitry Andric 
999349cc55cSDimitry Andric   // Always track SP. This avoids the implicit clobbering caused by regmasks
1000349cc55cSDimitry Andric   // from affectings its values. (LiveDebugValues disbelieves calls and
1001349cc55cSDimitry Andric   // regmasks that claim to clobber SP).
1002349cc55cSDimitry Andric   Register SP = TLI.getStackPointerRegisterToSaveRestore();
1003349cc55cSDimitry Andric   if (SP) {
1004349cc55cSDimitry Andric     unsigned ID = getLocID(SP);
1005349cc55cSDimitry Andric     (void)lookupOrTrackRegister(ID);
1006e8d8bef9SDimitry Andric 
1007349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
1008349cc55cSDimitry Andric       SPAliases.insert(*RAI);
1009349cc55cSDimitry Andric   }
1010e8d8bef9SDimitry Andric 
1011349cc55cSDimitry Andric   // Build some common stack positions -- full registers being spilt to the
1012349cc55cSDimitry Andric   // stack.
1013349cc55cSDimitry Andric   StackSlotIdxes.insert({{8, 0}, 0});
1014349cc55cSDimitry Andric   StackSlotIdxes.insert({{16, 0}, 1});
1015349cc55cSDimitry Andric   StackSlotIdxes.insert({{32, 0}, 2});
1016349cc55cSDimitry Andric   StackSlotIdxes.insert({{64, 0}, 3});
1017349cc55cSDimitry Andric   StackSlotIdxes.insert({{128, 0}, 4});
1018349cc55cSDimitry Andric   StackSlotIdxes.insert({{256, 0}, 5});
1019349cc55cSDimitry Andric   StackSlotIdxes.insert({{512, 0}, 6});
1020e8d8bef9SDimitry Andric 
1021349cc55cSDimitry Andric   // Traverse all the subregister idxes, and ensure there's an index for them.
1022349cc55cSDimitry Andric   // Duplicates are no problem: we're interested in their position in the
1023349cc55cSDimitry Andric   // stack slot, we don't want to type the slot.
1024349cc55cSDimitry Andric   for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
1025349cc55cSDimitry Andric     unsigned Size = TRI.getSubRegIdxSize(I);
1026349cc55cSDimitry Andric     unsigned Offs = TRI.getSubRegIdxOffset(I);
1027349cc55cSDimitry Andric     unsigned Idx = StackSlotIdxes.size();
1028e8d8bef9SDimitry Andric 
1029349cc55cSDimitry Andric     // Some subregs have -1, -2 and so forth fed into their fields, to mean
1030349cc55cSDimitry Andric     // special backend things. Ignore those.
1031349cc55cSDimitry Andric     if (Size > 60000 || Offs > 60000)
1032349cc55cSDimitry Andric       continue;
1033e8d8bef9SDimitry Andric 
1034349cc55cSDimitry Andric     StackSlotIdxes.insert({{Size, Offs}, Idx});
1035349cc55cSDimitry Andric   }
1036e8d8bef9SDimitry Andric 
103781ad6265SDimitry Andric   // There may also be strange register class sizes (think x86 fp80s).
103881ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI.regclasses()) {
103981ad6265SDimitry Andric     unsigned Size = TRI.getRegSizeInBits(*RC);
104081ad6265SDimitry Andric 
104181ad6265SDimitry Andric     // We might see special reserved values as sizes, and classes for other
104281ad6265SDimitry Andric     // stuff the machine tries to model. If it's more than 512 bits, then it
104381ad6265SDimitry Andric     // is very unlikely to be a register than can be spilt.
104481ad6265SDimitry Andric     if (Size > 512)
104581ad6265SDimitry Andric       continue;
104681ad6265SDimitry Andric 
104781ad6265SDimitry Andric     unsigned Idx = StackSlotIdxes.size();
104881ad6265SDimitry Andric     StackSlotIdxes.insert({{Size, 0}, Idx});
104981ad6265SDimitry Andric   }
105081ad6265SDimitry Andric 
1051349cc55cSDimitry Andric   for (auto &Idx : StackSlotIdxes)
1052349cc55cSDimitry Andric     StackIdxesToPos[Idx.second] = Idx.first;
1053e8d8bef9SDimitry Andric 
1054349cc55cSDimitry Andric   NumSlotIdxes = StackSlotIdxes.size();
1055349cc55cSDimitry Andric }
1056e8d8bef9SDimitry Andric 
1057349cc55cSDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) {
1058349cc55cSDimitry Andric   assert(ID != 0);
1059349cc55cSDimitry Andric   LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
1060349cc55cSDimitry Andric   LocIdxToIDNum.grow(NewIdx);
1061349cc55cSDimitry Andric   LocIdxToLocID.grow(NewIdx);
1062e8d8bef9SDimitry Andric 
1063349cc55cSDimitry Andric   // Default: it's an mphi.
1064349cc55cSDimitry Andric   ValueIDNum ValNum = {CurBB, 0, NewIdx};
1065349cc55cSDimitry Andric   // Was this reg ever touched by a regmask?
1066349cc55cSDimitry Andric   for (const auto &MaskPair : reverse(Masks)) {
1067349cc55cSDimitry Andric     if (MaskPair.first->clobbersPhysReg(ID)) {
1068349cc55cSDimitry Andric       // There was an earlier def we skipped.
1069349cc55cSDimitry Andric       ValNum = {CurBB, MaskPair.second, NewIdx};
1070349cc55cSDimitry Andric       break;
1071349cc55cSDimitry Andric     }
1072349cc55cSDimitry Andric   }
1073e8d8bef9SDimitry Andric 
1074349cc55cSDimitry Andric   LocIdxToIDNum[NewIdx] = ValNum;
1075349cc55cSDimitry Andric   LocIdxToLocID[NewIdx] = ID;
1076349cc55cSDimitry Andric   return NewIdx;
1077349cc55cSDimitry Andric }
1078e8d8bef9SDimitry Andric 
1079349cc55cSDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
1080349cc55cSDimitry Andric                                unsigned InstID) {
1081349cc55cSDimitry Andric   // Def any register we track have that isn't preserved. The regmask
1082349cc55cSDimitry Andric   // terminates the liveness of a register, meaning its value can't be
1083349cc55cSDimitry Andric   // relied upon -- we represent this by giving it a new value.
1084349cc55cSDimitry Andric   for (auto Location : locations()) {
1085349cc55cSDimitry Andric     unsigned ID = LocIdxToLocID[Location.Idx];
1086349cc55cSDimitry Andric     // Don't clobber SP, even if the mask says it's clobbered.
1087349cc55cSDimitry Andric     if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
1088349cc55cSDimitry Andric       defReg(ID, CurBB, InstID);
1089349cc55cSDimitry Andric   }
1090349cc55cSDimitry Andric   Masks.push_back(std::make_pair(MO, InstID));
1091349cc55cSDimitry Andric }
1092e8d8bef9SDimitry Andric 
1093bdd1243dSDimitry Andric std::optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
1094349cc55cSDimitry Andric   SpillLocationNo SpillID(SpillLocs.idFor(L));
1095d56accc7SDimitry Andric 
1096349cc55cSDimitry Andric   if (SpillID.id() == 0) {
1097d56accc7SDimitry Andric     // If there is no location, and we have reached the limit of how many stack
1098d56accc7SDimitry Andric     // slots to track, then don't track this one.
1099d56accc7SDimitry Andric     if (SpillLocs.size() >= StackWorkingSetLimit)
1100bdd1243dSDimitry Andric       return std::nullopt;
1101d56accc7SDimitry Andric 
1102349cc55cSDimitry Andric     // Spill location is untracked: create record for this one, and all
1103349cc55cSDimitry Andric     // subregister slots too.
1104349cc55cSDimitry Andric     SpillID = SpillLocationNo(SpillLocs.insert(L));
1105349cc55cSDimitry Andric     for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
1106349cc55cSDimitry Andric       unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
1107349cc55cSDimitry Andric       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
1108349cc55cSDimitry Andric       LocIdxToIDNum.grow(Idx);
1109349cc55cSDimitry Andric       LocIdxToLocID.grow(Idx);
1110349cc55cSDimitry Andric       LocIDToLocIdx.push_back(Idx);
1111349cc55cSDimitry Andric       LocIdxToLocID[Idx] = L;
1112349cc55cSDimitry Andric       // Initialize to PHI value; corresponds to the location's live-in value
1113349cc55cSDimitry Andric       // during transfer function construction.
1114349cc55cSDimitry Andric       LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
1115349cc55cSDimitry Andric     }
1116349cc55cSDimitry Andric   }
1117349cc55cSDimitry Andric   return SpillID;
1118349cc55cSDimitry Andric }
1119fe6060f1SDimitry Andric 
1120349cc55cSDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
1121349cc55cSDimitry Andric   unsigned ID = LocIdxToLocID[Idx];
1122349cc55cSDimitry Andric   if (ID >= NumRegs) {
1123349cc55cSDimitry Andric     StackSlotPos Pos = locIDToSpillIdx(ID);
1124349cc55cSDimitry Andric     ID -= NumRegs;
1125349cc55cSDimitry Andric     unsigned Slot = ID / NumSlotIdxes;
1126349cc55cSDimitry Andric     return Twine("slot ")
1127349cc55cSDimitry Andric         .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
1128349cc55cSDimitry Andric         .concat(Twine(" offs ").concat(Twine(Pos.second))))))
1129349cc55cSDimitry Andric         .str();
1130349cc55cSDimitry Andric   } else {
1131349cc55cSDimitry Andric     return TRI.getRegAsmName(ID).str();
1132349cc55cSDimitry Andric   }
1133349cc55cSDimitry Andric }
1134fe6060f1SDimitry Andric 
1135349cc55cSDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
1136349cc55cSDimitry Andric   std::string DefName = LocIdxToName(Num.getLoc());
1137349cc55cSDimitry Andric   return Num.asString(DefName);
1138349cc55cSDimitry Andric }
1139fe6060f1SDimitry Andric 
1140349cc55cSDimitry Andric #ifndef NDEBUG
1141349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() {
1142349cc55cSDimitry Andric   for (auto Location : locations()) {
1143349cc55cSDimitry Andric     std::string MLocName = LocIdxToName(Location.Value.getLoc());
1144349cc55cSDimitry Andric     std::string DefName = Location.Value.asString(MLocName);
1145349cc55cSDimitry Andric     dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
1146349cc55cSDimitry Andric   }
1147349cc55cSDimitry Andric }
1148e8d8bef9SDimitry Andric 
1149349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
1150349cc55cSDimitry Andric   for (auto Location : locations()) {
1151349cc55cSDimitry Andric     std::string foo = LocIdxToName(Location.Idx);
1152349cc55cSDimitry Andric     dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
1153349cc55cSDimitry Andric   }
1154349cc55cSDimitry Andric }
1155349cc55cSDimitry Andric #endif
1156e8d8bef9SDimitry Andric 
1157bdd1243dSDimitry Andric MachineInstrBuilder
1158bdd1243dSDimitry Andric MLocTracker::emitLoc(const SmallVectorImpl<ResolvedDbgOp> &DbgOps,
1159349cc55cSDimitry Andric                      const DebugVariable &Var,
1160349cc55cSDimitry Andric                      const DbgValueProperties &Properties) {
1161349cc55cSDimitry Andric   DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
1162349cc55cSDimitry Andric                                 Var.getVariable()->getScope(),
1163349cc55cSDimitry Andric                                 const_cast<DILocation *>(Var.getInlinedAt()));
1164bdd1243dSDimitry Andric 
1165bdd1243dSDimitry Andric   const MCInstrDesc &Desc = Properties.IsVariadic
1166bdd1243dSDimitry Andric                                 ? TII.get(TargetOpcode::DBG_VALUE_LIST)
1167bdd1243dSDimitry Andric                                 : TII.get(TargetOpcode::DBG_VALUE);
1168bdd1243dSDimitry Andric 
1169bdd1243dSDimitry Andric #ifdef EXPENSIVE_CHECKS
1170bdd1243dSDimitry Andric   assert(all_of(DbgOps,
1171bdd1243dSDimitry Andric                 [](const ResolvedDbgOp &Op) {
1172bdd1243dSDimitry Andric                   return Op.IsConst || !Op.Loc.isIllegal();
1173bdd1243dSDimitry Andric                 }) &&
1174bdd1243dSDimitry Andric          "Did not expect illegal ops in DbgOps.");
1175bdd1243dSDimitry Andric   assert((DbgOps.size() == 0 ||
1176bdd1243dSDimitry Andric           DbgOps.size() == Properties.getLocationOpCount()) &&
1177bdd1243dSDimitry Andric          "Expected to have either one DbgOp per MI LocationOp, or none.");
1178bdd1243dSDimitry Andric #endif
1179bdd1243dSDimitry Andric 
1180bdd1243dSDimitry Andric   auto GetRegOp = [](unsigned Reg) -> MachineOperand {
1181bdd1243dSDimitry Andric     return MachineOperand::CreateReg(
1182bdd1243dSDimitry Andric         /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
1183bdd1243dSDimitry Andric         /* isKill */ false, /* isDead */ false,
1184bdd1243dSDimitry Andric         /* isUndef */ false, /* isEarlyClobber */ false,
1185bdd1243dSDimitry Andric         /* SubReg */ 0, /* isDebug */ true);
1186bdd1243dSDimitry Andric   };
1187bdd1243dSDimitry Andric 
1188bdd1243dSDimitry Andric   SmallVector<MachineOperand> MOs;
1189bdd1243dSDimitry Andric 
1190bdd1243dSDimitry Andric   auto EmitUndef = [&]() {
1191bdd1243dSDimitry Andric     MOs.clear();
1192bdd1243dSDimitry Andric     MOs.assign(Properties.getLocationOpCount(), GetRegOp(0));
1193bdd1243dSDimitry Andric     return BuildMI(MF, DL, Desc, false, MOs, Var.getVariable(),
1194bdd1243dSDimitry Andric                    Properties.DIExpr);
1195bdd1243dSDimitry Andric   };
1196bdd1243dSDimitry Andric 
1197bdd1243dSDimitry Andric   // Don't bother passing any real operands to BuildMI if any of them would be
1198bdd1243dSDimitry Andric   // $noreg.
1199bdd1243dSDimitry Andric   if (DbgOps.empty())
1200bdd1243dSDimitry Andric     return EmitUndef();
1201bdd1243dSDimitry Andric 
1202bdd1243dSDimitry Andric   bool Indirect = Properties.Indirect;
1203e8d8bef9SDimitry Andric 
1204349cc55cSDimitry Andric   const DIExpression *Expr = Properties.DIExpr;
1205bdd1243dSDimitry Andric 
1206bdd1243dSDimitry Andric   assert(DbgOps.size() == Properties.getLocationOpCount());
1207bdd1243dSDimitry Andric 
1208bdd1243dSDimitry Andric   // If all locations are valid, accumulate them into our list of
1209bdd1243dSDimitry Andric   // MachineOperands. For any spilled locations, either update the indirectness
1210bdd1243dSDimitry Andric   // register or apply the appropriate transformations in the DIExpression.
1211bdd1243dSDimitry Andric   for (size_t Idx = 0; Idx < Properties.getLocationOpCount(); ++Idx) {
1212bdd1243dSDimitry Andric     const ResolvedDbgOp &Op = DbgOps[Idx];
1213bdd1243dSDimitry Andric 
1214bdd1243dSDimitry Andric     if (Op.IsConst) {
1215bdd1243dSDimitry Andric       MOs.push_back(Op.MO);
1216bdd1243dSDimitry Andric       continue;
1217bdd1243dSDimitry Andric     }
1218bdd1243dSDimitry Andric 
1219bdd1243dSDimitry Andric     LocIdx MLoc = Op.Loc;
1220bdd1243dSDimitry Andric     unsigned LocID = LocIdxToLocID[MLoc];
1221bdd1243dSDimitry Andric     if (LocID >= NumRegs) {
1222349cc55cSDimitry Andric       SpillLocationNo SpillID = locIDToSpill(LocID);
1223349cc55cSDimitry Andric       StackSlotPos StackIdx = locIDToSpillIdx(LocID);
1224349cc55cSDimitry Andric       unsigned short Offset = StackIdx.second;
1225e8d8bef9SDimitry Andric 
1226349cc55cSDimitry Andric       // TODO: support variables that are located in spill slots, with non-zero
1227349cc55cSDimitry Andric       // offsets from the start of the spill slot. It would require some more
1228349cc55cSDimitry Andric       // complex DIExpression calculations. This doesn't seem to be produced by
1229349cc55cSDimitry Andric       // LLVM right now, so don't try and support it.
1230349cc55cSDimitry Andric       // Accept no-subregister slots and subregisters where the offset is zero.
1231349cc55cSDimitry Andric       // The consumer should already have type information to work out how large
1232349cc55cSDimitry Andric       // the variable is.
1233349cc55cSDimitry Andric       if (Offset == 0) {
1234349cc55cSDimitry Andric         const SpillLoc &Spill = SpillLocs[SpillID.id()];
1235349cc55cSDimitry Andric         unsigned Base = Spill.SpillBase;
12364824e7fdSDimitry Andric 
123781ad6265SDimitry Andric         // There are several ways we can dereference things, and several inputs
123881ad6265SDimitry Andric         // to consider:
123981ad6265SDimitry Andric         // * NRVO variables will appear with IsIndirect set, but should have
124081ad6265SDimitry Andric         //   nothing else in their DIExpressions,
124181ad6265SDimitry Andric         // * Variables with DW_OP_stack_value in their expr already need an
124281ad6265SDimitry Andric         //   explicit dereference of the stack location,
124381ad6265SDimitry Andric         // * Values that don't match the variable size need DW_OP_deref_size,
124481ad6265SDimitry Andric         // * Everything else can just become a simple location expression.
124581ad6265SDimitry Andric 
124681ad6265SDimitry Andric         // We need to use deref_size whenever there's a mismatch between the
124781ad6265SDimitry Andric         // size of value and the size of variable portion being read.
124881ad6265SDimitry Andric         // Additionally, we should use it whenever dealing with stack_value
124981ad6265SDimitry Andric         // fragments, to avoid the consumer having to determine the deref size
125081ad6265SDimitry Andric         // from DW_OP_piece.
125181ad6265SDimitry Andric         bool UseDerefSize = false;
1252bdd1243dSDimitry Andric         unsigned ValueSizeInBits = getLocSizeInBits(MLoc);
125381ad6265SDimitry Andric         unsigned DerefSizeInBytes = ValueSizeInBits / 8;
125481ad6265SDimitry Andric         if (auto Fragment = Var.getFragment()) {
125581ad6265SDimitry Andric           unsigned VariableSizeInBits = Fragment->SizeInBits;
125681ad6265SDimitry Andric           if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex())
125781ad6265SDimitry Andric             UseDerefSize = true;
125881ad6265SDimitry Andric         } else if (auto Size = Var.getVariable()->getSizeInBits()) {
125981ad6265SDimitry Andric           if (*Size != ValueSizeInBits) {
126081ad6265SDimitry Andric             UseDerefSize = true;
126181ad6265SDimitry Andric           }
126281ad6265SDimitry Andric         }
126381ad6265SDimitry Andric 
1264bdd1243dSDimitry Andric         SmallVector<uint64_t, 5> OffsetOps;
1265bdd1243dSDimitry Andric         TRI.getOffsetOpcodes(Spill.SpillOffset, OffsetOps);
1266bdd1243dSDimitry Andric         bool StackValue = false;
1267bdd1243dSDimitry Andric 
12684824e7fdSDimitry Andric         if (Properties.Indirect) {
126981ad6265SDimitry Andric           // This is something like an NRVO variable, where the pointer has been
1270bdd1243dSDimitry Andric           // spilt to the stack. It should end up being a memory location, with
1271bdd1243dSDimitry Andric           // the pointer to the variable loaded off the stack with a deref:
127281ad6265SDimitry Andric           assert(!Expr->isImplicit());
1273bdd1243dSDimitry Andric           OffsetOps.push_back(dwarf::DW_OP_deref);
1274bdd1243dSDimitry Andric         } else if (UseDerefSize && Expr->isSingleLocationExpression()) {
1275bdd1243dSDimitry Andric           // TODO: Figure out how to handle deref size issues for variadic
1276bdd1243dSDimitry Andric           // values.
127781ad6265SDimitry Andric           // We're loading a value off the stack that's not the same size as the
1278bdd1243dSDimitry Andric           // variable. Add / subtract stack offset, explicitly deref with a
1279bdd1243dSDimitry Andric           // size, and add DW_OP_stack_value if not already present.
1280bdd1243dSDimitry Andric           OffsetOps.push_back(dwarf::DW_OP_deref_size);
1281bdd1243dSDimitry Andric           OffsetOps.push_back(DerefSizeInBytes);
1282bdd1243dSDimitry Andric           StackValue = true;
1283bdd1243dSDimitry Andric         } else if (Expr->isComplex() || Properties.IsVariadic) {
128481ad6265SDimitry Andric           // A variable with no size ambiguity, but with extra elements in it's
128581ad6265SDimitry Andric           // expression. Manually dereference the stack location.
1286bdd1243dSDimitry Andric           OffsetOps.push_back(dwarf::DW_OP_deref);
128781ad6265SDimitry Andric         } else {
128881ad6265SDimitry Andric           // A plain value that has been spilt to the stack, with no further
128981ad6265SDimitry Andric           // context. Request a location expression, marking the DBG_VALUE as
129081ad6265SDimitry Andric           // IsIndirect.
1291bdd1243dSDimitry Andric           Indirect = true;
12924824e7fdSDimitry Andric         }
1293bdd1243dSDimitry Andric 
1294bdd1243dSDimitry Andric         Expr = DIExpression::appendOpsToArg(Expr, OffsetOps, Idx, StackValue);
1295bdd1243dSDimitry Andric         MOs.push_back(GetRegOp(Base));
1296349cc55cSDimitry Andric       } else {
1297bdd1243dSDimitry Andric         // This is a stack location with a weird subregister offset: emit an
1298bdd1243dSDimitry Andric         // undef DBG_VALUE instead.
1299bdd1243dSDimitry Andric         return EmitUndef();
1300349cc55cSDimitry Andric       }
1301349cc55cSDimitry Andric     } else {
1302349cc55cSDimitry Andric       // Non-empty, non-stack slot, must be a plain register.
1303bdd1243dSDimitry Andric       MOs.push_back(GetRegOp(LocID));
1304bdd1243dSDimitry Andric     }
1305349cc55cSDimitry Andric   }
1306e8d8bef9SDimitry Andric 
1307bdd1243dSDimitry Andric   return BuildMI(MF, DL, Desc, Indirect, MOs, Var.getVariable(), Expr);
1308349cc55cSDimitry Andric }
1309e8d8bef9SDimitry Andric 
1310e8d8bef9SDimitry Andric /// Default construct and initialize the pass.
131181ad6265SDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() = default;
1312e8d8bef9SDimitry Andric 
1313349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
1314e8d8bef9SDimitry Andric   unsigned Reg = MTracker->LocIdxToLocID[L];
1315bdd1243dSDimitry Andric   return isCalleeSavedReg(Reg);
1316bdd1243dSDimitry Andric }
1317bdd1243dSDimitry Andric bool InstrRefBasedLDV::isCalleeSavedReg(Register R) const {
1318bdd1243dSDimitry Andric   for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI)
1319e8d8bef9SDimitry Andric     if (CalleeSavedRegs.test(*RAI))
1320e8d8bef9SDimitry Andric       return true;
1321e8d8bef9SDimitry Andric   return false;
1322e8d8bef9SDimitry Andric }
1323e8d8bef9SDimitry Andric 
1324e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1325e8d8bef9SDimitry Andric //            Debug Range Extension Implementation
1326e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1327e8d8bef9SDimitry Andric 
1328e8d8bef9SDimitry Andric #ifndef NDEBUG
1329e8d8bef9SDimitry Andric // Something to restore in the future.
1330e8d8bef9SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..)
1331e8d8bef9SDimitry Andric #endif
1332e8d8bef9SDimitry Andric 
1333bdd1243dSDimitry Andric std::optional<SpillLocationNo>
1334e8d8bef9SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1335e8d8bef9SDimitry Andric   assert(MI.hasOneMemOperand() &&
1336e8d8bef9SDimitry Andric          "Spill instruction does not have exactly one memory operand?");
1337e8d8bef9SDimitry Andric   auto MMOI = MI.memoperands_begin();
1338e8d8bef9SDimitry Andric   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1339e8d8bef9SDimitry Andric   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1340e8d8bef9SDimitry Andric          "Inconsistent memory operand in spill instruction");
1341e8d8bef9SDimitry Andric   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1342e8d8bef9SDimitry Andric   const MachineBasicBlock *MBB = MI.getParent();
1343e8d8bef9SDimitry Andric   Register Reg;
1344e8d8bef9SDimitry Andric   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1345349cc55cSDimitry Andric   return MTracker->getOrTrackSpillLoc({Reg, Offset});
1346349cc55cSDimitry Andric }
1347349cc55cSDimitry Andric 
1348bdd1243dSDimitry Andric std::optional<LocIdx>
1349d56accc7SDimitry Andric InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
1350bdd1243dSDimitry Andric   std::optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
1351d56accc7SDimitry Andric   if (!SpillLoc)
1352bdd1243dSDimitry Andric     return std::nullopt;
1353349cc55cSDimitry Andric 
1354349cc55cSDimitry Andric   // Where in the stack slot is this value defined -- i.e., what size of value
1355349cc55cSDimitry Andric   // is this? An important question, because it could be loaded into a register
1356349cc55cSDimitry Andric   // from the stack at some point. Happily the memory operand will tell us
1357349cc55cSDimitry Andric   // the size written to the stack.
1358349cc55cSDimitry Andric   auto *MemOperand = *MI.memoperands_begin();
1359349cc55cSDimitry Andric   unsigned SizeInBits = MemOperand->getSizeInBits();
1360349cc55cSDimitry Andric 
1361349cc55cSDimitry Andric   // Find that position in the stack indexes we're tracking.
1362349cc55cSDimitry Andric   auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0});
1363349cc55cSDimitry Andric   if (IdxIt == MTracker->StackSlotIdxes.end())
1364349cc55cSDimitry Andric     // That index is not tracked. This is suprising, and unlikely to ever
1365349cc55cSDimitry Andric     // occur, but the safe action is to indicate the variable is optimised out.
1366bdd1243dSDimitry Andric     return std::nullopt;
1367349cc55cSDimitry Andric 
1368d56accc7SDimitry Andric   unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second);
1369349cc55cSDimitry Andric   return MTracker->getSpillMLoc(SpillID);
1370e8d8bef9SDimitry Andric }
1371e8d8bef9SDimitry Andric 
1372e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI
1373e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr.
1374e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1375e8d8bef9SDimitry Andric   if (!MI.isDebugValue())
1376e8d8bef9SDimitry Andric     return false;
1377e8d8bef9SDimitry Andric 
1378e8d8bef9SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
1379e8d8bef9SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
1380e8d8bef9SDimitry Andric   const DILocation *DebugLoc = MI.getDebugLoc();
1381e8d8bef9SDimitry Andric   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1382e8d8bef9SDimitry Andric   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1383e8d8bef9SDimitry Andric          "Expected inlined-at fields to agree");
1384e8d8bef9SDimitry Andric 
1385e8d8bef9SDimitry Andric   DebugVariable V(Var, Expr, InlinedAt);
1386e8d8bef9SDimitry Andric   DbgValueProperties Properties(MI);
1387e8d8bef9SDimitry Andric 
1388e8d8bef9SDimitry Andric   // If there are no instructions in this lexical scope, do no location tracking
1389e8d8bef9SDimitry Andric   // at all, this variable shouldn't get a legitimate location range.
1390e8d8bef9SDimitry Andric   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1391e8d8bef9SDimitry Andric   if (Scope == nullptr)
1392e8d8bef9SDimitry Andric     return true; // handled it; by doing nothing
1393e8d8bef9SDimitry Andric 
1394e8d8bef9SDimitry Andric   // MLocTracker needs to know that this register is read, even if it's only
1395e8d8bef9SDimitry Andric   // read by a debug inst.
1396bdd1243dSDimitry Andric   for (const MachineOperand &MO : MI.debug_operands())
1397e8d8bef9SDimitry Andric     if (MO.isReg() && MO.getReg() != 0)
1398e8d8bef9SDimitry Andric       (void)MTracker->readReg(MO.getReg());
1399e8d8bef9SDimitry Andric 
1400e8d8bef9SDimitry Andric   // If we're preparing for the second analysis (variables), the machine value
1401e8d8bef9SDimitry Andric   // locations are already solved, and we report this DBG_VALUE and the value
1402e8d8bef9SDimitry Andric   // it refers to to VLocTracker.
1403e8d8bef9SDimitry Andric   if (VTracker) {
1404bdd1243dSDimitry Andric     SmallVector<DbgOpID> DebugOps;
1405bdd1243dSDimitry Andric     // Feed defVar the new variable location, or if this is a DBG_VALUE $noreg,
1406bdd1243dSDimitry Andric     // feed defVar None.
1407bdd1243dSDimitry Andric     if (!MI.isUndefDebugValue()) {
1408bdd1243dSDimitry Andric       for (const MachineOperand &MO : MI.debug_operands()) {
1409bdd1243dSDimitry Andric         // There should be no undef registers here, as we've screened for undef
1410bdd1243dSDimitry Andric         // debug values.
1411e8d8bef9SDimitry Andric         if (MO.isReg()) {
1412bdd1243dSDimitry Andric           DebugOps.push_back(DbgOpStore.insert(MTracker->readReg(MO.getReg())));
1413bdd1243dSDimitry Andric         } else if (MO.isImm() || MO.isFPImm() || MO.isCImm()) {
1414bdd1243dSDimitry Andric           DebugOps.push_back(DbgOpStore.insert(MO));
1415bdd1243dSDimitry Andric         } else {
1416bdd1243dSDimitry Andric           llvm_unreachable("Unexpected debug operand type.");
1417e8d8bef9SDimitry Andric         }
1418e8d8bef9SDimitry Andric       }
1419bdd1243dSDimitry Andric     }
1420bdd1243dSDimitry Andric     VTracker->defVar(MI, Properties, DebugOps);
1421bdd1243dSDimitry Andric   }
1422e8d8bef9SDimitry Andric 
1423e8d8bef9SDimitry Andric   // If performing final tracking of transfers, report this variable definition
1424e8d8bef9SDimitry Andric   // to the TransferTracker too.
1425e8d8bef9SDimitry Andric   if (TTracker)
1426e8d8bef9SDimitry Andric     TTracker->redefVar(MI);
1427e8d8bef9SDimitry Andric   return true;
1428e8d8bef9SDimitry Andric }
1429e8d8bef9SDimitry Andric 
1430bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::getValueForInstrRef(
1431bdd1243dSDimitry Andric     unsigned InstNo, unsigned OpNo, MachineInstr &MI,
1432bdd1243dSDimitry Andric     const ValueTable *MLiveOuts, const ValueTable *MLiveIns) {
1433e8d8bef9SDimitry Andric   // Various optimizations may have happened to the value during codegen,
1434e8d8bef9SDimitry Andric   // recorded in the value substitution table. Apply any substitutions to
1435fe6060f1SDimitry Andric   // the instruction / operand number in this DBG_INSTR_REF, and collect
1436fe6060f1SDimitry Andric   // any subregister extractions performed during optimization.
1437bdd1243dSDimitry Andric   const MachineFunction &MF = *MI.getParent()->getParent();
1438fe6060f1SDimitry Andric 
1439fe6060f1SDimitry Andric   // Create dummy substitution with Src set, for lookup.
1440fe6060f1SDimitry Andric   auto SoughtSub =
1441fe6060f1SDimitry Andric       MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1442fe6060f1SDimitry Andric 
1443fe6060f1SDimitry Andric   SmallVector<unsigned, 4> SeenSubregs;
1444fe6060f1SDimitry Andric   auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1445fe6060f1SDimitry Andric   while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1446fe6060f1SDimitry Andric          LowerBoundIt->Src == SoughtSub.Src) {
1447fe6060f1SDimitry Andric     std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1448fe6060f1SDimitry Andric     SoughtSub.Src = LowerBoundIt->Dest;
1449fe6060f1SDimitry Andric     if (unsigned Subreg = LowerBoundIt->Subreg)
1450fe6060f1SDimitry Andric       SeenSubregs.push_back(Subreg);
1451fe6060f1SDimitry Andric     LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1452e8d8bef9SDimitry Andric   }
1453e8d8bef9SDimitry Andric 
1454e8d8bef9SDimitry Andric   // Default machine value number is <None> -- if no instruction defines
1455e8d8bef9SDimitry Andric   // the corresponding value, it must have been optimized out.
1456bdd1243dSDimitry Andric   std::optional<ValueIDNum> NewID;
1457e8d8bef9SDimitry Andric 
1458e8d8bef9SDimitry Andric   // Try to lookup the instruction number, and find the machine value number
1459fe6060f1SDimitry Andric   // that it defines. It could be an instruction, or a PHI.
1460e8d8bef9SDimitry Andric   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1461bdd1243dSDimitry Andric   auto PHIIt = llvm::lower_bound(DebugPHINumToValue, InstNo);
1462e8d8bef9SDimitry Andric   if (InstrIt != DebugInstrNumToInstr.end()) {
1463e8d8bef9SDimitry Andric     const MachineInstr &TargetInstr = *InstrIt->second.first;
1464e8d8bef9SDimitry Andric     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1465e8d8bef9SDimitry Andric 
1466349cc55cSDimitry Andric     // Pick out the designated operand. It might be a memory reference, if
1467349cc55cSDimitry Andric     // a register def was folded into a stack store.
1468349cc55cSDimitry Andric     if (OpNo == MachineFunction::DebugOperandMemNumber &&
1469349cc55cSDimitry Andric         TargetInstr.hasOneMemOperand()) {
1470bdd1243dSDimitry Andric       std::optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1471349cc55cSDimitry Andric       if (L)
1472349cc55cSDimitry Andric         NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1473349cc55cSDimitry Andric     } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
147481ad6265SDimitry Andric       // Permit the debug-info to be completely wrong: identifying a nonexistant
147581ad6265SDimitry Andric       // operand, or one that is not a register definition, means something
147681ad6265SDimitry Andric       // unexpected happened during optimisation. Broken debug-info, however,
147781ad6265SDimitry Andric       // shouldn't crash the compiler -- instead leave the variable value as
147881ad6265SDimitry Andric       // None, which will make it appear "optimised out".
147981ad6265SDimitry Andric       if (OpNo < TargetInstr.getNumOperands()) {
1480e8d8bef9SDimitry Andric         const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1481e8d8bef9SDimitry Andric 
148281ad6265SDimitry Andric         if (MO.isReg() && MO.isDef() && MO.getReg()) {
1483349cc55cSDimitry Andric           unsigned LocID = MTracker->getLocID(MO.getReg());
1484e8d8bef9SDimitry Andric           LocIdx L = MTracker->LocIDToLocIdx[LocID];
1485e8d8bef9SDimitry Andric           NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1486349cc55cSDimitry Andric         }
148781ad6265SDimitry Andric       }
148881ad6265SDimitry Andric 
148981ad6265SDimitry Andric       if (!NewID) {
149081ad6265SDimitry Andric         LLVM_DEBUG(
149181ad6265SDimitry Andric             { dbgs() << "Seen instruction reference to illegal operand\n"; });
149281ad6265SDimitry Andric       }
149381ad6265SDimitry Andric     }
1494349cc55cSDimitry Andric     // else: NewID is left as None.
1495fe6060f1SDimitry Andric   } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1496fe6060f1SDimitry Andric     // It's actually a PHI value. Which value it is might not be obvious, use
1497fe6060f1SDimitry Andric     // the resolver helper to find out.
1498fe6060f1SDimitry Andric     NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
1499fe6060f1SDimitry Andric                            MI, InstNo);
1500fe6060f1SDimitry Andric   }
1501fe6060f1SDimitry Andric 
1502fe6060f1SDimitry Andric   // Apply any subregister extractions, in reverse. We might have seen code
1503fe6060f1SDimitry Andric   // like this:
1504fe6060f1SDimitry Andric   //    CALL64 @foo, implicit-def $rax
1505fe6060f1SDimitry Andric   //    %0:gr64 = COPY $rax
1506fe6060f1SDimitry Andric   //    %1:gr32 = COPY %0.sub_32bit
1507fe6060f1SDimitry Andric   //    %2:gr16 = COPY %1.sub_16bit
1508fe6060f1SDimitry Andric   //    %3:gr8  = COPY %2.sub_8bit
1509fe6060f1SDimitry Andric   // In which case each copy would have been recorded as a substitution with
1510fe6060f1SDimitry Andric   // a subregister qualifier. Apply those qualifiers now.
1511fe6060f1SDimitry Andric   if (NewID && !SeenSubregs.empty()) {
1512fe6060f1SDimitry Andric     unsigned Offset = 0;
1513fe6060f1SDimitry Andric     unsigned Size = 0;
1514fe6060f1SDimitry Andric 
1515fe6060f1SDimitry Andric     // Look at each subregister that we passed through, and progressively
1516fe6060f1SDimitry Andric     // narrow in, accumulating any offsets that occur. Substitutions should
1517fe6060f1SDimitry Andric     // only ever be the same or narrower width than what they read from;
1518fe6060f1SDimitry Andric     // iterate in reverse order so that we go from wide to small.
1519fe6060f1SDimitry Andric     for (unsigned Subreg : reverse(SeenSubregs)) {
1520fe6060f1SDimitry Andric       unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1521fe6060f1SDimitry Andric       unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1522fe6060f1SDimitry Andric       Offset += ThisOffset;
1523fe6060f1SDimitry Andric       Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1524fe6060f1SDimitry Andric     }
1525fe6060f1SDimitry Andric 
1526fe6060f1SDimitry Andric     // If that worked, look for an appropriate subregister with the register
1527fe6060f1SDimitry Andric     // where the define happens. Don't look at values that were defined during
1528fe6060f1SDimitry Andric     // a stack write: we can't currently express register locations within
1529fe6060f1SDimitry Andric     // spills.
1530fe6060f1SDimitry Andric     LocIdx L = NewID->getLoc();
1531fe6060f1SDimitry Andric     if (NewID && !MTracker->isSpill(L)) {
1532fe6060f1SDimitry Andric       // Find the register class for the register where this def happened.
1533fe6060f1SDimitry Andric       // FIXME: no index for this?
1534fe6060f1SDimitry Andric       Register Reg = MTracker->LocIdxToLocID[L];
1535fe6060f1SDimitry Andric       const TargetRegisterClass *TRC = nullptr;
1536fcaf7f86SDimitry Andric       for (const auto *TRCI : TRI->regclasses())
1537fe6060f1SDimitry Andric         if (TRCI->contains(Reg))
1538fe6060f1SDimitry Andric           TRC = TRCI;
1539fe6060f1SDimitry Andric       assert(TRC && "Couldn't find target register class?");
1540fe6060f1SDimitry Andric 
1541fe6060f1SDimitry Andric       // If the register we have isn't the right size or in the right place,
1542fe6060f1SDimitry Andric       // Try to find a subregister inside it.
1543fe6060f1SDimitry Andric       unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1544fe6060f1SDimitry Andric       if (Size != MainRegSize || Offset) {
1545fe6060f1SDimitry Andric         // Enumerate all subregisters, searching.
1546fe6060f1SDimitry Andric         Register NewReg = 0;
1547*06c3fb27SDimitry Andric         for (MCPhysReg SR : TRI->subregs(Reg)) {
1548*06c3fb27SDimitry Andric           unsigned Subreg = TRI->getSubRegIndex(Reg, SR);
1549fe6060f1SDimitry Andric           unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1550fe6060f1SDimitry Andric           unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1551fe6060f1SDimitry Andric           if (SubregSize == Size && SubregOffset == Offset) {
1552*06c3fb27SDimitry Andric             NewReg = SR;
1553fe6060f1SDimitry Andric             break;
1554fe6060f1SDimitry Andric           }
1555fe6060f1SDimitry Andric         }
1556fe6060f1SDimitry Andric 
1557fe6060f1SDimitry Andric         // If we didn't find anything: there's no way to express our value.
1558fe6060f1SDimitry Andric         if (!NewReg) {
1559bdd1243dSDimitry Andric           NewID = std::nullopt;
1560fe6060f1SDimitry Andric         } else {
1561fe6060f1SDimitry Andric           // Re-state the value as being defined within the subregister
1562fe6060f1SDimitry Andric           // that we found.
1563fe6060f1SDimitry Andric           LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1564fe6060f1SDimitry Andric           NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1565fe6060f1SDimitry Andric         }
1566fe6060f1SDimitry Andric       }
1567fe6060f1SDimitry Andric     } else {
1568fe6060f1SDimitry Andric       // If we can't handle subregisters, unset the new value.
1569bdd1243dSDimitry Andric       NewID = std::nullopt;
1570fe6060f1SDimitry Andric     }
1571e8d8bef9SDimitry Andric   }
1572e8d8bef9SDimitry Andric 
1573bdd1243dSDimitry Andric   return NewID;
1574bdd1243dSDimitry Andric }
1575bdd1243dSDimitry Andric 
1576bdd1243dSDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1577bdd1243dSDimitry Andric                                              const ValueTable *MLiveOuts,
1578bdd1243dSDimitry Andric                                              const ValueTable *MLiveIns) {
1579bdd1243dSDimitry Andric   if (!MI.isDebugRef())
1580bdd1243dSDimitry Andric     return false;
1581bdd1243dSDimitry Andric 
1582bdd1243dSDimitry Andric   // Only handle this instruction when we are building the variable value
1583bdd1243dSDimitry Andric   // transfer function.
1584bdd1243dSDimitry Andric   if (!VTracker && !TTracker)
1585bdd1243dSDimitry Andric     return false;
1586bdd1243dSDimitry Andric 
1587bdd1243dSDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
1588bdd1243dSDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
1589bdd1243dSDimitry Andric   const DILocation *DebugLoc = MI.getDebugLoc();
1590bdd1243dSDimitry Andric   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1591bdd1243dSDimitry Andric   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1592bdd1243dSDimitry Andric          "Expected inlined-at fields to agree");
1593bdd1243dSDimitry Andric 
1594bdd1243dSDimitry Andric   DebugVariable V(Var, Expr, InlinedAt);
1595bdd1243dSDimitry Andric 
1596bdd1243dSDimitry Andric   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1597bdd1243dSDimitry Andric   if (Scope == nullptr)
1598bdd1243dSDimitry Andric     return true; // Handled by doing nothing. This variable is never in scope.
1599bdd1243dSDimitry Andric 
1600bdd1243dSDimitry Andric   SmallVector<DbgOpID> DbgOpIDs;
1601bdd1243dSDimitry Andric   for (const MachineOperand &MO : MI.debug_operands()) {
1602bdd1243dSDimitry Andric     if (!MO.isDbgInstrRef()) {
1603bdd1243dSDimitry Andric       assert(!MO.isReg() && "DBG_INSTR_REF should not contain registers");
1604bdd1243dSDimitry Andric       DbgOpID ConstOpID = DbgOpStore.insert(DbgOp(MO));
1605bdd1243dSDimitry Andric       DbgOpIDs.push_back(ConstOpID);
1606bdd1243dSDimitry Andric       continue;
1607bdd1243dSDimitry Andric     }
1608bdd1243dSDimitry Andric 
1609bdd1243dSDimitry Andric     unsigned InstNo = MO.getInstrRefInstrIndex();
1610bdd1243dSDimitry Andric     unsigned OpNo = MO.getInstrRefOpIndex();
1611bdd1243dSDimitry Andric 
1612bdd1243dSDimitry Andric     // Default machine value number is <None> -- if no instruction defines
1613bdd1243dSDimitry Andric     // the corresponding value, it must have been optimized out.
1614bdd1243dSDimitry Andric     std::optional<ValueIDNum> NewID =
1615bdd1243dSDimitry Andric         getValueForInstrRef(InstNo, OpNo, MI, MLiveOuts, MLiveIns);
1616bdd1243dSDimitry Andric     // We have a value number or std::nullopt. If the latter, then kill the
1617bdd1243dSDimitry Andric     // entire debug value.
1618bdd1243dSDimitry Andric     if (NewID) {
1619bdd1243dSDimitry Andric       DbgOpIDs.push_back(DbgOpStore.insert(*NewID));
1620bdd1243dSDimitry Andric     } else {
1621bdd1243dSDimitry Andric       DbgOpIDs.clear();
1622bdd1243dSDimitry Andric       break;
1623bdd1243dSDimitry Andric     }
1624bdd1243dSDimitry Andric   }
1625bdd1243dSDimitry Andric 
1626bdd1243dSDimitry Andric   // We have a DbgOpID for every value or for none. Tell the variable value
1627bdd1243dSDimitry Andric   // tracker about it. The rest of this LiveDebugValues implementation acts
1628bdd1243dSDimitry Andric   // exactly the same for DBG_INSTR_REFs as DBG_VALUEs (just, the former can
1629bdd1243dSDimitry Andric   // refer to values that aren't immediately available).
1630bdd1243dSDimitry Andric   DbgValueProperties Properties(Expr, false, true);
1631d56accc7SDimitry Andric   if (VTracker)
1632bdd1243dSDimitry Andric     VTracker->defVar(MI, Properties, DbgOpIDs);
1633e8d8bef9SDimitry Andric 
1634e8d8bef9SDimitry Andric   // If we're on the final pass through the function, decompose this INSTR_REF
1635e8d8bef9SDimitry Andric   // into a plain DBG_VALUE.
1636e8d8bef9SDimitry Andric   if (!TTracker)
1637e8d8bef9SDimitry Andric     return true;
1638e8d8bef9SDimitry Andric 
1639bdd1243dSDimitry Andric   // Fetch the concrete DbgOps now, as we will need them later.
1640bdd1243dSDimitry Andric   SmallVector<DbgOp> DbgOps;
1641bdd1243dSDimitry Andric   for (DbgOpID OpID : DbgOpIDs) {
1642bdd1243dSDimitry Andric     DbgOps.push_back(DbgOpStore.find(OpID));
1643bdd1243dSDimitry Andric   }
1644bdd1243dSDimitry Andric 
1645e8d8bef9SDimitry Andric   // Pick a location for the machine value number, if such a location exists.
1646e8d8bef9SDimitry Andric   // (This information could be stored in TransferTracker to make it faster).
1647bdd1243dSDimitry Andric   SmallDenseMap<ValueIDNum, TransferTracker::LocationAndQuality> FoundLocs;
1648bdd1243dSDimitry Andric   SmallVector<ValueIDNum> ValuesToFind;
1649bdd1243dSDimitry Andric   // Initialized the preferred-location map with illegal locations, to be
1650bdd1243dSDimitry Andric   // filled in later.
1651bdd1243dSDimitry Andric   for (const DbgOp &Op : DbgOps) {
1652bdd1243dSDimitry Andric     if (!Op.IsConst)
1653bdd1243dSDimitry Andric       if (FoundLocs.insert({Op.ID, TransferTracker::LocationAndQuality()})
1654bdd1243dSDimitry Andric               .second)
1655bdd1243dSDimitry Andric         ValuesToFind.push_back(Op.ID);
1656bdd1243dSDimitry Andric   }
1657bdd1243dSDimitry Andric 
1658e8d8bef9SDimitry Andric   for (auto Location : MTracker->locations()) {
1659e8d8bef9SDimitry Andric     LocIdx CurL = Location.Idx;
1660349cc55cSDimitry Andric     ValueIDNum ID = MTracker->readMLoc(CurL);
1661bdd1243dSDimitry Andric     auto ValueToFindIt = find(ValuesToFind, ID);
1662bdd1243dSDimitry Andric     if (ValueToFindIt == ValuesToFind.end())
1663bdd1243dSDimitry Andric       continue;
1664bdd1243dSDimitry Andric     auto &Previous = FoundLocs.find(ID)->second;
1665e8d8bef9SDimitry Andric     // If this is the first location with that value, pick it. Otherwise,
1666e8d8bef9SDimitry Andric     // consider whether it's a "longer term" location.
1667bdd1243dSDimitry Andric     std::optional<TransferTracker::LocationQuality> ReplacementQuality =
1668bdd1243dSDimitry Andric         TTracker->getLocQualityIfBetter(CurL, Previous.getQuality());
1669bdd1243dSDimitry Andric     if (ReplacementQuality) {
1670bdd1243dSDimitry Andric       Previous = TransferTracker::LocationAndQuality(CurL, *ReplacementQuality);
1671bdd1243dSDimitry Andric       if (Previous.isBest()) {
1672bdd1243dSDimitry Andric         ValuesToFind.erase(ValueToFindIt);
1673bdd1243dSDimitry Andric         if (ValuesToFind.empty())
1674bdd1243dSDimitry Andric           break;
1675bdd1243dSDimitry Andric       }
1676bdd1243dSDimitry Andric     }
1677bdd1243dSDimitry Andric   }
1678bdd1243dSDimitry Andric 
1679bdd1243dSDimitry Andric   SmallVector<ResolvedDbgOp> NewLocs;
1680bdd1243dSDimitry Andric   for (const DbgOp &DbgOp : DbgOps) {
1681bdd1243dSDimitry Andric     if (DbgOp.IsConst) {
1682bdd1243dSDimitry Andric       NewLocs.push_back(DbgOp.MO);
1683e8d8bef9SDimitry Andric       continue;
1684e8d8bef9SDimitry Andric     }
1685bdd1243dSDimitry Andric     LocIdx FoundLoc = FoundLocs.find(DbgOp.ID)->second.getLoc();
1686bdd1243dSDimitry Andric     if (FoundLoc.isIllegal()) {
1687bdd1243dSDimitry Andric       NewLocs.clear();
1688bdd1243dSDimitry Andric       break;
1689e8d8bef9SDimitry Andric     }
1690bdd1243dSDimitry Andric     NewLocs.push_back(FoundLoc);
1691e8d8bef9SDimitry Andric   }
1692e8d8bef9SDimitry Andric   // Tell transfer tracker that the variable value has changed.
1693bdd1243dSDimitry Andric   TTracker->redefVar(MI, Properties, NewLocs);
1694e8d8bef9SDimitry Andric 
1695bdd1243dSDimitry Andric   // If there were values with no location, but all such values are defined in
1696bdd1243dSDimitry Andric   // later instructions in this block, this is a block-local use-before-def.
1697bdd1243dSDimitry Andric   if (!DbgOps.empty() && NewLocs.empty()) {
1698bdd1243dSDimitry Andric     bool IsValidUseBeforeDef = true;
1699bdd1243dSDimitry Andric     uint64_t LastUseBeforeDef = 0;
1700bdd1243dSDimitry Andric     for (auto ValueLoc : FoundLocs) {
1701bdd1243dSDimitry Andric       ValueIDNum NewID = ValueLoc.first;
1702bdd1243dSDimitry Andric       LocIdx FoundLoc = ValueLoc.second.getLoc();
1703bdd1243dSDimitry Andric       if (!FoundLoc.isIllegal())
1704bdd1243dSDimitry Andric         continue;
1705bdd1243dSDimitry Andric       // If we have an value with no location that is not defined in this block,
1706bdd1243dSDimitry Andric       // then it has no location in this block, leaving this value undefined.
1707bdd1243dSDimitry Andric       if (NewID.getBlock() != CurBB || NewID.getInst() <= CurInst) {
1708bdd1243dSDimitry Andric         IsValidUseBeforeDef = false;
1709bdd1243dSDimitry Andric         break;
1710bdd1243dSDimitry Andric       }
1711bdd1243dSDimitry Andric       LastUseBeforeDef = std::max(LastUseBeforeDef, NewID.getInst());
1712bdd1243dSDimitry Andric     }
1713bdd1243dSDimitry Andric     if (IsValidUseBeforeDef) {
1714bdd1243dSDimitry Andric       TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false, true},
1715bdd1243dSDimitry Andric                                 DbgOps, LastUseBeforeDef);
1716bdd1243dSDimitry Andric     }
1717bdd1243dSDimitry Andric   }
1718e8d8bef9SDimitry Andric 
1719e8d8bef9SDimitry Andric   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1720e8d8bef9SDimitry Andric   // This DBG_VALUE is potentially a $noreg / undefined location, if
1721bdd1243dSDimitry Andric   // FoundLoc is illegal.
1722e8d8bef9SDimitry Andric   // (XXX -- could morph the DBG_INSTR_REF in the future).
1723bdd1243dSDimitry Andric   MachineInstr *DbgMI = MTracker->emitLoc(NewLocs, V, Properties);
1724bdd1243dSDimitry Andric 
1725e8d8bef9SDimitry Andric   TTracker->PendingDbgValues.push_back(DbgMI);
1726e8d8bef9SDimitry Andric   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1727fe6060f1SDimitry Andric   return true;
1728fe6060f1SDimitry Andric }
1729fe6060f1SDimitry Andric 
1730fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1731fe6060f1SDimitry Andric   if (!MI.isDebugPHI())
1732fe6060f1SDimitry Andric     return false;
1733fe6060f1SDimitry Andric 
1734fe6060f1SDimitry Andric   // Analyse these only when solving the machine value location problem.
1735fe6060f1SDimitry Andric   if (VTracker || TTracker)
1736fe6060f1SDimitry Andric     return true;
1737fe6060f1SDimitry Andric 
1738fe6060f1SDimitry Andric   // First operand is the value location, either a stack slot or register.
1739fe6060f1SDimitry Andric   // Second is the debug instruction number of the original PHI.
1740fe6060f1SDimitry Andric   const MachineOperand &MO = MI.getOperand(0);
1741fe6060f1SDimitry Andric   unsigned InstrNum = MI.getOperand(1).getImm();
1742fe6060f1SDimitry Andric 
1743972a253aSDimitry Andric   auto EmitBadPHI = [this, &MI, InstrNum]() -> bool {
174481ad6265SDimitry Andric     // Helper lambda to do any accounting when we fail to find a location for
174581ad6265SDimitry Andric     // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
174681ad6265SDimitry Andric     // dead stack slot, for example.
174781ad6265SDimitry Andric     // Record a DebugPHIRecord with an empty value + location.
1748bdd1243dSDimitry Andric     DebugPHINumToValue.push_back(
1749bdd1243dSDimitry Andric         {InstrNum, MI.getParent(), std::nullopt, std::nullopt});
175081ad6265SDimitry Andric     return true;
175181ad6265SDimitry Andric   };
175281ad6265SDimitry Andric 
175381ad6265SDimitry Andric   if (MO.isReg() && MO.getReg()) {
1754fe6060f1SDimitry Andric     // The value is whatever's currently in the register. Read and record it,
1755fe6060f1SDimitry Andric     // to be analysed later.
1756fe6060f1SDimitry Andric     Register Reg = MO.getReg();
1757fe6060f1SDimitry Andric     ValueIDNum Num = MTracker->readReg(Reg);
1758fe6060f1SDimitry Andric     auto PHIRec = DebugPHIRecord(
1759fe6060f1SDimitry Andric         {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1760fe6060f1SDimitry Andric     DebugPHINumToValue.push_back(PHIRec);
1761349cc55cSDimitry Andric 
1762349cc55cSDimitry Andric     // Ensure this register is tracked.
1763349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1764349cc55cSDimitry Andric       MTracker->lookupOrTrackRegister(*RAI);
176581ad6265SDimitry Andric   } else if (MO.isFI()) {
1766fe6060f1SDimitry Andric     // The value is whatever's in this stack slot.
1767fe6060f1SDimitry Andric     unsigned FI = MO.getIndex();
1768fe6060f1SDimitry Andric 
1769fe6060f1SDimitry Andric     // If the stack slot is dead, then this was optimized away.
1770fe6060f1SDimitry Andric     // FIXME: stack slot colouring should account for slots that get merged.
1771fe6060f1SDimitry Andric     if (MFI->isDeadObjectIndex(FI))
177281ad6265SDimitry Andric       return EmitBadPHI();
1773fe6060f1SDimitry Andric 
1774349cc55cSDimitry Andric     // Identify this spill slot, ensure it's tracked.
1775fe6060f1SDimitry Andric     Register Base;
1776fe6060f1SDimitry Andric     StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1777fe6060f1SDimitry Andric     SpillLoc SL = {Base, Offs};
1778bdd1243dSDimitry Andric     std::optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
1779d56accc7SDimitry Andric 
1780d56accc7SDimitry Andric     // We might be able to find a value, but have chosen not to, to avoid
1781d56accc7SDimitry Andric     // tracking too much stack information.
1782d56accc7SDimitry Andric     if (!SpillNo)
178381ad6265SDimitry Andric       return EmitBadPHI();
1784fe6060f1SDimitry Andric 
178581ad6265SDimitry Andric     // Any stack location DBG_PHI should have an associate bit-size.
178681ad6265SDimitry Andric     assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
178781ad6265SDimitry Andric     unsigned slotBitSize = MI.getOperand(2).getImm();
1788349cc55cSDimitry Andric 
178981ad6265SDimitry Andric     unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0});
179081ad6265SDimitry Andric     LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
179181ad6265SDimitry Andric     ValueIDNum Result = MTracker->readMLoc(SpillLoc);
1792fe6060f1SDimitry Andric 
1793fe6060f1SDimitry Andric     // Record this DBG_PHI for later analysis.
179481ad6265SDimitry Andric     auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc});
1795fe6060f1SDimitry Andric     DebugPHINumToValue.push_back(DbgPHI);
179681ad6265SDimitry Andric   } else {
179781ad6265SDimitry Andric     // Else: if the operand is neither a legal register or a stack slot, then
179881ad6265SDimitry Andric     // we're being fed illegal debug-info. Record an empty PHI, so that any
179981ad6265SDimitry Andric     // debug users trying to read this number will be put off trying to
180081ad6265SDimitry Andric     // interpret the value.
180181ad6265SDimitry Andric     LLVM_DEBUG(
180281ad6265SDimitry Andric         { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
180381ad6265SDimitry Andric     return EmitBadPHI();
1804fe6060f1SDimitry Andric   }
1805e8d8bef9SDimitry Andric 
1806e8d8bef9SDimitry Andric   return true;
1807e8d8bef9SDimitry Andric }
1808e8d8bef9SDimitry Andric 
1809e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1810e8d8bef9SDimitry Andric   // Meta Instructions do not affect the debug liveness of any register they
1811e8d8bef9SDimitry Andric   // define.
1812e8d8bef9SDimitry Andric   if (MI.isImplicitDef()) {
1813e8d8bef9SDimitry Andric     // Except when there's an implicit def, and the location it's defining has
1814e8d8bef9SDimitry Andric     // no value number. The whole point of an implicit def is to announce that
1815e8d8bef9SDimitry Andric     // the register is live, without be specific about it's value. So define
1816e8d8bef9SDimitry Andric     // a value if there isn't one already.
1817e8d8bef9SDimitry Andric     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1818e8d8bef9SDimitry Andric     // Has a legitimate value -> ignore the implicit def.
1819e8d8bef9SDimitry Andric     if (Num.getLoc() != 0)
1820e8d8bef9SDimitry Andric       return;
1821e8d8bef9SDimitry Andric     // Otherwise, def it here.
1822e8d8bef9SDimitry Andric   } else if (MI.isMetaInstruction())
1823e8d8bef9SDimitry Andric     return;
1824e8d8bef9SDimitry Andric 
18254824e7fdSDimitry Andric   // We always ignore SP defines on call instructions, they don't actually
18264824e7fdSDimitry Andric   // change the value of the stack pointer... except for win32's _chkstk. This
18274824e7fdSDimitry Andric   // is rare: filter quickly for the common case (no stack adjustments, not a
18284824e7fdSDimitry Andric   // call, etc). If it is a call that modifies SP, recognise the SP register
18294824e7fdSDimitry Andric   // defs.
18304824e7fdSDimitry Andric   bool CallChangesSP = false;
18314824e7fdSDimitry Andric   if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
18324824e7fdSDimitry Andric       !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
18334824e7fdSDimitry Andric     CallChangesSP = true;
18344824e7fdSDimitry Andric 
18354824e7fdSDimitry Andric   // Test whether we should ignore a def of this register due to it being part
18364824e7fdSDimitry Andric   // of the stack pointer.
18374824e7fdSDimitry Andric   auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
18384824e7fdSDimitry Andric     if (CallChangesSP)
18394824e7fdSDimitry Andric       return false;
18404824e7fdSDimitry Andric     return MI.isCall() && MTracker->SPAliases.count(R);
18414824e7fdSDimitry Andric   };
18424824e7fdSDimitry Andric 
1843e8d8bef9SDimitry Andric   // Find the regs killed by MI, and find regmasks of preserved regs.
1844e8d8bef9SDimitry Andric   // Max out the number of statically allocated elements in `DeadRegs`, as this
1845e8d8bef9SDimitry Andric   // prevents fallback to std::set::count() operations.
1846e8d8bef9SDimitry Andric   SmallSet<uint32_t, 32> DeadRegs;
1847e8d8bef9SDimitry Andric   SmallVector<const uint32_t *, 4> RegMasks;
1848e8d8bef9SDimitry Andric   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1849e8d8bef9SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1850e8d8bef9SDimitry Andric     // Determine whether the operand is a register def.
1851bdd1243dSDimitry Andric     if (MO.isReg() && MO.isDef() && MO.getReg() && MO.getReg().isPhysical() &&
18524824e7fdSDimitry Andric         !IgnoreSPAlias(MO.getReg())) {
1853e8d8bef9SDimitry Andric       // Remove ranges of all aliased registers.
1854e8d8bef9SDimitry Andric       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1855e8d8bef9SDimitry Andric         // FIXME: Can we break out of this loop early if no insertion occurs?
1856e8d8bef9SDimitry Andric         DeadRegs.insert(*RAI);
1857e8d8bef9SDimitry Andric     } else if (MO.isRegMask()) {
1858e8d8bef9SDimitry Andric       RegMasks.push_back(MO.getRegMask());
1859e8d8bef9SDimitry Andric       RegMaskPtrs.push_back(&MO);
1860e8d8bef9SDimitry Andric     }
1861e8d8bef9SDimitry Andric   }
1862e8d8bef9SDimitry Andric 
1863e8d8bef9SDimitry Andric   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1864e8d8bef9SDimitry Andric   for (uint32_t DeadReg : DeadRegs)
1865e8d8bef9SDimitry Andric     MTracker->defReg(DeadReg, CurBB, CurInst);
1866e8d8bef9SDimitry Andric 
1867fcaf7f86SDimitry Andric   for (const auto *MO : RegMaskPtrs)
1868e8d8bef9SDimitry Andric     MTracker->writeRegMask(MO, CurBB, CurInst);
1869fe6060f1SDimitry Andric 
1870349cc55cSDimitry Andric   // If this instruction writes to a spill slot, def that slot.
1871349cc55cSDimitry Andric   if (hasFoldedStackStore(MI)) {
1872bdd1243dSDimitry Andric     if (std::optional<SpillLocationNo> SpillNo =
1873bdd1243dSDimitry Andric             extractSpillBaseRegAndOffset(MI)) {
1874349cc55cSDimitry Andric       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1875d56accc7SDimitry Andric         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1876349cc55cSDimitry Andric         LocIdx L = MTracker->getSpillMLoc(SpillID);
1877349cc55cSDimitry Andric         MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1878349cc55cSDimitry Andric       }
1879349cc55cSDimitry Andric     }
1880d56accc7SDimitry Andric   }
1881349cc55cSDimitry Andric 
1882fe6060f1SDimitry Andric   if (!TTracker)
1883fe6060f1SDimitry Andric     return;
1884fe6060f1SDimitry Andric 
1885fe6060f1SDimitry Andric   // When committing variable values to locations: tell transfer tracker that
1886fe6060f1SDimitry Andric   // we've clobbered things. It may be able to recover the variable from a
1887fe6060f1SDimitry Andric   // different location.
1888fe6060f1SDimitry Andric 
1889fe6060f1SDimitry Andric   // Inform TTracker about any direct clobbers.
1890fe6060f1SDimitry Andric   for (uint32_t DeadReg : DeadRegs) {
1891fe6060f1SDimitry Andric     LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
1892fe6060f1SDimitry Andric     TTracker->clobberMloc(Loc, MI.getIterator(), false);
1893fe6060f1SDimitry Andric   }
1894fe6060f1SDimitry Andric 
1895fe6060f1SDimitry Andric   // Look for any clobbers performed by a register mask. Only test locations
1896fe6060f1SDimitry Andric   // that are actually being tracked.
18971fd87a68SDimitry Andric   if (!RegMaskPtrs.empty()) {
1898fe6060f1SDimitry Andric     for (auto L : MTracker->locations()) {
1899fe6060f1SDimitry Andric       // Stack locations can't be clobbered by regmasks.
1900fe6060f1SDimitry Andric       if (MTracker->isSpill(L.Idx))
1901fe6060f1SDimitry Andric         continue;
1902fe6060f1SDimitry Andric 
1903fe6060f1SDimitry Andric       Register Reg = MTracker->LocIdxToLocID[L.Idx];
19044824e7fdSDimitry Andric       if (IgnoreSPAlias(Reg))
19054824e7fdSDimitry Andric         continue;
19064824e7fdSDimitry Andric 
1907fcaf7f86SDimitry Andric       for (const auto *MO : RegMaskPtrs)
1908fe6060f1SDimitry Andric         if (MO->clobbersPhysReg(Reg))
1909fe6060f1SDimitry Andric           TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
1910fe6060f1SDimitry Andric     }
19111fd87a68SDimitry Andric   }
1912349cc55cSDimitry Andric 
1913349cc55cSDimitry Andric   // Tell TTracker about any folded stack store.
1914349cc55cSDimitry Andric   if (hasFoldedStackStore(MI)) {
1915bdd1243dSDimitry Andric     if (std::optional<SpillLocationNo> SpillNo =
1916bdd1243dSDimitry Andric             extractSpillBaseRegAndOffset(MI)) {
1917349cc55cSDimitry Andric       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1918d56accc7SDimitry Andric         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1919349cc55cSDimitry Andric         LocIdx L = MTracker->getSpillMLoc(SpillID);
1920349cc55cSDimitry Andric         TTracker->clobberMloc(L, MI.getIterator(), true);
1921349cc55cSDimitry Andric       }
1922349cc55cSDimitry Andric     }
1923e8d8bef9SDimitry Andric   }
1924d56accc7SDimitry Andric }
1925e8d8bef9SDimitry Andric 
1926e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1927349cc55cSDimitry Andric   // In all circumstances, re-def all aliases. It's definitely a new value now.
1928349cc55cSDimitry Andric   for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1929349cc55cSDimitry Andric     MTracker->defReg(*RAI, CurBB, CurInst);
1930e8d8bef9SDimitry Andric 
1931349cc55cSDimitry Andric   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1932e8d8bef9SDimitry Andric   MTracker->setReg(DstRegNum, SrcValue);
1933e8d8bef9SDimitry Andric 
1934349cc55cSDimitry Andric   // Copy subregisters from one location to another.
1935e8d8bef9SDimitry Andric   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1936e8d8bef9SDimitry Andric     unsigned SrcSubReg = SRI.getSubReg();
1937e8d8bef9SDimitry Andric     unsigned SubRegIdx = SRI.getSubRegIndex();
1938e8d8bef9SDimitry Andric     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1939e8d8bef9SDimitry Andric     if (!DstSubReg)
1940e8d8bef9SDimitry Andric       continue;
1941e8d8bef9SDimitry Andric 
1942e8d8bef9SDimitry Andric     // Do copy. There are two matching subregisters, the source value should
1943e8d8bef9SDimitry Andric     // have been def'd when the super-reg was, the latter might not be tracked
1944e8d8bef9SDimitry Andric     // yet.
1945349cc55cSDimitry Andric     // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1946349cc55cSDimitry Andric     // mphi values if it wasn't tracked.
1947349cc55cSDimitry Andric     LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1948349cc55cSDimitry Andric     LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1949349cc55cSDimitry Andric     (void)SrcL;
1950e8d8bef9SDimitry Andric     (void)DstL;
1951349cc55cSDimitry Andric     ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1952e8d8bef9SDimitry Andric 
1953e8d8bef9SDimitry Andric     MTracker->setReg(DstSubReg, CpyValue);
1954e8d8bef9SDimitry Andric   }
1955e8d8bef9SDimitry Andric }
1956e8d8bef9SDimitry Andric 
1957bdd1243dSDimitry Andric std::optional<SpillLocationNo>
1958d56accc7SDimitry Andric InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1959e8d8bef9SDimitry Andric                                      MachineFunction *MF) {
1960e8d8bef9SDimitry Andric   // TODO: Handle multiple stores folded into one.
1961e8d8bef9SDimitry Andric   if (!MI.hasOneMemOperand())
1962bdd1243dSDimitry Andric     return std::nullopt;
1963e8d8bef9SDimitry Andric 
1964349cc55cSDimitry Andric   // Reject any memory operand that's aliased -- we can't guarantee its value.
1965349cc55cSDimitry Andric   auto MMOI = MI.memoperands_begin();
1966349cc55cSDimitry Andric   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1967349cc55cSDimitry Andric   if (PVal->isAliased(MFI))
1968bdd1243dSDimitry Andric     return std::nullopt;
1969349cc55cSDimitry Andric 
1970e8d8bef9SDimitry Andric   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1971bdd1243dSDimitry Andric     return std::nullopt; // This is not a spill instruction, since no valid size
1972bdd1243dSDimitry Andric                          // was returned from either function.
1973e8d8bef9SDimitry Andric 
1974d56accc7SDimitry Andric   return extractSpillBaseRegAndOffset(MI);
1975e8d8bef9SDimitry Andric }
1976e8d8bef9SDimitry Andric 
1977e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1978e8d8bef9SDimitry Andric                                        MachineFunction *MF, unsigned &Reg) {
1979e8d8bef9SDimitry Andric   if (!isSpillInstruction(MI, MF))
1980e8d8bef9SDimitry Andric     return false;
1981e8d8bef9SDimitry Andric 
1982e8d8bef9SDimitry Andric   int FI;
1983e8d8bef9SDimitry Andric   Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1984e8d8bef9SDimitry Andric   return Reg != 0;
1985e8d8bef9SDimitry Andric }
1986e8d8bef9SDimitry Andric 
1987bdd1243dSDimitry Andric std::optional<SpillLocationNo>
1988e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1989e8d8bef9SDimitry Andric                                        MachineFunction *MF, unsigned &Reg) {
1990e8d8bef9SDimitry Andric   if (!MI.hasOneMemOperand())
1991bdd1243dSDimitry Andric     return std::nullopt;
1992e8d8bef9SDimitry Andric 
1993e8d8bef9SDimitry Andric   // FIXME: Handle folded restore instructions with more than one memory
1994e8d8bef9SDimitry Andric   // operand.
1995e8d8bef9SDimitry Andric   if (MI.getRestoreSize(TII)) {
1996e8d8bef9SDimitry Andric     Reg = MI.getOperand(0).getReg();
1997e8d8bef9SDimitry Andric     return extractSpillBaseRegAndOffset(MI);
1998e8d8bef9SDimitry Andric   }
1999bdd1243dSDimitry Andric   return std::nullopt;
2000e8d8bef9SDimitry Andric }
2001e8d8bef9SDimitry Andric 
2002e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
2003e8d8bef9SDimitry Andric   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
2004e8d8bef9SDimitry Andric   // limitations under the new model. Therefore, when comparing them, compare
2005e8d8bef9SDimitry Andric   // versions that don't attempt spills or restores at all.
2006e8d8bef9SDimitry Andric   if (EmulateOldLDV)
2007e8d8bef9SDimitry Andric     return false;
2008e8d8bef9SDimitry Andric 
2009349cc55cSDimitry Andric   // Strictly limit ourselves to plain loads and stores, not all instructions
2010349cc55cSDimitry Andric   // that can access the stack.
2011349cc55cSDimitry Andric   int DummyFI = -1;
2012349cc55cSDimitry Andric   if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
2013349cc55cSDimitry Andric       !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
2014349cc55cSDimitry Andric     return false;
2015349cc55cSDimitry Andric 
2016e8d8bef9SDimitry Andric   MachineFunction *MF = MI.getMF();
2017e8d8bef9SDimitry Andric   unsigned Reg;
2018e8d8bef9SDimitry Andric 
2019e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
2020e8d8bef9SDimitry Andric 
2021349cc55cSDimitry Andric   // Strictly limit ourselves to plain loads and stores, not all instructions
2022349cc55cSDimitry Andric   // that can access the stack.
2023349cc55cSDimitry Andric   int FIDummy;
2024349cc55cSDimitry Andric   if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
2025349cc55cSDimitry Andric       !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
2026349cc55cSDimitry Andric     return false;
2027349cc55cSDimitry Andric 
2028e8d8bef9SDimitry Andric   // First, if there are any DBG_VALUEs pointing at a spill slot that is
2029e8d8bef9SDimitry Andric   // written to, terminate that variable location. The value in memory
2030e8d8bef9SDimitry Andric   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
2031bdd1243dSDimitry Andric   if (std::optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
2032349cc55cSDimitry Andric     // Un-set this location and clobber, so that earlier locations don't
2033349cc55cSDimitry Andric     // continue past this store.
2034349cc55cSDimitry Andric     for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
2035d56accc7SDimitry Andric       unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
2036bdd1243dSDimitry Andric       std::optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
2037349cc55cSDimitry Andric       if (!MLoc)
2038349cc55cSDimitry Andric         continue;
2039349cc55cSDimitry Andric 
2040349cc55cSDimitry Andric       // We need to over-write the stack slot with something (here, a def at
2041349cc55cSDimitry Andric       // this instruction) to ensure no values are preserved in this stack slot
2042349cc55cSDimitry Andric       // after the spill. It also prevents TTracker from trying to recover the
2043349cc55cSDimitry Andric       // location and re-installing it in the same place.
2044349cc55cSDimitry Andric       ValueIDNum Def(CurBB, CurInst, *MLoc);
2045349cc55cSDimitry Andric       MTracker->setMLoc(*MLoc, Def);
2046349cc55cSDimitry Andric       if (TTracker)
2047e8d8bef9SDimitry Andric         TTracker->clobberMloc(*MLoc, MI.getIterator());
2048e8d8bef9SDimitry Andric     }
2049e8d8bef9SDimitry Andric   }
2050e8d8bef9SDimitry Andric 
2051e8d8bef9SDimitry Andric   // Try to recognise spill and restore instructions that may transfer a value.
2052e8d8bef9SDimitry Andric   if (isLocationSpill(MI, MF, Reg)) {
2053d56accc7SDimitry Andric     // isLocationSpill returning true should guarantee we can extract a
2054d56accc7SDimitry Andric     // location.
2055d56accc7SDimitry Andric     SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
2056e8d8bef9SDimitry Andric 
2057349cc55cSDimitry Andric     auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
2058349cc55cSDimitry Andric       auto ReadValue = MTracker->readReg(SrcReg);
2059349cc55cSDimitry Andric       LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
2060349cc55cSDimitry Andric       MTracker->setMLoc(DstLoc, ReadValue);
2061e8d8bef9SDimitry Andric 
2062349cc55cSDimitry Andric       if (TTracker) {
2063349cc55cSDimitry Andric         LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
2064349cc55cSDimitry Andric         TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
2065e8d8bef9SDimitry Andric       }
2066349cc55cSDimitry Andric     };
2067349cc55cSDimitry Andric 
2068349cc55cSDimitry Andric     // Then, transfer subreg bits.
2069*06c3fb27SDimitry Andric     for (MCPhysReg SR : TRI->subregs(Reg)) {
2070349cc55cSDimitry Andric       // Ensure this reg is tracked,
2071*06c3fb27SDimitry Andric       (void)MTracker->lookupOrTrackRegister(SR);
2072*06c3fb27SDimitry Andric       unsigned SubregIdx = TRI->getSubRegIndex(Reg, SR);
2073349cc55cSDimitry Andric       unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
2074*06c3fb27SDimitry Andric       DoTransfer(SR, SpillID);
2075349cc55cSDimitry Andric     }
2076349cc55cSDimitry Andric 
2077349cc55cSDimitry Andric     // Directly lookup size of main source reg, and transfer.
2078349cc55cSDimitry Andric     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
2079349cc55cSDimitry Andric     unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
2080349cc55cSDimitry Andric     DoTransfer(Reg, SpillID);
2081349cc55cSDimitry Andric   } else {
2082bdd1243dSDimitry Andric     std::optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
2083d56accc7SDimitry Andric     if (!Loc)
2084349cc55cSDimitry Andric       return false;
2085349cc55cSDimitry Andric 
2086349cc55cSDimitry Andric     // Assumption: we're reading from the base of the stack slot, not some
2087349cc55cSDimitry Andric     // offset into it. It seems very unlikely LLVM would ever generate
2088349cc55cSDimitry Andric     // restores where this wasn't true. This then becomes a question of what
2089349cc55cSDimitry Andric     // subregisters in the destination register line up with positions in the
2090349cc55cSDimitry Andric     // stack slot.
2091349cc55cSDimitry Andric 
2092349cc55cSDimitry Andric     // Def all registers that alias the destination.
2093349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2094349cc55cSDimitry Andric       MTracker->defReg(*RAI, CurBB, CurInst);
2095349cc55cSDimitry Andric 
2096349cc55cSDimitry Andric     // Now find subregisters within the destination register, and load values
2097349cc55cSDimitry Andric     // from stack slot positions.
2098349cc55cSDimitry Andric     auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
2099349cc55cSDimitry Andric       LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
2100349cc55cSDimitry Andric       auto ReadValue = MTracker->readMLoc(SrcIdx);
2101349cc55cSDimitry Andric       MTracker->setReg(DestReg, ReadValue);
2102349cc55cSDimitry Andric     };
2103349cc55cSDimitry Andric 
2104*06c3fb27SDimitry Andric     for (MCPhysReg SR : TRI->subregs(Reg)) {
2105*06c3fb27SDimitry Andric       unsigned Subreg = TRI->getSubRegIndex(Reg, SR);
2106d56accc7SDimitry Andric       unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
2107*06c3fb27SDimitry Andric       DoTransfer(SR, SpillID);
2108349cc55cSDimitry Andric     }
2109349cc55cSDimitry Andric 
2110349cc55cSDimitry Andric     // Directly look up this registers slot idx by size, and transfer.
2111349cc55cSDimitry Andric     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
2112d56accc7SDimitry Andric     unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
2113349cc55cSDimitry Andric     DoTransfer(Reg, SpillID);
2114e8d8bef9SDimitry Andric   }
2115e8d8bef9SDimitry Andric   return true;
2116e8d8bef9SDimitry Andric }
2117e8d8bef9SDimitry Andric 
2118e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2119e8d8bef9SDimitry Andric   auto DestSrc = TII->isCopyInstr(MI);
2120e8d8bef9SDimitry Andric   if (!DestSrc)
2121e8d8bef9SDimitry Andric     return false;
2122e8d8bef9SDimitry Andric 
2123e8d8bef9SDimitry Andric   const MachineOperand *DestRegOp = DestSrc->Destination;
2124e8d8bef9SDimitry Andric   const MachineOperand *SrcRegOp = DestSrc->Source;
2125e8d8bef9SDimitry Andric 
2126e8d8bef9SDimitry Andric   Register SrcReg = SrcRegOp->getReg();
2127e8d8bef9SDimitry Andric   Register DestReg = DestRegOp->getReg();
2128e8d8bef9SDimitry Andric 
2129e8d8bef9SDimitry Andric   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2130e8d8bef9SDimitry Andric   if (SrcReg == DestReg)
2131e8d8bef9SDimitry Andric     return true;
2132e8d8bef9SDimitry Andric 
2133e8d8bef9SDimitry Andric   // For emulating VarLocBasedImpl:
2134e8d8bef9SDimitry Andric   // We want to recognize instructions where destination register is callee
2135e8d8bef9SDimitry Andric   // saved register. If register that could be clobbered by the call is
2136e8d8bef9SDimitry Andric   // included, there would be a great chance that it is going to be clobbered
2137e8d8bef9SDimitry Andric   // soon. It is more likely that previous register, which is callee saved, is
2138e8d8bef9SDimitry Andric   // going to stay unclobbered longer, even if it is killed.
2139e8d8bef9SDimitry Andric   //
2140e8d8bef9SDimitry Andric   // For InstrRefBasedImpl, we can track multiple locations per value, so
2141e8d8bef9SDimitry Andric   // ignore this condition.
2142e8d8bef9SDimitry Andric   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
2143e8d8bef9SDimitry Andric     return false;
2144e8d8bef9SDimitry Andric 
2145e8d8bef9SDimitry Andric   // InstrRefBasedImpl only followed killing copies.
2146e8d8bef9SDimitry Andric   if (EmulateOldLDV && !SrcRegOp->isKill())
2147e8d8bef9SDimitry Andric     return false;
2148e8d8bef9SDimitry Andric 
2149753f127fSDimitry Andric   // Before we update MTracker, remember which values were present in each of
2150753f127fSDimitry Andric   // the locations about to be overwritten, so that we can recover any
2151753f127fSDimitry Andric   // potentially clobbered variables.
2152753f127fSDimitry Andric   DenseMap<LocIdx, ValueIDNum> ClobberedLocs;
2153753f127fSDimitry Andric   if (TTracker) {
2154753f127fSDimitry Andric     for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
2155753f127fSDimitry Andric       LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
2156753f127fSDimitry Andric       auto MLocIt = TTracker->ActiveMLocs.find(ClobberedLoc);
2157753f127fSDimitry Andric       // If ActiveMLocs isn't tracking this location or there are no variables
2158753f127fSDimitry Andric       // using it, don't bother remembering.
2159753f127fSDimitry Andric       if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty())
2160753f127fSDimitry Andric         continue;
2161753f127fSDimitry Andric       ValueIDNum Value = MTracker->readReg(*RAI);
2162753f127fSDimitry Andric       ClobberedLocs[ClobberedLoc] = Value;
2163753f127fSDimitry Andric     }
2164753f127fSDimitry Andric   }
2165753f127fSDimitry Andric 
2166e8d8bef9SDimitry Andric   // Copy MTracker info, including subregs if available.
2167e8d8bef9SDimitry Andric   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
2168e8d8bef9SDimitry Andric 
2169753f127fSDimitry Andric   // The copy might have clobbered variables based on the destination register.
2170753f127fSDimitry Andric   // Tell TTracker about it, passing the old ValueIDNum to search for
2171753f127fSDimitry Andric   // alternative locations (or else terminating those variables).
2172753f127fSDimitry Andric   if (TTracker) {
2173753f127fSDimitry Andric     for (auto LocVal : ClobberedLocs) {
2174753f127fSDimitry Andric       TTracker->clobberMloc(LocVal.first, LocVal.second, MI.getIterator(), false);
2175753f127fSDimitry Andric     }
2176753f127fSDimitry Andric   }
2177753f127fSDimitry Andric 
2178e8d8bef9SDimitry Andric   // Only produce a transfer of DBG_VALUE within a block where old LDV
2179e8d8bef9SDimitry Andric   // would have. We might make use of the additional value tracking in some
2180e8d8bef9SDimitry Andric   // other way, later.
2181e8d8bef9SDimitry Andric   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
2182e8d8bef9SDimitry Andric     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
2183e8d8bef9SDimitry Andric                             MTracker->getRegMLoc(DestReg), MI.getIterator());
2184e8d8bef9SDimitry Andric 
2185e8d8bef9SDimitry Andric   // VarLocBasedImpl would quit tracking the old location after copying.
2186e8d8bef9SDimitry Andric   if (EmulateOldLDV && SrcReg != DestReg)
2187e8d8bef9SDimitry Andric     MTracker->defReg(SrcReg, CurBB, CurInst);
2188e8d8bef9SDimitry Andric 
2189e8d8bef9SDimitry Andric   return true;
2190e8d8bef9SDimitry Andric }
2191e8d8bef9SDimitry Andric 
2192e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
2193e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
2194e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
2195e8d8bef9SDimitry Andric /// known-to-overlap fragments are present".
21964824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for
2197e8d8bef9SDimitry Andric ///           fragment usage.
2198e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2199bdd1243dSDimitry Andric   assert(MI.isDebugValueLike());
2200e8d8bef9SDimitry Andric   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2201e8d8bef9SDimitry Andric                       MI.getDebugLoc()->getInlinedAt());
2202e8d8bef9SDimitry Andric   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2203e8d8bef9SDimitry Andric 
2204e8d8bef9SDimitry Andric   // If this is the first sighting of this variable, then we are guaranteed
2205e8d8bef9SDimitry Andric   // there are currently no overlapping fragments either. Initialize the set
2206e8d8bef9SDimitry Andric   // of seen fragments, record no overlaps for the current one, and return.
2207e8d8bef9SDimitry Andric   auto SeenIt = SeenFragments.find(MIVar.getVariable());
2208e8d8bef9SDimitry Andric   if (SeenIt == SeenFragments.end()) {
2209e8d8bef9SDimitry Andric     SmallSet<FragmentInfo, 4> OneFragment;
2210e8d8bef9SDimitry Andric     OneFragment.insert(ThisFragment);
2211e8d8bef9SDimitry Andric     SeenFragments.insert({MIVar.getVariable(), OneFragment});
2212e8d8bef9SDimitry Andric 
2213e8d8bef9SDimitry Andric     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2214e8d8bef9SDimitry Andric     return;
2215e8d8bef9SDimitry Andric   }
2216e8d8bef9SDimitry Andric 
2217e8d8bef9SDimitry Andric   // If this particular Variable/Fragment pair already exists in the overlap
2218e8d8bef9SDimitry Andric   // map, it has already been accounted for.
2219e8d8bef9SDimitry Andric   auto IsInOLapMap =
2220e8d8bef9SDimitry Andric       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2221e8d8bef9SDimitry Andric   if (!IsInOLapMap.second)
2222e8d8bef9SDimitry Andric     return;
2223e8d8bef9SDimitry Andric 
2224e8d8bef9SDimitry Andric   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2225e8d8bef9SDimitry Andric   auto &AllSeenFragments = SeenIt->second;
2226e8d8bef9SDimitry Andric 
2227e8d8bef9SDimitry Andric   // Otherwise, examine all other seen fragments for this variable, with "this"
2228e8d8bef9SDimitry Andric   // fragment being a previously unseen fragment. Record any pair of
2229e8d8bef9SDimitry Andric   // overlapping fragments.
2230fcaf7f86SDimitry Andric   for (const auto &ASeenFragment : AllSeenFragments) {
2231e8d8bef9SDimitry Andric     // Does this previously seen fragment overlap?
2232e8d8bef9SDimitry Andric     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
2233e8d8bef9SDimitry Andric       // Yes: Mark the current fragment as being overlapped.
2234e8d8bef9SDimitry Andric       ThisFragmentsOverlaps.push_back(ASeenFragment);
2235e8d8bef9SDimitry Andric       // Mark the previously seen fragment as being overlapped by the current
2236e8d8bef9SDimitry Andric       // one.
2237e8d8bef9SDimitry Andric       auto ASeenFragmentsOverlaps =
2238e8d8bef9SDimitry Andric           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
2239e8d8bef9SDimitry Andric       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2240e8d8bef9SDimitry Andric              "Previously seen var fragment has no vector of overlaps");
2241e8d8bef9SDimitry Andric       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
2242e8d8bef9SDimitry Andric     }
2243e8d8bef9SDimitry Andric   }
2244e8d8bef9SDimitry Andric 
2245e8d8bef9SDimitry Andric   AllSeenFragments.insert(ThisFragment);
2246e8d8bef9SDimitry Andric }
2247e8d8bef9SDimitry Andric 
224881ad6265SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts,
224981ad6265SDimitry Andric                                const ValueTable *MLiveIns) {
2250e8d8bef9SDimitry Andric   // Try to interpret an MI as a debug or transfer instruction. Only if it's
2251e8d8bef9SDimitry Andric   // none of these should we interpret it's register defs as new value
2252e8d8bef9SDimitry Andric   // definitions.
2253e8d8bef9SDimitry Andric   if (transferDebugValue(MI))
2254e8d8bef9SDimitry Andric     return;
2255fe6060f1SDimitry Andric   if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
2256fe6060f1SDimitry Andric     return;
2257fe6060f1SDimitry Andric   if (transferDebugPHI(MI))
2258e8d8bef9SDimitry Andric     return;
2259e8d8bef9SDimitry Andric   if (transferRegisterCopy(MI))
2260e8d8bef9SDimitry Andric     return;
2261e8d8bef9SDimitry Andric   if (transferSpillOrRestoreInst(MI))
2262e8d8bef9SDimitry Andric     return;
2263e8d8bef9SDimitry Andric   transferRegisterDef(MI);
2264e8d8bef9SDimitry Andric }
2265e8d8bef9SDimitry Andric 
2266e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction(
2267e8d8bef9SDimitry Andric     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2268e8d8bef9SDimitry Andric     unsigned MaxNumBlocks) {
2269e8d8bef9SDimitry Andric   // Because we try to optimize around register mask operands by ignoring regs
2270e8d8bef9SDimitry Andric   // that aren't currently tracked, we set up something ugly for later: RegMask
2271e8d8bef9SDimitry Andric   // operands that are seen earlier than the first use of a register, still need
2272e8d8bef9SDimitry Andric   // to clobber that register in the transfer function. But this information
2273e8d8bef9SDimitry Andric   // isn't actively recorded. Instead, we track each RegMask used in each block,
2274e8d8bef9SDimitry Andric   // and accumulated the clobbered but untracked registers in each block into
2275e8d8bef9SDimitry Andric   // the following bitvector. Later, if new values are tracked, we can add
2276e8d8bef9SDimitry Andric   // appropriate clobbers.
2277e8d8bef9SDimitry Andric   SmallVector<BitVector, 32> BlockMasks;
2278e8d8bef9SDimitry Andric   BlockMasks.resize(MaxNumBlocks);
2279e8d8bef9SDimitry Andric 
2280e8d8bef9SDimitry Andric   // Reserve one bit per register for the masks described above.
2281e8d8bef9SDimitry Andric   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
2282e8d8bef9SDimitry Andric   for (auto &BV : BlockMasks)
2283e8d8bef9SDimitry Andric     BV.resize(TRI->getNumRegs(), true);
2284e8d8bef9SDimitry Andric 
2285e8d8bef9SDimitry Andric   // Step through all instructions and inhale the transfer function.
2286e8d8bef9SDimitry Andric   for (auto &MBB : MF) {
2287e8d8bef9SDimitry Andric     // Object fields that are read by trackers to know where we are in the
2288e8d8bef9SDimitry Andric     // function.
2289e8d8bef9SDimitry Andric     CurBB = MBB.getNumber();
2290e8d8bef9SDimitry Andric     CurInst = 1;
2291e8d8bef9SDimitry Andric 
2292e8d8bef9SDimitry Andric     // Set all machine locations to a PHI value. For transfer function
2293e8d8bef9SDimitry Andric     // production only, this signifies the live-in value to the block.
2294e8d8bef9SDimitry Andric     MTracker->reset();
2295e8d8bef9SDimitry Andric     MTracker->setMPhis(CurBB);
2296e8d8bef9SDimitry Andric 
2297e8d8bef9SDimitry Andric     // Step through each instruction in this block.
2298e8d8bef9SDimitry Andric     for (auto &MI : MBB) {
229981ad6265SDimitry Andric       // Pass in an empty unique_ptr for the value tables when accumulating the
230081ad6265SDimitry Andric       // machine transfer function.
230181ad6265SDimitry Andric       process(MI, nullptr, nullptr);
230281ad6265SDimitry Andric 
2303e8d8bef9SDimitry Andric       // Also accumulate fragment map.
2304bdd1243dSDimitry Andric       if (MI.isDebugValueLike())
2305e8d8bef9SDimitry Andric         accumulateFragmentMap(MI);
2306e8d8bef9SDimitry Andric 
2307e8d8bef9SDimitry Andric       // Create a map from the instruction number (if present) to the
2308e8d8bef9SDimitry Andric       // MachineInstr and its position.
2309e8d8bef9SDimitry Andric       if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
2310e8d8bef9SDimitry Andric         auto InstrAndPos = std::make_pair(&MI, CurInst);
2311e8d8bef9SDimitry Andric         auto InsertResult =
2312e8d8bef9SDimitry Andric             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
2313e8d8bef9SDimitry Andric 
2314e8d8bef9SDimitry Andric         // There should never be duplicate instruction numbers.
2315e8d8bef9SDimitry Andric         assert(InsertResult.second);
2316e8d8bef9SDimitry Andric         (void)InsertResult;
2317e8d8bef9SDimitry Andric       }
2318e8d8bef9SDimitry Andric 
2319e8d8bef9SDimitry Andric       ++CurInst;
2320e8d8bef9SDimitry Andric     }
2321e8d8bef9SDimitry Andric 
2322e8d8bef9SDimitry Andric     // Produce the transfer function, a map of machine location to new value. If
2323e8d8bef9SDimitry Andric     // any machine location has the live-in phi value from the start of the
2324e8d8bef9SDimitry Andric     // block, it's live-through and doesn't need recording in the transfer
2325e8d8bef9SDimitry Andric     // function.
2326e8d8bef9SDimitry Andric     for (auto Location : MTracker->locations()) {
2327e8d8bef9SDimitry Andric       LocIdx Idx = Location.Idx;
2328e8d8bef9SDimitry Andric       ValueIDNum &P = Location.Value;
2329e8d8bef9SDimitry Andric       if (P.isPHI() && P.getLoc() == Idx.asU64())
2330e8d8bef9SDimitry Andric         continue;
2331e8d8bef9SDimitry Andric 
2332e8d8bef9SDimitry Andric       // Insert-or-update.
2333e8d8bef9SDimitry Andric       auto &TransferMap = MLocTransfer[CurBB];
2334e8d8bef9SDimitry Andric       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
2335e8d8bef9SDimitry Andric       if (!Result.second)
2336e8d8bef9SDimitry Andric         Result.first->second = P;
2337e8d8bef9SDimitry Andric     }
2338e8d8bef9SDimitry Andric 
2339bdd1243dSDimitry Andric     // Accumulate any bitmask operands into the clobbered reg mask for this
2340e8d8bef9SDimitry Andric     // block.
2341e8d8bef9SDimitry Andric     for (auto &P : MTracker->Masks) {
2342e8d8bef9SDimitry Andric       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
2343e8d8bef9SDimitry Andric     }
2344e8d8bef9SDimitry Andric   }
2345e8d8bef9SDimitry Andric 
2346e8d8bef9SDimitry Andric   // Compute a bitvector of all the registers that are tracked in this block.
2347e8d8bef9SDimitry Andric   BitVector UsedRegs(TRI->getNumRegs());
2348e8d8bef9SDimitry Andric   for (auto Location : MTracker->locations()) {
2349e8d8bef9SDimitry Andric     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2350349cc55cSDimitry Andric     // Ignore stack slots, and aliases of the stack pointer.
2351349cc55cSDimitry Andric     if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
2352e8d8bef9SDimitry Andric       continue;
2353e8d8bef9SDimitry Andric     UsedRegs.set(ID);
2354e8d8bef9SDimitry Andric   }
2355e8d8bef9SDimitry Andric 
2356e8d8bef9SDimitry Andric   // Check that any regmask-clobber of a register that gets tracked, is not
2357e8d8bef9SDimitry Andric   // live-through in the transfer function. It needs to be clobbered at the
2358e8d8bef9SDimitry Andric   // very least.
2359e8d8bef9SDimitry Andric   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2360e8d8bef9SDimitry Andric     BitVector &BV = BlockMasks[I];
2361e8d8bef9SDimitry Andric     BV.flip();
2362e8d8bef9SDimitry Andric     BV &= UsedRegs;
2363e8d8bef9SDimitry Andric     // This produces all the bits that we clobber, but also use. Check that
2364e8d8bef9SDimitry Andric     // they're all clobbered or at least set in the designated transfer
2365e8d8bef9SDimitry Andric     // elem.
2366e8d8bef9SDimitry Andric     for (unsigned Bit : BV.set_bits()) {
2367349cc55cSDimitry Andric       unsigned ID = MTracker->getLocID(Bit);
2368e8d8bef9SDimitry Andric       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2369e8d8bef9SDimitry Andric       auto &TransferMap = MLocTransfer[I];
2370e8d8bef9SDimitry Andric 
2371e8d8bef9SDimitry Andric       // Install a value representing the fact that this location is effectively
2372e8d8bef9SDimitry Andric       // written to in this block. As there's no reserved value, instead use
2373e8d8bef9SDimitry Andric       // a value number that is never generated. Pick the value number for the
2374e8d8bef9SDimitry Andric       // first instruction in the block, def'ing this location, which we know
2375e8d8bef9SDimitry Andric       // this block never used anyway.
2376e8d8bef9SDimitry Andric       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2377e8d8bef9SDimitry Andric       auto Result =
2378e8d8bef9SDimitry Andric         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
2379e8d8bef9SDimitry Andric       if (!Result.second) {
2380e8d8bef9SDimitry Andric         ValueIDNum &ValueID = Result.first->second;
2381e8d8bef9SDimitry Andric         if (ValueID.getBlock() == I && ValueID.isPHI())
2382e8d8bef9SDimitry Andric           // It was left as live-through. Set it to clobbered.
2383e8d8bef9SDimitry Andric           ValueID = NotGeneratedNum;
2384e8d8bef9SDimitry Andric       }
2385e8d8bef9SDimitry Andric     }
2386e8d8bef9SDimitry Andric   }
2387e8d8bef9SDimitry Andric }
2388e8d8bef9SDimitry Andric 
2389349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin(
2390349cc55cSDimitry Andric     MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
239181ad6265SDimitry Andric     FuncValueTable &OutLocs, ValueTable &InLocs) {
2392e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2393e8d8bef9SDimitry Andric   bool Changed = false;
2394e8d8bef9SDimitry Andric 
2395349cc55cSDimitry Andric   // Handle value-propagation when control flow merges on entry to a block. For
2396349cc55cSDimitry Andric   // any location without a PHI already placed, the location has the same value
2397349cc55cSDimitry Andric   // as its predecessors. If a PHI is placed, test to see whether it's now a
2398349cc55cSDimitry Andric   // redundant PHI that we can eliminate.
2399349cc55cSDimitry Andric 
2400e8d8bef9SDimitry Andric   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
2401fcaf7f86SDimitry Andric   for (auto *Pred : MBB.predecessors())
2402e8d8bef9SDimitry Andric     BlockOrders.push_back(Pred);
2403e8d8bef9SDimitry Andric 
2404e8d8bef9SDimitry Andric   // Visit predecessors in RPOT order.
2405e8d8bef9SDimitry Andric   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2406e8d8bef9SDimitry Andric     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2407e8d8bef9SDimitry Andric   };
2408e8d8bef9SDimitry Andric   llvm::sort(BlockOrders, Cmp);
2409e8d8bef9SDimitry Andric 
2410e8d8bef9SDimitry Andric   // Skip entry block.
2411e8d8bef9SDimitry Andric   if (BlockOrders.size() == 0)
2412349cc55cSDimitry Andric     return false;
2413e8d8bef9SDimitry Andric 
2414349cc55cSDimitry Andric   // Step through all machine locations, look at each predecessor and test
2415349cc55cSDimitry Andric   // whether we can eliminate redundant PHIs.
2416e8d8bef9SDimitry Andric   for (auto Location : MTracker->locations()) {
2417e8d8bef9SDimitry Andric     LocIdx Idx = Location.Idx;
2418349cc55cSDimitry Andric 
2419e8d8bef9SDimitry Andric     // Pick out the first predecessors live-out value for this location. It's
2420349cc55cSDimitry Andric     // guaranteed to not be a backedge, as we order by RPO.
2421349cc55cSDimitry Andric     ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
2422e8d8bef9SDimitry Andric 
2423349cc55cSDimitry Andric     // If we've already eliminated a PHI here, do no further checking, just
2424349cc55cSDimitry Andric     // propagate the first live-in value into this block.
2425349cc55cSDimitry Andric     if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
2426349cc55cSDimitry Andric       if (InLocs[Idx.asU64()] != FirstVal) {
2427349cc55cSDimitry Andric         InLocs[Idx.asU64()] = FirstVal;
2428349cc55cSDimitry Andric         Changed |= true;
2429349cc55cSDimitry Andric       }
2430349cc55cSDimitry Andric       continue;
2431349cc55cSDimitry Andric     }
2432349cc55cSDimitry Andric 
2433349cc55cSDimitry Andric     // We're now examining a PHI to see whether it's un-necessary. Loop around
2434349cc55cSDimitry Andric     // the other live-in values and test whether they're all the same.
2435e8d8bef9SDimitry Andric     bool Disagree = false;
2436e8d8bef9SDimitry Andric     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2437349cc55cSDimitry Andric       const MachineBasicBlock *PredMBB = BlockOrders[I];
2438349cc55cSDimitry Andric       const ValueIDNum &PredLiveOut =
2439349cc55cSDimitry Andric           OutLocs[PredMBB->getNumber()][Idx.asU64()];
2440349cc55cSDimitry Andric 
2441349cc55cSDimitry Andric       // Incoming values agree, continue trying to eliminate this PHI.
2442349cc55cSDimitry Andric       if (FirstVal == PredLiveOut)
2443349cc55cSDimitry Andric         continue;
2444349cc55cSDimitry Andric 
2445349cc55cSDimitry Andric       // We can also accept a PHI value that feeds back into itself.
2446349cc55cSDimitry Andric       if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
2447349cc55cSDimitry Andric         continue;
2448349cc55cSDimitry Andric 
2449e8d8bef9SDimitry Andric       // Live-out of a predecessor disagrees with the first predecessor.
2450e8d8bef9SDimitry Andric       Disagree = true;
2451e8d8bef9SDimitry Andric     }
2452e8d8bef9SDimitry Andric 
2453349cc55cSDimitry Andric     // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
2454349cc55cSDimitry Andric     if (!Disagree) {
2455349cc55cSDimitry Andric       InLocs[Idx.asU64()] = FirstVal;
2456e8d8bef9SDimitry Andric       Changed |= true;
2457e8d8bef9SDimitry Andric     }
2458e8d8bef9SDimitry Andric   }
2459e8d8bef9SDimitry Andric 
2460e8d8bef9SDimitry Andric   // TODO: Reimplement NumInserted and NumRemoved.
2461349cc55cSDimitry Andric   return Changed;
2462e8d8bef9SDimitry Andric }
2463e8d8bef9SDimitry Andric 
2464349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference(
2465349cc55cSDimitry Andric     SmallVectorImpl<unsigned> &Slots) {
2466349cc55cSDimitry Andric   // We could spend a bit of time finding the exact, minimal, set of stack
2467349cc55cSDimitry Andric   // indexes that interfere with each other, much like reg units. Or, we can
2468349cc55cSDimitry Andric   // rely on the fact that:
2469349cc55cSDimitry Andric   //  * The smallest / lowest index will interfere with everything at zero
2470349cc55cSDimitry Andric   //    offset, which will be the largest set of registers,
2471349cc55cSDimitry Andric   //  * Most indexes with non-zero offset will end up being interference units
2472349cc55cSDimitry Andric   //    anyway.
2473349cc55cSDimitry Andric   // So just pick those out and return them.
2474349cc55cSDimitry Andric 
2475349cc55cSDimitry Andric   // We can rely on a single-byte stack index existing already, because we
2476349cc55cSDimitry Andric   // initialize them in MLocTracker.
2477349cc55cSDimitry Andric   auto It = MTracker->StackSlotIdxes.find({8, 0});
2478349cc55cSDimitry Andric   assert(It != MTracker->StackSlotIdxes.end());
2479349cc55cSDimitry Andric   Slots.push_back(It->second);
2480349cc55cSDimitry Andric 
2481349cc55cSDimitry Andric   // Find anything that has a non-zero offset and add that too.
2482349cc55cSDimitry Andric   for (auto &Pair : MTracker->StackSlotIdxes) {
2483349cc55cSDimitry Andric     // Is offset zero? If so, ignore.
2484349cc55cSDimitry Andric     if (!Pair.first.second)
2485349cc55cSDimitry Andric       continue;
2486349cc55cSDimitry Andric     Slots.push_back(Pair.second);
2487349cc55cSDimitry Andric   }
2488349cc55cSDimitry Andric }
2489349cc55cSDimitry Andric 
2490349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs(
2491349cc55cSDimitry Andric     MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
249281ad6265SDimitry Andric     FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2493349cc55cSDimitry Andric   SmallVector<unsigned, 4> StackUnits;
2494349cc55cSDimitry Andric   findStackIndexInterference(StackUnits);
2495349cc55cSDimitry Andric 
2496349cc55cSDimitry Andric   // To avoid repeatedly running the PHI placement algorithm, leverage the
2497349cc55cSDimitry Andric   // fact that a def of register MUST also def its register units. Find the
2498349cc55cSDimitry Andric   // units for registers, place PHIs for them, and then replicate them for
2499349cc55cSDimitry Andric   // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2500349cc55cSDimitry Andric   // arguments) don't lead to register units being tracked, just place PHIs for
2501349cc55cSDimitry Andric   // those registers directly. Stack slots have their own form of "unit",
2502349cc55cSDimitry Andric   // store them to one side.
2503349cc55cSDimitry Andric   SmallSet<Register, 32> RegUnitsToPHIUp;
2504349cc55cSDimitry Andric   SmallSet<LocIdx, 32> NormalLocsToPHI;
2505349cc55cSDimitry Andric   SmallSet<SpillLocationNo, 32> StackSlots;
2506349cc55cSDimitry Andric   for (auto Location : MTracker->locations()) {
2507349cc55cSDimitry Andric     LocIdx L = Location.Idx;
2508349cc55cSDimitry Andric     if (MTracker->isSpill(L)) {
2509349cc55cSDimitry Andric       StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
2510349cc55cSDimitry Andric       continue;
2511349cc55cSDimitry Andric     }
2512349cc55cSDimitry Andric 
2513349cc55cSDimitry Andric     Register R = MTracker->LocIdxToLocID[L];
2514349cc55cSDimitry Andric     SmallSet<Register, 8> FoundRegUnits;
2515349cc55cSDimitry Andric     bool AnyIllegal = false;
2516*06c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(R.asMCReg())) {
2517*06c3fb27SDimitry Andric       for (MCRegUnitRootIterator URoot(Unit, TRI); URoot.isValid(); ++URoot) {
2518349cc55cSDimitry Andric         if (!MTracker->isRegisterTracked(*URoot)) {
2519349cc55cSDimitry Andric           // Not all roots were loaded into the tracking map: this register
2520349cc55cSDimitry Andric           // isn't actually def'd anywhere, we only read from it. Generate PHIs
2521349cc55cSDimitry Andric           // for this reg, but don't iterate units.
2522349cc55cSDimitry Andric           AnyIllegal = true;
2523349cc55cSDimitry Andric         } else {
2524349cc55cSDimitry Andric           FoundRegUnits.insert(*URoot);
2525349cc55cSDimitry Andric         }
2526349cc55cSDimitry Andric       }
2527349cc55cSDimitry Andric     }
2528349cc55cSDimitry Andric 
2529349cc55cSDimitry Andric     if (AnyIllegal) {
2530349cc55cSDimitry Andric       NormalLocsToPHI.insert(L);
2531349cc55cSDimitry Andric       continue;
2532349cc55cSDimitry Andric     }
2533349cc55cSDimitry Andric 
2534349cc55cSDimitry Andric     RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
2535349cc55cSDimitry Andric   }
2536349cc55cSDimitry Andric 
2537349cc55cSDimitry Andric   // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2538349cc55cSDimitry Andric   // collection.
2539349cc55cSDimitry Andric   SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2540349cc55cSDimitry Andric   auto CollectPHIsForLoc = [&](LocIdx L) {
2541349cc55cSDimitry Andric     // Collect the set of defs.
2542349cc55cSDimitry Andric     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2543349cc55cSDimitry Andric     for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2544349cc55cSDimitry Andric       MachineBasicBlock *MBB = OrderToBB[I];
2545349cc55cSDimitry Andric       const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2546349cc55cSDimitry Andric       if (TransferFunc.find(L) != TransferFunc.end())
2547349cc55cSDimitry Andric         DefBlocks.insert(MBB);
2548349cc55cSDimitry Andric     }
2549349cc55cSDimitry Andric 
2550349cc55cSDimitry Andric     // The entry block defs the location too: it's the live-in / argument value.
2551349cc55cSDimitry Andric     // Only insert if there are other defs though; everything is trivially live
2552349cc55cSDimitry Andric     // through otherwise.
2553349cc55cSDimitry Andric     if (!DefBlocks.empty())
2554349cc55cSDimitry Andric       DefBlocks.insert(&*MF.begin());
2555349cc55cSDimitry Andric 
2556349cc55cSDimitry Andric     // Ask the SSA construction algorithm where we should put PHIs. Clear
2557349cc55cSDimitry Andric     // anything that might have been hanging around from earlier.
2558349cc55cSDimitry Andric     PHIBlocks.clear();
2559349cc55cSDimitry Andric     BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2560349cc55cSDimitry Andric   };
2561349cc55cSDimitry Andric 
2562349cc55cSDimitry Andric   auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2563349cc55cSDimitry Andric     for (const MachineBasicBlock *MBB : PHIBlocks)
2564349cc55cSDimitry Andric       MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2565349cc55cSDimitry Andric   };
2566349cc55cSDimitry Andric 
2567349cc55cSDimitry Andric   // For locations with no reg units, just place PHIs.
2568349cc55cSDimitry Andric   for (LocIdx L : NormalLocsToPHI) {
2569349cc55cSDimitry Andric     CollectPHIsForLoc(L);
2570349cc55cSDimitry Andric     // Install those PHI values into the live-in value array.
2571349cc55cSDimitry Andric     InstallPHIsAtLoc(L);
2572349cc55cSDimitry Andric   }
2573349cc55cSDimitry Andric 
2574349cc55cSDimitry Andric   // For stack slots, calculate PHIs for the equivalent of the units, then
2575349cc55cSDimitry Andric   // install for each index.
2576349cc55cSDimitry Andric   for (SpillLocationNo Slot : StackSlots) {
2577349cc55cSDimitry Andric     for (unsigned Idx : StackUnits) {
2578349cc55cSDimitry Andric       unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2579349cc55cSDimitry Andric       LocIdx L = MTracker->getSpillMLoc(SpillID);
2580349cc55cSDimitry Andric       CollectPHIsForLoc(L);
2581349cc55cSDimitry Andric       InstallPHIsAtLoc(L);
2582349cc55cSDimitry Andric 
2583349cc55cSDimitry Andric       // Find anything that aliases this stack index, install PHIs for it too.
2584349cc55cSDimitry Andric       unsigned Size, Offset;
2585349cc55cSDimitry Andric       std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2586349cc55cSDimitry Andric       for (auto &Pair : MTracker->StackSlotIdxes) {
2587349cc55cSDimitry Andric         unsigned ThisSize, ThisOffset;
2588349cc55cSDimitry Andric         std::tie(ThisSize, ThisOffset) = Pair.first;
2589349cc55cSDimitry Andric         if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2590349cc55cSDimitry Andric           continue;
2591349cc55cSDimitry Andric 
2592349cc55cSDimitry Andric         unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2593349cc55cSDimitry Andric         LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2594349cc55cSDimitry Andric         InstallPHIsAtLoc(ThisL);
2595349cc55cSDimitry Andric       }
2596349cc55cSDimitry Andric     }
2597349cc55cSDimitry Andric   }
2598349cc55cSDimitry Andric 
2599349cc55cSDimitry Andric   // For reg units, place PHIs, and then place them for any aliasing registers.
2600349cc55cSDimitry Andric   for (Register R : RegUnitsToPHIUp) {
2601349cc55cSDimitry Andric     LocIdx L = MTracker->lookupOrTrackRegister(R);
2602349cc55cSDimitry Andric     CollectPHIsForLoc(L);
2603349cc55cSDimitry Andric 
2604349cc55cSDimitry Andric     // Install those PHI values into the live-in value array.
2605349cc55cSDimitry Andric     InstallPHIsAtLoc(L);
2606349cc55cSDimitry Andric 
2607349cc55cSDimitry Andric     // Now find aliases and install PHIs for those.
2608349cc55cSDimitry Andric     for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2609349cc55cSDimitry Andric       // Super-registers that are "above" the largest register read/written by
2610349cc55cSDimitry Andric       // the function will alias, but will not be tracked.
2611349cc55cSDimitry Andric       if (!MTracker->isRegisterTracked(*RAI))
2612349cc55cSDimitry Andric         continue;
2613349cc55cSDimitry Andric 
2614349cc55cSDimitry Andric       LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2615349cc55cSDimitry Andric       InstallPHIsAtLoc(AliasLoc);
2616349cc55cSDimitry Andric     }
2617349cc55cSDimitry Andric   }
2618349cc55cSDimitry Andric }
2619349cc55cSDimitry Andric 
2620349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap(
262181ad6265SDimitry Andric     MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2622e8d8bef9SDimitry Andric     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2623e8d8bef9SDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
2624e8d8bef9SDimitry Andric                       std::greater<unsigned int>>
2625e8d8bef9SDimitry Andric       Worklist, Pending;
2626e8d8bef9SDimitry Andric 
2627e8d8bef9SDimitry Andric   // We track what is on the current and pending worklist to avoid inserting
2628e8d8bef9SDimitry Andric   // the same thing twice. We could avoid this with a custom priority queue,
2629e8d8bef9SDimitry Andric   // but this is probably not worth it.
2630e8d8bef9SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2631e8d8bef9SDimitry Andric 
2632349cc55cSDimitry Andric   // Initialize worklist with every block to be visited. Also produce list of
2633349cc55cSDimitry Andric   // all blocks.
2634349cc55cSDimitry Andric   SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2635e8d8bef9SDimitry Andric   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2636e8d8bef9SDimitry Andric     Worklist.push(I);
2637e8d8bef9SDimitry Andric     OnWorklist.insert(OrderToBB[I]);
2638349cc55cSDimitry Andric     AllBlocks.insert(OrderToBB[I]);
2639e8d8bef9SDimitry Andric   }
2640e8d8bef9SDimitry Andric 
2641349cc55cSDimitry Andric   // Initialize entry block to PHIs. These represent arguments.
2642349cc55cSDimitry Andric   for (auto Location : MTracker->locations())
2643349cc55cSDimitry Andric     MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
2644349cc55cSDimitry Andric 
2645e8d8bef9SDimitry Andric   MTracker->reset();
2646e8d8bef9SDimitry Andric 
2647349cc55cSDimitry Andric   // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2648349cc55cSDimitry Andric   // any machine-location that isn't live-through a block to be def'd in that
2649349cc55cSDimitry Andric   // block.
2650349cc55cSDimitry Andric   placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2651e8d8bef9SDimitry Andric 
2652349cc55cSDimitry Andric   // Propagate values to eliminate redundant PHIs. At the same time, this
2653349cc55cSDimitry Andric   // produces the table of Block x Location => Value for the entry to each
2654349cc55cSDimitry Andric   // block.
2655349cc55cSDimitry Andric   // The kind of PHIs we can eliminate are, for example, where one path in a
2656349cc55cSDimitry Andric   // conditional spills and restores a register, and the register still has
2657349cc55cSDimitry Andric   // the same value once control flow joins, unbeknowns to the PHI placement
2658349cc55cSDimitry Andric   // code. Propagating values allows us to identify such un-necessary PHIs and
2659349cc55cSDimitry Andric   // remove them.
2660e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2661e8d8bef9SDimitry Andric   while (!Worklist.empty() || !Pending.empty()) {
2662e8d8bef9SDimitry Andric     // Vector for storing the evaluated block transfer function.
2663e8d8bef9SDimitry Andric     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2664e8d8bef9SDimitry Andric 
2665e8d8bef9SDimitry Andric     while (!Worklist.empty()) {
2666e8d8bef9SDimitry Andric       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2667e8d8bef9SDimitry Andric       CurBB = MBB->getNumber();
2668e8d8bef9SDimitry Andric       Worklist.pop();
2669e8d8bef9SDimitry Andric 
2670e8d8bef9SDimitry Andric       // Join the values in all predecessor blocks.
2671349cc55cSDimitry Andric       bool InLocsChanged;
2672349cc55cSDimitry Andric       InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2673e8d8bef9SDimitry Andric       InLocsChanged |= Visited.insert(MBB).second;
2674e8d8bef9SDimitry Andric 
2675e8d8bef9SDimitry Andric       // Don't examine transfer function if we've visited this loc at least
2676e8d8bef9SDimitry Andric       // once, and inlocs haven't changed.
2677e8d8bef9SDimitry Andric       if (!InLocsChanged)
2678e8d8bef9SDimitry Andric         continue;
2679e8d8bef9SDimitry Andric 
2680e8d8bef9SDimitry Andric       // Load the current set of live-ins into MLocTracker.
2681e8d8bef9SDimitry Andric       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2682e8d8bef9SDimitry Andric 
2683e8d8bef9SDimitry Andric       // Each element of the transfer function can be a new def, or a read of
2684e8d8bef9SDimitry Andric       // a live-in value. Evaluate each element, and store to "ToRemap".
2685e8d8bef9SDimitry Andric       ToRemap.clear();
2686e8d8bef9SDimitry Andric       for (auto &P : MLocTransfer[CurBB]) {
2687e8d8bef9SDimitry Andric         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2688e8d8bef9SDimitry Andric           // This is a movement of whatever was live in. Read it.
2689349cc55cSDimitry Andric           ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2690e8d8bef9SDimitry Andric           ToRemap.push_back(std::make_pair(P.first, NewID));
2691e8d8bef9SDimitry Andric         } else {
2692e8d8bef9SDimitry Andric           // It's a def. Just set it.
2693e8d8bef9SDimitry Andric           assert(P.second.getBlock() == CurBB);
2694e8d8bef9SDimitry Andric           ToRemap.push_back(std::make_pair(P.first, P.second));
2695e8d8bef9SDimitry Andric         }
2696e8d8bef9SDimitry Andric       }
2697e8d8bef9SDimitry Andric 
2698e8d8bef9SDimitry Andric       // Commit the transfer function changes into mloc tracker, which
2699e8d8bef9SDimitry Andric       // transforms the contents of the MLocTracker into the live-outs.
2700e8d8bef9SDimitry Andric       for (auto &P : ToRemap)
2701e8d8bef9SDimitry Andric         MTracker->setMLoc(P.first, P.second);
2702e8d8bef9SDimitry Andric 
2703e8d8bef9SDimitry Andric       // Now copy out-locs from mloc tracker into out-loc vector, checking
2704e8d8bef9SDimitry Andric       // whether changes have occurred. These changes can have come from both
2705e8d8bef9SDimitry Andric       // the transfer function, and mlocJoin.
2706e8d8bef9SDimitry Andric       bool OLChanged = false;
2707e8d8bef9SDimitry Andric       for (auto Location : MTracker->locations()) {
2708e8d8bef9SDimitry Andric         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2709e8d8bef9SDimitry Andric         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2710e8d8bef9SDimitry Andric       }
2711e8d8bef9SDimitry Andric 
2712e8d8bef9SDimitry Andric       MTracker->reset();
2713e8d8bef9SDimitry Andric 
2714e8d8bef9SDimitry Andric       // No need to examine successors again if out-locs didn't change.
2715e8d8bef9SDimitry Andric       if (!OLChanged)
2716e8d8bef9SDimitry Andric         continue;
2717e8d8bef9SDimitry Andric 
2718e8d8bef9SDimitry Andric       // All successors should be visited: put any back-edges on the pending
2719349cc55cSDimitry Andric       // list for the next pass-through, and any other successors to be
2720349cc55cSDimitry Andric       // visited this pass, if they're not going to be already.
2721fcaf7f86SDimitry Andric       for (auto *s : MBB->successors()) {
2722e8d8bef9SDimitry Andric         // Does branching to this successor represent a back-edge?
2723e8d8bef9SDimitry Andric         if (BBToOrder[s] > BBToOrder[MBB]) {
2724e8d8bef9SDimitry Andric           // No: visit it during this dataflow iteration.
2725e8d8bef9SDimitry Andric           if (OnWorklist.insert(s).second)
2726e8d8bef9SDimitry Andric             Worklist.push(BBToOrder[s]);
2727e8d8bef9SDimitry Andric         } else {
2728e8d8bef9SDimitry Andric           // Yes: visit it on the next iteration.
2729e8d8bef9SDimitry Andric           if (OnPending.insert(s).second)
2730e8d8bef9SDimitry Andric             Pending.push(BBToOrder[s]);
2731e8d8bef9SDimitry Andric         }
2732e8d8bef9SDimitry Andric       }
2733e8d8bef9SDimitry Andric     }
2734e8d8bef9SDimitry Andric 
2735e8d8bef9SDimitry Andric     Worklist.swap(Pending);
2736e8d8bef9SDimitry Andric     std::swap(OnPending, OnWorklist);
2737e8d8bef9SDimitry Andric     OnPending.clear();
2738e8d8bef9SDimitry Andric     // At this point, pending must be empty, since it was just the empty
2739e8d8bef9SDimitry Andric     // worklist
2740e8d8bef9SDimitry Andric     assert(Pending.empty() && "Pending should be empty");
2741e8d8bef9SDimitry Andric   }
2742e8d8bef9SDimitry Andric 
2743349cc55cSDimitry Andric   // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2744349cc55cSDimitry Andric   // redundant PHIs.
2745e8d8bef9SDimitry Andric }
2746e8d8bef9SDimitry Andric 
2747349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement(
2748349cc55cSDimitry Andric     const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2749349cc55cSDimitry Andric     const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2750349cc55cSDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2751349cc55cSDimitry Andric   // Apply IDF calculator to the designated set of location defs, storing
2752349cc55cSDimitry Andric   // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2753349cc55cSDimitry Andric   // InstrRefBasedLDV object.
27541fd87a68SDimitry Andric   IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
2755349cc55cSDimitry Andric 
2756349cc55cSDimitry Andric   IDF.setLiveInBlocks(AllBlocks);
2757349cc55cSDimitry Andric   IDF.setDefiningBlocks(DefBlocks);
2758349cc55cSDimitry Andric   IDF.calculate(PHIBlocks);
2759e8d8bef9SDimitry Andric }
2760e8d8bef9SDimitry Andric 
2761bdd1243dSDimitry Andric bool InstrRefBasedLDV::pickVPHILoc(
2762bdd1243dSDimitry Andric     SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
276381ad6265SDimitry Andric     const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2764349cc55cSDimitry Andric     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2765349cc55cSDimitry Andric 
2766349cc55cSDimitry Andric   // No predecessors means no PHIs.
2767349cc55cSDimitry Andric   if (BlockOrders.empty())
2768bdd1243dSDimitry Andric     return false;
2769e8d8bef9SDimitry Andric 
2770bdd1243dSDimitry Andric   // All the location operands that do not already agree need to be joined,
2771bdd1243dSDimitry Andric   // track the indices of each such location operand here.
2772bdd1243dSDimitry Andric   SmallDenseSet<unsigned> LocOpsToJoin;
2773bdd1243dSDimitry Andric 
2774bdd1243dSDimitry Andric   auto FirstValueIt = LiveOuts.find(BlockOrders[0]);
2775bdd1243dSDimitry Andric   if (FirstValueIt == LiveOuts.end())
2776bdd1243dSDimitry Andric     return false;
2777bdd1243dSDimitry Andric   const DbgValue &FirstValue = *FirstValueIt->second;
2778bdd1243dSDimitry Andric 
2779bdd1243dSDimitry Andric   for (const auto p : BlockOrders) {
2780349cc55cSDimitry Andric     auto OutValIt = LiveOuts.find(p);
2781349cc55cSDimitry Andric     if (OutValIt == LiveOuts.end())
2782349cc55cSDimitry Andric       // If we have a predecessor not in scope, we'll never find a PHI position.
2783bdd1243dSDimitry Andric       return false;
2784349cc55cSDimitry Andric     const DbgValue &OutVal = *OutValIt->second;
2785e8d8bef9SDimitry Andric 
2786bdd1243dSDimitry Andric     // No-values cannot have locations we can join on.
2787bdd1243dSDimitry Andric     if (OutVal.Kind == DbgValue::NoVal)
2788bdd1243dSDimitry Andric       return false;
2789e8d8bef9SDimitry Andric 
2790bdd1243dSDimitry Andric     // For unjoined VPHIs where we don't know the location, we definitely
2791bdd1243dSDimitry Andric     // can't find a join loc unless the VPHI is a backedge.
2792bdd1243dSDimitry Andric     if (OutVal.isUnjoinedPHI() && OutVal.BlockNo != MBB.getNumber())
2793bdd1243dSDimitry Andric       return false;
2794bdd1243dSDimitry Andric 
2795bdd1243dSDimitry Andric     if (!FirstValue.Properties.isJoinable(OutVal.Properties))
2796bdd1243dSDimitry Andric       return false;
2797bdd1243dSDimitry Andric 
2798bdd1243dSDimitry Andric     for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2799bdd1243dSDimitry Andric       // An unjoined PHI has no defined locations, and so a shared location must
2800bdd1243dSDimitry Andric       // be found for every operand.
2801bdd1243dSDimitry Andric       if (OutVal.isUnjoinedPHI()) {
2802bdd1243dSDimitry Andric         LocOpsToJoin.insert(Idx);
2803bdd1243dSDimitry Andric         continue;
2804bdd1243dSDimitry Andric       }
2805bdd1243dSDimitry Andric       DbgOpID FirstValOp = FirstValue.getDbgOpID(Idx);
2806bdd1243dSDimitry Andric       DbgOpID OutValOp = OutVal.getDbgOpID(Idx);
2807bdd1243dSDimitry Andric       if (FirstValOp != OutValOp) {
2808bdd1243dSDimitry Andric         // We can never join constant ops - the ops must either both be equal
2809bdd1243dSDimitry Andric         // constant ops or non-const ops.
2810bdd1243dSDimitry Andric         if (FirstValOp.isConst() || OutValOp.isConst())
2811bdd1243dSDimitry Andric           return false;
2812bdd1243dSDimitry Andric         else
2813bdd1243dSDimitry Andric           LocOpsToJoin.insert(Idx);
2814bdd1243dSDimitry Andric       }
2815bdd1243dSDimitry Andric     }
2816bdd1243dSDimitry Andric   }
2817bdd1243dSDimitry Andric 
2818bdd1243dSDimitry Andric   SmallVector<DbgOpID> NewDbgOps;
2819bdd1243dSDimitry Andric 
2820bdd1243dSDimitry Andric   for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2821bdd1243dSDimitry Andric     // If this op doesn't need to be joined because the values agree, use that
2822bdd1243dSDimitry Andric     // already-agreed value.
2823bdd1243dSDimitry Andric     if (!LocOpsToJoin.contains(Idx)) {
2824bdd1243dSDimitry Andric       NewDbgOps.push_back(FirstValue.getDbgOpID(Idx));
2825bdd1243dSDimitry Andric       continue;
2826bdd1243dSDimitry Andric     }
2827bdd1243dSDimitry Andric 
2828bdd1243dSDimitry Andric     std::optional<ValueIDNum> JoinedOpLoc =
2829bdd1243dSDimitry Andric         pickOperandPHILoc(Idx, MBB, LiveOuts, MOutLocs, BlockOrders);
2830bdd1243dSDimitry Andric 
2831bdd1243dSDimitry Andric     if (!JoinedOpLoc)
2832bdd1243dSDimitry Andric       return false;
2833bdd1243dSDimitry Andric 
2834bdd1243dSDimitry Andric     NewDbgOps.push_back(DbgOpStore.insert(*JoinedOpLoc));
2835bdd1243dSDimitry Andric   }
2836bdd1243dSDimitry Andric 
2837bdd1243dSDimitry Andric   OutValues.append(NewDbgOps);
2838bdd1243dSDimitry Andric   return true;
2839bdd1243dSDimitry Andric }
2840bdd1243dSDimitry Andric 
2841bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::pickOperandPHILoc(
2842bdd1243dSDimitry Andric     unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
2843bdd1243dSDimitry Andric     FuncValueTable &MOutLocs,
2844bdd1243dSDimitry Andric     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2845bdd1243dSDimitry Andric 
2846bdd1243dSDimitry Andric   // Collect a set of locations from predecessor where its live-out value can
2847bdd1243dSDimitry Andric   // be found.
2848bdd1243dSDimitry Andric   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2849bdd1243dSDimitry Andric   unsigned NumLocs = MTracker->getNumLocs();
2850bdd1243dSDimitry Andric 
2851bdd1243dSDimitry Andric   for (const auto p : BlockOrders) {
2852bdd1243dSDimitry Andric     unsigned ThisBBNum = p->getNumber();
2853bdd1243dSDimitry Andric     auto OutValIt = LiveOuts.find(p);
2854bdd1243dSDimitry Andric     assert(OutValIt != LiveOuts.end());
2855bdd1243dSDimitry Andric     const DbgValue &OutVal = *OutValIt->second;
2856bdd1243dSDimitry Andric     DbgOpID OutValOpID = OutVal.getDbgOpID(DbgOpIdx);
2857bdd1243dSDimitry Andric     DbgOp OutValOp = DbgOpStore.find(OutValOpID);
2858bdd1243dSDimitry Andric     assert(!OutValOp.IsConst);
2859349cc55cSDimitry Andric 
2860349cc55cSDimitry Andric     // Create new empty vector of locations.
2861349cc55cSDimitry Andric     Locs.resize(Locs.size() + 1);
2862349cc55cSDimitry Andric 
2863349cc55cSDimitry Andric     // If the live-in value is a def, find the locations where that value is
2864349cc55cSDimitry Andric     // present. Do the same for VPHIs where we know the VPHI value.
2865349cc55cSDimitry Andric     if (OutVal.Kind == DbgValue::Def ||
2866349cc55cSDimitry Andric         (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2867bdd1243dSDimitry Andric          !OutValOp.isUndef())) {
2868bdd1243dSDimitry Andric       ValueIDNum ValToLookFor = OutValOp.ID;
2869e8d8bef9SDimitry Andric       // Search the live-outs of the predecessor for the specified value.
2870e8d8bef9SDimitry Andric       for (unsigned int I = 0; I < NumLocs; ++I) {
2871e8d8bef9SDimitry Andric         if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2872e8d8bef9SDimitry Andric           Locs.back().push_back(LocIdx(I));
2873e8d8bef9SDimitry Andric       }
2874349cc55cSDimitry Andric     } else {
2875349cc55cSDimitry Andric       assert(OutVal.Kind == DbgValue::VPHI);
2876349cc55cSDimitry Andric       // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2877349cc55cSDimitry Andric       // a value that's live-through the whole loop. (It has to be a backedge,
2878349cc55cSDimitry Andric       // because a block can't dominate itself). We can accept as a PHI location
2879349cc55cSDimitry Andric       // any location where the other predecessors agree, _and_ the machine
2880349cc55cSDimitry Andric       // locations feed back into themselves. Therefore, add all self-looping
2881349cc55cSDimitry Andric       // machine-value PHI locations.
2882349cc55cSDimitry Andric       for (unsigned int I = 0; I < NumLocs; ++I) {
2883349cc55cSDimitry Andric         ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2884349cc55cSDimitry Andric         if (MOutLocs[ThisBBNum][I] == MPHI)
2885349cc55cSDimitry Andric           Locs.back().push_back(LocIdx(I));
2886349cc55cSDimitry Andric       }
2887349cc55cSDimitry Andric     }
2888e8d8bef9SDimitry Andric   }
2889349cc55cSDimitry Andric   // We should have found locations for all predecessors, or returned.
2890349cc55cSDimitry Andric   assert(Locs.size() == BlockOrders.size());
2891e8d8bef9SDimitry Andric 
2892e8d8bef9SDimitry Andric   // Starting with the first set of locations, take the intersection with
2893e8d8bef9SDimitry Andric   // subsequent sets.
2894349cc55cSDimitry Andric   SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2895349cc55cSDimitry Andric   for (unsigned int I = 1; I < Locs.size(); ++I) {
2896349cc55cSDimitry Andric     auto &LocVec = Locs[I];
2897349cc55cSDimitry Andric     SmallVector<LocIdx, 4> NewCandidates;
2898349cc55cSDimitry Andric     std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2899349cc55cSDimitry Andric                           LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2900349cc55cSDimitry Andric     CandidateLocs = NewCandidates;
2901e8d8bef9SDimitry Andric   }
2902349cc55cSDimitry Andric   if (CandidateLocs.empty())
2903bdd1243dSDimitry Andric     return std::nullopt;
2904e8d8bef9SDimitry Andric 
2905e8d8bef9SDimitry Andric   // We now have a set of LocIdxes that contain the right output value in
2906e8d8bef9SDimitry Andric   // each of the predecessors. Pick the lowest; if there's a register loc,
2907e8d8bef9SDimitry Andric   // that'll be it.
2908349cc55cSDimitry Andric   LocIdx L = *CandidateLocs.begin();
2909e8d8bef9SDimitry Andric 
2910e8d8bef9SDimitry Andric   // Return a PHI-value-number for the found location.
2911e8d8bef9SDimitry Andric   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2912349cc55cSDimitry Andric   return PHIVal;
2913e8d8bef9SDimitry Andric }
2914e8d8bef9SDimitry Andric 
2915349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin(
2916349cc55cSDimitry Andric     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2917e8d8bef9SDimitry Andric     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2918349cc55cSDimitry Andric     DbgValue &LiveIn) {
2919e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2920e8d8bef9SDimitry Andric   bool Changed = false;
2921e8d8bef9SDimitry Andric 
2922e8d8bef9SDimitry Andric   // Order predecessors by RPOT order, for exploring them in that order.
2923fe6060f1SDimitry Andric   SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2924e8d8bef9SDimitry Andric 
2925e8d8bef9SDimitry Andric   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2926e8d8bef9SDimitry Andric     return BBToOrder[A] < BBToOrder[B];
2927e8d8bef9SDimitry Andric   };
2928e8d8bef9SDimitry Andric 
2929e8d8bef9SDimitry Andric   llvm::sort(BlockOrders, Cmp);
2930e8d8bef9SDimitry Andric 
2931e8d8bef9SDimitry Andric   unsigned CurBlockRPONum = BBToOrder[&MBB];
2932e8d8bef9SDimitry Andric 
2933349cc55cSDimitry Andric   // Collect all the incoming DbgValues for this variable, from predecessor
2934349cc55cSDimitry Andric   // live-out values.
2935e8d8bef9SDimitry Andric   SmallVector<InValueT, 8> Values;
2936e8d8bef9SDimitry Andric   bool Bail = false;
2937349cc55cSDimitry Andric   int BackEdgesStart = 0;
2938fcaf7f86SDimitry Andric   for (auto *p : BlockOrders) {
2939e8d8bef9SDimitry Andric     // If the predecessor isn't in scope / to be explored, we'll never be
2940e8d8bef9SDimitry Andric     // able to join any locations.
2941e8d8bef9SDimitry Andric     if (!BlocksToExplore.contains(p)) {
2942e8d8bef9SDimitry Andric       Bail = true;
2943e8d8bef9SDimitry Andric       break;
2944e8d8bef9SDimitry Andric     }
2945e8d8bef9SDimitry Andric 
2946349cc55cSDimitry Andric     // All Live-outs will have been initialized.
2947349cc55cSDimitry Andric     DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2948e8d8bef9SDimitry Andric 
2949e8d8bef9SDimitry Andric     // Keep track of where back-edges begin in the Values vector. Relies on
2950e8d8bef9SDimitry Andric     // BlockOrders being sorted by RPO.
2951e8d8bef9SDimitry Andric     unsigned ThisBBRPONum = BBToOrder[p];
2952e8d8bef9SDimitry Andric     if (ThisBBRPONum < CurBlockRPONum)
2953e8d8bef9SDimitry Andric       ++BackEdgesStart;
2954e8d8bef9SDimitry Andric 
2955349cc55cSDimitry Andric     Values.push_back(std::make_pair(p, &OutLoc));
2956e8d8bef9SDimitry Andric   }
2957e8d8bef9SDimitry Andric 
2958e8d8bef9SDimitry Andric   // If there were no values, or one of the predecessors couldn't have a
2959e8d8bef9SDimitry Andric   // value, then give up immediately. It's not safe to produce a live-in
2960349cc55cSDimitry Andric   // value. Leave as whatever it was before.
2961e8d8bef9SDimitry Andric   if (Bail || Values.size() == 0)
2962349cc55cSDimitry Andric     return false;
2963e8d8bef9SDimitry Andric 
2964e8d8bef9SDimitry Andric   // All (non-entry) blocks have at least one non-backedge predecessor.
2965e8d8bef9SDimitry Andric   // Pick the variable value from the first of these, to compare against
2966e8d8bef9SDimitry Andric   // all others.
2967e8d8bef9SDimitry Andric   const DbgValue &FirstVal = *Values[0].second;
2968e8d8bef9SDimitry Andric 
2969349cc55cSDimitry Andric   // If the old live-in value is not a PHI then either a) no PHI is needed
2970349cc55cSDimitry Andric   // here, or b) we eliminated the PHI that was here. If so, we can just
2971349cc55cSDimitry Andric   // propagate in the first parent's incoming value.
2972349cc55cSDimitry Andric   if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
2973349cc55cSDimitry Andric     Changed = LiveIn != FirstVal;
2974349cc55cSDimitry Andric     if (Changed)
2975349cc55cSDimitry Andric       LiveIn = FirstVal;
2976349cc55cSDimitry Andric     return Changed;
2977349cc55cSDimitry Andric   }
2978349cc55cSDimitry Andric 
2979349cc55cSDimitry Andric   // Scan for variable values that can never be resolved: if they have
2980349cc55cSDimitry Andric   // different DIExpressions, different indirectness, or are mixed constants /
2981e8d8bef9SDimitry Andric   // non-constants.
2982bdd1243dSDimitry Andric   for (const auto &V : Values) {
2983bdd1243dSDimitry Andric     if (!V.second->Properties.isJoinable(FirstVal.Properties))
2984349cc55cSDimitry Andric       return false;
2985349cc55cSDimitry Andric     if (V.second->Kind == DbgValue::NoVal)
2986349cc55cSDimitry Andric       return false;
2987bdd1243dSDimitry Andric     if (!V.second->hasJoinableLocOps(FirstVal))
2988349cc55cSDimitry Andric       return false;
2989e8d8bef9SDimitry Andric   }
2990e8d8bef9SDimitry Andric 
2991349cc55cSDimitry Andric   // Try to eliminate this PHI. Do the incoming values all agree?
2992e8d8bef9SDimitry Andric   bool Disagree = false;
2993e8d8bef9SDimitry Andric   for (auto &V : Values) {
2994e8d8bef9SDimitry Andric     if (*V.second == FirstVal)
2995e8d8bef9SDimitry Andric       continue; // No disagreement.
2996e8d8bef9SDimitry Andric 
2997bdd1243dSDimitry Andric     // If both values are not equal but have equal non-empty IDs then they refer
2998bdd1243dSDimitry Andric     // to the same value from different sources (e.g. one is VPHI and the other
2999bdd1243dSDimitry Andric     // is Def), which does not cause disagreement.
3000bdd1243dSDimitry Andric     if (V.second->hasIdenticalValidLocOps(FirstVal))
3001bdd1243dSDimitry Andric       continue;
3002bdd1243dSDimitry Andric 
3003349cc55cSDimitry Andric     // Eliminate if a backedge feeds a VPHI back into itself.
3004349cc55cSDimitry Andric     if (V.second->Kind == DbgValue::VPHI &&
3005349cc55cSDimitry Andric         V.second->BlockNo == MBB.getNumber() &&
3006349cc55cSDimitry Andric         // Is this a backedge?
3007349cc55cSDimitry Andric         std::distance(Values.begin(), &V) >= BackEdgesStart)
3008349cc55cSDimitry Andric       continue;
3009349cc55cSDimitry Andric 
3010e8d8bef9SDimitry Andric     Disagree = true;
3011e8d8bef9SDimitry Andric   }
3012e8d8bef9SDimitry Andric 
3013349cc55cSDimitry Andric   // No disagreement -> live-through value.
3014349cc55cSDimitry Andric   if (!Disagree) {
3015349cc55cSDimitry Andric     Changed = LiveIn != FirstVal;
3016e8d8bef9SDimitry Andric     if (Changed)
3017349cc55cSDimitry Andric       LiveIn = FirstVal;
3018349cc55cSDimitry Andric     return Changed;
3019349cc55cSDimitry Andric   } else {
3020349cc55cSDimitry Andric     // Otherwise use a VPHI.
3021349cc55cSDimitry Andric     DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
3022349cc55cSDimitry Andric     Changed = LiveIn != VPHI;
3023349cc55cSDimitry Andric     if (Changed)
3024349cc55cSDimitry Andric       LiveIn = VPHI;
3025349cc55cSDimitry Andric     return Changed;
3026349cc55cSDimitry Andric   }
3027e8d8bef9SDimitry Andric }
3028e8d8bef9SDimitry Andric 
30291fd87a68SDimitry Andric void InstrRefBasedLDV::getBlocksForScope(
30301fd87a68SDimitry Andric     const DILocation *DILoc,
30311fd87a68SDimitry Andric     SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
30321fd87a68SDimitry Andric     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
30331fd87a68SDimitry Andric   // Get the set of "normal" in-lexical-scope blocks.
30341fd87a68SDimitry Andric   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
30351fd87a68SDimitry Andric 
30361fd87a68SDimitry Andric   // VarLoc LiveDebugValues tracks variable locations that are defined in
30371fd87a68SDimitry Andric   // blocks not in scope. This is something we could legitimately ignore, but
30381fd87a68SDimitry Andric   // lets allow it for now for the sake of coverage.
30391fd87a68SDimitry Andric   BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
30401fd87a68SDimitry Andric 
30411fd87a68SDimitry Andric   // Storage for artificial blocks we intend to add to BlocksToExplore.
30421fd87a68SDimitry Andric   DenseSet<const MachineBasicBlock *> ToAdd;
30431fd87a68SDimitry Andric 
30441fd87a68SDimitry Andric   // To avoid needlessly dropping large volumes of variable locations, propagate
30451fd87a68SDimitry Andric   // variables through aritifical blocks, i.e. those that don't have any
30461fd87a68SDimitry Andric   // instructions in scope at all. To accurately replicate VarLoc
30471fd87a68SDimitry Andric   // LiveDebugValues, this means exploring all artificial successors too.
30481fd87a68SDimitry Andric   // Perform a depth-first-search to enumerate those blocks.
3049fcaf7f86SDimitry Andric   for (const auto *MBB : BlocksToExplore) {
30501fd87a68SDimitry Andric     // Depth-first-search state: each node is a block and which successor
30511fd87a68SDimitry Andric     // we're currently exploring.
30521fd87a68SDimitry Andric     SmallVector<std::pair<const MachineBasicBlock *,
30531fd87a68SDimitry Andric                           MachineBasicBlock::const_succ_iterator>,
30541fd87a68SDimitry Andric                 8>
30551fd87a68SDimitry Andric         DFS;
30561fd87a68SDimitry Andric 
30571fd87a68SDimitry Andric     // Find any artificial successors not already tracked.
30581fd87a68SDimitry Andric     for (auto *succ : MBB->successors()) {
30591fd87a68SDimitry Andric       if (BlocksToExplore.count(succ))
30601fd87a68SDimitry Andric         continue;
30611fd87a68SDimitry Andric       if (!ArtificialBlocks.count(succ))
30621fd87a68SDimitry Andric         continue;
30631fd87a68SDimitry Andric       ToAdd.insert(succ);
30641fd87a68SDimitry Andric       DFS.push_back({succ, succ->succ_begin()});
30651fd87a68SDimitry Andric     }
30661fd87a68SDimitry Andric 
30671fd87a68SDimitry Andric     // Search all those blocks, depth first.
30681fd87a68SDimitry Andric     while (!DFS.empty()) {
30691fd87a68SDimitry Andric       const MachineBasicBlock *CurBB = DFS.back().first;
30701fd87a68SDimitry Andric       MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
30711fd87a68SDimitry Andric       // Walk back if we've explored this blocks successors to the end.
30721fd87a68SDimitry Andric       if (CurSucc == CurBB->succ_end()) {
30731fd87a68SDimitry Andric         DFS.pop_back();
30741fd87a68SDimitry Andric         continue;
30751fd87a68SDimitry Andric       }
30761fd87a68SDimitry Andric 
30771fd87a68SDimitry Andric       // If the current successor is artificial and unexplored, descend into
30781fd87a68SDimitry Andric       // it.
30791fd87a68SDimitry Andric       if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
30801fd87a68SDimitry Andric         ToAdd.insert(*CurSucc);
30811fd87a68SDimitry Andric         DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
30821fd87a68SDimitry Andric         continue;
30831fd87a68SDimitry Andric       }
30841fd87a68SDimitry Andric 
30851fd87a68SDimitry Andric       ++CurSucc;
30861fd87a68SDimitry Andric     }
30871fd87a68SDimitry Andric   };
30881fd87a68SDimitry Andric 
30891fd87a68SDimitry Andric   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
30901fd87a68SDimitry Andric }
30911fd87a68SDimitry Andric 
30921fd87a68SDimitry Andric void InstrRefBasedLDV::buildVLocValueMap(
30931fd87a68SDimitry Andric     const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
3094e8d8bef9SDimitry Andric     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
309581ad6265SDimitry Andric     FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3096e8d8bef9SDimitry Andric     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
3097349cc55cSDimitry Andric   // This method is much like buildMLocValueMap: but focuses on a single
3098e8d8bef9SDimitry Andric   // LexicalScope at a time. Pick out a set of blocks and variables that are
3099e8d8bef9SDimitry Andric   // to have their value assignments solved, then run our dataflow algorithm
3100e8d8bef9SDimitry Andric   // until a fixedpoint is reached.
3101e8d8bef9SDimitry Andric   std::priority_queue<unsigned int, std::vector<unsigned int>,
3102e8d8bef9SDimitry Andric                       std::greater<unsigned int>>
3103e8d8bef9SDimitry Andric       Worklist, Pending;
3104e8d8bef9SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
3105e8d8bef9SDimitry Andric 
3106e8d8bef9SDimitry Andric   // The set of blocks we'll be examining.
3107e8d8bef9SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3108e8d8bef9SDimitry Andric 
3109e8d8bef9SDimitry Andric   // The order in which to examine them (RPO).
3110e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 8> BlockOrders;
3111e8d8bef9SDimitry Andric 
3112e8d8bef9SDimitry Andric   // RPO ordering function.
3113e8d8bef9SDimitry Andric   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3114e8d8bef9SDimitry Andric     return BBToOrder[A] < BBToOrder[B];
3115e8d8bef9SDimitry Andric   };
3116e8d8bef9SDimitry Andric 
31171fd87a68SDimitry Andric   getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
3118e8d8bef9SDimitry Andric 
3119e8d8bef9SDimitry Andric   // Single block scope: not interesting! No propagation at all. Note that
3120e8d8bef9SDimitry Andric   // this could probably go above ArtificialBlocks without damage, but
3121e8d8bef9SDimitry Andric   // that then produces output differences from original-live-debug-values,
3122e8d8bef9SDimitry Andric   // which propagates from a single block into many artificial ones.
3123e8d8bef9SDimitry Andric   if (BlocksToExplore.size() == 1)
3124e8d8bef9SDimitry Andric     return;
3125e8d8bef9SDimitry Andric 
3126349cc55cSDimitry Andric   // Convert a const set to a non-const set. LexicalScopes
3127349cc55cSDimitry Andric   // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
3128349cc55cSDimitry Andric   // (Neither of them mutate anything).
3129349cc55cSDimitry Andric   SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
3130349cc55cSDimitry Andric   for (const auto *MBB : BlocksToExplore)
3131349cc55cSDimitry Andric     MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
3132349cc55cSDimitry Andric 
3133e8d8bef9SDimitry Andric   // Picks out relevants blocks RPO order and sort them.
3134fcaf7f86SDimitry Andric   for (const auto *MBB : BlocksToExplore)
3135e8d8bef9SDimitry Andric     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
3136e8d8bef9SDimitry Andric 
3137e8d8bef9SDimitry Andric   llvm::sort(BlockOrders, Cmp);
3138e8d8bef9SDimitry Andric   unsigned NumBlocks = BlockOrders.size();
3139e8d8bef9SDimitry Andric 
3140e8d8bef9SDimitry Andric   // Allocate some vectors for storing the live ins and live outs. Large.
3141349cc55cSDimitry Andric   SmallVector<DbgValue, 32> LiveIns, LiveOuts;
3142349cc55cSDimitry Andric   LiveIns.reserve(NumBlocks);
3143349cc55cSDimitry Andric   LiveOuts.reserve(NumBlocks);
3144349cc55cSDimitry Andric 
3145349cc55cSDimitry Andric   // Initialize all values to start as NoVals. This signifies "it's live
3146349cc55cSDimitry Andric   // through, but we don't know what it is".
3147bdd1243dSDimitry Andric   DbgValueProperties EmptyProperties(EmptyExpr, false, false);
3148349cc55cSDimitry Andric   for (unsigned int I = 0; I < NumBlocks; ++I) {
3149349cc55cSDimitry Andric     DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3150349cc55cSDimitry Andric     LiveIns.push_back(EmptyDbgValue);
3151349cc55cSDimitry Andric     LiveOuts.push_back(EmptyDbgValue);
3152349cc55cSDimitry Andric   }
3153e8d8bef9SDimitry Andric 
3154e8d8bef9SDimitry Andric   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3155e8d8bef9SDimitry Andric   // vlocJoin.
3156e8d8bef9SDimitry Andric   LiveIdxT LiveOutIdx, LiveInIdx;
3157e8d8bef9SDimitry Andric   LiveOutIdx.reserve(NumBlocks);
3158e8d8bef9SDimitry Andric   LiveInIdx.reserve(NumBlocks);
3159e8d8bef9SDimitry Andric   for (unsigned I = 0; I < NumBlocks; ++I) {
3160e8d8bef9SDimitry Andric     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3161e8d8bef9SDimitry Andric     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3162e8d8bef9SDimitry Andric   }
3163e8d8bef9SDimitry Andric 
3164349cc55cSDimitry Andric   // Loop over each variable and place PHIs for it, then propagate values
3165349cc55cSDimitry Andric   // between blocks. This keeps the locality of working on one lexical scope at
3166349cc55cSDimitry Andric   // at time, but avoids re-processing variable values because some other
3167349cc55cSDimitry Andric   // variable has been assigned.
3168fcaf7f86SDimitry Andric   for (const auto &Var : VarsWeCareAbout) {
3169349cc55cSDimitry Andric     // Re-initialize live-ins and live-outs, to clear the remains of previous
3170349cc55cSDimitry Andric     // variables live-ins / live-outs.
3171349cc55cSDimitry Andric     for (unsigned int I = 0; I < NumBlocks; ++I) {
3172349cc55cSDimitry Andric       DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3173349cc55cSDimitry Andric       LiveIns[I] = EmptyDbgValue;
3174349cc55cSDimitry Andric       LiveOuts[I] = EmptyDbgValue;
3175349cc55cSDimitry Andric     }
3176349cc55cSDimitry Andric 
3177349cc55cSDimitry Andric     // Place PHIs for variable values, using the LLVM IDF calculator.
3178349cc55cSDimitry Andric     // Collect the set of blocks where variables are def'd.
3179349cc55cSDimitry Andric     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
3180349cc55cSDimitry Andric     for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
3181349cc55cSDimitry Andric       auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
3182*06c3fb27SDimitry Andric       if (TransferFunc.contains(Var))
3183349cc55cSDimitry Andric         DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
3184349cc55cSDimitry Andric     }
3185349cc55cSDimitry Andric 
3186349cc55cSDimitry Andric     SmallVector<MachineBasicBlock *, 32> PHIBlocks;
3187349cc55cSDimitry Andric 
31881fd87a68SDimitry Andric     // Request the set of PHIs we should insert for this variable. If there's
31891fd87a68SDimitry Andric     // only one value definition, things are very simple.
31901fd87a68SDimitry Andric     if (DefBlocks.size() == 1) {
31911fd87a68SDimitry Andric       placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
31921fd87a68SDimitry Andric                                       AllTheVLocs, Var, Output);
31931fd87a68SDimitry Andric       continue;
31941fd87a68SDimitry Andric     }
31951fd87a68SDimitry Andric 
31961fd87a68SDimitry Andric     // Otherwise: we need to place PHIs through SSA and propagate values.
3197349cc55cSDimitry Andric     BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
3198349cc55cSDimitry Andric 
3199349cc55cSDimitry Andric     // Insert PHIs into the per-block live-in tables for this variable.
3200349cc55cSDimitry Andric     for (MachineBasicBlock *PHIMBB : PHIBlocks) {
3201349cc55cSDimitry Andric       unsigned BlockNo = PHIMBB->getNumber();
3202349cc55cSDimitry Andric       DbgValue *LiveIn = LiveInIdx[PHIMBB];
3203349cc55cSDimitry Andric       *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
3204349cc55cSDimitry Andric     }
3205349cc55cSDimitry Andric 
3206e8d8bef9SDimitry Andric     for (auto *MBB : BlockOrders) {
3207e8d8bef9SDimitry Andric       Worklist.push(BBToOrder[MBB]);
3208e8d8bef9SDimitry Andric       OnWorklist.insert(MBB);
3209e8d8bef9SDimitry Andric     }
3210e8d8bef9SDimitry Andric 
3211349cc55cSDimitry Andric     // Iterate over all the blocks we selected, propagating the variables value.
3212349cc55cSDimitry Andric     // This loop does two things:
3213349cc55cSDimitry Andric     //  * Eliminates un-necessary VPHIs in vlocJoin,
3214349cc55cSDimitry Andric     //  * Evaluates the blocks transfer function (i.e. variable assignments) and
3215349cc55cSDimitry Andric     //    stores the result to the blocks live-outs.
3216349cc55cSDimitry Andric     // Always evaluate the transfer function on the first iteration, and when
3217349cc55cSDimitry Andric     // the live-ins change thereafter.
3218e8d8bef9SDimitry Andric     bool FirstTrip = true;
3219e8d8bef9SDimitry Andric     while (!Worklist.empty() || !Pending.empty()) {
3220e8d8bef9SDimitry Andric       while (!Worklist.empty()) {
3221e8d8bef9SDimitry Andric         auto *MBB = OrderToBB[Worklist.top()];
3222e8d8bef9SDimitry Andric         CurBB = MBB->getNumber();
3223e8d8bef9SDimitry Andric         Worklist.pop();
3224e8d8bef9SDimitry Andric 
3225349cc55cSDimitry Andric         auto LiveInsIt = LiveInIdx.find(MBB);
3226349cc55cSDimitry Andric         assert(LiveInsIt != LiveInIdx.end());
3227349cc55cSDimitry Andric         DbgValue *LiveIn = LiveInsIt->second;
3228e8d8bef9SDimitry Andric 
3229e8d8bef9SDimitry Andric         // Join values from predecessors. Updates LiveInIdx, and writes output
3230e8d8bef9SDimitry Andric         // into JoinedInLocs.
3231349cc55cSDimitry Andric         bool InLocsChanged =
32324824e7fdSDimitry Andric             vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
3233e8d8bef9SDimitry Andric 
3234349cc55cSDimitry Andric         SmallVector<const MachineBasicBlock *, 8> Preds;
3235349cc55cSDimitry Andric         for (const auto *Pred : MBB->predecessors())
3236349cc55cSDimitry Andric           Preds.push_back(Pred);
3237e8d8bef9SDimitry Andric 
3238349cc55cSDimitry Andric         // If this block's live-in value is a VPHI, try to pick a machine-value
3239349cc55cSDimitry Andric         // for it. This makes the machine-value available and propagated
3240349cc55cSDimitry Andric         // through all blocks by the time value propagation finishes. We can't
3241349cc55cSDimitry Andric         // do this any earlier as it needs to read the block live-outs.
3242349cc55cSDimitry Andric         if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
3243349cc55cSDimitry Andric           // There's a small possibility that on a preceeding path, a VPHI is
3244349cc55cSDimitry Andric           // eliminated and transitions from VPHI-with-location to
3245349cc55cSDimitry Andric           // live-through-value. As a result, the selected location of any VPHI
3246349cc55cSDimitry Andric           // might change, so we need to re-compute it on each iteration.
3247bdd1243dSDimitry Andric           SmallVector<DbgOpID> JoinedOps;
3248e8d8bef9SDimitry Andric 
3249bdd1243dSDimitry Andric           if (pickVPHILoc(JoinedOps, *MBB, LiveOutIdx, MOutLocs, Preds)) {
3250bdd1243dSDimitry Andric             bool NewLocPicked = !equal(LiveIn->getDbgOpIDs(), JoinedOps);
3251bdd1243dSDimitry Andric             InLocsChanged |= NewLocPicked;
3252bdd1243dSDimitry Andric             if (NewLocPicked)
3253bdd1243dSDimitry Andric               LiveIn->setDbgOpIDs(JoinedOps);
3254349cc55cSDimitry Andric           }
3255349cc55cSDimitry Andric         }
3256e8d8bef9SDimitry Andric 
3257349cc55cSDimitry Andric         if (!InLocsChanged && !FirstTrip)
3258e8d8bef9SDimitry Andric           continue;
3259e8d8bef9SDimitry Andric 
3260349cc55cSDimitry Andric         DbgValue *LiveOut = LiveOutIdx[MBB];
3261349cc55cSDimitry Andric         bool OLChanged = false;
3262349cc55cSDimitry Andric 
3263e8d8bef9SDimitry Andric         // Do transfer function.
3264e8d8bef9SDimitry Andric         auto &VTracker = AllTheVLocs[MBB->getNumber()];
3265349cc55cSDimitry Andric         auto TransferIt = VTracker.Vars.find(Var);
3266349cc55cSDimitry Andric         if (TransferIt != VTracker.Vars.end()) {
3267e8d8bef9SDimitry Andric           // Erase on empty transfer (DBG_VALUE $noreg).
3268349cc55cSDimitry Andric           if (TransferIt->second.Kind == DbgValue::Undef) {
3269349cc55cSDimitry Andric             DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
3270349cc55cSDimitry Andric             if (*LiveOut != NewVal) {
3271349cc55cSDimitry Andric               *LiveOut = NewVal;
3272349cc55cSDimitry Andric               OLChanged = true;
3273349cc55cSDimitry Andric             }
3274e8d8bef9SDimitry Andric           } else {
3275e8d8bef9SDimitry Andric             // Insert new variable value; or overwrite.
3276349cc55cSDimitry Andric             if (*LiveOut != TransferIt->second) {
3277349cc55cSDimitry Andric               *LiveOut = TransferIt->second;
3278349cc55cSDimitry Andric               OLChanged = true;
3279e8d8bef9SDimitry Andric             }
3280e8d8bef9SDimitry Andric           }
3281349cc55cSDimitry Andric         } else {
3282349cc55cSDimitry Andric           // Just copy live-ins to live-outs, for anything not transferred.
3283349cc55cSDimitry Andric           if (*LiveOut != *LiveIn) {
3284349cc55cSDimitry Andric             *LiveOut = *LiveIn;
3285349cc55cSDimitry Andric             OLChanged = true;
3286349cc55cSDimitry Andric           }
3287e8d8bef9SDimitry Andric         }
3288e8d8bef9SDimitry Andric 
3289349cc55cSDimitry Andric         // If no live-out value changed, there's no need to explore further.
3290e8d8bef9SDimitry Andric         if (!OLChanged)
3291e8d8bef9SDimitry Andric           continue;
3292e8d8bef9SDimitry Andric 
3293e8d8bef9SDimitry Andric         // We should visit all successors. Ensure we'll visit any non-backedge
3294e8d8bef9SDimitry Andric         // successors during this dataflow iteration; book backedge successors
3295e8d8bef9SDimitry Andric         // to be visited next time around.
3296fcaf7f86SDimitry Andric         for (auto *s : MBB->successors()) {
3297e8d8bef9SDimitry Andric           // Ignore out of scope / not-to-be-explored successors.
3298*06c3fb27SDimitry Andric           if (!LiveInIdx.contains(s))
3299e8d8bef9SDimitry Andric             continue;
3300e8d8bef9SDimitry Andric 
3301e8d8bef9SDimitry Andric           if (BBToOrder[s] > BBToOrder[MBB]) {
3302e8d8bef9SDimitry Andric             if (OnWorklist.insert(s).second)
3303e8d8bef9SDimitry Andric               Worklist.push(BBToOrder[s]);
3304e8d8bef9SDimitry Andric           } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
3305e8d8bef9SDimitry Andric             Pending.push(BBToOrder[s]);
3306e8d8bef9SDimitry Andric           }
3307e8d8bef9SDimitry Andric         }
3308e8d8bef9SDimitry Andric       }
3309e8d8bef9SDimitry Andric       Worklist.swap(Pending);
3310e8d8bef9SDimitry Andric       std::swap(OnWorklist, OnPending);
3311e8d8bef9SDimitry Andric       OnPending.clear();
3312e8d8bef9SDimitry Andric       assert(Pending.empty());
3313e8d8bef9SDimitry Andric       FirstTrip = false;
3314e8d8bef9SDimitry Andric     }
3315e8d8bef9SDimitry Andric 
3316349cc55cSDimitry Andric     // Save live-ins to output vector. Ignore any that are still marked as being
3317349cc55cSDimitry Andric     // VPHIs with no location -- those are variables that we know the value of,
3318349cc55cSDimitry Andric     // but are not actually available in the register file.
3319e8d8bef9SDimitry Andric     for (auto *MBB : BlockOrders) {
3320349cc55cSDimitry Andric       DbgValue *BlockLiveIn = LiveInIdx[MBB];
3321349cc55cSDimitry Andric       if (BlockLiveIn->Kind == DbgValue::NoVal)
3322e8d8bef9SDimitry Andric         continue;
3323bdd1243dSDimitry Andric       if (BlockLiveIn->isUnjoinedPHI())
3324349cc55cSDimitry Andric         continue;
3325349cc55cSDimitry Andric       if (BlockLiveIn->Kind == DbgValue::VPHI)
3326349cc55cSDimitry Andric         BlockLiveIn->Kind = DbgValue::Def;
33274824e7fdSDimitry Andric       assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
33284824e7fdSDimitry Andric              Var.getFragment() && "Fragment info missing during value prop");
3329349cc55cSDimitry Andric       Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
3330e8d8bef9SDimitry Andric     }
3331349cc55cSDimitry Andric   } // Per-variable loop.
3332e8d8bef9SDimitry Andric 
3333e8d8bef9SDimitry Andric   BlockOrders.clear();
3334e8d8bef9SDimitry Andric   BlocksToExplore.clear();
3335e8d8bef9SDimitry Andric }
3336e8d8bef9SDimitry Andric 
33371fd87a68SDimitry Andric void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
33381fd87a68SDimitry Andric     const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
33391fd87a68SDimitry Andric     MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
33401fd87a68SDimitry Andric     const DebugVariable &Var, LiveInsT &Output) {
33411fd87a68SDimitry Andric   // If there is a single definition of the variable, then working out it's
33421fd87a68SDimitry Andric   // value everywhere is very simple: it's every block dominated by the
33431fd87a68SDimitry Andric   // definition. At the dominance frontier, the usual algorithm would:
33441fd87a68SDimitry Andric   //  * Place PHIs,
33451fd87a68SDimitry Andric   //  * Propagate values into them,
33461fd87a68SDimitry Andric   //  * Find there's no incoming variable value from the other incoming branches
33471fd87a68SDimitry Andric   //    of the dominance frontier,
33481fd87a68SDimitry Andric   //  * Specify there's no variable value in blocks past the frontier.
33491fd87a68SDimitry Andric   // This is a common case, hence it's worth special-casing it.
33501fd87a68SDimitry Andric 
33511fd87a68SDimitry Andric   // Pick out the variables value from the block transfer function.
33521fd87a68SDimitry Andric   VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
33531fd87a68SDimitry Andric   auto ValueIt = VLocs.Vars.find(Var);
33541fd87a68SDimitry Andric   const DbgValue &Value = ValueIt->second;
33551fd87a68SDimitry Andric 
3356d56accc7SDimitry Andric   // If it's an explicit assignment of "undef", that means there is no location
3357d56accc7SDimitry Andric   // anyway, anywhere.
3358d56accc7SDimitry Andric   if (Value.Kind == DbgValue::Undef)
3359d56accc7SDimitry Andric     return;
3360d56accc7SDimitry Andric 
33611fd87a68SDimitry Andric   // Assign the variable value to entry to each dominated block that's in scope.
33621fd87a68SDimitry Andric   // Skip the definition block -- it's assigned the variable value in the middle
33631fd87a68SDimitry Andric   // of the block somewhere.
33641fd87a68SDimitry Andric   for (auto *ScopeBlock : InScopeBlocks) {
33651fd87a68SDimitry Andric     if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
33661fd87a68SDimitry Andric       continue;
33671fd87a68SDimitry Andric 
33681fd87a68SDimitry Andric     Output[ScopeBlock->getNumber()].push_back({Var, Value});
33691fd87a68SDimitry Andric   }
33701fd87a68SDimitry Andric 
33711fd87a68SDimitry Andric   // All blocks that aren't dominated have no live-in value, thus no variable
33721fd87a68SDimitry Andric   // value will be given to them.
33731fd87a68SDimitry Andric }
33741fd87a68SDimitry Andric 
3375e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3376e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer(
3377e8d8bef9SDimitry Andric     const MLocTransferMap &mloc_transfer) const {
3378fcaf7f86SDimitry Andric   for (const auto &P : mloc_transfer) {
3379e8d8bef9SDimitry Andric     std::string foo = MTracker->LocIdxToName(P.first);
3380e8d8bef9SDimitry Andric     std::string bar = MTracker->IDAsString(P.second);
3381e8d8bef9SDimitry Andric     dbgs() << "Loc " << foo << " --> " << bar << "\n";
3382e8d8bef9SDimitry Andric   }
3383e8d8bef9SDimitry Andric }
3384e8d8bef9SDimitry Andric #endif
3385e8d8bef9SDimitry Andric 
3386e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3387e8d8bef9SDimitry Andric   // Build some useful data structures.
3388349cc55cSDimitry Andric 
3389349cc55cSDimitry Andric   LLVMContext &Context = MF.getFunction().getContext();
3390349cc55cSDimitry Andric   EmptyExpr = DIExpression::get(Context, {});
3391349cc55cSDimitry Andric 
3392e8d8bef9SDimitry Andric   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3393e8d8bef9SDimitry Andric     if (const DebugLoc &DL = MI.getDebugLoc())
3394e8d8bef9SDimitry Andric       return DL.getLine() != 0;
3395e8d8bef9SDimitry Andric     return false;
3396e8d8bef9SDimitry Andric   };
3397e8d8bef9SDimitry Andric   // Collect a set of all the artificial blocks.
3398e8d8bef9SDimitry Andric   for (auto &MBB : MF)
3399e8d8bef9SDimitry Andric     if (none_of(MBB.instrs(), hasNonArtificialLocation))
3400e8d8bef9SDimitry Andric       ArtificialBlocks.insert(&MBB);
3401e8d8bef9SDimitry Andric 
3402e8d8bef9SDimitry Andric   // Compute mappings of block <=> RPO order.
3403e8d8bef9SDimitry Andric   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3404e8d8bef9SDimitry Andric   unsigned int RPONumber = 0;
3405bdd1243dSDimitry Andric   auto processMBB = [&](MachineBasicBlock *MBB) {
3406fe6060f1SDimitry Andric     OrderToBB[RPONumber] = MBB;
3407fe6060f1SDimitry Andric     BBToOrder[MBB] = RPONumber;
3408fe6060f1SDimitry Andric     BBNumToRPO[MBB->getNumber()] = RPONumber;
3409e8d8bef9SDimitry Andric     ++RPONumber;
3410bdd1243dSDimitry Andric   };
3411bdd1243dSDimitry Andric   for (MachineBasicBlock *MBB : RPOT)
3412bdd1243dSDimitry Andric     processMBB(MBB);
3413bdd1243dSDimitry Andric   for (MachineBasicBlock &MBB : MF)
3414*06c3fb27SDimitry Andric     if (!BBToOrder.contains(&MBB))
3415bdd1243dSDimitry Andric       processMBB(&MBB);
3416fe6060f1SDimitry Andric 
3417fe6060f1SDimitry Andric   // Order value substitutions by their "source" operand pair, for quick lookup.
3418fe6060f1SDimitry Andric   llvm::sort(MF.DebugValueSubstitutions);
3419fe6060f1SDimitry Andric 
3420fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS
3421fe6060f1SDimitry Andric   // As an expensive check, test whether there are any duplicate substitution
3422fe6060f1SDimitry Andric   // sources in the collection.
3423fe6060f1SDimitry Andric   if (MF.DebugValueSubstitutions.size() > 2) {
3424fe6060f1SDimitry Andric     for (auto It = MF.DebugValueSubstitutions.begin();
3425fe6060f1SDimitry Andric          It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
3426fe6060f1SDimitry Andric       assert(It->Src != std::next(It)->Src && "Duplicate variable location "
3427fe6060f1SDimitry Andric                                               "substitution seen");
3428fe6060f1SDimitry Andric     }
3429fe6060f1SDimitry Andric   }
3430fe6060f1SDimitry Andric #endif
3431e8d8bef9SDimitry Andric }
3432e8d8bef9SDimitry Andric 
3433d56accc7SDimitry Andric // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
3434d56accc7SDimitry Andric // lexical scope it's used in. When exploring in DFS order and we pass that
3435d56accc7SDimitry Andric // scope, the block can be processed and any tracking information freed.
3436d56accc7SDimitry Andric void InstrRefBasedLDV::makeDepthFirstEjectionMap(
3437d56accc7SDimitry Andric     SmallVectorImpl<unsigned> &EjectionMap,
3438d56accc7SDimitry Andric     const ScopeToDILocT &ScopeToDILocation,
3439d56accc7SDimitry Andric     ScopeToAssignBlocksT &ScopeToAssignBlocks) {
3440d56accc7SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3441d56accc7SDimitry Andric   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3442d56accc7SDimitry Andric   auto *TopScope = LS.getCurrentFunctionScope();
3443d56accc7SDimitry Andric 
3444d56accc7SDimitry Andric   // Unlike lexical scope explorers, we explore in reverse order, to find the
3445d56accc7SDimitry Andric   // "last" lexical scope used for each block early.
3446d56accc7SDimitry Andric   WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
3447d56accc7SDimitry Andric 
3448d56accc7SDimitry Andric   while (!WorkStack.empty()) {
3449d56accc7SDimitry Andric     auto &ScopePosition = WorkStack.back();
3450d56accc7SDimitry Andric     LexicalScope *WS = ScopePosition.first;
3451d56accc7SDimitry Andric     ssize_t ChildNum = ScopePosition.second--;
3452d56accc7SDimitry Andric 
3453d56accc7SDimitry Andric     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3454d56accc7SDimitry Andric     if (ChildNum >= 0) {
3455d56accc7SDimitry Andric       // If ChildNum is positive, there are remaining children to explore.
3456d56accc7SDimitry Andric       // Push the child and its children-count onto the stack.
3457d56accc7SDimitry Andric       auto &ChildScope = Children[ChildNum];
3458d56accc7SDimitry Andric       WorkStack.push_back(
3459d56accc7SDimitry Andric           std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
3460d56accc7SDimitry Andric     } else {
3461d56accc7SDimitry Andric       WorkStack.pop_back();
3462d56accc7SDimitry Andric 
3463d56accc7SDimitry Andric       // We've explored all children and any later blocks: examine all blocks
3464d56accc7SDimitry Andric       // in our scope. If they haven't yet had an ejection number set, then
3465d56accc7SDimitry Andric       // this scope will be the last to use that block.
3466d56accc7SDimitry Andric       auto DILocationIt = ScopeToDILocation.find(WS);
3467d56accc7SDimitry Andric       if (DILocationIt != ScopeToDILocation.end()) {
3468d56accc7SDimitry Andric         getBlocksForScope(DILocationIt->second, BlocksToExplore,
3469d56accc7SDimitry Andric                           ScopeToAssignBlocks.find(WS)->second);
3470fcaf7f86SDimitry Andric         for (const auto *MBB : BlocksToExplore) {
3471d56accc7SDimitry Andric           unsigned BBNum = MBB->getNumber();
3472d56accc7SDimitry Andric           if (EjectionMap[BBNum] == 0)
3473d56accc7SDimitry Andric             EjectionMap[BBNum] = WS->getDFSOut();
3474d56accc7SDimitry Andric         }
3475d56accc7SDimitry Andric 
3476d56accc7SDimitry Andric         BlocksToExplore.clear();
3477d56accc7SDimitry Andric       }
3478d56accc7SDimitry Andric     }
3479d56accc7SDimitry Andric   }
3480d56accc7SDimitry Andric }
3481d56accc7SDimitry Andric 
3482d56accc7SDimitry Andric bool InstrRefBasedLDV::depthFirstVLocAndEmit(
3483d56accc7SDimitry Andric     unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
3484d56accc7SDimitry Andric     const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
348581ad6265SDimitry Andric     LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3486d56accc7SDimitry Andric     SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
3487d56accc7SDimitry Andric     DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
3488d56accc7SDimitry Andric     const TargetPassConfig &TPC) {
3489d56accc7SDimitry Andric   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
3490d56accc7SDimitry Andric   unsigned NumLocs = MTracker->getNumLocs();
3491d56accc7SDimitry Andric   VTracker = nullptr;
3492d56accc7SDimitry Andric 
3493d56accc7SDimitry Andric   // No scopes? No variable locations.
349481ad6265SDimitry Andric   if (!LS.getCurrentFunctionScope())
3495d56accc7SDimitry Andric     return false;
3496d56accc7SDimitry Andric 
3497d56accc7SDimitry Andric   // Build map from block number to the last scope that uses the block.
3498d56accc7SDimitry Andric   SmallVector<unsigned, 16> EjectionMap;
3499d56accc7SDimitry Andric   EjectionMap.resize(MaxNumBlocks, 0);
3500d56accc7SDimitry Andric   makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
3501d56accc7SDimitry Andric                             ScopeToAssignBlocks);
3502d56accc7SDimitry Andric 
3503d56accc7SDimitry Andric   // Helper lambda for ejecting a block -- if nothing is going to use the block,
3504d56accc7SDimitry Andric   // we can translate the variable location information into DBG_VALUEs and then
3505d56accc7SDimitry Andric   // free all of InstrRefBasedLDV's data structures.
3506d56accc7SDimitry Andric   auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
3507d56accc7SDimitry Andric     unsigned BBNum = MBB.getNumber();
3508d56accc7SDimitry Andric     AllTheVLocs[BBNum].clear();
3509d56accc7SDimitry Andric 
3510d56accc7SDimitry Andric     // Prime the transfer-tracker, and then step through all the block
3511d56accc7SDimitry Andric     // instructions, installing transfers.
3512d56accc7SDimitry Andric     MTracker->reset();
3513d56accc7SDimitry Andric     MTracker->loadFromArray(MInLocs[BBNum], BBNum);
3514bdd1243dSDimitry Andric     TTracker->loadInlocs(MBB, MInLocs[BBNum], DbgOpStore, Output[BBNum],
3515bdd1243dSDimitry Andric                          NumLocs);
3516d56accc7SDimitry Andric 
3517d56accc7SDimitry Andric     CurBB = BBNum;
3518d56accc7SDimitry Andric     CurInst = 1;
3519d56accc7SDimitry Andric     for (auto &MI : MBB) {
352081ad6265SDimitry Andric       process(MI, MOutLocs.get(), MInLocs.get());
3521d56accc7SDimitry Andric       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
3522d56accc7SDimitry Andric       ++CurInst;
3523d56accc7SDimitry Andric     }
3524d56accc7SDimitry Andric 
3525d56accc7SDimitry Andric     // Free machine-location tables for this block.
352681ad6265SDimitry Andric     MInLocs[BBNum].reset();
352781ad6265SDimitry Andric     MOutLocs[BBNum].reset();
3528d56accc7SDimitry Andric     // We don't need live-in variable values for this block either.
3529d56accc7SDimitry Andric     Output[BBNum].clear();
3530d56accc7SDimitry Andric     AllTheVLocs[BBNum].clear();
3531d56accc7SDimitry Andric   };
3532d56accc7SDimitry Andric 
3533d56accc7SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3534d56accc7SDimitry Andric   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3535d56accc7SDimitry Andric   WorkStack.push_back({LS.getCurrentFunctionScope(), 0});
3536d56accc7SDimitry Andric   unsigned HighestDFSIn = 0;
3537d56accc7SDimitry Andric 
3538d56accc7SDimitry Andric   // Proceed to explore in depth first order.
3539d56accc7SDimitry Andric   while (!WorkStack.empty()) {
3540d56accc7SDimitry Andric     auto &ScopePosition = WorkStack.back();
3541d56accc7SDimitry Andric     LexicalScope *WS = ScopePosition.first;
3542d56accc7SDimitry Andric     ssize_t ChildNum = ScopePosition.second++;
3543d56accc7SDimitry Andric 
3544d56accc7SDimitry Andric     // We obesrve scopes with children twice here, once descending in, once
3545d56accc7SDimitry Andric     // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
3546d56accc7SDimitry Andric     // we don't process a scope twice. Additionally, ignore scopes that don't
3547d56accc7SDimitry Andric     // have a DILocation -- by proxy, this means we never tracked any variable
3548d56accc7SDimitry Andric     // assignments in that scope.
3549d56accc7SDimitry Andric     auto DILocIt = ScopeToDILocation.find(WS);
3550d56accc7SDimitry Andric     if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
3551d56accc7SDimitry Andric       const DILocation *DILoc = DILocIt->second;
3552d56accc7SDimitry Andric       auto &VarsWeCareAbout = ScopeToVars.find(WS)->second;
3553d56accc7SDimitry Andric       auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second;
3554d56accc7SDimitry Andric 
3555d56accc7SDimitry Andric       buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs,
3556d56accc7SDimitry Andric                         MInLocs, AllTheVLocs);
3557d56accc7SDimitry Andric     }
3558d56accc7SDimitry Andric 
3559d56accc7SDimitry Andric     HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn());
3560d56accc7SDimitry Andric 
3561d56accc7SDimitry Andric     // Descend into any scope nests.
3562d56accc7SDimitry Andric     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3563d56accc7SDimitry Andric     if (ChildNum < (ssize_t)Children.size()) {
3564d56accc7SDimitry Andric       // There are children to explore -- push onto stack and continue.
3565d56accc7SDimitry Andric       auto &ChildScope = Children[ChildNum];
3566d56accc7SDimitry Andric       WorkStack.push_back(std::make_pair(ChildScope, 0));
3567d56accc7SDimitry Andric     } else {
3568d56accc7SDimitry Andric       WorkStack.pop_back();
3569d56accc7SDimitry Andric 
3570d56accc7SDimitry Andric       // We've explored a leaf, or have explored all the children of a scope.
3571d56accc7SDimitry Andric       // Try to eject any blocks where this is the last scope it's relevant to.
3572d56accc7SDimitry Andric       auto DILocationIt = ScopeToDILocation.find(WS);
3573d56accc7SDimitry Andric       if (DILocationIt == ScopeToDILocation.end())
3574d56accc7SDimitry Andric         continue;
3575d56accc7SDimitry Andric 
3576d56accc7SDimitry Andric       getBlocksForScope(DILocationIt->second, BlocksToExplore,
3577d56accc7SDimitry Andric                         ScopeToAssignBlocks.find(WS)->second);
3578fcaf7f86SDimitry Andric       for (const auto *MBB : BlocksToExplore)
3579d56accc7SDimitry Andric         if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
3580d56accc7SDimitry Andric           EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
3581d56accc7SDimitry Andric 
3582d56accc7SDimitry Andric       BlocksToExplore.clear();
3583d56accc7SDimitry Andric     }
3584d56accc7SDimitry Andric   }
3585d56accc7SDimitry Andric 
3586d56accc7SDimitry Andric   // Some artificial blocks may not have been ejected, meaning they're not
3587d56accc7SDimitry Andric   // connected to an actual legitimate scope. This can technically happen
3588d56accc7SDimitry Andric   // with things like the entry block. In theory, we shouldn't need to do
3589d56accc7SDimitry Andric   // anything for such out-of-scope blocks, but for the sake of being similar
3590d56accc7SDimitry Andric   // to VarLocBasedLDV, eject these too.
3591d56accc7SDimitry Andric   for (auto *MBB : ArtificialBlocks)
3592d56accc7SDimitry Andric     if (MOutLocs[MBB->getNumber()])
3593d56accc7SDimitry Andric       EjectBlock(*MBB);
3594d56accc7SDimitry Andric 
3595d56accc7SDimitry Andric   return emitTransfers(AllVarsNumbering);
3596d56accc7SDimitry Andric }
3597d56accc7SDimitry Andric 
35981fd87a68SDimitry Andric bool InstrRefBasedLDV::emitTransfers(
35991fd87a68SDimitry Andric     DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
36001fd87a68SDimitry Andric   // Go through all the transfers recorded in the TransferTracker -- this is
36011fd87a68SDimitry Andric   // both the live-ins to a block, and any movements of values that happen
36021fd87a68SDimitry Andric   // in the middle.
36031fd87a68SDimitry Andric   for (const auto &P : TTracker->Transfers) {
36041fd87a68SDimitry Andric     // We have to insert DBG_VALUEs in a consistent order, otherwise they
36051fd87a68SDimitry Andric     // appear in DWARF in different orders. Use the order that they appear
36061fd87a68SDimitry Andric     // when walking through each block / each instruction, stored in
36071fd87a68SDimitry Andric     // AllVarsNumbering.
36081fd87a68SDimitry Andric     SmallVector<std::pair<unsigned, MachineInstr *>> Insts;
36091fd87a68SDimitry Andric     for (MachineInstr *MI : P.Insts) {
36101fd87a68SDimitry Andric       DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(),
36111fd87a68SDimitry Andric                         MI->getDebugLoc()->getInlinedAt());
36121fd87a68SDimitry Andric       Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI);
36131fd87a68SDimitry Andric     }
3614972a253aSDimitry Andric     llvm::sort(Insts, llvm::less_first());
36151fd87a68SDimitry Andric 
36161fd87a68SDimitry Andric     // Insert either before or after the designated point...
36171fd87a68SDimitry Andric     if (P.MBB) {
36181fd87a68SDimitry Andric       MachineBasicBlock &MBB = *P.MBB;
36191fd87a68SDimitry Andric       for (const auto &Pair : Insts)
36201fd87a68SDimitry Andric         MBB.insert(P.Pos, Pair.second);
36211fd87a68SDimitry Andric     } else {
36221fd87a68SDimitry Andric       // Terminators, like tail calls, can clobber things. Don't try and place
36231fd87a68SDimitry Andric       // transfers after them.
36241fd87a68SDimitry Andric       if (P.Pos->isTerminator())
36251fd87a68SDimitry Andric         continue;
36261fd87a68SDimitry Andric 
36271fd87a68SDimitry Andric       MachineBasicBlock &MBB = *P.Pos->getParent();
36281fd87a68SDimitry Andric       for (const auto &Pair : Insts)
36291fd87a68SDimitry Andric         MBB.insertAfterBundle(P.Pos, Pair.second);
36301fd87a68SDimitry Andric     }
36311fd87a68SDimitry Andric   }
36321fd87a68SDimitry Andric 
36331fd87a68SDimitry Andric   return TTracker->Transfers.size() != 0;
36341fd87a68SDimitry Andric }
36351fd87a68SDimitry Andric 
3636e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and
3637e8d8bef9SDimitry Andric /// extend ranges across basic blocks.
3638e8d8bef9SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3639349cc55cSDimitry Andric                                     MachineDominatorTree *DomTree,
3640349cc55cSDimitry Andric                                     TargetPassConfig *TPC,
3641349cc55cSDimitry Andric                                     unsigned InputBBLimit,
3642349cc55cSDimitry Andric                                     unsigned InputDbgValLimit) {
3643e8d8bef9SDimitry Andric   // No subprogram means this function contains no debuginfo.
3644e8d8bef9SDimitry Andric   if (!MF.getFunction().getSubprogram())
3645e8d8bef9SDimitry Andric     return false;
3646e8d8bef9SDimitry Andric 
3647e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3648e8d8bef9SDimitry Andric   this->TPC = TPC;
3649e8d8bef9SDimitry Andric 
3650349cc55cSDimitry Andric   this->DomTree = DomTree;
3651e8d8bef9SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
3652349cc55cSDimitry Andric   MRI = &MF.getRegInfo();
3653e8d8bef9SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
3654e8d8bef9SDimitry Andric   TFI = MF.getSubtarget().getFrameLowering();
3655e8d8bef9SDimitry Andric   TFI->getCalleeSaves(MF, CalleeSavedRegs);
3656fe6060f1SDimitry Andric   MFI = &MF.getFrameInfo();
3657e8d8bef9SDimitry Andric   LS.initialize(MF);
3658e8d8bef9SDimitry Andric 
36594824e7fdSDimitry Andric   const auto &STI = MF.getSubtarget();
36604824e7fdSDimitry Andric   AdjustsStackInCalls = MFI->adjustsStack() &&
36614824e7fdSDimitry Andric                         STI.getFrameLowering()->stackProbeFunctionModifiesSP();
36624824e7fdSDimitry Andric   if (AdjustsStackInCalls)
36634824e7fdSDimitry Andric     StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
36644824e7fdSDimitry Andric 
3665e8d8bef9SDimitry Andric   MTracker =
3666e8d8bef9SDimitry Andric       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3667e8d8bef9SDimitry Andric   VTracker = nullptr;
3668e8d8bef9SDimitry Andric   TTracker = nullptr;
3669e8d8bef9SDimitry Andric 
3670e8d8bef9SDimitry Andric   SmallVector<MLocTransferMap, 32> MLocTransfer;
3671e8d8bef9SDimitry Andric   SmallVector<VLocTracker, 8> vlocs;
3672e8d8bef9SDimitry Andric   LiveInsT SavedLiveIns;
3673e8d8bef9SDimitry Andric 
3674e8d8bef9SDimitry Andric   int MaxNumBlocks = -1;
3675e8d8bef9SDimitry Andric   for (auto &MBB : MF)
3676e8d8bef9SDimitry Andric     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3677e8d8bef9SDimitry Andric   assert(MaxNumBlocks >= 0);
3678e8d8bef9SDimitry Andric   ++MaxNumBlocks;
3679e8d8bef9SDimitry Andric 
368081ad6265SDimitry Andric   initialSetup(MF);
368181ad6265SDimitry Andric 
3682e8d8bef9SDimitry Andric   MLocTransfer.resize(MaxNumBlocks);
36834824e7fdSDimitry Andric   vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr));
3684e8d8bef9SDimitry Andric   SavedLiveIns.resize(MaxNumBlocks);
3685e8d8bef9SDimitry Andric 
3686e8d8bef9SDimitry Andric   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3687e8d8bef9SDimitry Andric 
3688e8d8bef9SDimitry Andric   // Allocate and initialize two array-of-arrays for the live-in and live-out
3689e8d8bef9SDimitry Andric   // machine values. The outer dimension is the block number; while the inner
3690e8d8bef9SDimitry Andric   // dimension is a LocIdx from MLocTracker.
369181ad6265SDimitry Andric   FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
369281ad6265SDimitry Andric   FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3693e8d8bef9SDimitry Andric   unsigned NumLocs = MTracker->getNumLocs();
3694e8d8bef9SDimitry Andric   for (int i = 0; i < MaxNumBlocks; ++i) {
3695349cc55cSDimitry Andric     // These all auto-initialize to ValueIDNum::EmptyValue
369681ad6265SDimitry Andric     MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
369781ad6265SDimitry Andric     MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3698e8d8bef9SDimitry Andric   }
3699e8d8bef9SDimitry Andric 
3700e8d8bef9SDimitry Andric   // Solve the machine value dataflow problem using the MLocTransfer function,
3701e8d8bef9SDimitry Andric   // storing the computed live-ins / live-outs into the array-of-arrays. We use
3702e8d8bef9SDimitry Andric   // both live-ins and live-outs for decision making in the variable value
3703e8d8bef9SDimitry Andric   // dataflow problem.
3704349cc55cSDimitry Andric   buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3705e8d8bef9SDimitry Andric 
3706fe6060f1SDimitry Andric   // Patch up debug phi numbers, turning unknown block-live-in values into
3707fe6060f1SDimitry Andric   // either live-through machine values, or PHIs.
3708fe6060f1SDimitry Andric   for (auto &DBG_PHI : DebugPHINumToValue) {
3709fe6060f1SDimitry Andric     // Identify unresolved block-live-ins.
371081ad6265SDimitry Andric     if (!DBG_PHI.ValueRead)
371181ad6265SDimitry Andric       continue;
371281ad6265SDimitry Andric 
371381ad6265SDimitry Andric     ValueIDNum &Num = *DBG_PHI.ValueRead;
3714fe6060f1SDimitry Andric     if (!Num.isPHI())
3715fe6060f1SDimitry Andric       continue;
3716fe6060f1SDimitry Andric 
3717fe6060f1SDimitry Andric     unsigned BlockNo = Num.getBlock();
3718fe6060f1SDimitry Andric     LocIdx LocNo = Num.getLoc();
3719*06c3fb27SDimitry Andric     ValueIDNum ResolvedValue = MInLocs[BlockNo][LocNo.asU64()];
3720*06c3fb27SDimitry Andric     // If there is no resolved value for this live-in then it is not directly
3721*06c3fb27SDimitry Andric     // reachable from the entry block -- model it as a PHI on entry to this
3722*06c3fb27SDimitry Andric     // block, which means we leave the ValueIDNum unchanged.
3723*06c3fb27SDimitry Andric     if (ResolvedValue != ValueIDNum::EmptyValue)
3724*06c3fb27SDimitry Andric       Num = ResolvedValue;
3725fe6060f1SDimitry Andric   }
3726fe6060f1SDimitry Andric   // Later, we'll be looking up ranges of instruction numbers.
3727fe6060f1SDimitry Andric   llvm::sort(DebugPHINumToValue);
3728fe6060f1SDimitry Andric 
3729e8d8bef9SDimitry Andric   // Walk back through each block / instruction, collecting DBG_VALUE
3730e8d8bef9SDimitry Andric   // instructions and recording what machine value their operands refer to.
3731e8d8bef9SDimitry Andric   for (auto &OrderPair : OrderToBB) {
3732e8d8bef9SDimitry Andric     MachineBasicBlock &MBB = *OrderPair.second;
3733e8d8bef9SDimitry Andric     CurBB = MBB.getNumber();
3734e8d8bef9SDimitry Andric     VTracker = &vlocs[CurBB];
3735e8d8bef9SDimitry Andric     VTracker->MBB = &MBB;
3736e8d8bef9SDimitry Andric     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3737e8d8bef9SDimitry Andric     CurInst = 1;
3738e8d8bef9SDimitry Andric     for (auto &MI : MBB) {
373981ad6265SDimitry Andric       process(MI, MOutLocs.get(), MInLocs.get());
3740e8d8bef9SDimitry Andric       ++CurInst;
3741e8d8bef9SDimitry Andric     }
3742e8d8bef9SDimitry Andric     MTracker->reset();
3743e8d8bef9SDimitry Andric   }
3744e8d8bef9SDimitry Andric 
3745e8d8bef9SDimitry Andric   // Number all variables in the order that they appear, to be used as a stable
3746e8d8bef9SDimitry Andric   // insertion order later.
3747e8d8bef9SDimitry Andric   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3748e8d8bef9SDimitry Andric 
3749e8d8bef9SDimitry Andric   // Map from one LexicalScope to all the variables in that scope.
37501fd87a68SDimitry Andric   ScopeToVarsT ScopeToVars;
3751e8d8bef9SDimitry Andric 
37521fd87a68SDimitry Andric   // Map from One lexical scope to all blocks where assignments happen for
37531fd87a68SDimitry Andric   // that scope.
37541fd87a68SDimitry Andric   ScopeToAssignBlocksT ScopeToAssignBlocks;
3755e8d8bef9SDimitry Andric 
37561fd87a68SDimitry Andric   // Store map of DILocations that describes scopes.
37571fd87a68SDimitry Andric   ScopeToDILocT ScopeToDILocation;
3758e8d8bef9SDimitry Andric 
3759e8d8bef9SDimitry Andric   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3760e8d8bef9SDimitry Andric   // the order is unimportant, it just has to be stable.
3761349cc55cSDimitry Andric   unsigned VarAssignCount = 0;
3762e8d8bef9SDimitry Andric   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3763e8d8bef9SDimitry Andric     auto *MBB = OrderToBB[I];
3764e8d8bef9SDimitry Andric     auto *VTracker = &vlocs[MBB->getNumber()];
3765e8d8bef9SDimitry Andric     // Collect each variable with a DBG_VALUE in this block.
3766e8d8bef9SDimitry Andric     for (auto &idx : VTracker->Vars) {
3767e8d8bef9SDimitry Andric       const auto &Var = idx.first;
3768e8d8bef9SDimitry Andric       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3769e8d8bef9SDimitry Andric       assert(ScopeLoc != nullptr);
3770e8d8bef9SDimitry Andric       auto *Scope = LS.findLexicalScope(ScopeLoc);
3771e8d8bef9SDimitry Andric 
3772e8d8bef9SDimitry Andric       // No insts in scope -> shouldn't have been recorded.
3773e8d8bef9SDimitry Andric       assert(Scope != nullptr);
3774e8d8bef9SDimitry Andric 
3775e8d8bef9SDimitry Andric       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3776e8d8bef9SDimitry Andric       ScopeToVars[Scope].insert(Var);
37771fd87a68SDimitry Andric       ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
3778e8d8bef9SDimitry Andric       ScopeToDILocation[Scope] = ScopeLoc;
3779349cc55cSDimitry Andric       ++VarAssignCount;
3780e8d8bef9SDimitry Andric     }
3781e8d8bef9SDimitry Andric   }
3782e8d8bef9SDimitry Andric 
3783349cc55cSDimitry Andric   bool Changed = false;
3784349cc55cSDimitry Andric 
3785349cc55cSDimitry Andric   // If we have an extremely large number of variable assignments and blocks,
3786349cc55cSDimitry Andric   // bail out at this point. We've burnt some time doing analysis already,
3787349cc55cSDimitry Andric   // however we should cut our losses.
3788349cc55cSDimitry Andric   if ((unsigned)MaxNumBlocks > InputBBLimit &&
3789349cc55cSDimitry Andric       VarAssignCount > InputDbgValLimit) {
3790349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3791349cc55cSDimitry Andric                       << " has " << MaxNumBlocks << " basic blocks and "
3792349cc55cSDimitry Andric                       << VarAssignCount
3793349cc55cSDimitry Andric                       << " variable assignments, exceeding limits.\n");
3794d56accc7SDimitry Andric   } else {
3795d56accc7SDimitry Andric     // Optionally, solve the variable value problem and emit to blocks by using
3796d56accc7SDimitry Andric     // a lexical-scope-depth search. It should be functionally identical to
3797d56accc7SDimitry Andric     // the "else" block of this condition.
3798d56accc7SDimitry Andric     Changed = depthFirstVLocAndEmit(
3799d56accc7SDimitry Andric         MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
3800d56accc7SDimitry Andric         SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC);
3801d56accc7SDimitry Andric   }
3802d56accc7SDimitry Andric 
3803e8d8bef9SDimitry Andric   delete MTracker;
3804e8d8bef9SDimitry Andric   delete TTracker;
3805e8d8bef9SDimitry Andric   MTracker = nullptr;
3806e8d8bef9SDimitry Andric   VTracker = nullptr;
3807e8d8bef9SDimitry Andric   TTracker = nullptr;
3808e8d8bef9SDimitry Andric 
3809e8d8bef9SDimitry Andric   ArtificialBlocks.clear();
3810e8d8bef9SDimitry Andric   OrderToBB.clear();
3811e8d8bef9SDimitry Andric   BBToOrder.clear();
3812e8d8bef9SDimitry Andric   BBNumToRPO.clear();
3813e8d8bef9SDimitry Andric   DebugInstrNumToInstr.clear();
3814fe6060f1SDimitry Andric   DebugPHINumToValue.clear();
38154824e7fdSDimitry Andric   OverlapFragments.clear();
38164824e7fdSDimitry Andric   SeenFragments.clear();
3817d56accc7SDimitry Andric   SeenDbgPHIs.clear();
3818bdd1243dSDimitry Andric   DbgOpStore.clear();
3819e8d8bef9SDimitry Andric 
3820e8d8bef9SDimitry Andric   return Changed;
3821e8d8bef9SDimitry Andric }
3822e8d8bef9SDimitry Andric 
3823e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3824e8d8bef9SDimitry Andric   return new InstrRefBasedLDV();
3825e8d8bef9SDimitry Andric }
3826fe6060f1SDimitry Andric 
3827fe6060f1SDimitry Andric namespace {
3828fe6060f1SDimitry Andric class LDVSSABlock;
3829fe6060f1SDimitry Andric class LDVSSAUpdater;
3830fe6060f1SDimitry Andric 
3831fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We
3832fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater
3833fe6060f1SDimitry Andric // expects to zero-initialize the type.
3834fe6060f1SDimitry Andric typedef uint64_t BlockValueNum;
3835fe6060f1SDimitry Andric 
3836fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block
3837fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming
3838fe6060f1SDimitry Andric /// values from parent blocks.
3839fe6060f1SDimitry Andric class LDVSSAPhi {
3840fe6060f1SDimitry Andric public:
3841fe6060f1SDimitry Andric   SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3842fe6060f1SDimitry Andric   LDVSSABlock *ParentBlock;
3843fe6060f1SDimitry Andric   BlockValueNum PHIValNum;
3844fe6060f1SDimitry Andric   LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3845fe6060f1SDimitry Andric       : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3846fe6060f1SDimitry Andric 
3847fe6060f1SDimitry Andric   LDVSSABlock *getParent() { return ParentBlock; }
3848fe6060f1SDimitry Andric };
3849fe6060f1SDimitry Andric 
3850fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a
3851fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock.
3852fe6060f1SDimitry Andric class LDVSSABlockIterator {
3853fe6060f1SDimitry Andric public:
3854fe6060f1SDimitry Andric   MachineBasicBlock::pred_iterator PredIt;
3855fe6060f1SDimitry Andric   LDVSSAUpdater &Updater;
3856fe6060f1SDimitry Andric 
3857fe6060f1SDimitry Andric   LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3858fe6060f1SDimitry Andric                       LDVSSAUpdater &Updater)
3859fe6060f1SDimitry Andric       : PredIt(PredIt), Updater(Updater) {}
3860fe6060f1SDimitry Andric 
3861fe6060f1SDimitry Andric   bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3862fe6060f1SDimitry Andric     return OtherIt.PredIt != PredIt;
3863fe6060f1SDimitry Andric   }
3864fe6060f1SDimitry Andric 
3865fe6060f1SDimitry Andric   LDVSSABlockIterator &operator++() {
3866fe6060f1SDimitry Andric     ++PredIt;
3867fe6060f1SDimitry Andric     return *this;
3868fe6060f1SDimitry Andric   }
3869fe6060f1SDimitry Andric 
3870fe6060f1SDimitry Andric   LDVSSABlock *operator*();
3871fe6060f1SDimitry Andric };
3872fe6060f1SDimitry Andric 
3873fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because
3874fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary
3875fe6060f1SDimitry Andric /// in this block.
3876fe6060f1SDimitry Andric class LDVSSABlock {
3877fe6060f1SDimitry Andric public:
3878fe6060f1SDimitry Andric   MachineBasicBlock &BB;
3879fe6060f1SDimitry Andric   LDVSSAUpdater &Updater;
3880fe6060f1SDimitry Andric   using PHIListT = SmallVector<LDVSSAPhi, 1>;
3881fe6060f1SDimitry Andric   /// List of PHIs in this block. There should only ever be one.
3882fe6060f1SDimitry Andric   PHIListT PHIList;
3883fe6060f1SDimitry Andric 
3884fe6060f1SDimitry Andric   LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3885fe6060f1SDimitry Andric       : BB(BB), Updater(Updater) {}
3886fe6060f1SDimitry Andric 
3887fe6060f1SDimitry Andric   LDVSSABlockIterator succ_begin() {
3888fe6060f1SDimitry Andric     return LDVSSABlockIterator(BB.succ_begin(), Updater);
3889fe6060f1SDimitry Andric   }
3890fe6060f1SDimitry Andric 
3891fe6060f1SDimitry Andric   LDVSSABlockIterator succ_end() {
3892fe6060f1SDimitry Andric     return LDVSSABlockIterator(BB.succ_end(), Updater);
3893fe6060f1SDimitry Andric   }
3894fe6060f1SDimitry Andric 
3895fe6060f1SDimitry Andric   /// SSAUpdater has requested a PHI: create that within this block record.
3896fe6060f1SDimitry Andric   LDVSSAPhi *newPHI(BlockValueNum Value) {
3897fe6060f1SDimitry Andric     PHIList.emplace_back(Value, this);
3898fe6060f1SDimitry Andric     return &PHIList.back();
3899fe6060f1SDimitry Andric   }
3900fe6060f1SDimitry Andric 
3901fe6060f1SDimitry Andric   /// SSAUpdater wishes to know what PHIs already exist in this block.
3902fe6060f1SDimitry Andric   PHIListT &phis() { return PHIList; }
3903fe6060f1SDimitry Andric };
3904fe6060f1SDimitry Andric 
3905fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3906fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3907fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>.
3908fe6060f1SDimitry Andric class LDVSSAUpdater {
3909fe6060f1SDimitry Andric public:
3910fe6060f1SDimitry Andric   /// Map of value numbers to PHI records.
3911fe6060f1SDimitry Andric   DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3912fe6060f1SDimitry Andric   /// Map of which blocks generate Undef values -- blocks that are not
3913fe6060f1SDimitry Andric   /// dominated by any Def.
3914fe6060f1SDimitry Andric   DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3915fe6060f1SDimitry Andric   /// Map of machine blocks to our own records of them.
3916fe6060f1SDimitry Andric   DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3917fe6060f1SDimitry Andric   /// Machine location where any PHI must occur.
3918fe6060f1SDimitry Andric   LocIdx Loc;
3919fe6060f1SDimitry Andric   /// Table of live-in machine value numbers for blocks / locations.
392081ad6265SDimitry Andric   const ValueTable *MLiveIns;
3921fe6060f1SDimitry Andric 
392281ad6265SDimitry Andric   LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns)
392381ad6265SDimitry Andric       : Loc(L), MLiveIns(MLiveIns) {}
3924fe6060f1SDimitry Andric 
3925fe6060f1SDimitry Andric   void reset() {
3926fe6060f1SDimitry Andric     for (auto &Block : BlockMap)
3927fe6060f1SDimitry Andric       delete Block.second;
3928fe6060f1SDimitry Andric 
3929fe6060f1SDimitry Andric     PHIs.clear();
3930fe6060f1SDimitry Andric     UndefMap.clear();
3931fe6060f1SDimitry Andric     BlockMap.clear();
3932fe6060f1SDimitry Andric   }
3933fe6060f1SDimitry Andric 
3934fe6060f1SDimitry Andric   ~LDVSSAUpdater() { reset(); }
3935fe6060f1SDimitry Andric 
3936fe6060f1SDimitry Andric   /// For a given MBB, create a wrapper block for it. Stores it in the
3937fe6060f1SDimitry Andric   /// LDVSSAUpdater block map.
3938fe6060f1SDimitry Andric   LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3939fe6060f1SDimitry Andric     auto it = BlockMap.find(BB);
3940fe6060f1SDimitry Andric     if (it == BlockMap.end()) {
3941fe6060f1SDimitry Andric       BlockMap[BB] = new LDVSSABlock(*BB, *this);
3942fe6060f1SDimitry Andric       it = BlockMap.find(BB);
3943fe6060f1SDimitry Andric     }
3944fe6060f1SDimitry Andric     return it->second;
3945fe6060f1SDimitry Andric   }
3946fe6060f1SDimitry Andric 
3947fe6060f1SDimitry Andric   /// Find the live-in value number for the given block. Looks up the value at
3948fe6060f1SDimitry Andric   /// the PHI location on entry.
3949fe6060f1SDimitry Andric   BlockValueNum getValue(LDVSSABlock *LDVBB) {
3950fe6060f1SDimitry Andric     return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3951fe6060f1SDimitry Andric   }
3952fe6060f1SDimitry Andric };
3953fe6060f1SDimitry Andric 
3954fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() {
3955fe6060f1SDimitry Andric   return Updater.getSSALDVBlock(*PredIt);
3956fe6060f1SDimitry Andric }
3957fe6060f1SDimitry Andric 
3958fe6060f1SDimitry Andric #ifndef NDEBUG
3959fe6060f1SDimitry Andric 
3960fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3961fe6060f1SDimitry Andric   out << "SSALDVPHI " << PHI.PHIValNum;
3962fe6060f1SDimitry Andric   return out;
3963fe6060f1SDimitry Andric }
3964fe6060f1SDimitry Andric 
3965fe6060f1SDimitry Andric #endif
3966fe6060f1SDimitry Andric 
3967fe6060f1SDimitry Andric } // namespace
3968fe6060f1SDimitry Andric 
3969fe6060f1SDimitry Andric namespace llvm {
3970fe6060f1SDimitry Andric 
3971fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value
3972fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the
3973fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define.
3974fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them.
3975fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3976fe6060f1SDimitry Andric public:
3977fe6060f1SDimitry Andric   using BlkT = LDVSSABlock;
3978fe6060f1SDimitry Andric   using ValT = BlockValueNum;
3979fe6060f1SDimitry Andric   using PhiT = LDVSSAPhi;
3980fe6060f1SDimitry Andric   using BlkSucc_iterator = LDVSSABlockIterator;
3981fe6060f1SDimitry Andric 
3982fe6060f1SDimitry Andric   // Methods to access block successors -- dereferencing to our wrapper class.
3983fe6060f1SDimitry Andric   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
3984fe6060f1SDimitry Andric   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3985fe6060f1SDimitry Andric 
3986fe6060f1SDimitry Andric   /// Iterator for PHI operands.
3987fe6060f1SDimitry Andric   class PHI_iterator {
3988fe6060f1SDimitry Andric   private:
3989fe6060f1SDimitry Andric     LDVSSAPhi *PHI;
3990fe6060f1SDimitry Andric     unsigned Idx;
3991fe6060f1SDimitry Andric 
3992fe6060f1SDimitry Andric   public:
3993fe6060f1SDimitry Andric     explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3994fe6060f1SDimitry Andric         : PHI(P), Idx(0) {}
3995fe6060f1SDimitry Andric     PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3996fe6060f1SDimitry Andric         : PHI(P), Idx(PHI->IncomingValues.size()) {}
3997fe6060f1SDimitry Andric 
3998fe6060f1SDimitry Andric     PHI_iterator &operator++() {
3999fe6060f1SDimitry Andric       Idx++;
4000fe6060f1SDimitry Andric       return *this;
4001fe6060f1SDimitry Andric     }
4002fe6060f1SDimitry Andric     bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
4003fe6060f1SDimitry Andric     bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
4004fe6060f1SDimitry Andric 
4005fe6060f1SDimitry Andric     BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
4006fe6060f1SDimitry Andric 
4007fe6060f1SDimitry Andric     LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
4008fe6060f1SDimitry Andric   };
4009fe6060f1SDimitry Andric 
4010fe6060f1SDimitry Andric   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
4011fe6060f1SDimitry Andric 
4012fe6060f1SDimitry Andric   static inline PHI_iterator PHI_end(PhiT *PHI) {
4013fe6060f1SDimitry Andric     return PHI_iterator(PHI, true);
4014fe6060f1SDimitry Andric   }
4015fe6060f1SDimitry Andric 
4016fe6060f1SDimitry Andric   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
4017fe6060f1SDimitry Andric   /// vector.
4018fe6060f1SDimitry Andric   static void FindPredecessorBlocks(LDVSSABlock *BB,
4019fe6060f1SDimitry Andric                                     SmallVectorImpl<LDVSSABlock *> *Preds) {
4020349cc55cSDimitry Andric     for (MachineBasicBlock *Pred : BB->BB.predecessors())
4021349cc55cSDimitry Andric       Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
4022fe6060f1SDimitry Andric   }
4023fe6060f1SDimitry Andric 
4024fe6060f1SDimitry Andric   /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
4025fe6060f1SDimitry Andric   /// register. For LiveDebugValues, represents a block identified as not having
4026fe6060f1SDimitry Andric   /// any DBG_PHI predecessors.
4027fe6060f1SDimitry Andric   static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
4028fe6060f1SDimitry Andric     // Create a value number for this block -- it needs to be unique and in the
4029fe6060f1SDimitry Andric     // "undef" collection, so that we know it's not real. Use a number
4030fe6060f1SDimitry Andric     // representing a PHI into this block.
4031fe6060f1SDimitry Andric     BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
4032fe6060f1SDimitry Andric     Updater->UndefMap[&BB->BB] = Num;
4033fe6060f1SDimitry Andric     return Num;
4034fe6060f1SDimitry Andric   }
4035fe6060f1SDimitry Andric 
4036fe6060f1SDimitry Andric   /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
4037fe6060f1SDimitry Andric   /// SSAUpdater will populate it with information about incoming values. The
4038fe6060f1SDimitry Andric   /// value number of this PHI is whatever the  machine value number problem
4039fe6060f1SDimitry Andric   /// solution determined it to be. This includes non-phi values if SSAUpdater
4040fe6060f1SDimitry Andric   /// tries to create a PHI where the incoming values are identical.
4041fe6060f1SDimitry Andric   static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
4042fe6060f1SDimitry Andric                                    LDVSSAUpdater *Updater) {
4043fe6060f1SDimitry Andric     BlockValueNum PHIValNum = Updater->getValue(BB);
4044fe6060f1SDimitry Andric     LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
4045fe6060f1SDimitry Andric     Updater->PHIs[PHIValNum] = PHI;
4046fe6060f1SDimitry Andric     return PHIValNum;
4047fe6060f1SDimitry Andric   }
4048fe6060f1SDimitry Andric 
4049fe6060f1SDimitry Andric   /// AddPHIOperand - Add the specified value as an operand of the PHI for
4050fe6060f1SDimitry Andric   /// the specified predecessor block.
4051fe6060f1SDimitry Andric   static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
4052fe6060f1SDimitry Andric     PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
4053fe6060f1SDimitry Andric   }
4054fe6060f1SDimitry Andric 
4055fe6060f1SDimitry Andric   /// ValueIsPHI - Check if the instruction that defines the specified value
4056fe6060f1SDimitry Andric   /// is a PHI instruction.
4057fe6060f1SDimitry Andric   static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4058*06c3fb27SDimitry Andric     return Updater->PHIs.lookup(Val);
4059fe6060f1SDimitry Andric   }
4060fe6060f1SDimitry Andric 
4061fe6060f1SDimitry Andric   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
4062fe6060f1SDimitry Andric   /// operands, i.e., it was just added.
4063fe6060f1SDimitry Andric   static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4064fe6060f1SDimitry Andric     LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
4065fe6060f1SDimitry Andric     if (PHI && PHI->IncomingValues.size() == 0)
4066fe6060f1SDimitry Andric       return PHI;
4067fe6060f1SDimitry Andric     return nullptr;
4068fe6060f1SDimitry Andric   }
4069fe6060f1SDimitry Andric 
4070fe6060f1SDimitry Andric   /// GetPHIValue - For the specified PHI instruction, return the value
4071fe6060f1SDimitry Andric   /// that it defines.
4072fe6060f1SDimitry Andric   static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
4073fe6060f1SDimitry Andric };
4074fe6060f1SDimitry Andric 
4075fe6060f1SDimitry Andric } // end namespace llvm
4076fe6060f1SDimitry Andric 
4077bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
407881ad6265SDimitry Andric     MachineFunction &MF, const ValueTable *MLiveOuts,
407981ad6265SDimitry Andric     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
408081ad6265SDimitry Andric   assert(MLiveOuts && MLiveIns &&
408181ad6265SDimitry Andric          "Tried to resolve DBG_PHI before location "
408281ad6265SDimitry Andric          "tables allocated?");
408381ad6265SDimitry Andric 
4084d56accc7SDimitry Andric   // This function will be called twice per DBG_INSTR_REF, and might end up
4085d56accc7SDimitry Andric   // computing lots of SSA information: memoize it.
4086bdd1243dSDimitry Andric   auto SeenDbgPHIIt = SeenDbgPHIs.find(std::make_pair(&Here, InstrNum));
4087d56accc7SDimitry Andric   if (SeenDbgPHIIt != SeenDbgPHIs.end())
4088d56accc7SDimitry Andric     return SeenDbgPHIIt->second;
4089d56accc7SDimitry Andric 
4090bdd1243dSDimitry Andric   std::optional<ValueIDNum> Result =
4091d56accc7SDimitry Andric       resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
4092bdd1243dSDimitry Andric   SeenDbgPHIs.insert({std::make_pair(&Here, InstrNum), Result});
4093d56accc7SDimitry Andric   return Result;
4094d56accc7SDimitry Andric }
4095d56accc7SDimitry Andric 
4096bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
409781ad6265SDimitry Andric     MachineFunction &MF, const ValueTable *MLiveOuts,
409881ad6265SDimitry Andric     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4099fe6060f1SDimitry Andric   // Pick out records of DBG_PHI instructions that have been observed. If there
4100fe6060f1SDimitry Andric   // are none, then we cannot compute a value number.
4101fe6060f1SDimitry Andric   auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
4102fe6060f1SDimitry Andric                                     DebugPHINumToValue.end(), InstrNum);
4103fe6060f1SDimitry Andric   auto LowerIt = RangePair.first;
4104fe6060f1SDimitry Andric   auto UpperIt = RangePair.second;
4105fe6060f1SDimitry Andric 
4106fe6060f1SDimitry Andric   // No DBG_PHI means there can be no location.
4107fe6060f1SDimitry Andric   if (LowerIt == UpperIt)
4108bdd1243dSDimitry Andric     return std::nullopt;
4109fe6060f1SDimitry Andric 
411081ad6265SDimitry Andric   // If any DBG_PHIs referred to a location we didn't understand, don't try to
411181ad6265SDimitry Andric   // compute a value. There might be scenarios where we could recover a value
411281ad6265SDimitry Andric   // for some range of DBG_INSTR_REFs, but at this point we can have high
411381ad6265SDimitry Andric   // confidence that we've seen a bug.
411481ad6265SDimitry Andric   auto DBGPHIRange = make_range(LowerIt, UpperIt);
411581ad6265SDimitry Andric   for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
411681ad6265SDimitry Andric     if (!DBG_PHI.ValueRead)
4117bdd1243dSDimitry Andric       return std::nullopt;
411881ad6265SDimitry Andric 
4119fe6060f1SDimitry Andric   // If there's only one DBG_PHI, then that is our value number.
4120fe6060f1SDimitry Andric   if (std::distance(LowerIt, UpperIt) == 1)
412181ad6265SDimitry Andric     return *LowerIt->ValueRead;
4122fe6060f1SDimitry Andric 
4123fe6060f1SDimitry Andric   // Pick out the location (physreg, slot) where any PHIs must occur. It's
4124fe6060f1SDimitry Andric   // technically possible for us to merge values in different registers in each
4125fe6060f1SDimitry Andric   // block, but highly unlikely that LLVM will generate such code after register
4126fe6060f1SDimitry Andric   // allocation.
412781ad6265SDimitry Andric   LocIdx Loc = *LowerIt->ReadLoc;
4128fe6060f1SDimitry Andric 
4129fe6060f1SDimitry Andric   // We have several DBG_PHIs, and a use position (the Here inst). All each
4130fe6060f1SDimitry Andric   // DBG_PHI does is identify a value at a program position. We can treat each
4131fe6060f1SDimitry Andric   // DBG_PHI like it's a Def of a value, and the use position is a Use of a
4132fe6060f1SDimitry Andric   // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
4133fe6060f1SDimitry Andric   // determine which Def is used at the Use, and any PHIs that happen along
4134fe6060f1SDimitry Andric   // the way.
4135fe6060f1SDimitry Andric   // Adapted LLVM SSA Updater:
4136fe6060f1SDimitry Andric   LDVSSAUpdater Updater(Loc, MLiveIns);
4137fe6060f1SDimitry Andric   // Map of which Def or PHI is the current value in each block.
4138fe6060f1SDimitry Andric   DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
4139fe6060f1SDimitry Andric   // Set of PHIs that we have created along the way.
4140fe6060f1SDimitry Andric   SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
4141fe6060f1SDimitry Andric 
4142fe6060f1SDimitry Andric   // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
4143fe6060f1SDimitry Andric   // for the SSAUpdater.
4144fe6060f1SDimitry Andric   for (const auto &DBG_PHI : DBGPHIRange) {
4145fe6060f1SDimitry Andric     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
414681ad6265SDimitry Andric     const ValueIDNum &Num = *DBG_PHI.ValueRead;
4147fe6060f1SDimitry Andric     AvailableValues.insert(std::make_pair(Block, Num.asU64()));
4148fe6060f1SDimitry Andric   }
4149fe6060f1SDimitry Andric 
4150fe6060f1SDimitry Andric   LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
4151fe6060f1SDimitry Andric   const auto &AvailIt = AvailableValues.find(HereBlock);
4152fe6060f1SDimitry Andric   if (AvailIt != AvailableValues.end()) {
4153fe6060f1SDimitry Andric     // Actually, we already know what the value is -- the Use is in the same
4154fe6060f1SDimitry Andric     // block as the Def.
4155fe6060f1SDimitry Andric     return ValueIDNum::fromU64(AvailIt->second);
4156fe6060f1SDimitry Andric   }
4157fe6060f1SDimitry Andric 
4158fe6060f1SDimitry Andric   // Otherwise, we must use the SSA Updater. It will identify the value number
4159fe6060f1SDimitry Andric   // that we are to use, and the PHIs that must happen along the way.
4160fe6060f1SDimitry Andric   SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
4161fe6060f1SDimitry Andric   BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
4162fe6060f1SDimitry Andric   ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
4163fe6060f1SDimitry Andric 
4164fe6060f1SDimitry Andric   // We have the number for a PHI, or possibly live-through value, to be used
4165fe6060f1SDimitry Andric   // at this Use. There are a number of things we have to check about it though:
4166fe6060f1SDimitry Andric   //  * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
4167fe6060f1SDimitry Andric   //    Use was not completely dominated by DBG_PHIs and we should abort.
4168fe6060f1SDimitry Andric   //  * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
4169fe6060f1SDimitry Andric   //    we've left SSA form. Validate that the inputs to each PHI are the
4170fe6060f1SDimitry Andric   //    expected values.
4171fe6060f1SDimitry Andric   //  * Is a PHI we've created actually a merging of values, or are all the
4172fe6060f1SDimitry Andric   //    predecessor values the same, leading to a non-PHI machine value number?
4173fe6060f1SDimitry Andric   //    (SSAUpdater doesn't know that either). Remap validated PHIs into the
4174fe6060f1SDimitry Andric   //    the ValidatedValues collection below to sort this out.
4175fe6060f1SDimitry Andric   DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
4176fe6060f1SDimitry Andric 
4177fe6060f1SDimitry Andric   // Define all the input DBG_PHI values in ValidatedValues.
4178fe6060f1SDimitry Andric   for (const auto &DBG_PHI : DBGPHIRange) {
4179fe6060f1SDimitry Andric     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
418081ad6265SDimitry Andric     const ValueIDNum &Num = *DBG_PHI.ValueRead;
4181fe6060f1SDimitry Andric     ValidatedValues.insert(std::make_pair(Block, Num));
4182fe6060f1SDimitry Andric   }
4183fe6060f1SDimitry Andric 
4184fe6060f1SDimitry Andric   // Sort PHIs to validate into RPO-order.
4185fe6060f1SDimitry Andric   SmallVector<LDVSSAPhi *, 8> SortedPHIs;
4186fe6060f1SDimitry Andric   for (auto &PHI : CreatedPHIs)
4187fe6060f1SDimitry Andric     SortedPHIs.push_back(PHI);
4188fe6060f1SDimitry Andric 
4189fcaf7f86SDimitry Andric   llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) {
4190fe6060f1SDimitry Andric     return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
4191fe6060f1SDimitry Andric   });
4192fe6060f1SDimitry Andric 
4193fe6060f1SDimitry Andric   for (auto &PHI : SortedPHIs) {
4194fe6060f1SDimitry Andric     ValueIDNum ThisBlockValueNum =
4195fe6060f1SDimitry Andric         MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
4196fe6060f1SDimitry Andric 
4197fe6060f1SDimitry Andric     // Are all these things actually defined?
4198fe6060f1SDimitry Andric     for (auto &PHIIt : PHI->IncomingValues) {
4199fe6060f1SDimitry Andric       // Any undef input means DBG_PHIs didn't dominate the use point.
4200*06c3fb27SDimitry Andric       if (Updater.UndefMap.contains(&PHIIt.first->BB))
4201bdd1243dSDimitry Andric         return std::nullopt;
4202fe6060f1SDimitry Andric 
4203fe6060f1SDimitry Andric       ValueIDNum ValueToCheck;
420481ad6265SDimitry Andric       const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
4205fe6060f1SDimitry Andric 
4206fe6060f1SDimitry Andric       auto VVal = ValidatedValues.find(PHIIt.first);
4207fe6060f1SDimitry Andric       if (VVal == ValidatedValues.end()) {
4208fe6060f1SDimitry Andric         // We cross a loop, and this is a backedge. LLVMs tail duplication
4209fe6060f1SDimitry Andric         // happens so late that DBG_PHI instructions should not be able to
4210fe6060f1SDimitry Andric         // migrate into loops -- meaning we can only be live-through this
4211fe6060f1SDimitry Andric         // loop.
4212fe6060f1SDimitry Andric         ValueToCheck = ThisBlockValueNum;
4213fe6060f1SDimitry Andric       } else {
4214fe6060f1SDimitry Andric         // Does the block have as a live-out, in the location we're examining,
4215fe6060f1SDimitry Andric         // the value that we expect? If not, it's been moved or clobbered.
4216fe6060f1SDimitry Andric         ValueToCheck = VVal->second;
4217fe6060f1SDimitry Andric       }
4218fe6060f1SDimitry Andric 
4219fe6060f1SDimitry Andric       if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
4220bdd1243dSDimitry Andric         return std::nullopt;
4221fe6060f1SDimitry Andric     }
4222fe6060f1SDimitry Andric 
4223fe6060f1SDimitry Andric     // Record this value as validated.
4224fe6060f1SDimitry Andric     ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
4225fe6060f1SDimitry Andric   }
4226fe6060f1SDimitry Andric 
4227fe6060f1SDimitry Andric   // All the PHIs are valid: we can return what the SSAUpdater said our value
4228fe6060f1SDimitry Andric   // number was.
4229fe6060f1SDimitry Andric   return Result;
4230fe6060f1SDimitry Andric }
4231