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
ResolvedDbgValueTransferTracker::ResolvedDbgValue204bdd1243dSDimitry 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.
loc_indicesTransferTracker::ResolvedDbgValue210bdd1243dSDimitry 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;
UseBeforeDefTransferTracker::UseBeforeDef250bdd1243dSDimitry 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
TransferTracker(const TargetInstrInfo * TII,MLocTracker * MTracker,MachineFunction & MF,const TargetRegisterInfo & TRI,const BitVector & CalleeSavedRegs,const TargetPassConfig & TPC)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
isCalleeSaved(LocIdx L) const278bdd1243dSDimitry 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:
LocationAndQuality()306bdd1243dSDimitry Andric LocationAndQuality() : Location(0), Quality(0) {}
LocationAndQuality(LocIdx L,LocationQuality Q)307bdd1243dSDimitry Andric LocationAndQuality(LocIdx L, LocationQuality Q)
308bdd1243dSDimitry Andric : Location(L.asU64()), Quality(static_cast<unsigned>(Q)) {}
getLoc() const309bdd1243dSDimitry Andric LocIdx getLoc() const {
310bdd1243dSDimitry Andric if (!Quality)
311bdd1243dSDimitry Andric return LocIdx::MakeIllegalLoc();
312bdd1243dSDimitry Andric return LocIdx(Location);
313bdd1243dSDimitry Andric }
getQuality() const314bdd1243dSDimitry Andric LocationQuality getQuality() const { return LocationQuality(Quality); }
isIllegal() const315bdd1243dSDimitry Andric bool isIllegal() const { return !Quality; }
isBest() const316bdd1243dSDimitry 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>
getLocQualityIfBetter(LocIdx L,LocationQuality Min) const322bdd1243dSDimitry 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.
loadVarInloc(MachineBasicBlock & MBB,DbgOpIDMap & DbgOpStore,const DenseMap<ValueIDNum,LocationAndQuality> & ValueToLoc,DebugVariable Var,DbgValue 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
loadInlocs(MachineBasicBlock & MBB,ValueTable & MLocs,DbgOpIDMap & DbgOpStore,const SmallVectorImpl<std::pair<DebugVariable,DbgValue>> & VLocs,unsigned NumLocs)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.
addUseBeforeDef(const DebugVariable & Var,const DbgValueProperties & Properties,const SmallVectorImpl<DbgOp> & DbgOps,unsigned Inst)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.
checkInstForNewValues(unsigned Inst,MachineBasicBlock::iterator pos)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.
flushDbgValues(MachineBasicBlock::iterator Pos,MachineBasicBlock * MBB)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
isEntryValueVariable(const DebugVariable & Var,const DIExpression * Expr) const596fe6060f1SDimitry 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
604fe013be4SDimitry Andric if (Expr->getNumElements() > 0 && !Expr->isDeref())
605fe6060f1SDimitry Andric return false;
606fe6060f1SDimitry Andric
607fe6060f1SDimitry Andric return true;
608fe6060f1SDimitry Andric }
609fe6060f1SDimitry Andric
isEntryValueValue(const ValueIDNum & Val) const610fe6060f1SDimitry 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
recoverAsEntryValue(const DebugVariable & Var,const DbgValueProperties & Prop,const ValueIDNum & Num)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.
redefVar(const MachineInstr & MI)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.
redefVar(const MachineInstr & MI,const DbgValueProperties & Properties,SmallVectorImpl<ResolvedDbgOp> & NewLocs)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.
clobberMloc(LocIdx MLoc,MachineBasicBlock::iterator Pos,bool MakeUndef=true)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.
clobberMloc(LocIdx MLoc,ValueIDNum OldValue,MachineBasicBlock::iterator Pos,bool MakeUndef=true)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.
transferMlocs(LocIdx Src,LocIdx Dst,MachineBasicBlock::iterator Pos)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
emitMOLoc(const MachineOperand & MO,const DebugVariable & Var,const DbgValueProperties & Properties)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
dump(const MLocTracker * MTrack) const945bdd1243dSDimitry 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 }
dump(const MLocTracker * MTrack) const952bdd1243dSDimitry 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 }
dump(const MLocTracker * MTrack,const DbgOpIDMap * OpStore) const959bdd1243dSDimitry 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 }
dump(const MLocTracker * MTrack,const DbgOpIDMap * OpStore) const966bdd1243dSDimitry 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
MLocTracker(MachineFunction & MF,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const TargetLowering & TLI)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
trackRegister(unsigned ID)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
writeRegMask(const MachineOperand * MO,unsigned CurBB,unsigned InstID)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
getOrTrackSpillLoc(SpillLoc L)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
LocIdxToName(LocIdx Idx) const1120349cc55cSDimitry 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
IDAsString(const ValueIDNum & Num) const1135349cc55cSDimitry 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
dump()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
dump_mloc_map()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
emitLoc(const SmallVectorImpl<ResolvedDbgOp> & DbgOps,const DebugVariable & Var,const DbgValueProperties & Properties)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
isCalleeSaved(LocIdx L) const1313349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
1314e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L];
1315bdd1243dSDimitry Andric return isCalleeSavedReg(Reg);
1316bdd1243dSDimitry Andric }
isCalleeSavedReg(Register R) const1317bdd1243dSDimitry 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>
extractSpillBaseRegAndOffset(const MachineInstr & MI)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>
findLocationForMemOperand(const MachineInstr & MI)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.
transferDebugValue(const MachineInstr & MI)1374e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1375e8d8bef9SDimitry Andric if (!MI.isDebugValue())
1376e8d8bef9SDimitry Andric return false;
1377e8d8bef9SDimitry Andric
1378e710425bSDimitry Andric assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
1379e8d8bef9SDimitry Andric "Expected inlined-at fields to agree");
1380e8d8bef9SDimitry Andric
1381e8d8bef9SDimitry Andric // If there are no instructions in this lexical scope, do no location tracking
1382e8d8bef9SDimitry Andric // at all, this variable shouldn't get a legitimate location range.
1383e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1384e8d8bef9SDimitry Andric if (Scope == nullptr)
1385e8d8bef9SDimitry Andric return true; // handled it; by doing nothing
1386e8d8bef9SDimitry Andric
1387e8d8bef9SDimitry Andric // MLocTracker needs to know that this register is read, even if it's only
1388e8d8bef9SDimitry Andric // read by a debug inst.
1389bdd1243dSDimitry Andric for (const MachineOperand &MO : MI.debug_operands())
1390e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg() != 0)
1391e8d8bef9SDimitry Andric (void)MTracker->readReg(MO.getReg());
1392e8d8bef9SDimitry Andric
1393e8d8bef9SDimitry Andric // If we're preparing for the second analysis (variables), the machine value
1394e8d8bef9SDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value
1395e8d8bef9SDimitry Andric // it refers to to VLocTracker.
1396e8d8bef9SDimitry Andric if (VTracker) {
1397bdd1243dSDimitry Andric SmallVector<DbgOpID> DebugOps;
1398bdd1243dSDimitry Andric // Feed defVar the new variable location, or if this is a DBG_VALUE $noreg,
1399bdd1243dSDimitry Andric // feed defVar None.
1400bdd1243dSDimitry Andric if (!MI.isUndefDebugValue()) {
1401bdd1243dSDimitry Andric for (const MachineOperand &MO : MI.debug_operands()) {
1402bdd1243dSDimitry Andric // There should be no undef registers here, as we've screened for undef
1403bdd1243dSDimitry Andric // debug values.
1404e8d8bef9SDimitry Andric if (MO.isReg()) {
1405bdd1243dSDimitry Andric DebugOps.push_back(DbgOpStore.insert(MTracker->readReg(MO.getReg())));
1406bdd1243dSDimitry Andric } else if (MO.isImm() || MO.isFPImm() || MO.isCImm()) {
1407bdd1243dSDimitry Andric DebugOps.push_back(DbgOpStore.insert(MO));
1408bdd1243dSDimitry Andric } else {
1409bdd1243dSDimitry Andric llvm_unreachable("Unexpected debug operand type.");
1410e8d8bef9SDimitry Andric }
1411e8d8bef9SDimitry Andric }
1412bdd1243dSDimitry Andric }
1413e710425bSDimitry Andric VTracker->defVar(MI, DbgValueProperties(MI), DebugOps);
1414bdd1243dSDimitry Andric }
1415e8d8bef9SDimitry Andric
1416e8d8bef9SDimitry Andric // If performing final tracking of transfers, report this variable definition
1417e8d8bef9SDimitry Andric // to the TransferTracker too.
1418e8d8bef9SDimitry Andric if (TTracker)
1419e8d8bef9SDimitry Andric TTracker->redefVar(MI);
1420e8d8bef9SDimitry Andric return true;
1421e8d8bef9SDimitry Andric }
1422e8d8bef9SDimitry Andric
getValueForInstrRef(unsigned InstNo,unsigned OpNo,MachineInstr & MI,const FuncValueTable * MLiveOuts,const FuncValueTable * MLiveIns)1423bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::getValueForInstrRef(
1424bdd1243dSDimitry Andric unsigned InstNo, unsigned OpNo, MachineInstr &MI,
1425c9157d92SDimitry Andric const FuncValueTable *MLiveOuts, const FuncValueTable *MLiveIns) {
1426e8d8bef9SDimitry Andric // Various optimizations may have happened to the value during codegen,
1427e8d8bef9SDimitry Andric // recorded in the value substitution table. Apply any substitutions to
1428fe6060f1SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect
1429fe6060f1SDimitry Andric // any subregister extractions performed during optimization.
1430bdd1243dSDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent();
1431fe6060f1SDimitry Andric
1432fe6060f1SDimitry Andric // Create dummy substitution with Src set, for lookup.
1433fe6060f1SDimitry Andric auto SoughtSub =
1434fe6060f1SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1435fe6060f1SDimitry Andric
1436fe6060f1SDimitry Andric SmallVector<unsigned, 4> SeenSubregs;
1437fe6060f1SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1438fe6060f1SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1439fe6060f1SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) {
1440fe6060f1SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1441fe6060f1SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest;
1442fe6060f1SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg)
1443fe6060f1SDimitry Andric SeenSubregs.push_back(Subreg);
1444fe6060f1SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1445e8d8bef9SDimitry Andric }
1446e8d8bef9SDimitry Andric
1447e8d8bef9SDimitry Andric // Default machine value number is <None> -- if no instruction defines
1448e8d8bef9SDimitry Andric // the corresponding value, it must have been optimized out.
1449bdd1243dSDimitry Andric std::optional<ValueIDNum> NewID;
1450e8d8bef9SDimitry Andric
1451e8d8bef9SDimitry Andric // Try to lookup the instruction number, and find the machine value number
1452fe6060f1SDimitry Andric // that it defines. It could be an instruction, or a PHI.
1453e8d8bef9SDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1454bdd1243dSDimitry Andric auto PHIIt = llvm::lower_bound(DebugPHINumToValue, InstNo);
1455e8d8bef9SDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) {
1456e8d8bef9SDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first;
1457e8d8bef9SDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1458e8d8bef9SDimitry Andric
1459349cc55cSDimitry Andric // Pick out the designated operand. It might be a memory reference, if
1460349cc55cSDimitry Andric // a register def was folded into a stack store.
1461349cc55cSDimitry Andric if (OpNo == MachineFunction::DebugOperandMemNumber &&
1462349cc55cSDimitry Andric TargetInstr.hasOneMemOperand()) {
1463bdd1243dSDimitry Andric std::optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1464349cc55cSDimitry Andric if (L)
1465349cc55cSDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1466349cc55cSDimitry Andric } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
146781ad6265SDimitry Andric // Permit the debug-info to be completely wrong: identifying a nonexistant
146881ad6265SDimitry Andric // operand, or one that is not a register definition, means something
146981ad6265SDimitry Andric // unexpected happened during optimisation. Broken debug-info, however,
147081ad6265SDimitry Andric // shouldn't crash the compiler -- instead leave the variable value as
147181ad6265SDimitry Andric // None, which will make it appear "optimised out".
147281ad6265SDimitry Andric if (OpNo < TargetInstr.getNumOperands()) {
1473e8d8bef9SDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1474e8d8bef9SDimitry Andric
147581ad6265SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg()) {
1476349cc55cSDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg());
1477e8d8bef9SDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID];
1478e8d8bef9SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1479349cc55cSDimitry Andric }
148081ad6265SDimitry Andric }
148181ad6265SDimitry Andric
148281ad6265SDimitry Andric if (!NewID) {
148381ad6265SDimitry Andric LLVM_DEBUG(
148481ad6265SDimitry Andric { dbgs() << "Seen instruction reference to illegal operand\n"; });
148581ad6265SDimitry Andric }
148681ad6265SDimitry Andric }
1487349cc55cSDimitry Andric // else: NewID is left as None.
1488fe6060f1SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1489fe6060f1SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use
1490fe6060f1SDimitry Andric // the resolver helper to find out.
1491c9157d92SDimitry Andric assert(MLiveOuts && MLiveIns);
1492c9157d92SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), *MLiveOuts, *MLiveIns,
1493fe6060f1SDimitry Andric MI, InstNo);
1494fe6060f1SDimitry Andric }
1495fe6060f1SDimitry Andric
1496fe6060f1SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code
1497fe6060f1SDimitry Andric // like this:
1498fe6060f1SDimitry Andric // CALL64 @foo, implicit-def $rax
1499fe6060f1SDimitry Andric // %0:gr64 = COPY $rax
1500fe6060f1SDimitry Andric // %1:gr32 = COPY %0.sub_32bit
1501fe6060f1SDimitry Andric // %2:gr16 = COPY %1.sub_16bit
1502fe6060f1SDimitry Andric // %3:gr8 = COPY %2.sub_8bit
1503fe6060f1SDimitry Andric // In which case each copy would have been recorded as a substitution with
1504fe6060f1SDimitry Andric // a subregister qualifier. Apply those qualifiers now.
1505fe6060f1SDimitry Andric if (NewID && !SeenSubregs.empty()) {
1506fe6060f1SDimitry Andric unsigned Offset = 0;
1507fe6060f1SDimitry Andric unsigned Size = 0;
1508fe6060f1SDimitry Andric
1509fe6060f1SDimitry Andric // Look at each subregister that we passed through, and progressively
1510fe6060f1SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should
1511fe6060f1SDimitry Andric // only ever be the same or narrower width than what they read from;
1512fe6060f1SDimitry Andric // iterate in reverse order so that we go from wide to small.
1513fe6060f1SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) {
1514fe6060f1SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1515fe6060f1SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1516fe6060f1SDimitry Andric Offset += ThisOffset;
1517fe6060f1SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1518fe6060f1SDimitry Andric }
1519fe6060f1SDimitry Andric
1520fe6060f1SDimitry Andric // If that worked, look for an appropriate subregister with the register
1521fe6060f1SDimitry Andric // where the define happens. Don't look at values that were defined during
1522fe6060f1SDimitry Andric // a stack write: we can't currently express register locations within
1523fe6060f1SDimitry Andric // spills.
1524fe6060f1SDimitry Andric LocIdx L = NewID->getLoc();
1525fe6060f1SDimitry Andric if (NewID && !MTracker->isSpill(L)) {
1526fe6060f1SDimitry Andric // Find the register class for the register where this def happened.
1527fe6060f1SDimitry Andric // FIXME: no index for this?
1528fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L];
1529fe6060f1SDimitry Andric const TargetRegisterClass *TRC = nullptr;
1530fcaf7f86SDimitry Andric for (const auto *TRCI : TRI->regclasses())
1531fe6060f1SDimitry Andric if (TRCI->contains(Reg))
1532fe6060f1SDimitry Andric TRC = TRCI;
1533fe6060f1SDimitry Andric assert(TRC && "Couldn't find target register class?");
1534fe6060f1SDimitry Andric
1535fe6060f1SDimitry Andric // If the register we have isn't the right size or in the right place,
1536fe6060f1SDimitry Andric // Try to find a subregister inside it.
1537fe6060f1SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1538fe6060f1SDimitry Andric if (Size != MainRegSize || Offset) {
1539fe6060f1SDimitry Andric // Enumerate all subregisters, searching.
1540fe6060f1SDimitry Andric Register NewReg = 0;
1541fe013be4SDimitry Andric for (MCPhysReg SR : TRI->subregs(Reg)) {
1542fe013be4SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, SR);
1543fe6060f1SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1544fe6060f1SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1545fe6060f1SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) {
1546fe013be4SDimitry Andric NewReg = SR;
1547fe6060f1SDimitry Andric break;
1548fe6060f1SDimitry Andric }
1549fe6060f1SDimitry Andric }
1550fe6060f1SDimitry Andric
1551fe6060f1SDimitry Andric // If we didn't find anything: there's no way to express our value.
1552fe6060f1SDimitry Andric if (!NewReg) {
1553bdd1243dSDimitry Andric NewID = std::nullopt;
1554fe6060f1SDimitry Andric } else {
1555fe6060f1SDimitry Andric // Re-state the value as being defined within the subregister
1556fe6060f1SDimitry Andric // that we found.
1557fe6060f1SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1558fe6060f1SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1559fe6060f1SDimitry Andric }
1560fe6060f1SDimitry Andric }
1561fe6060f1SDimitry Andric } else {
1562fe6060f1SDimitry Andric // If we can't handle subregisters, unset the new value.
1563bdd1243dSDimitry Andric NewID = std::nullopt;
1564fe6060f1SDimitry Andric }
1565e8d8bef9SDimitry Andric }
1566e8d8bef9SDimitry Andric
1567bdd1243dSDimitry Andric return NewID;
1568bdd1243dSDimitry Andric }
1569bdd1243dSDimitry Andric
transferDebugInstrRef(MachineInstr & MI,const FuncValueTable * MLiveOuts,const FuncValueTable * MLiveIns)1570bdd1243dSDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1571c9157d92SDimitry Andric const FuncValueTable *MLiveOuts,
1572c9157d92SDimitry Andric const FuncValueTable *MLiveIns) {
1573bdd1243dSDimitry Andric if (!MI.isDebugRef())
1574bdd1243dSDimitry Andric return false;
1575bdd1243dSDimitry Andric
1576bdd1243dSDimitry Andric // Only handle this instruction when we are building the variable value
1577bdd1243dSDimitry Andric // transfer function.
1578bdd1243dSDimitry Andric if (!VTracker && !TTracker)
1579bdd1243dSDimitry Andric return false;
1580bdd1243dSDimitry Andric
1581bdd1243dSDimitry Andric const DILocalVariable *Var = MI.getDebugVariable();
1582bdd1243dSDimitry Andric const DIExpression *Expr = MI.getDebugExpression();
1583bdd1243dSDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc();
1584bdd1243dSDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1585bdd1243dSDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1586bdd1243dSDimitry Andric "Expected inlined-at fields to agree");
1587bdd1243dSDimitry Andric
1588bdd1243dSDimitry Andric DebugVariable V(Var, Expr, InlinedAt);
1589bdd1243dSDimitry Andric
1590bdd1243dSDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1591bdd1243dSDimitry Andric if (Scope == nullptr)
1592bdd1243dSDimitry Andric return true; // Handled by doing nothing. This variable is never in scope.
1593bdd1243dSDimitry Andric
1594bdd1243dSDimitry Andric SmallVector<DbgOpID> DbgOpIDs;
1595bdd1243dSDimitry Andric for (const MachineOperand &MO : MI.debug_operands()) {
1596bdd1243dSDimitry Andric if (!MO.isDbgInstrRef()) {
1597bdd1243dSDimitry Andric assert(!MO.isReg() && "DBG_INSTR_REF should not contain registers");
1598bdd1243dSDimitry Andric DbgOpID ConstOpID = DbgOpStore.insert(DbgOp(MO));
1599bdd1243dSDimitry Andric DbgOpIDs.push_back(ConstOpID);
1600bdd1243dSDimitry Andric continue;
1601bdd1243dSDimitry Andric }
1602bdd1243dSDimitry Andric
1603bdd1243dSDimitry Andric unsigned InstNo = MO.getInstrRefInstrIndex();
1604bdd1243dSDimitry Andric unsigned OpNo = MO.getInstrRefOpIndex();
1605bdd1243dSDimitry Andric
1606bdd1243dSDimitry Andric // Default machine value number is <None> -- if no instruction defines
1607bdd1243dSDimitry Andric // the corresponding value, it must have been optimized out.
1608bdd1243dSDimitry Andric std::optional<ValueIDNum> NewID =
1609bdd1243dSDimitry Andric getValueForInstrRef(InstNo, OpNo, MI, MLiveOuts, MLiveIns);
1610bdd1243dSDimitry Andric // We have a value number or std::nullopt. If the latter, then kill the
1611bdd1243dSDimitry Andric // entire debug value.
1612bdd1243dSDimitry Andric if (NewID) {
1613bdd1243dSDimitry Andric DbgOpIDs.push_back(DbgOpStore.insert(*NewID));
1614bdd1243dSDimitry Andric } else {
1615bdd1243dSDimitry Andric DbgOpIDs.clear();
1616bdd1243dSDimitry Andric break;
1617bdd1243dSDimitry Andric }
1618bdd1243dSDimitry Andric }
1619bdd1243dSDimitry Andric
1620bdd1243dSDimitry Andric // We have a DbgOpID for every value or for none. Tell the variable value
1621bdd1243dSDimitry Andric // tracker about it. The rest of this LiveDebugValues implementation acts
1622bdd1243dSDimitry Andric // exactly the same for DBG_INSTR_REFs as DBG_VALUEs (just, the former can
1623bdd1243dSDimitry Andric // refer to values that aren't immediately available).
1624bdd1243dSDimitry Andric DbgValueProperties Properties(Expr, false, true);
1625d56accc7SDimitry Andric if (VTracker)
1626bdd1243dSDimitry Andric VTracker->defVar(MI, Properties, DbgOpIDs);
1627e8d8bef9SDimitry Andric
1628e8d8bef9SDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF
1629e8d8bef9SDimitry Andric // into a plain DBG_VALUE.
1630e8d8bef9SDimitry Andric if (!TTracker)
1631e8d8bef9SDimitry Andric return true;
1632e8d8bef9SDimitry Andric
1633bdd1243dSDimitry Andric // Fetch the concrete DbgOps now, as we will need them later.
1634bdd1243dSDimitry Andric SmallVector<DbgOp> DbgOps;
1635bdd1243dSDimitry Andric for (DbgOpID OpID : DbgOpIDs) {
1636bdd1243dSDimitry Andric DbgOps.push_back(DbgOpStore.find(OpID));
1637bdd1243dSDimitry Andric }
1638bdd1243dSDimitry Andric
1639e8d8bef9SDimitry Andric // Pick a location for the machine value number, if such a location exists.
1640e8d8bef9SDimitry Andric // (This information could be stored in TransferTracker to make it faster).
1641bdd1243dSDimitry Andric SmallDenseMap<ValueIDNum, TransferTracker::LocationAndQuality> FoundLocs;
1642bdd1243dSDimitry Andric SmallVector<ValueIDNum> ValuesToFind;
1643bdd1243dSDimitry Andric // Initialized the preferred-location map with illegal locations, to be
1644bdd1243dSDimitry Andric // filled in later.
1645bdd1243dSDimitry Andric for (const DbgOp &Op : DbgOps) {
1646bdd1243dSDimitry Andric if (!Op.IsConst)
1647bdd1243dSDimitry Andric if (FoundLocs.insert({Op.ID, TransferTracker::LocationAndQuality()})
1648bdd1243dSDimitry Andric .second)
1649bdd1243dSDimitry Andric ValuesToFind.push_back(Op.ID);
1650bdd1243dSDimitry Andric }
1651bdd1243dSDimitry Andric
1652e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) {
1653e8d8bef9SDimitry Andric LocIdx CurL = Location.Idx;
1654349cc55cSDimitry Andric ValueIDNum ID = MTracker->readMLoc(CurL);
1655bdd1243dSDimitry Andric auto ValueToFindIt = find(ValuesToFind, ID);
1656bdd1243dSDimitry Andric if (ValueToFindIt == ValuesToFind.end())
1657bdd1243dSDimitry Andric continue;
1658bdd1243dSDimitry Andric auto &Previous = FoundLocs.find(ID)->second;
1659e8d8bef9SDimitry Andric // If this is the first location with that value, pick it. Otherwise,
1660e8d8bef9SDimitry Andric // consider whether it's a "longer term" location.
1661bdd1243dSDimitry Andric std::optional<TransferTracker::LocationQuality> ReplacementQuality =
1662bdd1243dSDimitry Andric TTracker->getLocQualityIfBetter(CurL, Previous.getQuality());
1663bdd1243dSDimitry Andric if (ReplacementQuality) {
1664bdd1243dSDimitry Andric Previous = TransferTracker::LocationAndQuality(CurL, *ReplacementQuality);
1665bdd1243dSDimitry Andric if (Previous.isBest()) {
1666bdd1243dSDimitry Andric ValuesToFind.erase(ValueToFindIt);
1667bdd1243dSDimitry Andric if (ValuesToFind.empty())
1668bdd1243dSDimitry Andric break;
1669bdd1243dSDimitry Andric }
1670bdd1243dSDimitry Andric }
1671bdd1243dSDimitry Andric }
1672bdd1243dSDimitry Andric
1673bdd1243dSDimitry Andric SmallVector<ResolvedDbgOp> NewLocs;
1674bdd1243dSDimitry Andric for (const DbgOp &DbgOp : DbgOps) {
1675bdd1243dSDimitry Andric if (DbgOp.IsConst) {
1676bdd1243dSDimitry Andric NewLocs.push_back(DbgOp.MO);
1677e8d8bef9SDimitry Andric continue;
1678e8d8bef9SDimitry Andric }
1679bdd1243dSDimitry Andric LocIdx FoundLoc = FoundLocs.find(DbgOp.ID)->second.getLoc();
1680bdd1243dSDimitry Andric if (FoundLoc.isIllegal()) {
1681bdd1243dSDimitry Andric NewLocs.clear();
1682bdd1243dSDimitry Andric break;
1683e8d8bef9SDimitry Andric }
1684bdd1243dSDimitry Andric NewLocs.push_back(FoundLoc);
1685e8d8bef9SDimitry Andric }
1686e8d8bef9SDimitry Andric // Tell transfer tracker that the variable value has changed.
1687bdd1243dSDimitry Andric TTracker->redefVar(MI, Properties, NewLocs);
1688e8d8bef9SDimitry Andric
1689bdd1243dSDimitry Andric // If there were values with no location, but all such values are defined in
1690bdd1243dSDimitry Andric // later instructions in this block, this is a block-local use-before-def.
1691bdd1243dSDimitry Andric if (!DbgOps.empty() && NewLocs.empty()) {
1692bdd1243dSDimitry Andric bool IsValidUseBeforeDef = true;
1693bdd1243dSDimitry Andric uint64_t LastUseBeforeDef = 0;
1694bdd1243dSDimitry Andric for (auto ValueLoc : FoundLocs) {
1695bdd1243dSDimitry Andric ValueIDNum NewID = ValueLoc.first;
1696bdd1243dSDimitry Andric LocIdx FoundLoc = ValueLoc.second.getLoc();
1697bdd1243dSDimitry Andric if (!FoundLoc.isIllegal())
1698bdd1243dSDimitry Andric continue;
1699bdd1243dSDimitry Andric // If we have an value with no location that is not defined in this block,
1700bdd1243dSDimitry Andric // then it has no location in this block, leaving this value undefined.
1701bdd1243dSDimitry Andric if (NewID.getBlock() != CurBB || NewID.getInst() <= CurInst) {
1702bdd1243dSDimitry Andric IsValidUseBeforeDef = false;
1703bdd1243dSDimitry Andric break;
1704bdd1243dSDimitry Andric }
1705bdd1243dSDimitry Andric LastUseBeforeDef = std::max(LastUseBeforeDef, NewID.getInst());
1706bdd1243dSDimitry Andric }
1707bdd1243dSDimitry Andric if (IsValidUseBeforeDef) {
1708bdd1243dSDimitry Andric TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false, true},
1709bdd1243dSDimitry Andric DbgOps, LastUseBeforeDef);
1710bdd1243dSDimitry Andric }
1711bdd1243dSDimitry Andric }
1712e8d8bef9SDimitry Andric
1713e8d8bef9SDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1714e8d8bef9SDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if
1715bdd1243dSDimitry Andric // FoundLoc is illegal.
1716e8d8bef9SDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future).
1717bdd1243dSDimitry Andric MachineInstr *DbgMI = MTracker->emitLoc(NewLocs, V, Properties);
1718bdd1243dSDimitry Andric
1719e8d8bef9SDimitry Andric TTracker->PendingDbgValues.push_back(DbgMI);
1720e8d8bef9SDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr);
1721fe6060f1SDimitry Andric return true;
1722fe6060f1SDimitry Andric }
1723fe6060f1SDimitry Andric
transferDebugPHI(MachineInstr & MI)1724fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1725fe6060f1SDimitry Andric if (!MI.isDebugPHI())
1726fe6060f1SDimitry Andric return false;
1727fe6060f1SDimitry Andric
1728fe6060f1SDimitry Andric // Analyse these only when solving the machine value location problem.
1729fe6060f1SDimitry Andric if (VTracker || TTracker)
1730fe6060f1SDimitry Andric return true;
1731fe6060f1SDimitry Andric
1732fe6060f1SDimitry Andric // First operand is the value location, either a stack slot or register.
1733fe6060f1SDimitry Andric // Second is the debug instruction number of the original PHI.
1734fe6060f1SDimitry Andric const MachineOperand &MO = MI.getOperand(0);
1735fe6060f1SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm();
1736fe6060f1SDimitry Andric
1737972a253aSDimitry Andric auto EmitBadPHI = [this, &MI, InstrNum]() -> bool {
173881ad6265SDimitry Andric // Helper lambda to do any accounting when we fail to find a location for
173981ad6265SDimitry Andric // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
174081ad6265SDimitry Andric // dead stack slot, for example.
174181ad6265SDimitry Andric // Record a DebugPHIRecord with an empty value + location.
1742bdd1243dSDimitry Andric DebugPHINumToValue.push_back(
1743bdd1243dSDimitry Andric {InstrNum, MI.getParent(), std::nullopt, std::nullopt});
174481ad6265SDimitry Andric return true;
174581ad6265SDimitry Andric };
174681ad6265SDimitry Andric
174781ad6265SDimitry Andric if (MO.isReg() && MO.getReg()) {
1748fe6060f1SDimitry Andric // The value is whatever's currently in the register. Read and record it,
1749fe6060f1SDimitry Andric // to be analysed later.
1750fe6060f1SDimitry Andric Register Reg = MO.getReg();
1751fe6060f1SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg);
1752fe6060f1SDimitry Andric auto PHIRec = DebugPHIRecord(
1753fe6060f1SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1754fe6060f1SDimitry Andric DebugPHINumToValue.push_back(PHIRec);
1755349cc55cSDimitry Andric
1756349cc55cSDimitry Andric // Ensure this register is tracked.
1757349cc55cSDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1758349cc55cSDimitry Andric MTracker->lookupOrTrackRegister(*RAI);
175981ad6265SDimitry Andric } else if (MO.isFI()) {
1760fe6060f1SDimitry Andric // The value is whatever's in this stack slot.
1761fe6060f1SDimitry Andric unsigned FI = MO.getIndex();
1762fe6060f1SDimitry Andric
1763fe6060f1SDimitry Andric // If the stack slot is dead, then this was optimized away.
1764fe6060f1SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged.
1765fe6060f1SDimitry Andric if (MFI->isDeadObjectIndex(FI))
176681ad6265SDimitry Andric return EmitBadPHI();
1767fe6060f1SDimitry Andric
1768349cc55cSDimitry Andric // Identify this spill slot, ensure it's tracked.
1769fe6060f1SDimitry Andric Register Base;
1770fe6060f1SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1771fe6060f1SDimitry Andric SpillLoc SL = {Base, Offs};
1772bdd1243dSDimitry Andric std::optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
1773d56accc7SDimitry Andric
1774d56accc7SDimitry Andric // We might be able to find a value, but have chosen not to, to avoid
1775d56accc7SDimitry Andric // tracking too much stack information.
1776d56accc7SDimitry Andric if (!SpillNo)
177781ad6265SDimitry Andric return EmitBadPHI();
1778fe6060f1SDimitry Andric
177981ad6265SDimitry Andric // Any stack location DBG_PHI should have an associate bit-size.
178081ad6265SDimitry Andric assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
178181ad6265SDimitry Andric unsigned slotBitSize = MI.getOperand(2).getImm();
1782349cc55cSDimitry Andric
178381ad6265SDimitry Andric unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0});
178481ad6265SDimitry Andric LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
178581ad6265SDimitry Andric ValueIDNum Result = MTracker->readMLoc(SpillLoc);
1786fe6060f1SDimitry Andric
1787fe6060f1SDimitry Andric // Record this DBG_PHI for later analysis.
178881ad6265SDimitry Andric auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc});
1789fe6060f1SDimitry Andric DebugPHINumToValue.push_back(DbgPHI);
179081ad6265SDimitry Andric } else {
179181ad6265SDimitry Andric // Else: if the operand is neither a legal register or a stack slot, then
179281ad6265SDimitry Andric // we're being fed illegal debug-info. Record an empty PHI, so that any
179381ad6265SDimitry Andric // debug users trying to read this number will be put off trying to
179481ad6265SDimitry Andric // interpret the value.
179581ad6265SDimitry Andric LLVM_DEBUG(
179681ad6265SDimitry Andric { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
179781ad6265SDimitry Andric return EmitBadPHI();
1798fe6060f1SDimitry Andric }
1799e8d8bef9SDimitry Andric
1800e8d8bef9SDimitry Andric return true;
1801e8d8bef9SDimitry Andric }
1802e8d8bef9SDimitry Andric
transferRegisterDef(MachineInstr & MI)1803e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1804e8d8bef9SDimitry Andric // Meta Instructions do not affect the debug liveness of any register they
1805e8d8bef9SDimitry Andric // define.
1806e8d8bef9SDimitry Andric if (MI.isImplicitDef()) {
1807e8d8bef9SDimitry Andric // Except when there's an implicit def, and the location it's defining has
1808e8d8bef9SDimitry Andric // no value number. The whole point of an implicit def is to announce that
1809e8d8bef9SDimitry Andric // the register is live, without be specific about it's value. So define
1810e8d8bef9SDimitry Andric // a value if there isn't one already.
1811e8d8bef9SDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1812e8d8bef9SDimitry Andric // Has a legitimate value -> ignore the implicit def.
1813e8d8bef9SDimitry Andric if (Num.getLoc() != 0)
1814e8d8bef9SDimitry Andric return;
1815e8d8bef9SDimitry Andric // Otherwise, def it here.
1816e8d8bef9SDimitry Andric } else if (MI.isMetaInstruction())
1817e8d8bef9SDimitry Andric return;
1818e8d8bef9SDimitry Andric
18194824e7fdSDimitry Andric // We always ignore SP defines on call instructions, they don't actually
18204824e7fdSDimitry Andric // change the value of the stack pointer... except for win32's _chkstk. This
18214824e7fdSDimitry Andric // is rare: filter quickly for the common case (no stack adjustments, not a
18224824e7fdSDimitry Andric // call, etc). If it is a call that modifies SP, recognise the SP register
18234824e7fdSDimitry Andric // defs.
18244824e7fdSDimitry Andric bool CallChangesSP = false;
18254824e7fdSDimitry Andric if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
18264824e7fdSDimitry Andric !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
18274824e7fdSDimitry Andric CallChangesSP = true;
18284824e7fdSDimitry Andric
18294824e7fdSDimitry Andric // Test whether we should ignore a def of this register due to it being part
18304824e7fdSDimitry Andric // of the stack pointer.
18314824e7fdSDimitry Andric auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
18324824e7fdSDimitry Andric if (CallChangesSP)
18334824e7fdSDimitry Andric return false;
18344824e7fdSDimitry Andric return MI.isCall() && MTracker->SPAliases.count(R);
18354824e7fdSDimitry Andric };
18364824e7fdSDimitry Andric
1837e8d8bef9SDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs.
1838e8d8bef9SDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this
1839e8d8bef9SDimitry Andric // prevents fallback to std::set::count() operations.
1840e8d8bef9SDimitry Andric SmallSet<uint32_t, 32> DeadRegs;
1841e8d8bef9SDimitry Andric SmallVector<const uint32_t *, 4> RegMasks;
1842e8d8bef9SDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1843e8d8bef9SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
1844e8d8bef9SDimitry Andric // Determine whether the operand is a register def.
1845bdd1243dSDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() && MO.getReg().isPhysical() &&
18464824e7fdSDimitry Andric !IgnoreSPAlias(MO.getReg())) {
1847e8d8bef9SDimitry Andric // Remove ranges of all aliased registers.
1848e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1849e8d8bef9SDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs?
1850e8d8bef9SDimitry Andric DeadRegs.insert(*RAI);
1851e8d8bef9SDimitry Andric } else if (MO.isRegMask()) {
1852e8d8bef9SDimitry Andric RegMasks.push_back(MO.getRegMask());
1853e8d8bef9SDimitry Andric RegMaskPtrs.push_back(&MO);
1854e8d8bef9SDimitry Andric }
1855e8d8bef9SDimitry Andric }
1856e8d8bef9SDimitry Andric
1857e8d8bef9SDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise.
1858e8d8bef9SDimitry Andric for (uint32_t DeadReg : DeadRegs)
1859e8d8bef9SDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst);
1860e8d8bef9SDimitry Andric
1861fcaf7f86SDimitry Andric for (const auto *MO : RegMaskPtrs)
1862e8d8bef9SDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst);
1863fe6060f1SDimitry Andric
1864349cc55cSDimitry Andric // If this instruction writes to a spill slot, def that slot.
1865349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) {
1866bdd1243dSDimitry Andric if (std::optional<SpillLocationNo> SpillNo =
1867bdd1243dSDimitry Andric extractSpillBaseRegAndOffset(MI)) {
1868349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1869d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1870349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID);
1871349cc55cSDimitry Andric MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1872349cc55cSDimitry Andric }
1873349cc55cSDimitry Andric }
1874d56accc7SDimitry Andric }
1875349cc55cSDimitry Andric
1876fe6060f1SDimitry Andric if (!TTracker)
1877fe6060f1SDimitry Andric return;
1878fe6060f1SDimitry Andric
1879fe6060f1SDimitry Andric // When committing variable values to locations: tell transfer tracker that
1880fe6060f1SDimitry Andric // we've clobbered things. It may be able to recover the variable from a
1881fe6060f1SDimitry Andric // different location.
1882fe6060f1SDimitry Andric
1883fe6060f1SDimitry Andric // Inform TTracker about any direct clobbers.
1884fe6060f1SDimitry Andric for (uint32_t DeadReg : DeadRegs) {
1885fe6060f1SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
1886fe6060f1SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false);
1887fe6060f1SDimitry Andric }
1888fe6060f1SDimitry Andric
1889fe6060f1SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations
1890fe6060f1SDimitry Andric // that are actually being tracked.
18911fd87a68SDimitry Andric if (!RegMaskPtrs.empty()) {
1892fe6060f1SDimitry Andric for (auto L : MTracker->locations()) {
1893fe6060f1SDimitry Andric // Stack locations can't be clobbered by regmasks.
1894fe6060f1SDimitry Andric if (MTracker->isSpill(L.Idx))
1895fe6060f1SDimitry Andric continue;
1896fe6060f1SDimitry Andric
1897fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx];
18984824e7fdSDimitry Andric if (IgnoreSPAlias(Reg))
18994824e7fdSDimitry Andric continue;
19004824e7fdSDimitry Andric
1901fcaf7f86SDimitry Andric for (const auto *MO : RegMaskPtrs)
1902fe6060f1SDimitry Andric if (MO->clobbersPhysReg(Reg))
1903fe6060f1SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
1904fe6060f1SDimitry Andric }
19051fd87a68SDimitry Andric }
1906349cc55cSDimitry Andric
1907349cc55cSDimitry Andric // Tell TTracker about any folded stack store.
1908349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) {
1909bdd1243dSDimitry Andric if (std::optional<SpillLocationNo> SpillNo =
1910bdd1243dSDimitry Andric extractSpillBaseRegAndOffset(MI)) {
1911349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1912d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1913349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID);
1914349cc55cSDimitry Andric TTracker->clobberMloc(L, MI.getIterator(), true);
1915349cc55cSDimitry Andric }
1916349cc55cSDimitry Andric }
1917e8d8bef9SDimitry Andric }
1918d56accc7SDimitry Andric }
1919e8d8bef9SDimitry Andric
performCopy(Register SrcRegNum,Register DstRegNum)1920e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1921349cc55cSDimitry Andric // In all circumstances, re-def all aliases. It's definitely a new value now.
1922349cc55cSDimitry Andric for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1923349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst);
1924e8d8bef9SDimitry Andric
1925349cc55cSDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1926e8d8bef9SDimitry Andric MTracker->setReg(DstRegNum, SrcValue);
1927e8d8bef9SDimitry Andric
1928349cc55cSDimitry Andric // Copy subregisters from one location to another.
1929e8d8bef9SDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1930e8d8bef9SDimitry Andric unsigned SrcSubReg = SRI.getSubReg();
1931e8d8bef9SDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex();
1932e8d8bef9SDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1933e8d8bef9SDimitry Andric if (!DstSubReg)
1934e8d8bef9SDimitry Andric continue;
1935e8d8bef9SDimitry Andric
1936e8d8bef9SDimitry Andric // Do copy. There are two matching subregisters, the source value should
1937e8d8bef9SDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked
1938e8d8bef9SDimitry Andric // yet.
1939349cc55cSDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1940349cc55cSDimitry Andric // mphi values if it wasn't tracked.
1941349cc55cSDimitry Andric LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1942349cc55cSDimitry Andric LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1943349cc55cSDimitry Andric (void)SrcL;
1944e8d8bef9SDimitry Andric (void)DstL;
1945349cc55cSDimitry Andric ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1946e8d8bef9SDimitry Andric
1947e8d8bef9SDimitry Andric MTracker->setReg(DstSubReg, CpyValue);
1948e8d8bef9SDimitry Andric }
1949e8d8bef9SDimitry Andric }
1950e8d8bef9SDimitry Andric
1951bdd1243dSDimitry Andric std::optional<SpillLocationNo>
isSpillInstruction(const MachineInstr & MI,MachineFunction * MF)1952d56accc7SDimitry Andric InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1953e8d8bef9SDimitry Andric MachineFunction *MF) {
1954e8d8bef9SDimitry Andric // TODO: Handle multiple stores folded into one.
1955e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand())
1956bdd1243dSDimitry Andric return std::nullopt;
1957e8d8bef9SDimitry Andric
1958349cc55cSDimitry Andric // Reject any memory operand that's aliased -- we can't guarantee its value.
1959349cc55cSDimitry Andric auto MMOI = MI.memoperands_begin();
1960349cc55cSDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1961349cc55cSDimitry Andric if (PVal->isAliased(MFI))
1962bdd1243dSDimitry Andric return std::nullopt;
1963349cc55cSDimitry Andric
1964e8d8bef9SDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1965bdd1243dSDimitry Andric return std::nullopt; // This is not a spill instruction, since no valid size
1966bdd1243dSDimitry Andric // was returned from either function.
1967e8d8bef9SDimitry Andric
1968d56accc7SDimitry Andric return extractSpillBaseRegAndOffset(MI);
1969e8d8bef9SDimitry Andric }
1970e8d8bef9SDimitry Andric
isLocationSpill(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)1971e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1972e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) {
1973e8d8bef9SDimitry Andric if (!isSpillInstruction(MI, MF))
1974e8d8bef9SDimitry Andric return false;
1975e8d8bef9SDimitry Andric
1976e8d8bef9SDimitry Andric int FI;
1977e8d8bef9SDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1978e8d8bef9SDimitry Andric return Reg != 0;
1979e8d8bef9SDimitry Andric }
1980e8d8bef9SDimitry Andric
1981bdd1243dSDimitry Andric std::optional<SpillLocationNo>
isRestoreInstruction(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)1982e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1983e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) {
1984e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand())
1985bdd1243dSDimitry Andric return std::nullopt;
1986e8d8bef9SDimitry Andric
1987e8d8bef9SDimitry Andric // FIXME: Handle folded restore instructions with more than one memory
1988e8d8bef9SDimitry Andric // operand.
1989e8d8bef9SDimitry Andric if (MI.getRestoreSize(TII)) {
1990e8d8bef9SDimitry Andric Reg = MI.getOperand(0).getReg();
1991e8d8bef9SDimitry Andric return extractSpillBaseRegAndOffset(MI);
1992e8d8bef9SDimitry Andric }
1993bdd1243dSDimitry Andric return std::nullopt;
1994e8d8bef9SDimitry Andric }
1995e8d8bef9SDimitry Andric
transferSpillOrRestoreInst(MachineInstr & MI)1996e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1997e8d8bef9SDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location
1998e8d8bef9SDimitry Andric // limitations under the new model. Therefore, when comparing them, compare
1999e8d8bef9SDimitry Andric // versions that don't attempt spills or restores at all.
2000e8d8bef9SDimitry Andric if (EmulateOldLDV)
2001e8d8bef9SDimitry Andric return false;
2002e8d8bef9SDimitry Andric
2003349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions
2004349cc55cSDimitry Andric // that can access the stack.
2005349cc55cSDimitry Andric int DummyFI = -1;
2006349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
2007349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
2008349cc55cSDimitry Andric return false;
2009349cc55cSDimitry Andric
2010e8d8bef9SDimitry Andric MachineFunction *MF = MI.getMF();
2011e8d8bef9SDimitry Andric unsigned Reg;
2012e8d8bef9SDimitry Andric
2013e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
2014e8d8bef9SDimitry Andric
2015349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions
2016349cc55cSDimitry Andric // that can access the stack.
2017349cc55cSDimitry Andric int FIDummy;
2018349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
2019349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
2020349cc55cSDimitry Andric return false;
2021349cc55cSDimitry Andric
2022e8d8bef9SDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is
2023e8d8bef9SDimitry Andric // written to, terminate that variable location. The value in memory
2024e8d8bef9SDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
2025bdd1243dSDimitry Andric if (std::optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
2026349cc55cSDimitry Andric // Un-set this location and clobber, so that earlier locations don't
2027349cc55cSDimitry Andric // continue past this store.
2028349cc55cSDimitry Andric for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
2029d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
2030bdd1243dSDimitry Andric std::optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
2031349cc55cSDimitry Andric if (!MLoc)
2032349cc55cSDimitry Andric continue;
2033349cc55cSDimitry Andric
2034349cc55cSDimitry Andric // We need to over-write the stack slot with something (here, a def at
2035349cc55cSDimitry Andric // this instruction) to ensure no values are preserved in this stack slot
2036349cc55cSDimitry Andric // after the spill. It also prevents TTracker from trying to recover the
2037349cc55cSDimitry Andric // location and re-installing it in the same place.
2038349cc55cSDimitry Andric ValueIDNum Def(CurBB, CurInst, *MLoc);
2039349cc55cSDimitry Andric MTracker->setMLoc(*MLoc, Def);
2040349cc55cSDimitry Andric if (TTracker)
2041e8d8bef9SDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator());
2042e8d8bef9SDimitry Andric }
2043e8d8bef9SDimitry Andric }
2044e8d8bef9SDimitry Andric
2045e8d8bef9SDimitry Andric // Try to recognise spill and restore instructions that may transfer a value.
2046e8d8bef9SDimitry Andric if (isLocationSpill(MI, MF, Reg)) {
2047d56accc7SDimitry Andric // isLocationSpill returning true should guarantee we can extract a
2048d56accc7SDimitry Andric // location.
2049d56accc7SDimitry Andric SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
2050e8d8bef9SDimitry Andric
2051349cc55cSDimitry Andric auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
2052349cc55cSDimitry Andric auto ReadValue = MTracker->readReg(SrcReg);
2053349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
2054349cc55cSDimitry Andric MTracker->setMLoc(DstLoc, ReadValue);
2055e8d8bef9SDimitry Andric
2056349cc55cSDimitry Andric if (TTracker) {
2057349cc55cSDimitry Andric LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
2058349cc55cSDimitry Andric TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
2059e8d8bef9SDimitry Andric }
2060349cc55cSDimitry Andric };
2061349cc55cSDimitry Andric
2062349cc55cSDimitry Andric // Then, transfer subreg bits.
2063fe013be4SDimitry Andric for (MCPhysReg SR : TRI->subregs(Reg)) {
2064349cc55cSDimitry Andric // Ensure this reg is tracked,
2065fe013be4SDimitry Andric (void)MTracker->lookupOrTrackRegister(SR);
2066fe013be4SDimitry Andric unsigned SubregIdx = TRI->getSubRegIndex(Reg, SR);
2067349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
2068fe013be4SDimitry Andric DoTransfer(SR, SpillID);
2069349cc55cSDimitry Andric }
2070349cc55cSDimitry Andric
2071349cc55cSDimitry Andric // Directly lookup size of main source reg, and transfer.
2072349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
2073349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
2074349cc55cSDimitry Andric DoTransfer(Reg, SpillID);
2075349cc55cSDimitry Andric } else {
2076bdd1243dSDimitry Andric std::optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
2077d56accc7SDimitry Andric if (!Loc)
2078349cc55cSDimitry Andric return false;
2079349cc55cSDimitry Andric
2080349cc55cSDimitry Andric // Assumption: we're reading from the base of the stack slot, not some
2081349cc55cSDimitry Andric // offset into it. It seems very unlikely LLVM would ever generate
2082349cc55cSDimitry Andric // restores where this wasn't true. This then becomes a question of what
2083349cc55cSDimitry Andric // subregisters in the destination register line up with positions in the
2084349cc55cSDimitry Andric // stack slot.
2085349cc55cSDimitry Andric
2086349cc55cSDimitry Andric // Def all registers that alias the destination.
2087349cc55cSDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2088349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst);
2089349cc55cSDimitry Andric
2090349cc55cSDimitry Andric // Now find subregisters within the destination register, and load values
2091349cc55cSDimitry Andric // from stack slot positions.
2092349cc55cSDimitry Andric auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
2093349cc55cSDimitry Andric LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
2094349cc55cSDimitry Andric auto ReadValue = MTracker->readMLoc(SrcIdx);
2095349cc55cSDimitry Andric MTracker->setReg(DestReg, ReadValue);
2096349cc55cSDimitry Andric };
2097349cc55cSDimitry Andric
2098fe013be4SDimitry Andric for (MCPhysReg SR : TRI->subregs(Reg)) {
2099fe013be4SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, SR);
2100d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
2101fe013be4SDimitry Andric DoTransfer(SR, SpillID);
2102349cc55cSDimitry Andric }
2103349cc55cSDimitry Andric
2104349cc55cSDimitry Andric // Directly look up this registers slot idx by size, and transfer.
2105349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
2106d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
2107349cc55cSDimitry Andric DoTransfer(Reg, SpillID);
2108e8d8bef9SDimitry Andric }
2109e8d8bef9SDimitry Andric return true;
2110e8d8bef9SDimitry Andric }
2111e8d8bef9SDimitry Andric
transferRegisterCopy(MachineInstr & MI)2112e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2113c9157d92SDimitry Andric auto DestSrc = TII->isCopyLikeInstr(MI);
2114e8d8bef9SDimitry Andric if (!DestSrc)
2115e8d8bef9SDimitry Andric return false;
2116e8d8bef9SDimitry Andric
2117e8d8bef9SDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination;
2118e8d8bef9SDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source;
2119e8d8bef9SDimitry Andric
2120e8d8bef9SDimitry Andric Register SrcReg = SrcRegOp->getReg();
2121e8d8bef9SDimitry Andric Register DestReg = DestRegOp->getReg();
2122e8d8bef9SDimitry Andric
2123e8d8bef9SDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2124e8d8bef9SDimitry Andric if (SrcReg == DestReg)
2125e8d8bef9SDimitry Andric return true;
2126e8d8bef9SDimitry Andric
2127e8d8bef9SDimitry Andric // For emulating VarLocBasedImpl:
2128e8d8bef9SDimitry Andric // We want to recognize instructions where destination register is callee
2129e8d8bef9SDimitry Andric // saved register. If register that could be clobbered by the call is
2130e8d8bef9SDimitry Andric // included, there would be a great chance that it is going to be clobbered
2131e8d8bef9SDimitry Andric // soon. It is more likely that previous register, which is callee saved, is
2132e8d8bef9SDimitry Andric // going to stay unclobbered longer, even if it is killed.
2133e8d8bef9SDimitry Andric //
2134e8d8bef9SDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so
2135e8d8bef9SDimitry Andric // ignore this condition.
2136e8d8bef9SDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
2137e8d8bef9SDimitry Andric return false;
2138e8d8bef9SDimitry Andric
2139e8d8bef9SDimitry Andric // InstrRefBasedImpl only followed killing copies.
2140e8d8bef9SDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill())
2141e8d8bef9SDimitry Andric return false;
2142e8d8bef9SDimitry Andric
2143753f127fSDimitry Andric // Before we update MTracker, remember which values were present in each of
2144753f127fSDimitry Andric // the locations about to be overwritten, so that we can recover any
2145753f127fSDimitry Andric // potentially clobbered variables.
2146753f127fSDimitry Andric DenseMap<LocIdx, ValueIDNum> ClobberedLocs;
2147753f127fSDimitry Andric if (TTracker) {
2148753f127fSDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
2149753f127fSDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
2150753f127fSDimitry Andric auto MLocIt = TTracker->ActiveMLocs.find(ClobberedLoc);
2151753f127fSDimitry Andric // If ActiveMLocs isn't tracking this location or there are no variables
2152753f127fSDimitry Andric // using it, don't bother remembering.
2153753f127fSDimitry Andric if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty())
2154753f127fSDimitry Andric continue;
2155753f127fSDimitry Andric ValueIDNum Value = MTracker->readReg(*RAI);
2156753f127fSDimitry Andric ClobberedLocs[ClobberedLoc] = Value;
2157753f127fSDimitry Andric }
2158753f127fSDimitry Andric }
2159753f127fSDimitry Andric
2160e8d8bef9SDimitry Andric // Copy MTracker info, including subregs if available.
2161e8d8bef9SDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg);
2162e8d8bef9SDimitry Andric
2163753f127fSDimitry Andric // The copy might have clobbered variables based on the destination register.
2164753f127fSDimitry Andric // Tell TTracker about it, passing the old ValueIDNum to search for
2165753f127fSDimitry Andric // alternative locations (or else terminating those variables).
2166753f127fSDimitry Andric if (TTracker) {
2167753f127fSDimitry Andric for (auto LocVal : ClobberedLocs) {
2168753f127fSDimitry Andric TTracker->clobberMloc(LocVal.first, LocVal.second, MI.getIterator(), false);
2169753f127fSDimitry Andric }
2170753f127fSDimitry Andric }
2171753f127fSDimitry Andric
2172e8d8bef9SDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV
2173e8d8bef9SDimitry Andric // would have. We might make use of the additional value tracking in some
2174e8d8bef9SDimitry Andric // other way, later.
2175e8d8bef9SDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
2176e8d8bef9SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
2177e8d8bef9SDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator());
2178e8d8bef9SDimitry Andric
2179e8d8bef9SDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying.
2180e8d8bef9SDimitry Andric if (EmulateOldLDV && SrcReg != DestReg)
2181e8d8bef9SDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst);
2182e8d8bef9SDimitry Andric
2183e8d8bef9SDimitry Andric return true;
2184e8d8bef9SDimitry Andric }
2185e8d8bef9SDimitry Andric
2186e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
2187e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
2188e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
2189e8d8bef9SDimitry Andric /// known-to-overlap fragments are present".
21904824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for
2191e8d8bef9SDimitry Andric /// fragment usage.
accumulateFragmentMap(MachineInstr & MI)2192e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2193bdd1243dSDimitry Andric assert(MI.isDebugValueLike());
2194e8d8bef9SDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2195e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt());
2196e8d8bef9SDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2197e8d8bef9SDimitry Andric
2198e8d8bef9SDimitry Andric // If this is the first sighting of this variable, then we are guaranteed
2199e8d8bef9SDimitry Andric // there are currently no overlapping fragments either. Initialize the set
2200e8d8bef9SDimitry Andric // of seen fragments, record no overlaps for the current one, and return.
2201e8d8bef9SDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable());
2202e8d8bef9SDimitry Andric if (SeenIt == SeenFragments.end()) {
2203e8d8bef9SDimitry Andric SmallSet<FragmentInfo, 4> OneFragment;
2204e8d8bef9SDimitry Andric OneFragment.insert(ThisFragment);
2205e8d8bef9SDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment});
2206e8d8bef9SDimitry Andric
2207e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2208e8d8bef9SDimitry Andric return;
2209e8d8bef9SDimitry Andric }
2210e8d8bef9SDimitry Andric
2211e8d8bef9SDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap
2212e8d8bef9SDimitry Andric // map, it has already been accounted for.
2213e8d8bef9SDimitry Andric auto IsInOLapMap =
2214e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2215e8d8bef9SDimitry Andric if (!IsInOLapMap.second)
2216e8d8bef9SDimitry Andric return;
2217e8d8bef9SDimitry Andric
2218e8d8bef9SDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2219e8d8bef9SDimitry Andric auto &AllSeenFragments = SeenIt->second;
2220e8d8bef9SDimitry Andric
2221e8d8bef9SDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this"
2222e8d8bef9SDimitry Andric // fragment being a previously unseen fragment. Record any pair of
2223e8d8bef9SDimitry Andric // overlapping fragments.
2224fcaf7f86SDimitry Andric for (const auto &ASeenFragment : AllSeenFragments) {
2225e8d8bef9SDimitry Andric // Does this previously seen fragment overlap?
2226e8d8bef9SDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
2227e8d8bef9SDimitry Andric // Yes: Mark the current fragment as being overlapped.
2228e8d8bef9SDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment);
2229e8d8bef9SDimitry Andric // Mark the previously seen fragment as being overlapped by the current
2230e8d8bef9SDimitry Andric // one.
2231e8d8bef9SDimitry Andric auto ASeenFragmentsOverlaps =
2232e8d8bef9SDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
2233e8d8bef9SDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2234e8d8bef9SDimitry Andric "Previously seen var fragment has no vector of overlaps");
2235e8d8bef9SDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment);
2236e8d8bef9SDimitry Andric }
2237e8d8bef9SDimitry Andric }
2238e8d8bef9SDimitry Andric
2239e8d8bef9SDimitry Andric AllSeenFragments.insert(ThisFragment);
2240e8d8bef9SDimitry Andric }
2241e8d8bef9SDimitry Andric
process(MachineInstr & MI,const FuncValueTable * MLiveOuts,const FuncValueTable * MLiveIns)2242c9157d92SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI,
2243c9157d92SDimitry Andric const FuncValueTable *MLiveOuts,
2244c9157d92SDimitry Andric const FuncValueTable *MLiveIns) {
2245e8d8bef9SDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's
2246e8d8bef9SDimitry Andric // none of these should we interpret it's register defs as new value
2247e8d8bef9SDimitry Andric // definitions.
2248e8d8bef9SDimitry Andric if (transferDebugValue(MI))
2249e8d8bef9SDimitry Andric return;
2250fe6060f1SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
2251fe6060f1SDimitry Andric return;
2252fe6060f1SDimitry Andric if (transferDebugPHI(MI))
2253e8d8bef9SDimitry Andric return;
2254e8d8bef9SDimitry Andric if (transferRegisterCopy(MI))
2255e8d8bef9SDimitry Andric return;
2256e8d8bef9SDimitry Andric if (transferSpillOrRestoreInst(MI))
2257e8d8bef9SDimitry Andric return;
2258e8d8bef9SDimitry Andric transferRegisterDef(MI);
2259e8d8bef9SDimitry Andric }
2260e8d8bef9SDimitry Andric
produceMLocTransferFunction(MachineFunction & MF,SmallVectorImpl<MLocTransferMap> & MLocTransfer,unsigned MaxNumBlocks)2261e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction(
2262e8d8bef9SDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2263e8d8bef9SDimitry Andric unsigned MaxNumBlocks) {
2264e8d8bef9SDimitry Andric // Because we try to optimize around register mask operands by ignoring regs
2265e8d8bef9SDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask
2266e8d8bef9SDimitry Andric // operands that are seen earlier than the first use of a register, still need
2267e8d8bef9SDimitry Andric // to clobber that register in the transfer function. But this information
2268e8d8bef9SDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block,
2269e8d8bef9SDimitry Andric // and accumulated the clobbered but untracked registers in each block into
2270e8d8bef9SDimitry Andric // the following bitvector. Later, if new values are tracked, we can add
2271e8d8bef9SDimitry Andric // appropriate clobbers.
2272e8d8bef9SDimitry Andric SmallVector<BitVector, 32> BlockMasks;
2273e8d8bef9SDimitry Andric BlockMasks.resize(MaxNumBlocks);
2274e8d8bef9SDimitry Andric
2275e8d8bef9SDimitry Andric // Reserve one bit per register for the masks described above.
2276e8d8bef9SDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
2277e8d8bef9SDimitry Andric for (auto &BV : BlockMasks)
2278e8d8bef9SDimitry Andric BV.resize(TRI->getNumRegs(), true);
2279e8d8bef9SDimitry Andric
2280e8d8bef9SDimitry Andric // Step through all instructions and inhale the transfer function.
2281e8d8bef9SDimitry Andric for (auto &MBB : MF) {
2282e8d8bef9SDimitry Andric // Object fields that are read by trackers to know where we are in the
2283e8d8bef9SDimitry Andric // function.
2284e8d8bef9SDimitry Andric CurBB = MBB.getNumber();
2285e8d8bef9SDimitry Andric CurInst = 1;
2286e8d8bef9SDimitry Andric
2287e8d8bef9SDimitry Andric // Set all machine locations to a PHI value. For transfer function
2288e8d8bef9SDimitry Andric // production only, this signifies the live-in value to the block.
2289e8d8bef9SDimitry Andric MTracker->reset();
2290e8d8bef9SDimitry Andric MTracker->setMPhis(CurBB);
2291e8d8bef9SDimitry Andric
2292e8d8bef9SDimitry Andric // Step through each instruction in this block.
2293e8d8bef9SDimitry Andric for (auto &MI : MBB) {
229481ad6265SDimitry Andric // Pass in an empty unique_ptr for the value tables when accumulating the
229581ad6265SDimitry Andric // machine transfer function.
229681ad6265SDimitry Andric process(MI, nullptr, nullptr);
229781ad6265SDimitry Andric
2298e8d8bef9SDimitry Andric // Also accumulate fragment map.
2299bdd1243dSDimitry Andric if (MI.isDebugValueLike())
2300e8d8bef9SDimitry Andric accumulateFragmentMap(MI);
2301e8d8bef9SDimitry Andric
2302e8d8bef9SDimitry Andric // Create a map from the instruction number (if present) to the
2303e8d8bef9SDimitry Andric // MachineInstr and its position.
2304e8d8bef9SDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
2305e8d8bef9SDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst);
2306e8d8bef9SDimitry Andric auto InsertResult =
2307e8d8bef9SDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
2308e8d8bef9SDimitry Andric
2309e8d8bef9SDimitry Andric // There should never be duplicate instruction numbers.
2310e8d8bef9SDimitry Andric assert(InsertResult.second);
2311e8d8bef9SDimitry Andric (void)InsertResult;
2312e8d8bef9SDimitry Andric }
2313e8d8bef9SDimitry Andric
2314e8d8bef9SDimitry Andric ++CurInst;
2315e8d8bef9SDimitry Andric }
2316e8d8bef9SDimitry Andric
2317e8d8bef9SDimitry Andric // Produce the transfer function, a map of machine location to new value. If
2318e8d8bef9SDimitry Andric // any machine location has the live-in phi value from the start of the
2319e8d8bef9SDimitry Andric // block, it's live-through and doesn't need recording in the transfer
2320e8d8bef9SDimitry Andric // function.
2321e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) {
2322e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx;
2323e8d8bef9SDimitry Andric ValueIDNum &P = Location.Value;
2324e8d8bef9SDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64())
2325e8d8bef9SDimitry Andric continue;
2326e8d8bef9SDimitry Andric
2327e8d8bef9SDimitry Andric // Insert-or-update.
2328e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[CurBB];
2329e8d8bef9SDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
2330e8d8bef9SDimitry Andric if (!Result.second)
2331e8d8bef9SDimitry Andric Result.first->second = P;
2332e8d8bef9SDimitry Andric }
2333e8d8bef9SDimitry Andric
2334bdd1243dSDimitry Andric // Accumulate any bitmask operands into the clobbered reg mask for this
2335e8d8bef9SDimitry Andric // block.
2336e8d8bef9SDimitry Andric for (auto &P : MTracker->Masks) {
2337e8d8bef9SDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
2338e8d8bef9SDimitry Andric }
2339e8d8bef9SDimitry Andric }
2340e8d8bef9SDimitry Andric
2341e8d8bef9SDimitry Andric // Compute a bitvector of all the registers that are tracked in this block.
2342e8d8bef9SDimitry Andric BitVector UsedRegs(TRI->getNumRegs());
2343e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) {
2344e8d8bef9SDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2345349cc55cSDimitry Andric // Ignore stack slots, and aliases of the stack pointer.
2346349cc55cSDimitry Andric if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
2347e8d8bef9SDimitry Andric continue;
2348e8d8bef9SDimitry Andric UsedRegs.set(ID);
2349e8d8bef9SDimitry Andric }
2350e8d8bef9SDimitry Andric
2351e8d8bef9SDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not
2352e8d8bef9SDimitry Andric // live-through in the transfer function. It needs to be clobbered at the
2353e8d8bef9SDimitry Andric // very least.
2354e8d8bef9SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2355e8d8bef9SDimitry Andric BitVector &BV = BlockMasks[I];
2356e8d8bef9SDimitry Andric BV.flip();
2357e8d8bef9SDimitry Andric BV &= UsedRegs;
2358e8d8bef9SDimitry Andric // This produces all the bits that we clobber, but also use. Check that
2359e8d8bef9SDimitry Andric // they're all clobbered or at least set in the designated transfer
2360e8d8bef9SDimitry Andric // elem.
2361e8d8bef9SDimitry Andric for (unsigned Bit : BV.set_bits()) {
2362349cc55cSDimitry Andric unsigned ID = MTracker->getLocID(Bit);
2363e8d8bef9SDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2364e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[I];
2365e8d8bef9SDimitry Andric
2366e8d8bef9SDimitry Andric // Install a value representing the fact that this location is effectively
2367e8d8bef9SDimitry Andric // written to in this block. As there's no reserved value, instead use
2368e8d8bef9SDimitry Andric // a value number that is never generated. Pick the value number for the
2369e8d8bef9SDimitry Andric // first instruction in the block, def'ing this location, which we know
2370e8d8bef9SDimitry Andric // this block never used anyway.
2371e8d8bef9SDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2372e8d8bef9SDimitry Andric auto Result =
2373e8d8bef9SDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
2374e8d8bef9SDimitry Andric if (!Result.second) {
2375e8d8bef9SDimitry Andric ValueIDNum &ValueID = Result.first->second;
2376e8d8bef9SDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI())
2377e8d8bef9SDimitry Andric // It was left as live-through. Set it to clobbered.
2378e8d8bef9SDimitry Andric ValueID = NotGeneratedNum;
2379e8d8bef9SDimitry Andric }
2380e8d8bef9SDimitry Andric }
2381e8d8bef9SDimitry Andric }
2382e8d8bef9SDimitry Andric }
2383e8d8bef9SDimitry Andric
mlocJoin(MachineBasicBlock & MBB,SmallPtrSet<const MachineBasicBlock *,16> & Visited,FuncValueTable & OutLocs,ValueTable & InLocs)2384349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin(
2385349cc55cSDimitry Andric MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
238681ad6265SDimitry Andric FuncValueTable &OutLocs, ValueTable &InLocs) {
2387e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2388e8d8bef9SDimitry Andric bool Changed = false;
2389e8d8bef9SDimitry Andric
2390349cc55cSDimitry Andric // Handle value-propagation when control flow merges on entry to a block. For
2391349cc55cSDimitry Andric // any location without a PHI already placed, the location has the same value
2392349cc55cSDimitry Andric // as its predecessors. If a PHI is placed, test to see whether it's now a
2393349cc55cSDimitry Andric // redundant PHI that we can eliminate.
2394349cc55cSDimitry Andric
2395e8d8bef9SDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders;
2396fcaf7f86SDimitry Andric for (auto *Pred : MBB.predecessors())
2397e8d8bef9SDimitry Andric BlockOrders.push_back(Pred);
2398e8d8bef9SDimitry Andric
2399e8d8bef9SDimitry Andric // Visit predecessors in RPOT order.
2400e8d8bef9SDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2401e8d8bef9SDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2402e8d8bef9SDimitry Andric };
2403e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp);
2404e8d8bef9SDimitry Andric
2405e8d8bef9SDimitry Andric // Skip entry block.
2406*6c20abcdSDimitry Andric if (BlockOrders.size() == 0) {
2407*6c20abcdSDimitry Andric // FIXME: We don't use assert here to prevent instr-ref-unreachable.mir
2408*6c20abcdSDimitry Andric // failing.
2409*6c20abcdSDimitry Andric LLVM_DEBUG(if (!MBB.isEntryBlock()) dbgs()
2410*6c20abcdSDimitry Andric << "Found not reachable block " << MBB.getFullName()
2411*6c20abcdSDimitry Andric << " from entry which may lead out of "
2412*6c20abcdSDimitry Andric "bound access to VarLocs\n");
2413349cc55cSDimitry Andric return false;
2414*6c20abcdSDimitry Andric }
2415e8d8bef9SDimitry Andric
2416349cc55cSDimitry Andric // Step through all machine locations, look at each predecessor and test
2417349cc55cSDimitry Andric // whether we can eliminate redundant PHIs.
2418e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) {
2419e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx;
2420349cc55cSDimitry Andric
2421e8d8bef9SDimitry Andric // Pick out the first predecessors live-out value for this location. It's
2422349cc55cSDimitry Andric // guaranteed to not be a backedge, as we order by RPO.
2423e710425bSDimitry Andric ValueIDNum FirstVal = OutLocs[*BlockOrders[0]][Idx.asU64()];
2424e8d8bef9SDimitry Andric
2425349cc55cSDimitry Andric // If we've already eliminated a PHI here, do no further checking, just
2426349cc55cSDimitry Andric // propagate the first live-in value into this block.
2427349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
2428349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != FirstVal) {
2429349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal;
2430349cc55cSDimitry Andric Changed |= true;
2431349cc55cSDimitry Andric }
2432349cc55cSDimitry Andric continue;
2433349cc55cSDimitry Andric }
2434349cc55cSDimitry Andric
2435349cc55cSDimitry Andric // We're now examining a PHI to see whether it's un-necessary. Loop around
2436349cc55cSDimitry Andric // the other live-in values and test whether they're all the same.
2437e8d8bef9SDimitry Andric bool Disagree = false;
2438e8d8bef9SDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2439349cc55cSDimitry Andric const MachineBasicBlock *PredMBB = BlockOrders[I];
2440e710425bSDimitry Andric const ValueIDNum &PredLiveOut = OutLocs[*PredMBB][Idx.asU64()];
2441349cc55cSDimitry Andric
2442349cc55cSDimitry Andric // Incoming values agree, continue trying to eliminate this PHI.
2443349cc55cSDimitry Andric if (FirstVal == PredLiveOut)
2444349cc55cSDimitry Andric continue;
2445349cc55cSDimitry Andric
2446349cc55cSDimitry Andric // We can also accept a PHI value that feeds back into itself.
2447349cc55cSDimitry Andric if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
2448349cc55cSDimitry Andric continue;
2449349cc55cSDimitry Andric
2450e8d8bef9SDimitry Andric // Live-out of a predecessor disagrees with the first predecessor.
2451e8d8bef9SDimitry Andric Disagree = true;
2452e8d8bef9SDimitry Andric }
2453e8d8bef9SDimitry Andric
2454349cc55cSDimitry Andric // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
2455349cc55cSDimitry Andric if (!Disagree) {
2456349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal;
2457e8d8bef9SDimitry Andric Changed |= true;
2458e8d8bef9SDimitry Andric }
2459e8d8bef9SDimitry Andric }
2460e8d8bef9SDimitry Andric
2461e8d8bef9SDimitry Andric // TODO: Reimplement NumInserted and NumRemoved.
2462349cc55cSDimitry Andric return Changed;
2463e8d8bef9SDimitry Andric }
2464e8d8bef9SDimitry Andric
findStackIndexInterference(SmallVectorImpl<unsigned> & Slots)2465349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference(
2466349cc55cSDimitry Andric SmallVectorImpl<unsigned> &Slots) {
2467349cc55cSDimitry Andric // We could spend a bit of time finding the exact, minimal, set of stack
2468349cc55cSDimitry Andric // indexes that interfere with each other, much like reg units. Or, we can
2469349cc55cSDimitry Andric // rely on the fact that:
2470349cc55cSDimitry Andric // * The smallest / lowest index will interfere with everything at zero
2471349cc55cSDimitry Andric // offset, which will be the largest set of registers,
2472349cc55cSDimitry Andric // * Most indexes with non-zero offset will end up being interference units
2473349cc55cSDimitry Andric // anyway.
2474349cc55cSDimitry Andric // So just pick those out and return them.
2475349cc55cSDimitry Andric
2476349cc55cSDimitry Andric // We can rely on a single-byte stack index existing already, because we
2477349cc55cSDimitry Andric // initialize them in MLocTracker.
2478349cc55cSDimitry Andric auto It = MTracker->StackSlotIdxes.find({8, 0});
2479349cc55cSDimitry Andric assert(It != MTracker->StackSlotIdxes.end());
2480349cc55cSDimitry Andric Slots.push_back(It->second);
2481349cc55cSDimitry Andric
2482349cc55cSDimitry Andric // Find anything that has a non-zero offset and add that too.
2483349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) {
2484349cc55cSDimitry Andric // Is offset zero? If so, ignore.
2485349cc55cSDimitry Andric if (!Pair.first.second)
2486349cc55cSDimitry Andric continue;
2487349cc55cSDimitry Andric Slots.push_back(Pair.second);
2488349cc55cSDimitry Andric }
2489349cc55cSDimitry Andric }
2490349cc55cSDimitry Andric
placeMLocPHIs(MachineFunction & MF,SmallPtrSetImpl<MachineBasicBlock * > & AllBlocks,FuncValueTable & MInLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)2491349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs(
2492349cc55cSDimitry Andric MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
249381ad6265SDimitry Andric FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2494349cc55cSDimitry Andric SmallVector<unsigned, 4> StackUnits;
2495349cc55cSDimitry Andric findStackIndexInterference(StackUnits);
2496349cc55cSDimitry Andric
2497349cc55cSDimitry Andric // To avoid repeatedly running the PHI placement algorithm, leverage the
2498349cc55cSDimitry Andric // fact that a def of register MUST also def its register units. Find the
2499349cc55cSDimitry Andric // units for registers, place PHIs for them, and then replicate them for
2500349cc55cSDimitry Andric // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2501349cc55cSDimitry Andric // arguments) don't lead to register units being tracked, just place PHIs for
2502349cc55cSDimitry Andric // those registers directly. Stack slots have their own form of "unit",
2503349cc55cSDimitry Andric // store them to one side.
2504349cc55cSDimitry Andric SmallSet<Register, 32> RegUnitsToPHIUp;
2505349cc55cSDimitry Andric SmallSet<LocIdx, 32> NormalLocsToPHI;
2506349cc55cSDimitry Andric SmallSet<SpillLocationNo, 32> StackSlots;
2507349cc55cSDimitry Andric for (auto Location : MTracker->locations()) {
2508349cc55cSDimitry Andric LocIdx L = Location.Idx;
2509349cc55cSDimitry Andric if (MTracker->isSpill(L)) {
2510349cc55cSDimitry Andric StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
2511349cc55cSDimitry Andric continue;
2512349cc55cSDimitry Andric }
2513349cc55cSDimitry Andric
2514349cc55cSDimitry Andric Register R = MTracker->LocIdxToLocID[L];
2515349cc55cSDimitry Andric SmallSet<Register, 8> FoundRegUnits;
2516349cc55cSDimitry Andric bool AnyIllegal = false;
2517fe013be4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(R.asMCReg())) {
2518fe013be4SDimitry Andric for (MCRegUnitRootIterator URoot(Unit, TRI); URoot.isValid(); ++URoot) {
2519349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*URoot)) {
2520349cc55cSDimitry Andric // Not all roots were loaded into the tracking map: this register
2521349cc55cSDimitry Andric // isn't actually def'd anywhere, we only read from it. Generate PHIs
2522349cc55cSDimitry Andric // for this reg, but don't iterate units.
2523349cc55cSDimitry Andric AnyIllegal = true;
2524349cc55cSDimitry Andric } else {
2525349cc55cSDimitry Andric FoundRegUnits.insert(*URoot);
2526349cc55cSDimitry Andric }
2527349cc55cSDimitry Andric }
2528349cc55cSDimitry Andric }
2529349cc55cSDimitry Andric
2530349cc55cSDimitry Andric if (AnyIllegal) {
2531349cc55cSDimitry Andric NormalLocsToPHI.insert(L);
2532349cc55cSDimitry Andric continue;
2533349cc55cSDimitry Andric }
2534349cc55cSDimitry Andric
2535349cc55cSDimitry Andric RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
2536349cc55cSDimitry Andric }
2537349cc55cSDimitry Andric
2538349cc55cSDimitry Andric // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2539349cc55cSDimitry Andric // collection.
2540349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2541349cc55cSDimitry Andric auto CollectPHIsForLoc = [&](LocIdx L) {
2542349cc55cSDimitry Andric // Collect the set of defs.
2543349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2544349cc55cSDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2545349cc55cSDimitry Andric MachineBasicBlock *MBB = OrderToBB[I];
2546349cc55cSDimitry Andric const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2547c9157d92SDimitry Andric if (TransferFunc.contains(L))
2548349cc55cSDimitry Andric DefBlocks.insert(MBB);
2549349cc55cSDimitry Andric }
2550349cc55cSDimitry Andric
2551349cc55cSDimitry Andric // The entry block defs the location too: it's the live-in / argument value.
2552349cc55cSDimitry Andric // Only insert if there are other defs though; everything is trivially live
2553349cc55cSDimitry Andric // through otherwise.
2554349cc55cSDimitry Andric if (!DefBlocks.empty())
2555349cc55cSDimitry Andric DefBlocks.insert(&*MF.begin());
2556349cc55cSDimitry Andric
2557349cc55cSDimitry Andric // Ask the SSA construction algorithm where we should put PHIs. Clear
2558349cc55cSDimitry Andric // anything that might have been hanging around from earlier.
2559349cc55cSDimitry Andric PHIBlocks.clear();
2560349cc55cSDimitry Andric BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2561349cc55cSDimitry Andric };
2562349cc55cSDimitry Andric
2563349cc55cSDimitry Andric auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2564349cc55cSDimitry Andric for (const MachineBasicBlock *MBB : PHIBlocks)
2565e710425bSDimitry Andric MInLocs[*MBB][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2566349cc55cSDimitry Andric };
2567349cc55cSDimitry Andric
2568349cc55cSDimitry Andric // For locations with no reg units, just place PHIs.
2569349cc55cSDimitry Andric for (LocIdx L : NormalLocsToPHI) {
2570349cc55cSDimitry Andric CollectPHIsForLoc(L);
2571349cc55cSDimitry Andric // Install those PHI values into the live-in value array.
2572349cc55cSDimitry Andric InstallPHIsAtLoc(L);
2573349cc55cSDimitry Andric }
2574349cc55cSDimitry Andric
2575349cc55cSDimitry Andric // For stack slots, calculate PHIs for the equivalent of the units, then
2576349cc55cSDimitry Andric // install for each index.
2577349cc55cSDimitry Andric for (SpillLocationNo Slot : StackSlots) {
2578349cc55cSDimitry Andric for (unsigned Idx : StackUnits) {
2579349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2580349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID);
2581349cc55cSDimitry Andric CollectPHIsForLoc(L);
2582349cc55cSDimitry Andric InstallPHIsAtLoc(L);
2583349cc55cSDimitry Andric
2584349cc55cSDimitry Andric // Find anything that aliases this stack index, install PHIs for it too.
2585349cc55cSDimitry Andric unsigned Size, Offset;
2586349cc55cSDimitry Andric std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2587349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) {
2588349cc55cSDimitry Andric unsigned ThisSize, ThisOffset;
2589349cc55cSDimitry Andric std::tie(ThisSize, ThisOffset) = Pair.first;
2590349cc55cSDimitry Andric if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2591349cc55cSDimitry Andric continue;
2592349cc55cSDimitry Andric
2593349cc55cSDimitry Andric unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2594349cc55cSDimitry Andric LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2595349cc55cSDimitry Andric InstallPHIsAtLoc(ThisL);
2596349cc55cSDimitry Andric }
2597349cc55cSDimitry Andric }
2598349cc55cSDimitry Andric }
2599349cc55cSDimitry Andric
2600349cc55cSDimitry Andric // For reg units, place PHIs, and then place them for any aliasing registers.
2601349cc55cSDimitry Andric for (Register R : RegUnitsToPHIUp) {
2602349cc55cSDimitry Andric LocIdx L = MTracker->lookupOrTrackRegister(R);
2603349cc55cSDimitry Andric CollectPHIsForLoc(L);
2604349cc55cSDimitry Andric
2605349cc55cSDimitry Andric // Install those PHI values into the live-in value array.
2606349cc55cSDimitry Andric InstallPHIsAtLoc(L);
2607349cc55cSDimitry Andric
2608349cc55cSDimitry Andric // Now find aliases and install PHIs for those.
2609349cc55cSDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2610349cc55cSDimitry Andric // Super-registers that are "above" the largest register read/written by
2611349cc55cSDimitry Andric // the function will alias, but will not be tracked.
2612349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*RAI))
2613349cc55cSDimitry Andric continue;
2614349cc55cSDimitry Andric
2615349cc55cSDimitry Andric LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2616349cc55cSDimitry Andric InstallPHIsAtLoc(AliasLoc);
2617349cc55cSDimitry Andric }
2618349cc55cSDimitry Andric }
2619349cc55cSDimitry Andric }
2620349cc55cSDimitry Andric
buildMLocValueMap(MachineFunction & MF,FuncValueTable & MInLocs,FuncValueTable & MOutLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)2621349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap(
262281ad6265SDimitry Andric MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2623e8d8bef9SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2624e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>,
2625e8d8bef9SDimitry Andric std::greater<unsigned int>>
2626e8d8bef9SDimitry Andric Worklist, Pending;
2627e8d8bef9SDimitry Andric
2628e8d8bef9SDimitry Andric // We track what is on the current and pending worklist to avoid inserting
2629e8d8bef9SDimitry Andric // the same thing twice. We could avoid this with a custom priority queue,
2630e8d8bef9SDimitry Andric // but this is probably not worth it.
2631e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2632e8d8bef9SDimitry Andric
2633349cc55cSDimitry Andric // Initialize worklist with every block to be visited. Also produce list of
2634349cc55cSDimitry Andric // all blocks.
2635349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2636e8d8bef9SDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2637e8d8bef9SDimitry Andric Worklist.push(I);
2638e8d8bef9SDimitry Andric OnWorklist.insert(OrderToBB[I]);
2639349cc55cSDimitry Andric AllBlocks.insert(OrderToBB[I]);
2640e8d8bef9SDimitry Andric }
2641e8d8bef9SDimitry Andric
2642349cc55cSDimitry Andric // Initialize entry block to PHIs. These represent arguments.
2643349cc55cSDimitry Andric for (auto Location : MTracker->locations())
2644e710425bSDimitry Andric MInLocs.tableForEntryMBB()[Location.Idx.asU64()] =
2645e710425bSDimitry Andric ValueIDNum(0, 0, Location.Idx);
2646349cc55cSDimitry Andric
2647e8d8bef9SDimitry Andric MTracker->reset();
2648e8d8bef9SDimitry Andric
2649349cc55cSDimitry Andric // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2650349cc55cSDimitry Andric // any machine-location that isn't live-through a block to be def'd in that
2651349cc55cSDimitry Andric // block.
2652349cc55cSDimitry Andric placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2653e8d8bef9SDimitry Andric
2654349cc55cSDimitry Andric // Propagate values to eliminate redundant PHIs. At the same time, this
2655349cc55cSDimitry Andric // produces the table of Block x Location => Value for the entry to each
2656349cc55cSDimitry Andric // block.
2657349cc55cSDimitry Andric // The kind of PHIs we can eliminate are, for example, where one path in a
2658349cc55cSDimitry Andric // conditional spills and restores a register, and the register still has
2659349cc55cSDimitry Andric // the same value once control flow joins, unbeknowns to the PHI placement
2660349cc55cSDimitry Andric // code. Propagating values allows us to identify such un-necessary PHIs and
2661349cc55cSDimitry Andric // remove them.
2662e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2663e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) {
2664e8d8bef9SDimitry Andric // Vector for storing the evaluated block transfer function.
2665e8d8bef9SDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2666e8d8bef9SDimitry Andric
2667e8d8bef9SDimitry Andric while (!Worklist.empty()) {
2668e8d8bef9SDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2669e8d8bef9SDimitry Andric CurBB = MBB->getNumber();
2670e8d8bef9SDimitry Andric Worklist.pop();
2671e8d8bef9SDimitry Andric
2672e8d8bef9SDimitry Andric // Join the values in all predecessor blocks.
2673349cc55cSDimitry Andric bool InLocsChanged;
2674e710425bSDimitry Andric InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[*MBB]);
2675e8d8bef9SDimitry Andric InLocsChanged |= Visited.insert(MBB).second;
2676e8d8bef9SDimitry Andric
2677e8d8bef9SDimitry Andric // Don't examine transfer function if we've visited this loc at least
2678e8d8bef9SDimitry Andric // once, and inlocs haven't changed.
2679e8d8bef9SDimitry Andric if (!InLocsChanged)
2680e8d8bef9SDimitry Andric continue;
2681e8d8bef9SDimitry Andric
2682e8d8bef9SDimitry Andric // Load the current set of live-ins into MLocTracker.
2683e710425bSDimitry Andric MTracker->loadFromArray(MInLocs[*MBB], CurBB);
2684e8d8bef9SDimitry Andric
2685e8d8bef9SDimitry Andric // Each element of the transfer function can be a new def, or a read of
2686e8d8bef9SDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap".
2687e8d8bef9SDimitry Andric ToRemap.clear();
2688e8d8bef9SDimitry Andric for (auto &P : MLocTransfer[CurBB]) {
2689e8d8bef9SDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2690e8d8bef9SDimitry Andric // This is a movement of whatever was live in. Read it.
2691349cc55cSDimitry Andric ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2692e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID));
2693e8d8bef9SDimitry Andric } else {
2694e8d8bef9SDimitry Andric // It's a def. Just set it.
2695e8d8bef9SDimitry Andric assert(P.second.getBlock() == CurBB);
2696e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second));
2697e8d8bef9SDimitry Andric }
2698e8d8bef9SDimitry Andric }
2699e8d8bef9SDimitry Andric
2700e8d8bef9SDimitry Andric // Commit the transfer function changes into mloc tracker, which
2701e8d8bef9SDimitry Andric // transforms the contents of the MLocTracker into the live-outs.
2702e8d8bef9SDimitry Andric for (auto &P : ToRemap)
2703e8d8bef9SDimitry Andric MTracker->setMLoc(P.first, P.second);
2704e8d8bef9SDimitry Andric
2705e8d8bef9SDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking
2706e8d8bef9SDimitry Andric // whether changes have occurred. These changes can have come from both
2707e8d8bef9SDimitry Andric // the transfer function, and mlocJoin.
2708e8d8bef9SDimitry Andric bool OLChanged = false;
2709e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) {
2710e710425bSDimitry Andric OLChanged |= MOutLocs[*MBB][Location.Idx.asU64()] != Location.Value;
2711e710425bSDimitry Andric MOutLocs[*MBB][Location.Idx.asU64()] = Location.Value;
2712e8d8bef9SDimitry Andric }
2713e8d8bef9SDimitry Andric
2714e8d8bef9SDimitry Andric MTracker->reset();
2715e8d8bef9SDimitry Andric
2716e8d8bef9SDimitry Andric // No need to examine successors again if out-locs didn't change.
2717e8d8bef9SDimitry Andric if (!OLChanged)
2718e8d8bef9SDimitry Andric continue;
2719e8d8bef9SDimitry Andric
2720e8d8bef9SDimitry Andric // All successors should be visited: put any back-edges on the pending
2721349cc55cSDimitry Andric // list for the next pass-through, and any other successors to be
2722349cc55cSDimitry Andric // visited this pass, if they're not going to be already.
2723fcaf7f86SDimitry Andric for (auto *s : MBB->successors()) {
2724e8d8bef9SDimitry Andric // Does branching to this successor represent a back-edge?
2725e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) {
2726e8d8bef9SDimitry Andric // No: visit it during this dataflow iteration.
2727e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second)
2728e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]);
2729e8d8bef9SDimitry Andric } else {
2730e8d8bef9SDimitry Andric // Yes: visit it on the next iteration.
2731e8d8bef9SDimitry Andric if (OnPending.insert(s).second)
2732e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]);
2733e8d8bef9SDimitry Andric }
2734e8d8bef9SDimitry Andric }
2735e8d8bef9SDimitry Andric }
2736e8d8bef9SDimitry Andric
2737e8d8bef9SDimitry Andric Worklist.swap(Pending);
2738e8d8bef9SDimitry Andric std::swap(OnPending, OnWorklist);
2739e8d8bef9SDimitry Andric OnPending.clear();
2740e8d8bef9SDimitry Andric // At this point, pending must be empty, since it was just the empty
2741e8d8bef9SDimitry Andric // worklist
2742e8d8bef9SDimitry Andric assert(Pending.empty() && "Pending should be empty");
2743e8d8bef9SDimitry Andric }
2744e8d8bef9SDimitry Andric
2745349cc55cSDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2746349cc55cSDimitry Andric // redundant PHIs.
2747e8d8bef9SDimitry Andric }
2748e8d8bef9SDimitry Andric
BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock * > & AllBlocks,const SmallPtrSetImpl<MachineBasicBlock * > & DefBlocks,SmallVectorImpl<MachineBasicBlock * > & PHIBlocks)2749349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement(
2750349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2751349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2752349cc55cSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2753349cc55cSDimitry Andric // Apply IDF calculator to the designated set of location defs, storing
2754349cc55cSDimitry Andric // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2755349cc55cSDimitry Andric // InstrRefBasedLDV object.
27561fd87a68SDimitry Andric IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
2757349cc55cSDimitry Andric
2758349cc55cSDimitry Andric IDF.setLiveInBlocks(AllBlocks);
2759349cc55cSDimitry Andric IDF.setDefiningBlocks(DefBlocks);
2760349cc55cSDimitry Andric IDF.calculate(PHIBlocks);
2761e8d8bef9SDimitry Andric }
2762e8d8bef9SDimitry Andric
pickVPHILoc(SmallVectorImpl<DbgOpID> & OutValues,const MachineBasicBlock & MBB,const LiveIdxT & LiveOuts,FuncValueTable & MOutLocs,const SmallVectorImpl<const MachineBasicBlock * > & BlockOrders)2763bdd1243dSDimitry Andric bool InstrRefBasedLDV::pickVPHILoc(
2764bdd1243dSDimitry Andric SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
276581ad6265SDimitry Andric const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2766349cc55cSDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2767349cc55cSDimitry Andric
2768349cc55cSDimitry Andric // No predecessors means no PHIs.
2769349cc55cSDimitry Andric if (BlockOrders.empty())
2770bdd1243dSDimitry Andric return false;
2771e8d8bef9SDimitry Andric
2772bdd1243dSDimitry Andric // All the location operands that do not already agree need to be joined,
2773bdd1243dSDimitry Andric // track the indices of each such location operand here.
2774bdd1243dSDimitry Andric SmallDenseSet<unsigned> LocOpsToJoin;
2775bdd1243dSDimitry Andric
2776bdd1243dSDimitry Andric auto FirstValueIt = LiveOuts.find(BlockOrders[0]);
2777bdd1243dSDimitry Andric if (FirstValueIt == LiveOuts.end())
2778bdd1243dSDimitry Andric return false;
2779bdd1243dSDimitry Andric const DbgValue &FirstValue = *FirstValueIt->second;
2780bdd1243dSDimitry Andric
2781bdd1243dSDimitry Andric for (const auto p : BlockOrders) {
2782349cc55cSDimitry Andric auto OutValIt = LiveOuts.find(p);
2783349cc55cSDimitry Andric if (OutValIt == LiveOuts.end())
2784349cc55cSDimitry Andric // If we have a predecessor not in scope, we'll never find a PHI position.
2785bdd1243dSDimitry Andric return false;
2786349cc55cSDimitry Andric const DbgValue &OutVal = *OutValIt->second;
2787e8d8bef9SDimitry Andric
2788bdd1243dSDimitry Andric // No-values cannot have locations we can join on.
2789bdd1243dSDimitry Andric if (OutVal.Kind == DbgValue::NoVal)
2790bdd1243dSDimitry Andric return false;
2791e8d8bef9SDimitry Andric
2792bdd1243dSDimitry Andric // For unjoined VPHIs where we don't know the location, we definitely
2793bdd1243dSDimitry Andric // can't find a join loc unless the VPHI is a backedge.
2794bdd1243dSDimitry Andric if (OutVal.isUnjoinedPHI() && OutVal.BlockNo != MBB.getNumber())
2795bdd1243dSDimitry Andric return false;
2796bdd1243dSDimitry Andric
2797bdd1243dSDimitry Andric if (!FirstValue.Properties.isJoinable(OutVal.Properties))
2798bdd1243dSDimitry Andric return false;
2799bdd1243dSDimitry Andric
2800bdd1243dSDimitry Andric for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2801bdd1243dSDimitry Andric // An unjoined PHI has no defined locations, and so a shared location must
2802bdd1243dSDimitry Andric // be found for every operand.
2803bdd1243dSDimitry Andric if (OutVal.isUnjoinedPHI()) {
2804bdd1243dSDimitry Andric LocOpsToJoin.insert(Idx);
2805bdd1243dSDimitry Andric continue;
2806bdd1243dSDimitry Andric }
2807bdd1243dSDimitry Andric DbgOpID FirstValOp = FirstValue.getDbgOpID(Idx);
2808bdd1243dSDimitry Andric DbgOpID OutValOp = OutVal.getDbgOpID(Idx);
2809bdd1243dSDimitry Andric if (FirstValOp != OutValOp) {
2810bdd1243dSDimitry Andric // We can never join constant ops - the ops must either both be equal
2811bdd1243dSDimitry Andric // constant ops or non-const ops.
2812bdd1243dSDimitry Andric if (FirstValOp.isConst() || OutValOp.isConst())
2813bdd1243dSDimitry Andric return false;
2814bdd1243dSDimitry Andric else
2815bdd1243dSDimitry Andric LocOpsToJoin.insert(Idx);
2816bdd1243dSDimitry Andric }
2817bdd1243dSDimitry Andric }
2818bdd1243dSDimitry Andric }
2819bdd1243dSDimitry Andric
2820bdd1243dSDimitry Andric SmallVector<DbgOpID> NewDbgOps;
2821bdd1243dSDimitry Andric
2822bdd1243dSDimitry Andric for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2823bdd1243dSDimitry Andric // If this op doesn't need to be joined because the values agree, use that
2824bdd1243dSDimitry Andric // already-agreed value.
2825bdd1243dSDimitry Andric if (!LocOpsToJoin.contains(Idx)) {
2826bdd1243dSDimitry Andric NewDbgOps.push_back(FirstValue.getDbgOpID(Idx));
2827bdd1243dSDimitry Andric continue;
2828bdd1243dSDimitry Andric }
2829bdd1243dSDimitry Andric
2830bdd1243dSDimitry Andric std::optional<ValueIDNum> JoinedOpLoc =
2831bdd1243dSDimitry Andric pickOperandPHILoc(Idx, MBB, LiveOuts, MOutLocs, BlockOrders);
2832bdd1243dSDimitry Andric
2833bdd1243dSDimitry Andric if (!JoinedOpLoc)
2834bdd1243dSDimitry Andric return false;
2835bdd1243dSDimitry Andric
2836bdd1243dSDimitry Andric NewDbgOps.push_back(DbgOpStore.insert(*JoinedOpLoc));
2837bdd1243dSDimitry Andric }
2838bdd1243dSDimitry Andric
2839bdd1243dSDimitry Andric OutValues.append(NewDbgOps);
2840bdd1243dSDimitry Andric return true;
2841bdd1243dSDimitry Andric }
2842bdd1243dSDimitry Andric
pickOperandPHILoc(unsigned DbgOpIdx,const MachineBasicBlock & MBB,const LiveIdxT & LiveOuts,FuncValueTable & MOutLocs,const SmallVectorImpl<const MachineBasicBlock * > & BlockOrders)2843bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::pickOperandPHILoc(
2844bdd1243dSDimitry Andric unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
2845bdd1243dSDimitry Andric FuncValueTable &MOutLocs,
2846bdd1243dSDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2847bdd1243dSDimitry Andric
2848bdd1243dSDimitry Andric // Collect a set of locations from predecessor where its live-out value can
2849bdd1243dSDimitry Andric // be found.
2850bdd1243dSDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2851bdd1243dSDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
2852bdd1243dSDimitry Andric
2853bdd1243dSDimitry Andric for (const auto p : BlockOrders) {
2854bdd1243dSDimitry Andric auto OutValIt = LiveOuts.find(p);
2855bdd1243dSDimitry Andric assert(OutValIt != LiveOuts.end());
2856bdd1243dSDimitry Andric const DbgValue &OutVal = *OutValIt->second;
2857bdd1243dSDimitry Andric DbgOpID OutValOpID = OutVal.getDbgOpID(DbgOpIdx);
2858bdd1243dSDimitry Andric DbgOp OutValOp = DbgOpStore.find(OutValOpID);
2859bdd1243dSDimitry Andric assert(!OutValOp.IsConst);
2860349cc55cSDimitry Andric
2861349cc55cSDimitry Andric // Create new empty vector of locations.
2862349cc55cSDimitry Andric Locs.resize(Locs.size() + 1);
2863349cc55cSDimitry Andric
2864349cc55cSDimitry Andric // If the live-in value is a def, find the locations where that value is
2865349cc55cSDimitry Andric // present. Do the same for VPHIs where we know the VPHI value.
2866349cc55cSDimitry Andric if (OutVal.Kind == DbgValue::Def ||
2867349cc55cSDimitry Andric (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2868bdd1243dSDimitry Andric !OutValOp.isUndef())) {
2869bdd1243dSDimitry Andric ValueIDNum ValToLookFor = OutValOp.ID;
2870e8d8bef9SDimitry Andric // Search the live-outs of the predecessor for the specified value.
2871e8d8bef9SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) {
2872e710425bSDimitry Andric if (MOutLocs[*p][I] == ValToLookFor)
2873e8d8bef9SDimitry Andric Locs.back().push_back(LocIdx(I));
2874e8d8bef9SDimitry Andric }
2875349cc55cSDimitry Andric } else {
2876349cc55cSDimitry Andric assert(OutVal.Kind == DbgValue::VPHI);
2877349cc55cSDimitry Andric // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2878349cc55cSDimitry Andric // a value that's live-through the whole loop. (It has to be a backedge,
2879349cc55cSDimitry Andric // because a block can't dominate itself). We can accept as a PHI location
2880349cc55cSDimitry Andric // any location where the other predecessors agree, _and_ the machine
2881349cc55cSDimitry Andric // locations feed back into themselves. Therefore, add all self-looping
2882349cc55cSDimitry Andric // machine-value PHI locations.
2883349cc55cSDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) {
2884349cc55cSDimitry Andric ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2885e710425bSDimitry Andric if (MOutLocs[*p][I] == MPHI)
2886349cc55cSDimitry Andric Locs.back().push_back(LocIdx(I));
2887349cc55cSDimitry Andric }
2888349cc55cSDimitry Andric }
2889e8d8bef9SDimitry Andric }
2890349cc55cSDimitry Andric // We should have found locations for all predecessors, or returned.
2891349cc55cSDimitry Andric assert(Locs.size() == BlockOrders.size());
2892e8d8bef9SDimitry Andric
2893e8d8bef9SDimitry Andric // Starting with the first set of locations, take the intersection with
2894e8d8bef9SDimitry Andric // subsequent sets.
2895349cc55cSDimitry Andric SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2896349cc55cSDimitry Andric for (unsigned int I = 1; I < Locs.size(); ++I) {
2897349cc55cSDimitry Andric auto &LocVec = Locs[I];
2898349cc55cSDimitry Andric SmallVector<LocIdx, 4> NewCandidates;
2899349cc55cSDimitry Andric std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2900349cc55cSDimitry Andric LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2901349cc55cSDimitry Andric CandidateLocs = NewCandidates;
2902e8d8bef9SDimitry Andric }
2903349cc55cSDimitry Andric if (CandidateLocs.empty())
2904bdd1243dSDimitry Andric return std::nullopt;
2905e8d8bef9SDimitry Andric
2906e8d8bef9SDimitry Andric // We now have a set of LocIdxes that contain the right output value in
2907e8d8bef9SDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc,
2908e8d8bef9SDimitry Andric // that'll be it.
2909349cc55cSDimitry Andric LocIdx L = *CandidateLocs.begin();
2910e8d8bef9SDimitry Andric
2911e8d8bef9SDimitry Andric // Return a PHI-value-number for the found location.
2912e8d8bef9SDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2913349cc55cSDimitry Andric return PHIVal;
2914e8d8bef9SDimitry Andric }
2915e8d8bef9SDimitry Andric
vlocJoin(MachineBasicBlock & MBB,LiveIdxT & VLOCOutLocs,SmallPtrSet<const MachineBasicBlock *,8> & BlocksToExplore,DbgValue & LiveIn)2916349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin(
2917349cc55cSDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2918e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2919349cc55cSDimitry Andric DbgValue &LiveIn) {
2920e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2921e8d8bef9SDimitry Andric bool Changed = false;
2922e8d8bef9SDimitry Andric
2923e8d8bef9SDimitry Andric // Order predecessors by RPOT order, for exploring them in that order.
2924fe6060f1SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2925e8d8bef9SDimitry Andric
2926e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2927e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B];
2928e8d8bef9SDimitry Andric };
2929e8d8bef9SDimitry Andric
2930e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp);
2931e8d8bef9SDimitry Andric
2932e8d8bef9SDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB];
2933e8d8bef9SDimitry Andric
2934349cc55cSDimitry Andric // Collect all the incoming DbgValues for this variable, from predecessor
2935349cc55cSDimitry Andric // live-out values.
2936e8d8bef9SDimitry Andric SmallVector<InValueT, 8> Values;
2937e8d8bef9SDimitry Andric bool Bail = false;
2938349cc55cSDimitry Andric int BackEdgesStart = 0;
2939fcaf7f86SDimitry Andric for (auto *p : BlockOrders) {
2940e8d8bef9SDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be
2941e8d8bef9SDimitry Andric // able to join any locations.
2942e8d8bef9SDimitry Andric if (!BlocksToExplore.contains(p)) {
2943e8d8bef9SDimitry Andric Bail = true;
2944e8d8bef9SDimitry Andric break;
2945e8d8bef9SDimitry Andric }
2946e8d8bef9SDimitry Andric
2947349cc55cSDimitry Andric // All Live-outs will have been initialized.
2948349cc55cSDimitry Andric DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2949e8d8bef9SDimitry Andric
2950e8d8bef9SDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on
2951e8d8bef9SDimitry Andric // BlockOrders being sorted by RPO.
2952e8d8bef9SDimitry Andric unsigned ThisBBRPONum = BBToOrder[p];
2953e8d8bef9SDimitry Andric if (ThisBBRPONum < CurBlockRPONum)
2954e8d8bef9SDimitry Andric ++BackEdgesStart;
2955e8d8bef9SDimitry Andric
2956349cc55cSDimitry Andric Values.push_back(std::make_pair(p, &OutLoc));
2957e8d8bef9SDimitry Andric }
2958e8d8bef9SDimitry Andric
2959e8d8bef9SDimitry Andric // If there were no values, or one of the predecessors couldn't have a
2960e8d8bef9SDimitry Andric // value, then give up immediately. It's not safe to produce a live-in
2961349cc55cSDimitry Andric // value. Leave as whatever it was before.
2962e8d8bef9SDimitry Andric if (Bail || Values.size() == 0)
2963349cc55cSDimitry Andric return false;
2964e8d8bef9SDimitry Andric
2965e8d8bef9SDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor.
2966e8d8bef9SDimitry Andric // Pick the variable value from the first of these, to compare against
2967e8d8bef9SDimitry Andric // all others.
2968e8d8bef9SDimitry Andric const DbgValue &FirstVal = *Values[0].second;
2969e8d8bef9SDimitry Andric
2970349cc55cSDimitry Andric // If the old live-in value is not a PHI then either a) no PHI is needed
2971349cc55cSDimitry Andric // here, or b) we eliminated the PHI that was here. If so, we can just
2972349cc55cSDimitry Andric // propagate in the first parent's incoming value.
2973349cc55cSDimitry Andric if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
2974349cc55cSDimitry Andric Changed = LiveIn != FirstVal;
2975349cc55cSDimitry Andric if (Changed)
2976349cc55cSDimitry Andric LiveIn = FirstVal;
2977349cc55cSDimitry Andric return Changed;
2978349cc55cSDimitry Andric }
2979349cc55cSDimitry Andric
2980349cc55cSDimitry Andric // Scan for variable values that can never be resolved: if they have
2981349cc55cSDimitry Andric // different DIExpressions, different indirectness, or are mixed constants /
2982e8d8bef9SDimitry Andric // non-constants.
2983bdd1243dSDimitry Andric for (const auto &V : Values) {
2984bdd1243dSDimitry Andric if (!V.second->Properties.isJoinable(FirstVal.Properties))
2985349cc55cSDimitry Andric return false;
2986349cc55cSDimitry Andric if (V.second->Kind == DbgValue::NoVal)
2987349cc55cSDimitry Andric return false;
2988bdd1243dSDimitry Andric if (!V.second->hasJoinableLocOps(FirstVal))
2989349cc55cSDimitry Andric return false;
2990e8d8bef9SDimitry Andric }
2991e8d8bef9SDimitry Andric
2992349cc55cSDimitry Andric // Try to eliminate this PHI. Do the incoming values all agree?
2993e8d8bef9SDimitry Andric bool Disagree = false;
2994e8d8bef9SDimitry Andric for (auto &V : Values) {
2995e8d8bef9SDimitry Andric if (*V.second == FirstVal)
2996e8d8bef9SDimitry Andric continue; // No disagreement.
2997e8d8bef9SDimitry Andric
2998bdd1243dSDimitry Andric // If both values are not equal but have equal non-empty IDs then they refer
2999bdd1243dSDimitry Andric // to the same value from different sources (e.g. one is VPHI and the other
3000bdd1243dSDimitry Andric // is Def), which does not cause disagreement.
3001bdd1243dSDimitry Andric if (V.second->hasIdenticalValidLocOps(FirstVal))
3002bdd1243dSDimitry Andric continue;
3003bdd1243dSDimitry Andric
3004349cc55cSDimitry Andric // Eliminate if a backedge feeds a VPHI back into itself.
3005349cc55cSDimitry Andric if (V.second->Kind == DbgValue::VPHI &&
3006349cc55cSDimitry Andric V.second->BlockNo == MBB.getNumber() &&
3007349cc55cSDimitry Andric // Is this a backedge?
3008349cc55cSDimitry Andric std::distance(Values.begin(), &V) >= BackEdgesStart)
3009349cc55cSDimitry Andric continue;
3010349cc55cSDimitry Andric
3011e8d8bef9SDimitry Andric Disagree = true;
3012e8d8bef9SDimitry Andric }
3013e8d8bef9SDimitry Andric
3014349cc55cSDimitry Andric // No disagreement -> live-through value.
3015349cc55cSDimitry Andric if (!Disagree) {
3016349cc55cSDimitry Andric Changed = LiveIn != FirstVal;
3017e8d8bef9SDimitry Andric if (Changed)
3018349cc55cSDimitry Andric LiveIn = FirstVal;
3019349cc55cSDimitry Andric return Changed;
3020349cc55cSDimitry Andric } else {
3021349cc55cSDimitry Andric // Otherwise use a VPHI.
3022349cc55cSDimitry Andric DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
3023349cc55cSDimitry Andric Changed = LiveIn != VPHI;
3024349cc55cSDimitry Andric if (Changed)
3025349cc55cSDimitry Andric LiveIn = VPHI;
3026349cc55cSDimitry Andric return Changed;
3027349cc55cSDimitry Andric }
3028e8d8bef9SDimitry Andric }
3029e8d8bef9SDimitry Andric
getBlocksForScope(const DILocation * DILoc,SmallPtrSetImpl<const MachineBasicBlock * > & BlocksToExplore,const SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks)30301fd87a68SDimitry Andric void InstrRefBasedLDV::getBlocksForScope(
30311fd87a68SDimitry Andric const DILocation *DILoc,
30321fd87a68SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
30331fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
30341fd87a68SDimitry Andric // Get the set of "normal" in-lexical-scope blocks.
30351fd87a68SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
30361fd87a68SDimitry Andric
30371fd87a68SDimitry Andric // VarLoc LiveDebugValues tracks variable locations that are defined in
30381fd87a68SDimitry Andric // blocks not in scope. This is something we could legitimately ignore, but
30391fd87a68SDimitry Andric // lets allow it for now for the sake of coverage.
30401fd87a68SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
30411fd87a68SDimitry Andric
30421fd87a68SDimitry Andric // Storage for artificial blocks we intend to add to BlocksToExplore.
30431fd87a68SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd;
30441fd87a68SDimitry Andric
30451fd87a68SDimitry Andric // To avoid needlessly dropping large volumes of variable locations, propagate
30461fd87a68SDimitry Andric // variables through aritifical blocks, i.e. those that don't have any
30471fd87a68SDimitry Andric // instructions in scope at all. To accurately replicate VarLoc
30481fd87a68SDimitry Andric // LiveDebugValues, this means exploring all artificial successors too.
30491fd87a68SDimitry Andric // Perform a depth-first-search to enumerate those blocks.
3050fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore) {
30511fd87a68SDimitry Andric // Depth-first-search state: each node is a block and which successor
30521fd87a68SDimitry Andric // we're currently exploring.
30531fd87a68SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *,
30541fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator>,
30551fd87a68SDimitry Andric 8>
30561fd87a68SDimitry Andric DFS;
30571fd87a68SDimitry Andric
30581fd87a68SDimitry Andric // Find any artificial successors not already tracked.
30591fd87a68SDimitry Andric for (auto *succ : MBB->successors()) {
30601fd87a68SDimitry Andric if (BlocksToExplore.count(succ))
30611fd87a68SDimitry Andric continue;
30621fd87a68SDimitry Andric if (!ArtificialBlocks.count(succ))
30631fd87a68SDimitry Andric continue;
30641fd87a68SDimitry Andric ToAdd.insert(succ);
30651fd87a68SDimitry Andric DFS.push_back({succ, succ->succ_begin()});
30661fd87a68SDimitry Andric }
30671fd87a68SDimitry Andric
30681fd87a68SDimitry Andric // Search all those blocks, depth first.
30691fd87a68SDimitry Andric while (!DFS.empty()) {
30701fd87a68SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first;
30711fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
30721fd87a68SDimitry Andric // Walk back if we've explored this blocks successors to the end.
30731fd87a68SDimitry Andric if (CurSucc == CurBB->succ_end()) {
30741fd87a68SDimitry Andric DFS.pop_back();
30751fd87a68SDimitry Andric continue;
30761fd87a68SDimitry Andric }
30771fd87a68SDimitry Andric
30781fd87a68SDimitry Andric // If the current successor is artificial and unexplored, descend into
30791fd87a68SDimitry Andric // it.
30801fd87a68SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
30811fd87a68SDimitry Andric ToAdd.insert(*CurSucc);
30821fd87a68SDimitry Andric DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
30831fd87a68SDimitry Andric continue;
30841fd87a68SDimitry Andric }
30851fd87a68SDimitry Andric
30861fd87a68SDimitry Andric ++CurSucc;
30871fd87a68SDimitry Andric }
30881fd87a68SDimitry Andric };
30891fd87a68SDimitry Andric
30901fd87a68SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
30911fd87a68SDimitry Andric }
30921fd87a68SDimitry Andric
buildVLocValueMap(const DILocation * DILoc,const SmallSet<DebugVariable,4> & VarsWeCareAbout,SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks,LiveInsT & Output,FuncValueTable & MOutLocs,FuncValueTable & MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs)30931fd87a68SDimitry Andric void InstrRefBasedLDV::buildVLocValueMap(
30941fd87a68SDimitry Andric const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
3095e8d8bef9SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
309681ad6265SDimitry Andric FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3097e8d8bef9SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) {
3098349cc55cSDimitry Andric // This method is much like buildMLocValueMap: but focuses on a single
3099e8d8bef9SDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are
3100e8d8bef9SDimitry Andric // to have their value assignments solved, then run our dataflow algorithm
3101e8d8bef9SDimitry Andric // until a fixedpoint is reached.
3102e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>,
3103e8d8bef9SDimitry Andric std::greater<unsigned int>>
3104e8d8bef9SDimitry Andric Worklist, Pending;
3105e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
3106e8d8bef9SDimitry Andric
3107e8d8bef9SDimitry Andric // The set of blocks we'll be examining.
3108e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3109e8d8bef9SDimitry Andric
3110e8d8bef9SDimitry Andric // The order in which to examine them (RPO).
3111e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders;
3112e8d8bef9SDimitry Andric
3113e8d8bef9SDimitry Andric // RPO ordering function.
3114e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3115e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B];
3116e8d8bef9SDimitry Andric };
3117e8d8bef9SDimitry Andric
31181fd87a68SDimitry Andric getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
3119e8d8bef9SDimitry Andric
3120e8d8bef9SDimitry Andric // Single block scope: not interesting! No propagation at all. Note that
3121e8d8bef9SDimitry Andric // this could probably go above ArtificialBlocks without damage, but
3122e8d8bef9SDimitry Andric // that then produces output differences from original-live-debug-values,
3123e8d8bef9SDimitry Andric // which propagates from a single block into many artificial ones.
3124e8d8bef9SDimitry Andric if (BlocksToExplore.size() == 1)
3125e8d8bef9SDimitry Andric return;
3126e8d8bef9SDimitry Andric
3127349cc55cSDimitry Andric // Convert a const set to a non-const set. LexicalScopes
3128349cc55cSDimitry Andric // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
3129349cc55cSDimitry Andric // (Neither of them mutate anything).
3130349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
3131349cc55cSDimitry Andric for (const auto *MBB : BlocksToExplore)
3132349cc55cSDimitry Andric MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
3133349cc55cSDimitry Andric
3134e8d8bef9SDimitry Andric // Picks out relevants blocks RPO order and sort them.
3135fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore)
3136e8d8bef9SDimitry Andric BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
3137e8d8bef9SDimitry Andric
3138e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp);
3139e8d8bef9SDimitry Andric unsigned NumBlocks = BlockOrders.size();
3140e8d8bef9SDimitry Andric
3141e8d8bef9SDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large.
3142349cc55cSDimitry Andric SmallVector<DbgValue, 32> LiveIns, LiveOuts;
3143349cc55cSDimitry Andric LiveIns.reserve(NumBlocks);
3144349cc55cSDimitry Andric LiveOuts.reserve(NumBlocks);
3145349cc55cSDimitry Andric
3146349cc55cSDimitry Andric // Initialize all values to start as NoVals. This signifies "it's live
3147349cc55cSDimitry Andric // through, but we don't know what it is".
3148bdd1243dSDimitry Andric DbgValueProperties EmptyProperties(EmptyExpr, false, false);
3149349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) {
3150349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3151349cc55cSDimitry Andric LiveIns.push_back(EmptyDbgValue);
3152349cc55cSDimitry Andric LiveOuts.push_back(EmptyDbgValue);
3153349cc55cSDimitry Andric }
3154e8d8bef9SDimitry Andric
3155e8d8bef9SDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3156e8d8bef9SDimitry Andric // vlocJoin.
3157e8d8bef9SDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx;
3158e8d8bef9SDimitry Andric LiveOutIdx.reserve(NumBlocks);
3159e8d8bef9SDimitry Andric LiveInIdx.reserve(NumBlocks);
3160e8d8bef9SDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) {
3161e8d8bef9SDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3162e8d8bef9SDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3163e8d8bef9SDimitry Andric }
3164e8d8bef9SDimitry Andric
3165349cc55cSDimitry Andric // Loop over each variable and place PHIs for it, then propagate values
3166349cc55cSDimitry Andric // between blocks. This keeps the locality of working on one lexical scope at
3167349cc55cSDimitry Andric // at time, but avoids re-processing variable values because some other
3168349cc55cSDimitry Andric // variable has been assigned.
3169fcaf7f86SDimitry Andric for (const auto &Var : VarsWeCareAbout) {
3170349cc55cSDimitry Andric // Re-initialize live-ins and live-outs, to clear the remains of previous
3171349cc55cSDimitry Andric // variables live-ins / live-outs.
3172349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) {
3173349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3174349cc55cSDimitry Andric LiveIns[I] = EmptyDbgValue;
3175349cc55cSDimitry Andric LiveOuts[I] = EmptyDbgValue;
3176349cc55cSDimitry Andric }
3177349cc55cSDimitry Andric
3178349cc55cSDimitry Andric // Place PHIs for variable values, using the LLVM IDF calculator.
3179349cc55cSDimitry Andric // Collect the set of blocks where variables are def'd.
3180349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
3181349cc55cSDimitry Andric for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
3182349cc55cSDimitry Andric auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
3183fe013be4SDimitry Andric if (TransferFunc.contains(Var))
3184349cc55cSDimitry Andric DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
3185349cc55cSDimitry Andric }
3186349cc55cSDimitry Andric
3187349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks;
3188349cc55cSDimitry Andric
31891fd87a68SDimitry Andric // Request the set of PHIs we should insert for this variable. If there's
31901fd87a68SDimitry Andric // only one value definition, things are very simple.
31911fd87a68SDimitry Andric if (DefBlocks.size() == 1) {
31921fd87a68SDimitry Andric placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
31931fd87a68SDimitry Andric AllTheVLocs, Var, Output);
31941fd87a68SDimitry Andric continue;
31951fd87a68SDimitry Andric }
31961fd87a68SDimitry Andric
31971fd87a68SDimitry Andric // Otherwise: we need to place PHIs through SSA and propagate values.
3198349cc55cSDimitry Andric BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
3199349cc55cSDimitry Andric
3200349cc55cSDimitry Andric // Insert PHIs into the per-block live-in tables for this variable.
3201349cc55cSDimitry Andric for (MachineBasicBlock *PHIMBB : PHIBlocks) {
3202349cc55cSDimitry Andric unsigned BlockNo = PHIMBB->getNumber();
3203349cc55cSDimitry Andric DbgValue *LiveIn = LiveInIdx[PHIMBB];
3204349cc55cSDimitry Andric *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
3205349cc55cSDimitry Andric }
3206349cc55cSDimitry Andric
3207e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) {
3208e8d8bef9SDimitry Andric Worklist.push(BBToOrder[MBB]);
3209e8d8bef9SDimitry Andric OnWorklist.insert(MBB);
3210e8d8bef9SDimitry Andric }
3211e8d8bef9SDimitry Andric
3212349cc55cSDimitry Andric // Iterate over all the blocks we selected, propagating the variables value.
3213349cc55cSDimitry Andric // This loop does two things:
3214349cc55cSDimitry Andric // * Eliminates un-necessary VPHIs in vlocJoin,
3215349cc55cSDimitry Andric // * Evaluates the blocks transfer function (i.e. variable assignments) and
3216349cc55cSDimitry Andric // stores the result to the blocks live-outs.
3217349cc55cSDimitry Andric // Always evaluate the transfer function on the first iteration, and when
3218349cc55cSDimitry Andric // the live-ins change thereafter.
3219e8d8bef9SDimitry Andric bool FirstTrip = true;
3220e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) {
3221e8d8bef9SDimitry Andric while (!Worklist.empty()) {
3222e8d8bef9SDimitry Andric auto *MBB = OrderToBB[Worklist.top()];
3223e8d8bef9SDimitry Andric CurBB = MBB->getNumber();
3224e8d8bef9SDimitry Andric Worklist.pop();
3225e8d8bef9SDimitry Andric
3226349cc55cSDimitry Andric auto LiveInsIt = LiveInIdx.find(MBB);
3227349cc55cSDimitry Andric assert(LiveInsIt != LiveInIdx.end());
3228349cc55cSDimitry Andric DbgValue *LiveIn = LiveInsIt->second;
3229e8d8bef9SDimitry Andric
3230e8d8bef9SDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output
3231e8d8bef9SDimitry Andric // into JoinedInLocs.
3232349cc55cSDimitry Andric bool InLocsChanged =
32334824e7fdSDimitry Andric vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
3234e8d8bef9SDimitry Andric
3235349cc55cSDimitry Andric SmallVector<const MachineBasicBlock *, 8> Preds;
3236349cc55cSDimitry Andric for (const auto *Pred : MBB->predecessors())
3237349cc55cSDimitry Andric Preds.push_back(Pred);
3238e8d8bef9SDimitry Andric
3239349cc55cSDimitry Andric // If this block's live-in value is a VPHI, try to pick a machine-value
3240349cc55cSDimitry Andric // for it. This makes the machine-value available and propagated
3241349cc55cSDimitry Andric // through all blocks by the time value propagation finishes. We can't
3242349cc55cSDimitry Andric // do this any earlier as it needs to read the block live-outs.
3243349cc55cSDimitry Andric if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
3244349cc55cSDimitry Andric // There's a small possibility that on a preceeding path, a VPHI is
3245349cc55cSDimitry Andric // eliminated and transitions from VPHI-with-location to
3246349cc55cSDimitry Andric // live-through-value. As a result, the selected location of any VPHI
3247349cc55cSDimitry Andric // might change, so we need to re-compute it on each iteration.
3248bdd1243dSDimitry Andric SmallVector<DbgOpID> JoinedOps;
3249e8d8bef9SDimitry Andric
3250bdd1243dSDimitry Andric if (pickVPHILoc(JoinedOps, *MBB, LiveOutIdx, MOutLocs, Preds)) {
3251bdd1243dSDimitry Andric bool NewLocPicked = !equal(LiveIn->getDbgOpIDs(), JoinedOps);
3252bdd1243dSDimitry Andric InLocsChanged |= NewLocPicked;
3253bdd1243dSDimitry Andric if (NewLocPicked)
3254bdd1243dSDimitry Andric LiveIn->setDbgOpIDs(JoinedOps);
3255349cc55cSDimitry Andric }
3256349cc55cSDimitry Andric }
3257e8d8bef9SDimitry Andric
3258349cc55cSDimitry Andric if (!InLocsChanged && !FirstTrip)
3259e8d8bef9SDimitry Andric continue;
3260e8d8bef9SDimitry Andric
3261349cc55cSDimitry Andric DbgValue *LiveOut = LiveOutIdx[MBB];
3262349cc55cSDimitry Andric bool OLChanged = false;
3263349cc55cSDimitry Andric
3264e8d8bef9SDimitry Andric // Do transfer function.
3265e8d8bef9SDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()];
3266349cc55cSDimitry Andric auto TransferIt = VTracker.Vars.find(Var);
3267349cc55cSDimitry Andric if (TransferIt != VTracker.Vars.end()) {
3268e8d8bef9SDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg).
3269349cc55cSDimitry Andric if (TransferIt->second.Kind == DbgValue::Undef) {
3270349cc55cSDimitry Andric DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
3271349cc55cSDimitry Andric if (*LiveOut != NewVal) {
3272349cc55cSDimitry Andric *LiveOut = NewVal;
3273349cc55cSDimitry Andric OLChanged = true;
3274349cc55cSDimitry Andric }
3275e8d8bef9SDimitry Andric } else {
3276e8d8bef9SDimitry Andric // Insert new variable value; or overwrite.
3277349cc55cSDimitry Andric if (*LiveOut != TransferIt->second) {
3278349cc55cSDimitry Andric *LiveOut = TransferIt->second;
3279349cc55cSDimitry Andric OLChanged = true;
3280e8d8bef9SDimitry Andric }
3281e8d8bef9SDimitry Andric }
3282349cc55cSDimitry Andric } else {
3283349cc55cSDimitry Andric // Just copy live-ins to live-outs, for anything not transferred.
3284349cc55cSDimitry Andric if (*LiveOut != *LiveIn) {
3285349cc55cSDimitry Andric *LiveOut = *LiveIn;
3286349cc55cSDimitry Andric OLChanged = true;
3287349cc55cSDimitry Andric }
3288e8d8bef9SDimitry Andric }
3289e8d8bef9SDimitry Andric
3290349cc55cSDimitry Andric // If no live-out value changed, there's no need to explore further.
3291e8d8bef9SDimitry Andric if (!OLChanged)
3292e8d8bef9SDimitry Andric continue;
3293e8d8bef9SDimitry Andric
3294e8d8bef9SDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge
3295e8d8bef9SDimitry Andric // successors during this dataflow iteration; book backedge successors
3296e8d8bef9SDimitry Andric // to be visited next time around.
3297fcaf7f86SDimitry Andric for (auto *s : MBB->successors()) {
3298e8d8bef9SDimitry Andric // Ignore out of scope / not-to-be-explored successors.
3299fe013be4SDimitry Andric if (!LiveInIdx.contains(s))
3300e8d8bef9SDimitry Andric continue;
3301e8d8bef9SDimitry Andric
3302e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) {
3303e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second)
3304e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]);
3305e8d8bef9SDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
3306e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]);
3307e8d8bef9SDimitry Andric }
3308e8d8bef9SDimitry Andric }
3309e8d8bef9SDimitry Andric }
3310e8d8bef9SDimitry Andric Worklist.swap(Pending);
3311e8d8bef9SDimitry Andric std::swap(OnWorklist, OnPending);
3312e8d8bef9SDimitry Andric OnPending.clear();
3313e8d8bef9SDimitry Andric assert(Pending.empty());
3314e8d8bef9SDimitry Andric FirstTrip = false;
3315e8d8bef9SDimitry Andric }
3316e8d8bef9SDimitry Andric
3317349cc55cSDimitry Andric // Save live-ins to output vector. Ignore any that are still marked as being
3318349cc55cSDimitry Andric // VPHIs with no location -- those are variables that we know the value of,
3319349cc55cSDimitry Andric // but are not actually available in the register file.
3320e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) {
3321349cc55cSDimitry Andric DbgValue *BlockLiveIn = LiveInIdx[MBB];
3322349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::NoVal)
3323e8d8bef9SDimitry Andric continue;
3324bdd1243dSDimitry Andric if (BlockLiveIn->isUnjoinedPHI())
3325349cc55cSDimitry Andric continue;
3326349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI)
3327349cc55cSDimitry Andric BlockLiveIn->Kind = DbgValue::Def;
33284824e7fdSDimitry Andric assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
33294824e7fdSDimitry Andric Var.getFragment() && "Fragment info missing during value prop");
3330349cc55cSDimitry Andric Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
3331e8d8bef9SDimitry Andric }
3332349cc55cSDimitry Andric } // Per-variable loop.
3333e8d8bef9SDimitry Andric
3334e8d8bef9SDimitry Andric BlockOrders.clear();
3335e8d8bef9SDimitry Andric BlocksToExplore.clear();
3336e8d8bef9SDimitry Andric }
3337e8d8bef9SDimitry Andric
placePHIsForSingleVarDefinition(const SmallPtrSetImpl<MachineBasicBlock * > & InScopeBlocks,MachineBasicBlock * AssignMBB,SmallVectorImpl<VLocTracker> & AllTheVLocs,const DebugVariable & Var,LiveInsT & Output)33381fd87a68SDimitry Andric void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
33391fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
33401fd87a68SDimitry Andric MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
33411fd87a68SDimitry Andric const DebugVariable &Var, LiveInsT &Output) {
33421fd87a68SDimitry Andric // If there is a single definition of the variable, then working out it's
33431fd87a68SDimitry Andric // value everywhere is very simple: it's every block dominated by the
33441fd87a68SDimitry Andric // definition. At the dominance frontier, the usual algorithm would:
33451fd87a68SDimitry Andric // * Place PHIs,
33461fd87a68SDimitry Andric // * Propagate values into them,
33471fd87a68SDimitry Andric // * Find there's no incoming variable value from the other incoming branches
33481fd87a68SDimitry Andric // of the dominance frontier,
33491fd87a68SDimitry Andric // * Specify there's no variable value in blocks past the frontier.
33501fd87a68SDimitry Andric // This is a common case, hence it's worth special-casing it.
33511fd87a68SDimitry Andric
33521fd87a68SDimitry Andric // Pick out the variables value from the block transfer function.
33531fd87a68SDimitry Andric VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
33541fd87a68SDimitry Andric auto ValueIt = VLocs.Vars.find(Var);
33551fd87a68SDimitry Andric const DbgValue &Value = ValueIt->second;
33561fd87a68SDimitry Andric
3357d56accc7SDimitry Andric // If it's an explicit assignment of "undef", that means there is no location
3358d56accc7SDimitry Andric // anyway, anywhere.
3359d56accc7SDimitry Andric if (Value.Kind == DbgValue::Undef)
3360d56accc7SDimitry Andric return;
3361d56accc7SDimitry Andric
33621fd87a68SDimitry Andric // Assign the variable value to entry to each dominated block that's in scope.
33631fd87a68SDimitry Andric // Skip the definition block -- it's assigned the variable value in the middle
33641fd87a68SDimitry Andric // of the block somewhere.
33651fd87a68SDimitry Andric for (auto *ScopeBlock : InScopeBlocks) {
33661fd87a68SDimitry Andric if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
33671fd87a68SDimitry Andric continue;
33681fd87a68SDimitry Andric
33691fd87a68SDimitry Andric Output[ScopeBlock->getNumber()].push_back({Var, Value});
33701fd87a68SDimitry Andric }
33711fd87a68SDimitry Andric
33721fd87a68SDimitry Andric // All blocks that aren't dominated have no live-in value, thus no variable
33731fd87a68SDimitry Andric // value will be given to them.
33741fd87a68SDimitry Andric }
33751fd87a68SDimitry Andric
3376e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump_mloc_transfer(const MLocTransferMap & mloc_transfer) const3377e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer(
3378e8d8bef9SDimitry Andric const MLocTransferMap &mloc_transfer) const {
3379fcaf7f86SDimitry Andric for (const auto &P : mloc_transfer) {
3380e8d8bef9SDimitry Andric std::string foo = MTracker->LocIdxToName(P.first);
3381e8d8bef9SDimitry Andric std::string bar = MTracker->IDAsString(P.second);
3382e8d8bef9SDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n";
3383e8d8bef9SDimitry Andric }
3384e8d8bef9SDimitry Andric }
3385e8d8bef9SDimitry Andric #endif
3386e8d8bef9SDimitry Andric
initialSetup(MachineFunction & MF)3387e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3388e8d8bef9SDimitry Andric // Build some useful data structures.
3389349cc55cSDimitry Andric
3390349cc55cSDimitry Andric LLVMContext &Context = MF.getFunction().getContext();
3391349cc55cSDimitry Andric EmptyExpr = DIExpression::get(Context, {});
3392349cc55cSDimitry Andric
3393e8d8bef9SDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3394e8d8bef9SDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc())
3395e8d8bef9SDimitry Andric return DL.getLine() != 0;
3396e8d8bef9SDimitry Andric return false;
3397e8d8bef9SDimitry Andric };
3398e8d8bef9SDimitry Andric // Collect a set of all the artificial blocks.
3399e8d8bef9SDimitry Andric for (auto &MBB : MF)
3400e8d8bef9SDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation))
3401e8d8bef9SDimitry Andric ArtificialBlocks.insert(&MBB);
3402e8d8bef9SDimitry Andric
3403e8d8bef9SDimitry Andric // Compute mappings of block <=> RPO order.
3404e8d8bef9SDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3405e8d8bef9SDimitry Andric unsigned int RPONumber = 0;
3406bdd1243dSDimitry Andric auto processMBB = [&](MachineBasicBlock *MBB) {
3407fe6060f1SDimitry Andric OrderToBB[RPONumber] = MBB;
3408fe6060f1SDimitry Andric BBToOrder[MBB] = RPONumber;
3409fe6060f1SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber;
3410e8d8bef9SDimitry Andric ++RPONumber;
3411bdd1243dSDimitry Andric };
3412bdd1243dSDimitry Andric for (MachineBasicBlock *MBB : RPOT)
3413bdd1243dSDimitry Andric processMBB(MBB);
3414bdd1243dSDimitry Andric for (MachineBasicBlock &MBB : MF)
3415fe013be4SDimitry Andric if (!BBToOrder.contains(&MBB))
3416bdd1243dSDimitry Andric processMBB(&MBB);
3417fe6060f1SDimitry Andric
3418fe6060f1SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup.
3419fe6060f1SDimitry Andric llvm::sort(MF.DebugValueSubstitutions);
3420fe6060f1SDimitry Andric
3421fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS
3422fe6060f1SDimitry Andric // As an expensive check, test whether there are any duplicate substitution
3423fe6060f1SDimitry Andric // sources in the collection.
3424fe6060f1SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) {
3425fe6060f1SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin();
3426fe6060f1SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
3427fe6060f1SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location "
3428fe6060f1SDimitry Andric "substitution seen");
3429fe6060f1SDimitry Andric }
3430fe6060f1SDimitry Andric }
3431fe6060f1SDimitry Andric #endif
3432e8d8bef9SDimitry Andric }
3433e8d8bef9SDimitry Andric
3434d56accc7SDimitry Andric // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
3435d56accc7SDimitry Andric // lexical scope it's used in. When exploring in DFS order and we pass that
3436d56accc7SDimitry Andric // scope, the block can be processed and any tracking information freed.
makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> & EjectionMap,const ScopeToDILocT & ScopeToDILocation,ScopeToAssignBlocksT & ScopeToAssignBlocks)3437d56accc7SDimitry Andric void InstrRefBasedLDV::makeDepthFirstEjectionMap(
3438d56accc7SDimitry Andric SmallVectorImpl<unsigned> &EjectionMap,
3439d56accc7SDimitry Andric const ScopeToDILocT &ScopeToDILocation,
3440d56accc7SDimitry Andric ScopeToAssignBlocksT &ScopeToAssignBlocks) {
3441d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3442d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3443d56accc7SDimitry Andric auto *TopScope = LS.getCurrentFunctionScope();
3444d56accc7SDimitry Andric
3445d56accc7SDimitry Andric // Unlike lexical scope explorers, we explore in reverse order, to find the
3446d56accc7SDimitry Andric // "last" lexical scope used for each block early.
3447d56accc7SDimitry Andric WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
3448d56accc7SDimitry Andric
3449d56accc7SDimitry Andric while (!WorkStack.empty()) {
3450d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back();
3451d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first;
3452d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second--;
3453d56accc7SDimitry Andric
3454d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3455d56accc7SDimitry Andric if (ChildNum >= 0) {
3456d56accc7SDimitry Andric // If ChildNum is positive, there are remaining children to explore.
3457d56accc7SDimitry Andric // Push the child and its children-count onto the stack.
3458d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum];
3459d56accc7SDimitry Andric WorkStack.push_back(
3460d56accc7SDimitry Andric std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
3461d56accc7SDimitry Andric } else {
3462d56accc7SDimitry Andric WorkStack.pop_back();
3463d56accc7SDimitry Andric
3464d56accc7SDimitry Andric // We've explored all children and any later blocks: examine all blocks
3465d56accc7SDimitry Andric // in our scope. If they haven't yet had an ejection number set, then
3466d56accc7SDimitry Andric // this scope will be the last to use that block.
3467d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS);
3468d56accc7SDimitry Andric if (DILocationIt != ScopeToDILocation.end()) {
3469d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore,
3470d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second);
3471fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore) {
3472d56accc7SDimitry Andric unsigned BBNum = MBB->getNumber();
3473d56accc7SDimitry Andric if (EjectionMap[BBNum] == 0)
3474d56accc7SDimitry Andric EjectionMap[BBNum] = WS->getDFSOut();
3475d56accc7SDimitry Andric }
3476d56accc7SDimitry Andric
3477d56accc7SDimitry Andric BlocksToExplore.clear();
3478d56accc7SDimitry Andric }
3479d56accc7SDimitry Andric }
3480d56accc7SDimitry Andric }
3481d56accc7SDimitry Andric }
3482d56accc7SDimitry Andric
depthFirstVLocAndEmit(unsigned MaxNumBlocks,const ScopeToDILocT & ScopeToDILocation,const ScopeToVarsT & ScopeToVars,ScopeToAssignBlocksT & ScopeToAssignBlocks,LiveInsT & Output,FuncValueTable & MOutLocs,FuncValueTable & MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs,MachineFunction & MF,DenseMap<DebugVariable,unsigned> & AllVarsNumbering,const TargetPassConfig & TPC)3483d56accc7SDimitry Andric bool InstrRefBasedLDV::depthFirstVLocAndEmit(
3484d56accc7SDimitry Andric unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
3485d56accc7SDimitry Andric const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
348681ad6265SDimitry Andric LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3487d56accc7SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
3488d56accc7SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
3489d56accc7SDimitry Andric const TargetPassConfig &TPC) {
3490d56accc7SDimitry Andric TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
3491d56accc7SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
3492d56accc7SDimitry Andric VTracker = nullptr;
3493d56accc7SDimitry Andric
3494d56accc7SDimitry Andric // No scopes? No variable locations.
349581ad6265SDimitry Andric if (!LS.getCurrentFunctionScope())
3496d56accc7SDimitry Andric return false;
3497d56accc7SDimitry Andric
3498d56accc7SDimitry Andric // Build map from block number to the last scope that uses the block.
3499d56accc7SDimitry Andric SmallVector<unsigned, 16> EjectionMap;
3500d56accc7SDimitry Andric EjectionMap.resize(MaxNumBlocks, 0);
3501d56accc7SDimitry Andric makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
3502d56accc7SDimitry Andric ScopeToAssignBlocks);
3503d56accc7SDimitry Andric
3504d56accc7SDimitry Andric // Helper lambda for ejecting a block -- if nothing is going to use the block,
3505d56accc7SDimitry Andric // we can translate the variable location information into DBG_VALUEs and then
3506d56accc7SDimitry Andric // free all of InstrRefBasedLDV's data structures.
3507d56accc7SDimitry Andric auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
3508d56accc7SDimitry Andric unsigned BBNum = MBB.getNumber();
3509d56accc7SDimitry Andric AllTheVLocs[BBNum].clear();
3510d56accc7SDimitry Andric
3511d56accc7SDimitry Andric // Prime the transfer-tracker, and then step through all the block
3512d56accc7SDimitry Andric // instructions, installing transfers.
3513d56accc7SDimitry Andric MTracker->reset();
3514e710425bSDimitry Andric MTracker->loadFromArray(MInLocs[MBB], BBNum);
3515e710425bSDimitry Andric TTracker->loadInlocs(MBB, MInLocs[MBB], DbgOpStore, Output[BBNum], NumLocs);
3516d56accc7SDimitry Andric
3517d56accc7SDimitry Andric CurBB = BBNum;
3518d56accc7SDimitry Andric CurInst = 1;
3519d56accc7SDimitry Andric for (auto &MI : MBB) {
3520c9157d92SDimitry Andric process(MI, &MOutLocs, &MInLocs);
3521d56accc7SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator());
3522d56accc7SDimitry Andric ++CurInst;
3523d56accc7SDimitry Andric }
3524d56accc7SDimitry Andric
3525d56accc7SDimitry Andric // Free machine-location tables for this block.
3526e710425bSDimitry Andric MInLocs.ejectTableForBlock(MBB);
3527e710425bSDimitry Andric MOutLocs.ejectTableForBlock(MBB);
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)
3592e710425bSDimitry Andric if (MInLocs.hasTableFor(*MBB))
3593d56accc7SDimitry Andric EjectBlock(*MBB);
3594d56accc7SDimitry Andric
3595d56accc7SDimitry Andric return emitTransfers(AllVarsNumbering);
3596d56accc7SDimitry Andric }
3597d56accc7SDimitry Andric
emitTransfers(DenseMap<DebugVariable,unsigned> & AllVarsNumbering)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.
ExtendRanges(MachineFunction & MF,MachineDominatorTree * DomTree,TargetPassConfig * TPC,unsigned InputBBLimit,unsigned InputDbgValLimit)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.
3691e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
3692e710425bSDimitry Andric FuncValueTable MOutLocs(MaxNumBlocks, NumLocs);
3693e710425bSDimitry Andric FuncValueTable MInLocs(MaxNumBlocks, NumLocs);
3694e8d8bef9SDimitry Andric
3695e8d8bef9SDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function,
3696e8d8bef9SDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use
3697e8d8bef9SDimitry Andric // both live-ins and live-outs for decision making in the variable value
3698e8d8bef9SDimitry Andric // dataflow problem.
3699349cc55cSDimitry Andric buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3700e8d8bef9SDimitry Andric
3701fe6060f1SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into
3702fe6060f1SDimitry Andric // either live-through machine values, or PHIs.
3703fe6060f1SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) {
3704fe6060f1SDimitry Andric // Identify unresolved block-live-ins.
370581ad6265SDimitry Andric if (!DBG_PHI.ValueRead)
370681ad6265SDimitry Andric continue;
370781ad6265SDimitry Andric
370881ad6265SDimitry Andric ValueIDNum &Num = *DBG_PHI.ValueRead;
3709fe6060f1SDimitry Andric if (!Num.isPHI())
3710fe6060f1SDimitry Andric continue;
3711fe6060f1SDimitry Andric
3712fe6060f1SDimitry Andric unsigned BlockNo = Num.getBlock();
3713fe6060f1SDimitry Andric LocIdx LocNo = Num.getLoc();
3714fe013be4SDimitry Andric ValueIDNum ResolvedValue = MInLocs[BlockNo][LocNo.asU64()];
3715fe013be4SDimitry Andric // If there is no resolved value for this live-in then it is not directly
3716fe013be4SDimitry Andric // reachable from the entry block -- model it as a PHI on entry to this
3717fe013be4SDimitry Andric // block, which means we leave the ValueIDNum unchanged.
3718fe013be4SDimitry Andric if (ResolvedValue != ValueIDNum::EmptyValue)
3719fe013be4SDimitry Andric Num = ResolvedValue;
3720fe6060f1SDimitry Andric }
3721fe6060f1SDimitry Andric // Later, we'll be looking up ranges of instruction numbers.
3722fe6060f1SDimitry Andric llvm::sort(DebugPHINumToValue);
3723fe6060f1SDimitry Andric
3724e8d8bef9SDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE
3725e8d8bef9SDimitry Andric // instructions and recording what machine value their operands refer to.
3726e8d8bef9SDimitry Andric for (auto &OrderPair : OrderToBB) {
3727e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *OrderPair.second;
3728e8d8bef9SDimitry Andric CurBB = MBB.getNumber();
3729e8d8bef9SDimitry Andric VTracker = &vlocs[CurBB];
3730e8d8bef9SDimitry Andric VTracker->MBB = &MBB;
3731e710425bSDimitry Andric MTracker->loadFromArray(MInLocs[MBB], CurBB);
3732e8d8bef9SDimitry Andric CurInst = 1;
3733e8d8bef9SDimitry Andric for (auto &MI : MBB) {
3734c9157d92SDimitry Andric process(MI, &MOutLocs, &MInLocs);
3735e8d8bef9SDimitry Andric ++CurInst;
3736e8d8bef9SDimitry Andric }
3737e8d8bef9SDimitry Andric MTracker->reset();
3738e8d8bef9SDimitry Andric }
3739e8d8bef9SDimitry Andric
3740e8d8bef9SDimitry Andric // Number all variables in the order that they appear, to be used as a stable
3741e8d8bef9SDimitry Andric // insertion order later.
3742e8d8bef9SDimitry Andric DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3743e8d8bef9SDimitry Andric
3744e8d8bef9SDimitry Andric // Map from one LexicalScope to all the variables in that scope.
37451fd87a68SDimitry Andric ScopeToVarsT ScopeToVars;
3746e8d8bef9SDimitry Andric
37471fd87a68SDimitry Andric // Map from One lexical scope to all blocks where assignments happen for
37481fd87a68SDimitry Andric // that scope.
37491fd87a68SDimitry Andric ScopeToAssignBlocksT ScopeToAssignBlocks;
3750e8d8bef9SDimitry Andric
37511fd87a68SDimitry Andric // Store map of DILocations that describes scopes.
37521fd87a68SDimitry Andric ScopeToDILocT ScopeToDILocation;
3753e8d8bef9SDimitry Andric
3754e8d8bef9SDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3755e8d8bef9SDimitry Andric // the order is unimportant, it just has to be stable.
3756349cc55cSDimitry Andric unsigned VarAssignCount = 0;
3757e8d8bef9SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3758e8d8bef9SDimitry Andric auto *MBB = OrderToBB[I];
3759e8d8bef9SDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()];
3760e8d8bef9SDimitry Andric // Collect each variable with a DBG_VALUE in this block.
3761e8d8bef9SDimitry Andric for (auto &idx : VTracker->Vars) {
3762e8d8bef9SDimitry Andric const auto &Var = idx.first;
3763e8d8bef9SDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[Var];
3764e8d8bef9SDimitry Andric assert(ScopeLoc != nullptr);
3765e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc);
3766e8d8bef9SDimitry Andric
3767e8d8bef9SDimitry Andric // No insts in scope -> shouldn't have been recorded.
3768e8d8bef9SDimitry Andric assert(Scope != nullptr);
3769e8d8bef9SDimitry Andric
3770e8d8bef9SDimitry Andric AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3771e8d8bef9SDimitry Andric ScopeToVars[Scope].insert(Var);
37721fd87a68SDimitry Andric ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
3773e8d8bef9SDimitry Andric ScopeToDILocation[Scope] = ScopeLoc;
3774349cc55cSDimitry Andric ++VarAssignCount;
3775e8d8bef9SDimitry Andric }
3776e8d8bef9SDimitry Andric }
3777e8d8bef9SDimitry Andric
3778349cc55cSDimitry Andric bool Changed = false;
3779349cc55cSDimitry Andric
3780349cc55cSDimitry Andric // If we have an extremely large number of variable assignments and blocks,
3781349cc55cSDimitry Andric // bail out at this point. We've burnt some time doing analysis already,
3782349cc55cSDimitry Andric // however we should cut our losses.
3783349cc55cSDimitry Andric if ((unsigned)MaxNumBlocks > InputBBLimit &&
3784349cc55cSDimitry Andric VarAssignCount > InputDbgValLimit) {
3785349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3786349cc55cSDimitry Andric << " has " << MaxNumBlocks << " basic blocks and "
3787349cc55cSDimitry Andric << VarAssignCount
3788349cc55cSDimitry Andric << " variable assignments, exceeding limits.\n");
3789d56accc7SDimitry Andric } else {
3790d56accc7SDimitry Andric // Optionally, solve the variable value problem and emit to blocks by using
3791d56accc7SDimitry Andric // a lexical-scope-depth search. It should be functionally identical to
3792d56accc7SDimitry Andric // the "else" block of this condition.
3793d56accc7SDimitry Andric Changed = depthFirstVLocAndEmit(
3794d56accc7SDimitry Andric MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
3795d56accc7SDimitry Andric SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC);
3796d56accc7SDimitry Andric }
3797d56accc7SDimitry Andric
3798e8d8bef9SDimitry Andric delete MTracker;
3799e8d8bef9SDimitry Andric delete TTracker;
3800e8d8bef9SDimitry Andric MTracker = nullptr;
3801e8d8bef9SDimitry Andric VTracker = nullptr;
3802e8d8bef9SDimitry Andric TTracker = nullptr;
3803e8d8bef9SDimitry Andric
3804e8d8bef9SDimitry Andric ArtificialBlocks.clear();
3805e8d8bef9SDimitry Andric OrderToBB.clear();
3806e8d8bef9SDimitry Andric BBToOrder.clear();
3807e8d8bef9SDimitry Andric BBNumToRPO.clear();
3808e8d8bef9SDimitry Andric DebugInstrNumToInstr.clear();
3809fe6060f1SDimitry Andric DebugPHINumToValue.clear();
38104824e7fdSDimitry Andric OverlapFragments.clear();
38114824e7fdSDimitry Andric SeenFragments.clear();
3812d56accc7SDimitry Andric SeenDbgPHIs.clear();
3813bdd1243dSDimitry Andric DbgOpStore.clear();
3814e8d8bef9SDimitry Andric
3815e8d8bef9SDimitry Andric return Changed;
3816e8d8bef9SDimitry Andric }
3817e8d8bef9SDimitry Andric
makeInstrRefBasedLiveDebugValues()3818e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3819e8d8bef9SDimitry Andric return new InstrRefBasedLDV();
3820e8d8bef9SDimitry Andric }
3821fe6060f1SDimitry Andric
3822fe6060f1SDimitry Andric namespace {
3823fe6060f1SDimitry Andric class LDVSSABlock;
3824fe6060f1SDimitry Andric class LDVSSAUpdater;
3825fe6060f1SDimitry Andric
3826fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We
3827fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater
3828fe6060f1SDimitry Andric // expects to zero-initialize the type.
3829fe6060f1SDimitry Andric typedef uint64_t BlockValueNum;
3830fe6060f1SDimitry Andric
3831fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block
3832fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming
3833fe6060f1SDimitry Andric /// values from parent blocks.
3834fe6060f1SDimitry Andric class LDVSSAPhi {
3835fe6060f1SDimitry Andric public:
3836fe6060f1SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3837fe6060f1SDimitry Andric LDVSSABlock *ParentBlock;
3838fe6060f1SDimitry Andric BlockValueNum PHIValNum;
LDVSSAPhi(BlockValueNum PHIValNum,LDVSSABlock * ParentBlock)3839fe6060f1SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3840fe6060f1SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3841fe6060f1SDimitry Andric
getParent()3842fe6060f1SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; }
3843fe6060f1SDimitry Andric };
3844fe6060f1SDimitry Andric
3845fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a
3846fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock.
3847fe6060f1SDimitry Andric class LDVSSABlockIterator {
3848fe6060f1SDimitry Andric public:
3849fe6060f1SDimitry Andric MachineBasicBlock::pred_iterator PredIt;
3850fe6060f1SDimitry Andric LDVSSAUpdater &Updater;
3851fe6060f1SDimitry Andric
LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,LDVSSAUpdater & Updater)3852fe6060f1SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3853fe6060f1SDimitry Andric LDVSSAUpdater &Updater)
3854fe6060f1SDimitry Andric : PredIt(PredIt), Updater(Updater) {}
3855fe6060f1SDimitry Andric
operator !=(const LDVSSABlockIterator & OtherIt) const3856fe6060f1SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3857fe6060f1SDimitry Andric return OtherIt.PredIt != PredIt;
3858fe6060f1SDimitry Andric }
3859fe6060f1SDimitry Andric
operator ++()3860fe6060f1SDimitry Andric LDVSSABlockIterator &operator++() {
3861fe6060f1SDimitry Andric ++PredIt;
3862fe6060f1SDimitry Andric return *this;
3863fe6060f1SDimitry Andric }
3864fe6060f1SDimitry Andric
3865fe6060f1SDimitry Andric LDVSSABlock *operator*();
3866fe6060f1SDimitry Andric };
3867fe6060f1SDimitry Andric
3868fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because
3869fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary
3870fe6060f1SDimitry Andric /// in this block.
3871fe6060f1SDimitry Andric class LDVSSABlock {
3872fe6060f1SDimitry Andric public:
3873fe6060f1SDimitry Andric MachineBasicBlock &BB;
3874fe6060f1SDimitry Andric LDVSSAUpdater &Updater;
3875fe6060f1SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>;
3876fe6060f1SDimitry Andric /// List of PHIs in this block. There should only ever be one.
3877fe6060f1SDimitry Andric PHIListT PHIList;
3878fe6060f1SDimitry Andric
LDVSSABlock(MachineBasicBlock & BB,LDVSSAUpdater & Updater)3879fe6060f1SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3880fe6060f1SDimitry Andric : BB(BB), Updater(Updater) {}
3881fe6060f1SDimitry Andric
succ_begin()3882fe6060f1SDimitry Andric LDVSSABlockIterator succ_begin() {
3883fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater);
3884fe6060f1SDimitry Andric }
3885fe6060f1SDimitry Andric
succ_end()3886fe6060f1SDimitry Andric LDVSSABlockIterator succ_end() {
3887fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater);
3888fe6060f1SDimitry Andric }
3889fe6060f1SDimitry Andric
3890fe6060f1SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record.
newPHI(BlockValueNum Value)3891fe6060f1SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) {
3892fe6060f1SDimitry Andric PHIList.emplace_back(Value, this);
3893fe6060f1SDimitry Andric return &PHIList.back();
3894fe6060f1SDimitry Andric }
3895fe6060f1SDimitry Andric
3896fe6060f1SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block.
phis()3897fe6060f1SDimitry Andric PHIListT &phis() { return PHIList; }
3898fe6060f1SDimitry Andric };
3899fe6060f1SDimitry Andric
3900fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3901fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3902fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>.
3903fe6060f1SDimitry Andric class LDVSSAUpdater {
3904fe6060f1SDimitry Andric public:
3905fe6060f1SDimitry Andric /// Map of value numbers to PHI records.
3906fe6060f1SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3907fe6060f1SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not
3908fe6060f1SDimitry Andric /// dominated by any Def.
3909fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3910fe6060f1SDimitry Andric /// Map of machine blocks to our own records of them.
3911fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3912fe6060f1SDimitry Andric /// Machine location where any PHI must occur.
3913fe6060f1SDimitry Andric LocIdx Loc;
3914fe6060f1SDimitry Andric /// Table of live-in machine value numbers for blocks / locations.
3915c9157d92SDimitry Andric const FuncValueTable &MLiveIns;
3916fe6060f1SDimitry Andric
LDVSSAUpdater(LocIdx L,const FuncValueTable & MLiveIns)3917c9157d92SDimitry Andric LDVSSAUpdater(LocIdx L, const FuncValueTable &MLiveIns)
391881ad6265SDimitry Andric : Loc(L), MLiveIns(MLiveIns) {}
3919fe6060f1SDimitry Andric
reset()3920fe6060f1SDimitry Andric void reset() {
3921fe6060f1SDimitry Andric for (auto &Block : BlockMap)
3922fe6060f1SDimitry Andric delete Block.second;
3923fe6060f1SDimitry Andric
3924fe6060f1SDimitry Andric PHIs.clear();
3925fe6060f1SDimitry Andric UndefMap.clear();
3926fe6060f1SDimitry Andric BlockMap.clear();
3927fe6060f1SDimitry Andric }
3928fe6060f1SDimitry Andric
~LDVSSAUpdater()3929fe6060f1SDimitry Andric ~LDVSSAUpdater() { reset(); }
3930fe6060f1SDimitry Andric
3931fe6060f1SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the
3932fe6060f1SDimitry Andric /// LDVSSAUpdater block map.
getSSALDVBlock(MachineBasicBlock * BB)3933fe6060f1SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3934fe6060f1SDimitry Andric auto it = BlockMap.find(BB);
3935fe6060f1SDimitry Andric if (it == BlockMap.end()) {
3936fe6060f1SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this);
3937fe6060f1SDimitry Andric it = BlockMap.find(BB);
3938fe6060f1SDimitry Andric }
3939fe6060f1SDimitry Andric return it->second;
3940fe6060f1SDimitry Andric }
3941fe6060f1SDimitry Andric
3942fe6060f1SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at
3943fe6060f1SDimitry Andric /// the PHI location on entry.
getValue(LDVSSABlock * LDVBB)3944fe6060f1SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) {
3945e710425bSDimitry Andric return MLiveIns[LDVBB->BB][Loc.asU64()].asU64();
3946fe6060f1SDimitry Andric }
3947fe6060f1SDimitry Andric };
3948fe6060f1SDimitry Andric
operator *()3949fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() {
3950fe6060f1SDimitry Andric return Updater.getSSALDVBlock(*PredIt);
3951fe6060f1SDimitry Andric }
3952fe6060f1SDimitry Andric
3953fe6060f1SDimitry Andric #ifndef NDEBUG
3954fe6060f1SDimitry Andric
operator <<(raw_ostream & out,const LDVSSAPhi & PHI)3955fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3956fe6060f1SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum;
3957fe6060f1SDimitry Andric return out;
3958fe6060f1SDimitry Andric }
3959fe6060f1SDimitry Andric
3960fe6060f1SDimitry Andric #endif
3961fe6060f1SDimitry Andric
3962fe6060f1SDimitry Andric } // namespace
3963fe6060f1SDimitry Andric
3964fe6060f1SDimitry Andric namespace llvm {
3965fe6060f1SDimitry Andric
3966fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value
3967fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the
3968fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define.
3969fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them.
3970fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3971fe6060f1SDimitry Andric public:
3972fe6060f1SDimitry Andric using BlkT = LDVSSABlock;
3973fe6060f1SDimitry Andric using ValT = BlockValueNum;
3974fe6060f1SDimitry Andric using PhiT = LDVSSAPhi;
3975fe6060f1SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator;
3976fe6060f1SDimitry Andric
3977fe6060f1SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class.
BlkSucc_begin(BlkT * BB)3978fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
BlkSucc_end(BlkT * BB)3979fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3980fe6060f1SDimitry Andric
3981fe6060f1SDimitry Andric /// Iterator for PHI operands.
3982fe6060f1SDimitry Andric class PHI_iterator {
3983fe6060f1SDimitry Andric private:
3984fe6060f1SDimitry Andric LDVSSAPhi *PHI;
3985fe6060f1SDimitry Andric unsigned Idx;
3986fe6060f1SDimitry Andric
3987fe6060f1SDimitry Andric public:
PHI_iterator(LDVSSAPhi * P)3988fe6060f1SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3989fe6060f1SDimitry Andric : PHI(P), Idx(0) {}
PHI_iterator(LDVSSAPhi * P,bool)3990fe6060f1SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3991fe6060f1SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {}
3992fe6060f1SDimitry Andric
operator ++()3993fe6060f1SDimitry Andric PHI_iterator &operator++() {
3994fe6060f1SDimitry Andric Idx++;
3995fe6060f1SDimitry Andric return *this;
3996fe6060f1SDimitry Andric }
operator ==(const PHI_iterator & X) const3997fe6060f1SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
operator !=(const PHI_iterator & X) const3998fe6060f1SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3999fe6060f1SDimitry Andric
getIncomingValue()4000fe6060f1SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
4001fe6060f1SDimitry Andric
getIncomingBlock()4002fe6060f1SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
4003fe6060f1SDimitry Andric };
4004fe6060f1SDimitry Andric
PHI_begin(PhiT * PHI)4005fe6060f1SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
4006fe6060f1SDimitry Andric
PHI_end(PhiT * PHI)4007fe6060f1SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) {
4008fe6060f1SDimitry Andric return PHI_iterator(PHI, true);
4009fe6060f1SDimitry Andric }
4010fe6060f1SDimitry Andric
4011fe6060f1SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
4012fe6060f1SDimitry Andric /// vector.
FindPredecessorBlocks(LDVSSABlock * BB,SmallVectorImpl<LDVSSABlock * > * Preds)4013fe6060f1SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB,
4014fe6060f1SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) {
4015349cc55cSDimitry Andric for (MachineBasicBlock *Pred : BB->BB.predecessors())
4016349cc55cSDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
4017fe6060f1SDimitry Andric }
4018fe6060f1SDimitry Andric
4019fe6060f1SDimitry Andric /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
4020fe6060f1SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having
4021fe6060f1SDimitry Andric /// any DBG_PHI predecessors.
GetUndefVal(LDVSSABlock * BB,LDVSSAUpdater * Updater)4022fe6060f1SDimitry Andric static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
4023fe6060f1SDimitry Andric // Create a value number for this block -- it needs to be unique and in the
4024fe6060f1SDimitry Andric // "undef" collection, so that we know it's not real. Use a number
4025fe6060f1SDimitry Andric // representing a PHI into this block.
4026fe6060f1SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
4027fe6060f1SDimitry Andric Updater->UndefMap[&BB->BB] = Num;
4028fe6060f1SDimitry Andric return Num;
4029fe6060f1SDimitry Andric }
4030fe6060f1SDimitry Andric
4031fe6060f1SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
4032fe6060f1SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The
4033fe6060f1SDimitry Andric /// value number of this PHI is whatever the machine value number problem
4034fe6060f1SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater
4035fe6060f1SDimitry Andric /// tries to create a PHI where the incoming values are identical.
CreateEmptyPHI(LDVSSABlock * BB,unsigned NumPreds,LDVSSAUpdater * Updater)4036fe6060f1SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
4037fe6060f1SDimitry Andric LDVSSAUpdater *Updater) {
4038fe6060f1SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB);
4039fe6060f1SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
4040fe6060f1SDimitry Andric Updater->PHIs[PHIValNum] = PHI;
4041fe6060f1SDimitry Andric return PHIValNum;
4042fe6060f1SDimitry Andric }
4043fe6060f1SDimitry Andric
4044fe6060f1SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for
4045fe6060f1SDimitry Andric /// the specified predecessor block.
AddPHIOperand(LDVSSAPhi * PHI,BlockValueNum Val,LDVSSABlock * Pred)4046fe6060f1SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
4047fe6060f1SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
4048fe6060f1SDimitry Andric }
4049fe6060f1SDimitry Andric
4050fe6060f1SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value
4051fe6060f1SDimitry Andric /// is a PHI instruction.
ValueIsPHI(BlockValueNum Val,LDVSSAUpdater * Updater)4052fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4053fe013be4SDimitry Andric return Updater->PHIs.lookup(Val);
4054fe6060f1SDimitry Andric }
4055fe6060f1SDimitry Andric
4056fe6060f1SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
4057fe6060f1SDimitry Andric /// operands, i.e., it was just added.
ValueIsNewPHI(BlockValueNum Val,LDVSSAUpdater * Updater)4058fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4059fe6060f1SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
4060fe6060f1SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0)
4061fe6060f1SDimitry Andric return PHI;
4062fe6060f1SDimitry Andric return nullptr;
4063fe6060f1SDimitry Andric }
4064fe6060f1SDimitry Andric
4065fe6060f1SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value
4066fe6060f1SDimitry Andric /// that it defines.
GetPHIValue(LDVSSAPhi * PHI)4067fe6060f1SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
4068fe6060f1SDimitry Andric };
4069fe6060f1SDimitry Andric
4070fe6060f1SDimitry Andric } // end namespace llvm
4071fe6060f1SDimitry Andric
resolveDbgPHIs(MachineFunction & MF,const FuncValueTable & MLiveOuts,const FuncValueTable & MLiveIns,MachineInstr & Here,uint64_t InstrNum)4072bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
4073c9157d92SDimitry Andric MachineFunction &MF, const FuncValueTable &MLiveOuts,
4074c9157d92SDimitry Andric const FuncValueTable &MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4075d56accc7SDimitry Andric // This function will be called twice per DBG_INSTR_REF, and might end up
4076d56accc7SDimitry Andric // computing lots of SSA information: memoize it.
4077bdd1243dSDimitry Andric auto SeenDbgPHIIt = SeenDbgPHIs.find(std::make_pair(&Here, InstrNum));
4078d56accc7SDimitry Andric if (SeenDbgPHIIt != SeenDbgPHIs.end())
4079d56accc7SDimitry Andric return SeenDbgPHIIt->second;
4080d56accc7SDimitry Andric
4081bdd1243dSDimitry Andric std::optional<ValueIDNum> Result =
4082d56accc7SDimitry Andric resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
4083bdd1243dSDimitry Andric SeenDbgPHIs.insert({std::make_pair(&Here, InstrNum), Result});
4084d56accc7SDimitry Andric return Result;
4085d56accc7SDimitry Andric }
4086d56accc7SDimitry Andric
resolveDbgPHIsImpl(MachineFunction & MF,const FuncValueTable & MLiveOuts,const FuncValueTable & MLiveIns,MachineInstr & Here,uint64_t InstrNum)4087bdd1243dSDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
4088c9157d92SDimitry Andric MachineFunction &MF, const FuncValueTable &MLiveOuts,
4089c9157d92SDimitry Andric const FuncValueTable &MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4090fe6060f1SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there
4091fe6060f1SDimitry Andric // are none, then we cannot compute a value number.
4092fe6060f1SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
4093fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstrNum);
4094fe6060f1SDimitry Andric auto LowerIt = RangePair.first;
4095fe6060f1SDimitry Andric auto UpperIt = RangePair.second;
4096fe6060f1SDimitry Andric
4097fe6060f1SDimitry Andric // No DBG_PHI means there can be no location.
4098fe6060f1SDimitry Andric if (LowerIt == UpperIt)
4099bdd1243dSDimitry Andric return std::nullopt;
4100fe6060f1SDimitry Andric
410181ad6265SDimitry Andric // If any DBG_PHIs referred to a location we didn't understand, don't try to
410281ad6265SDimitry Andric // compute a value. There might be scenarios where we could recover a value
410381ad6265SDimitry Andric // for some range of DBG_INSTR_REFs, but at this point we can have high
410481ad6265SDimitry Andric // confidence that we've seen a bug.
410581ad6265SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt);
410681ad6265SDimitry Andric for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
410781ad6265SDimitry Andric if (!DBG_PHI.ValueRead)
4108bdd1243dSDimitry Andric return std::nullopt;
410981ad6265SDimitry Andric
4110fe6060f1SDimitry Andric // If there's only one DBG_PHI, then that is our value number.
4111fe6060f1SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1)
411281ad6265SDimitry Andric return *LowerIt->ValueRead;
4113fe6060f1SDimitry Andric
4114fe6060f1SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's
4115fe6060f1SDimitry Andric // technically possible for us to merge values in different registers in each
4116fe6060f1SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register
4117fe6060f1SDimitry Andric // allocation.
411881ad6265SDimitry Andric LocIdx Loc = *LowerIt->ReadLoc;
4119fe6060f1SDimitry Andric
4120fe6060f1SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each
4121fe6060f1SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each
4122fe6060f1SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a
4123fe6060f1SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
4124fe6060f1SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along
4125fe6060f1SDimitry Andric // the way.
4126fe6060f1SDimitry Andric // Adapted LLVM SSA Updater:
4127fe6060f1SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns);
4128fe6060f1SDimitry Andric // Map of which Def or PHI is the current value in each block.
4129fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
4130fe6060f1SDimitry Andric // Set of PHIs that we have created along the way.
4131fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
4132fe6060f1SDimitry Andric
4133fe6060f1SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
4134fe6060f1SDimitry Andric // for the SSAUpdater.
4135fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) {
4136fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
413781ad6265SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead;
4138fe6060f1SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64()));
4139fe6060f1SDimitry Andric }
4140fe6060f1SDimitry Andric
4141fe6060f1SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
4142fe6060f1SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock);
4143fe6060f1SDimitry Andric if (AvailIt != AvailableValues.end()) {
4144fe6060f1SDimitry Andric // Actually, we already know what the value is -- the Use is in the same
4145fe6060f1SDimitry Andric // block as the Def.
4146fe6060f1SDimitry Andric return ValueIDNum::fromU64(AvailIt->second);
4147fe6060f1SDimitry Andric }
4148fe6060f1SDimitry Andric
4149fe6060f1SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number
4150fe6060f1SDimitry Andric // that we are to use, and the PHIs that must happen along the way.
4151fe6060f1SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
4152fe6060f1SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
4153fe6060f1SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
4154fe6060f1SDimitry Andric
4155fe6060f1SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used
4156fe6060f1SDimitry Andric // at this Use. There are a number of things we have to check about it though:
4157fe6060f1SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
4158fe6060f1SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort.
4159fe6060f1SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
4160fe6060f1SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the
4161fe6060f1SDimitry Andric // expected values.
4162fe6060f1SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the
4163fe6060f1SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number?
4164fe6060f1SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the
4165fe6060f1SDimitry Andric // the ValidatedValues collection below to sort this out.
4166fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
4167fe6060f1SDimitry Andric
4168fe6060f1SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues.
4169fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) {
4170fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
417181ad6265SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead;
4172fe6060f1SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num));
4173fe6060f1SDimitry Andric }
4174fe6060f1SDimitry Andric
4175fe6060f1SDimitry Andric // Sort PHIs to validate into RPO-order.
4176fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs;
4177fe6060f1SDimitry Andric for (auto &PHI : CreatedPHIs)
4178fe6060f1SDimitry Andric SortedPHIs.push_back(PHI);
4179fe6060f1SDimitry Andric
4180fcaf7f86SDimitry Andric llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) {
4181fe6060f1SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
4182fe6060f1SDimitry Andric });
4183fe6060f1SDimitry Andric
4184fe6060f1SDimitry Andric for (auto &PHI : SortedPHIs) {
4185e710425bSDimitry Andric ValueIDNum ThisBlockValueNum = MLiveIns[PHI->ParentBlock->BB][Loc.asU64()];
4186fe6060f1SDimitry Andric
4187fe6060f1SDimitry Andric // Are all these things actually defined?
4188fe6060f1SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) {
4189fe6060f1SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point.
4190fe013be4SDimitry Andric if (Updater.UndefMap.contains(&PHIIt.first->BB))
4191bdd1243dSDimitry Andric return std::nullopt;
4192fe6060f1SDimitry Andric
4193fe6060f1SDimitry Andric ValueIDNum ValueToCheck;
4194e710425bSDimitry Andric const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB];
4195fe6060f1SDimitry Andric
4196fe6060f1SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first);
4197fe6060f1SDimitry Andric if (VVal == ValidatedValues.end()) {
4198fe6060f1SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication
4199fe6060f1SDimitry Andric // happens so late that DBG_PHI instructions should not be able to
4200fe6060f1SDimitry Andric // migrate into loops -- meaning we can only be live-through this
4201fe6060f1SDimitry Andric // loop.
4202fe6060f1SDimitry Andric ValueToCheck = ThisBlockValueNum;
4203fe6060f1SDimitry Andric } else {
4204fe6060f1SDimitry Andric // Does the block have as a live-out, in the location we're examining,
4205fe6060f1SDimitry Andric // the value that we expect? If not, it's been moved or clobbered.
4206fe6060f1SDimitry Andric ValueToCheck = VVal->second;
4207fe6060f1SDimitry Andric }
4208fe6060f1SDimitry Andric
4209fe6060f1SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
4210bdd1243dSDimitry Andric return std::nullopt;
4211fe6060f1SDimitry Andric }
4212fe6060f1SDimitry Andric
4213fe6060f1SDimitry Andric // Record this value as validated.
4214fe6060f1SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
4215fe6060f1SDimitry Andric }
4216fe6060f1SDimitry Andric
4217fe6060f1SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value
4218fe6060f1SDimitry Andric // number was.
4219fe6060f1SDimitry Andric return Result;
4220fe6060f1SDimitry Andric }
4221