1af732203SDimitry Andric //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
2af732203SDimitry Andric //
3af732203SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4af732203SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5af732203SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af732203SDimitry Andric //
7af732203SDimitry Andric //===----------------------------------------------------------------------===//
8af732203SDimitry Andric /// \file InstrRefBasedImpl.cpp
9af732203SDimitry Andric ///
10af732203SDimitry Andric /// This is a separate implementation of LiveDebugValues, see
11af732203SDimitry Andric /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12af732203SDimitry Andric ///
13af732203SDimitry Andric /// This pass propagates variable locations between basic blocks, resolving
14af732203SDimitry Andric /// control flow conflicts between them. The problem is much like SSA
15af732203SDimitry Andric /// construction, where each DBG_VALUE instruction assigns the *value* that
16af732203SDimitry Andric /// a variable has, and every instruction where the variable is in scope uses
17af732203SDimitry Andric /// that variable. The resulting map of instruction-to-value is then translated
18af732203SDimitry Andric /// into a register (or spill) location for each variable over each instruction.
19af732203SDimitry Andric ///
20af732203SDimitry Andric /// This pass determines which DBG_VALUE dominates which instructions, or if
21af732203SDimitry Andric /// none do, where values must be merged (like PHI nodes). The added
22af732203SDimitry Andric /// complication is that because codegen has already finished, a PHI node may
23af732203SDimitry Andric /// be needed for a variable location to be correct, but no register or spill
24af732203SDimitry Andric /// slot merges the necessary values. In these circumstances, the variable
25af732203SDimitry Andric /// location is dropped.
26af732203SDimitry Andric ///
27af732203SDimitry Andric /// What makes this analysis non-trivial is loops: we cannot tell in advance
28af732203SDimitry Andric /// whether a variable location is live throughout a loop, or whether its
29af732203SDimitry Andric /// location is clobbered (or redefined by another DBG_VALUE), without
30af732203SDimitry Andric /// exploring all the way through.
31af732203SDimitry Andric ///
32af732203SDimitry Andric /// To make this simpler we perform two kinds of analysis. First, we identify
33af732203SDimitry Andric /// every value defined by every instruction (ignoring those that only move
34af732203SDimitry Andric /// another value), then compute a map of which values are available for each
35af732203SDimitry Andric /// instruction. This is stronger than a reaching-def analysis, as we create
36af732203SDimitry Andric /// PHI values where other values merge.
37af732203SDimitry Andric ///
38af732203SDimitry Andric /// Secondly, for each variable, we effectively re-construct SSA using each
39af732203SDimitry Andric /// DBG_VALUE as a def. The DBG_VALUEs read a value-number computed by the
40af732203SDimitry Andric /// first analysis from the location they refer to. We can then compute the
41af732203SDimitry Andric /// dominance frontiers of where a variable has a value, and create PHI nodes
42af732203SDimitry Andric /// where they merge.
43af732203SDimitry Andric /// This isn't precisely SSA-construction though, because the function shape
44af732203SDimitry Andric /// is pre-defined. If a variable location requires a PHI node, but no
45af732203SDimitry Andric /// PHI for the relevant values is present in the function (as computed by the
46af732203SDimitry Andric /// first analysis), the location must be dropped.
47af732203SDimitry Andric ///
48af732203SDimitry Andric /// Once both are complete, we can pass back over all instructions knowing:
49af732203SDimitry Andric /// * What _value_ each variable should contain, either defined by an
50af732203SDimitry Andric /// instruction or where control flow merges
51af732203SDimitry Andric /// * What the location of that value is (if any).
52af732203SDimitry Andric /// Allowing us to create appropriate live-in DBG_VALUEs, and DBG_VALUEs when
53af732203SDimitry Andric /// a value moves location. After this pass runs, all variable locations within
54af732203SDimitry Andric /// a block should be specified by DBG_VALUEs within that block, allowing
55af732203SDimitry Andric /// DbgEntityHistoryCalculator to focus on individual blocks.
56af732203SDimitry Andric ///
57af732203SDimitry Andric /// This pass is able to go fast because the size of the first
58af732203SDimitry Andric /// reaching-definition analysis is proportional to the working-set size of
59af732203SDimitry Andric /// the function, which the compiler tries to keep small. (It's also
60af732203SDimitry Andric /// proportional to the number of blocks). Additionally, we repeatedly perform
61af732203SDimitry Andric /// the second reaching-definition analysis with only the variables and blocks
62af732203SDimitry Andric /// in a single lexical scope, exploiting their locality.
63af732203SDimitry Andric ///
64af732203SDimitry Andric /// Determining where PHIs happen is trickier with this approach, and it comes
65af732203SDimitry Andric /// to a head in the major problem for LiveDebugValues: is a value live-through
66af732203SDimitry Andric /// a loop, or not? Your garden-variety dataflow analysis aims to build a set of
67af732203SDimitry Andric /// facts about a function, however this analysis needs to generate new value
68af732203SDimitry Andric /// numbers at joins.
69af732203SDimitry Andric ///
70af732203SDimitry Andric /// To do this, consider a lattice of all definition values, from instructions
71af732203SDimitry Andric /// and from PHIs. Each PHI is characterised by the RPO number of the block it
72af732203SDimitry Andric /// occurs in. Each value pair A, B can be ordered by RPO(A) < RPO(B):
73af732203SDimitry Andric /// with non-PHI values at the top, and any PHI value in the last block (by RPO
74af732203SDimitry Andric /// order) at the bottom.
75af732203SDimitry Andric ///
76af732203SDimitry Andric /// (Awkwardly: lower-down-the _lattice_ means a greater RPO _number_. Below,
77af732203SDimitry Andric /// "rank" always refers to the former).
78af732203SDimitry Andric ///
79af732203SDimitry Andric /// At any join, for each register, we consider:
80af732203SDimitry Andric /// * All incoming values, and
81af732203SDimitry Andric /// * The PREVIOUS live-in value at this join.
82af732203SDimitry Andric /// If all incoming values agree: that's the live-in value. If they do not, the
83af732203SDimitry Andric /// incoming values are ranked according to the partial order, and the NEXT
84af732203SDimitry Andric /// LOWEST rank after the PREVIOUS live-in value is picked (multiple values of
85af732203SDimitry Andric /// the same rank are ignored as conflicting). If there are no candidate values,
86af732203SDimitry Andric /// or if the rank of the live-in would be lower than the rank of the current
87af732203SDimitry Andric /// blocks PHIs, create a new PHI value.
88af732203SDimitry Andric ///
89af732203SDimitry Andric /// Intuitively: if it's not immediately obvious what value a join should result
90af732203SDimitry Andric /// in, we iteratively descend from instruction-definitions down through PHI
91af732203SDimitry Andric /// values, getting closer to the current block each time. If the current block
92af732203SDimitry Andric /// is a loop head, this ordering is effectively searching outer levels of
93af732203SDimitry Andric /// loops, to find a value that's live-through the current loop.
94af732203SDimitry Andric ///
95af732203SDimitry Andric /// If there is no value that's live-through this loop, a PHI is created for
96af732203SDimitry Andric /// this location instead. We can't use a lower-ranked PHI because by definition
97af732203SDimitry Andric /// it doesn't dominate the current block. We can't create a PHI value any
98af732203SDimitry Andric /// earlier, because we risk creating a PHI value at a location where values do
99af732203SDimitry Andric /// not in fact merge, thus misrepresenting the truth, and not making the true
100af732203SDimitry Andric /// live-through value for variable locations.
101af732203SDimitry Andric ///
102af732203SDimitry Andric /// This algorithm applies to both calculating the availability of values in
103af732203SDimitry Andric /// the first analysis, and the location of variables in the second. However
104af732203SDimitry Andric /// for the second we add an extra dimension of pain: creating a variable
105af732203SDimitry Andric /// location PHI is only valid if, for each incoming edge,
106af732203SDimitry Andric /// * There is a value for the variable on the incoming edge, and
107af732203SDimitry Andric /// * All the edges have that value in the same register.
108af732203SDimitry Andric /// Or put another way: we can only create a variable-location PHI if there is
109af732203SDimitry Andric /// a matching machine-location PHI, each input to which is the variables value
110af732203SDimitry Andric /// in the predecessor block.
111af732203SDimitry Andric ///
112af732203SDimitry Andric /// To accommodate this difference, each point on the lattice is split in
113af732203SDimitry Andric /// two: a "proposed" PHI and "definite" PHI. Any PHI that can immediately
114af732203SDimitry Andric /// have a location determined are "definite" PHIs, and no further work is
115af732203SDimitry Andric /// needed. Otherwise, a location that all non-backedge predecessors agree
116af732203SDimitry Andric /// on is picked and propagated as a "proposed" PHI value. If that PHI value
117af732203SDimitry Andric /// is truly live-through, it'll appear on the loop backedges on the next
118af732203SDimitry Andric /// dataflow iteration, after which the block live-in moves to be a "definite"
119af732203SDimitry Andric /// PHI. If it's not truly live-through, the variable value will be downgraded
120af732203SDimitry Andric /// further as we explore the lattice, or remains "proposed" and is considered
121af732203SDimitry Andric /// invalid once dataflow completes.
122af732203SDimitry Andric ///
123af732203SDimitry Andric /// ### Terminology
124af732203SDimitry Andric ///
125af732203SDimitry Andric /// A machine location is a register or spill slot, a value is something that's
126af732203SDimitry Andric /// defined by an instruction or PHI node, while a variable value is the value
127af732203SDimitry Andric /// assigned to a variable. A variable location is a machine location, that must
128af732203SDimitry Andric /// contain the appropriate variable value. A value that is a PHI node is
129af732203SDimitry Andric /// occasionally called an mphi.
130af732203SDimitry Andric ///
131af732203SDimitry Andric /// The first dataflow problem is the "machine value location" problem,
132af732203SDimitry Andric /// because we're determining which machine locations contain which values.
133af732203SDimitry Andric /// The "locations" are constant: what's unknown is what value they contain.
134af732203SDimitry Andric ///
135af732203SDimitry Andric /// The second dataflow problem (the one for variables) is the "variable value
136af732203SDimitry Andric /// problem", because it's determining what values a variable has, rather than
137af732203SDimitry Andric /// what location those values are placed in. Unfortunately, it's not that
138af732203SDimitry Andric /// simple, because producing a PHI value always involves picking a location.
139af732203SDimitry Andric /// This is an imperfection that we just have to accept, at least for now.
140af732203SDimitry Andric ///
141af732203SDimitry Andric /// TODO:
142af732203SDimitry Andric /// Overlapping fragments
143af732203SDimitry Andric /// Entry values
144af732203SDimitry Andric /// Add back DEBUG statements for debugging this
145af732203SDimitry Andric /// Collect statistics
146af732203SDimitry Andric ///
147af732203SDimitry Andric //===----------------------------------------------------------------------===//
148af732203SDimitry Andric
149af732203SDimitry Andric #include "llvm/ADT/DenseMap.h"
150af732203SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
151*5f7ddb14SDimitry Andric #include "llvm/ADT/STLExtras.h"
152af732203SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
153af732203SDimitry Andric #include "llvm/ADT/SmallSet.h"
154af732203SDimitry Andric #include "llvm/ADT/SmallVector.h"
155af732203SDimitry Andric #include "llvm/ADT/Statistic.h"
156af732203SDimitry Andric #include "llvm/ADT/UniqueVector.h"
157af732203SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
158af732203SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
159af732203SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
160af732203SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
161af732203SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
162af732203SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
163af732203SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
164*5f7ddb14SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
165af732203SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
166af732203SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
167af732203SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
168af732203SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
169af732203SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
170af732203SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
171af732203SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
172af732203SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
173af732203SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
174af732203SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
175af732203SDimitry Andric #include "llvm/Config/llvm-config.h"
176af732203SDimitry Andric #include "llvm/IR/DIBuilder.h"
177af732203SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
178af732203SDimitry Andric #include "llvm/IR/DebugLoc.h"
179af732203SDimitry Andric #include "llvm/IR/Function.h"
180af732203SDimitry Andric #include "llvm/IR/Module.h"
181af732203SDimitry Andric #include "llvm/InitializePasses.h"
182af732203SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
183af732203SDimitry Andric #include "llvm/Pass.h"
184af732203SDimitry Andric #include "llvm/Support/Casting.h"
185af732203SDimitry Andric #include "llvm/Support/Compiler.h"
186af732203SDimitry Andric #include "llvm/Support/Debug.h"
187af732203SDimitry Andric #include "llvm/Support/TypeSize.h"
188af732203SDimitry Andric #include "llvm/Support/raw_ostream.h"
189*5f7ddb14SDimitry Andric #include "llvm/Target/TargetMachine.h"
190*5f7ddb14SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
191af732203SDimitry Andric #include <algorithm>
192af732203SDimitry Andric #include <cassert>
193af732203SDimitry Andric #include <cstdint>
194af732203SDimitry Andric #include <functional>
195af732203SDimitry Andric #include <queue>
196af732203SDimitry Andric #include <tuple>
197af732203SDimitry Andric #include <utility>
198af732203SDimitry Andric #include <vector>
199af732203SDimitry Andric #include <limits.h>
200af732203SDimitry Andric #include <limits>
201af732203SDimitry Andric
202af732203SDimitry Andric #include "LiveDebugValues.h"
203af732203SDimitry Andric
204af732203SDimitry Andric using namespace llvm;
205af732203SDimitry Andric
206*5f7ddb14SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it.
207*5f7ddb14SDimitry Andric #undef DEBUG_TYPE
208af732203SDimitry Andric #define DEBUG_TYPE "livedebugvalues"
209af732203SDimitry Andric
210af732203SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too
211af732203SDimitry Andric // far and ignoring some transfers.
212af732203SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
213af732203SDimitry Andric cl::desc("Act like old LiveDebugValues did"),
214af732203SDimitry Andric cl::init(false));
215af732203SDimitry Andric
216af732203SDimitry Andric namespace {
217af732203SDimitry Andric
218af732203SDimitry Andric // The location at which a spilled value resides. It consists of a register and
219af732203SDimitry Andric // an offset.
220af732203SDimitry Andric struct SpillLoc {
221af732203SDimitry Andric unsigned SpillBase;
222af732203SDimitry Andric StackOffset SpillOffset;
operator ==__anon36b66d1c0111::SpillLoc223af732203SDimitry Andric bool operator==(const SpillLoc &Other) const {
224af732203SDimitry Andric return std::make_pair(SpillBase, SpillOffset) ==
225af732203SDimitry Andric std::make_pair(Other.SpillBase, Other.SpillOffset);
226af732203SDimitry Andric }
operator <__anon36b66d1c0111::SpillLoc227af732203SDimitry Andric bool operator<(const SpillLoc &Other) const {
228af732203SDimitry Andric return std::make_tuple(SpillBase, SpillOffset.getFixed(),
229af732203SDimitry Andric SpillOffset.getScalable()) <
230af732203SDimitry Andric std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
231af732203SDimitry Andric Other.SpillOffset.getScalable());
232af732203SDimitry Andric }
233af732203SDimitry Andric };
234af732203SDimitry Andric
235af732203SDimitry Andric class LocIdx {
236af732203SDimitry Andric unsigned Location;
237af732203SDimitry Andric
238af732203SDimitry Andric // Default constructor is private, initializing to an illegal location number.
239af732203SDimitry Andric // Use only for "not an entry" elements in IndexedMaps.
LocIdx()240af732203SDimitry Andric LocIdx() : Location(UINT_MAX) { }
241af732203SDimitry Andric
242af732203SDimitry Andric public:
243af732203SDimitry Andric #define NUM_LOC_BITS 24
LocIdx(unsigned L)244af732203SDimitry Andric LocIdx(unsigned L) : Location(L) {
245af732203SDimitry Andric assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
246af732203SDimitry Andric }
247af732203SDimitry Andric
MakeIllegalLoc()248af732203SDimitry Andric static LocIdx MakeIllegalLoc() {
249af732203SDimitry Andric return LocIdx();
250af732203SDimitry Andric }
251af732203SDimitry Andric
isIllegal() const252af732203SDimitry Andric bool isIllegal() const {
253af732203SDimitry Andric return Location == UINT_MAX;
254af732203SDimitry Andric }
255af732203SDimitry Andric
asU64() const256af732203SDimitry Andric uint64_t asU64() const {
257af732203SDimitry Andric return Location;
258af732203SDimitry Andric }
259af732203SDimitry Andric
operator ==(unsigned L) const260af732203SDimitry Andric bool operator==(unsigned L) const {
261af732203SDimitry Andric return Location == L;
262af732203SDimitry Andric }
263af732203SDimitry Andric
operator ==(const LocIdx & L) const264af732203SDimitry Andric bool operator==(const LocIdx &L) const {
265af732203SDimitry Andric return Location == L.Location;
266af732203SDimitry Andric }
267af732203SDimitry Andric
operator !=(unsigned L) const268af732203SDimitry Andric bool operator!=(unsigned L) const {
269af732203SDimitry Andric return !(*this == L);
270af732203SDimitry Andric }
271af732203SDimitry Andric
operator !=(const LocIdx & L) const272af732203SDimitry Andric bool operator!=(const LocIdx &L) const {
273af732203SDimitry Andric return !(*this == L);
274af732203SDimitry Andric }
275af732203SDimitry Andric
operator <(const LocIdx & Other) const276af732203SDimitry Andric bool operator<(const LocIdx &Other) const {
277af732203SDimitry Andric return Location < Other.Location;
278af732203SDimitry Andric }
279af732203SDimitry Andric };
280af732203SDimitry Andric
281af732203SDimitry Andric class LocIdxToIndexFunctor {
282af732203SDimitry Andric public:
283af732203SDimitry Andric using argument_type = LocIdx;
operator ()(const LocIdx & L) const284af732203SDimitry Andric unsigned operator()(const LocIdx &L) const {
285af732203SDimitry Andric return L.asU64();
286af732203SDimitry Andric }
287af732203SDimitry Andric };
288af732203SDimitry Andric
289af732203SDimitry Andric /// Unique identifier for a value defined by an instruction, as a value type.
290af732203SDimitry Andric /// Casts back and forth to a uint64_t. Probably replacable with something less
291af732203SDimitry Andric /// bit-constrained. Each value identifies the instruction and machine location
292af732203SDimitry Andric /// where the value is defined, although there may be no corresponding machine
293af732203SDimitry Andric /// operand for it (ex: regmasks clobbering values). The instructions are
294af732203SDimitry Andric /// one-based, and definitions that are PHIs have instruction number zero.
295af732203SDimitry Andric ///
296af732203SDimitry Andric /// The obvious limits of a 1M block function or 1M instruction blocks are
297af732203SDimitry Andric /// problematic; but by that point we should probably have bailed out of
298af732203SDimitry Andric /// trying to analyse the function.
299af732203SDimitry Andric class ValueIDNum {
300af732203SDimitry Andric uint64_t BlockNo : 20; /// The block where the def happens.
301af732203SDimitry Andric uint64_t InstNo : 20; /// The Instruction where the def happens.
302af732203SDimitry Andric /// One based, is distance from start of block.
303af732203SDimitry Andric uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens.
304af732203SDimitry Andric
305af732203SDimitry Andric public:
306af732203SDimitry Andric // XXX -- temporarily enabled while the live-in / live-out tables are moved
307af732203SDimitry Andric // to something more type-y
ValueIDNum()308af732203SDimitry Andric ValueIDNum() : BlockNo(0xFFFFF),
309af732203SDimitry Andric InstNo(0xFFFFF),
310af732203SDimitry Andric LocNo(0xFFFFFF) { }
311af732203SDimitry Andric
ValueIDNum(uint64_t Block,uint64_t Inst,uint64_t Loc)312af732203SDimitry Andric ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc)
313af732203SDimitry Andric : BlockNo(Block), InstNo(Inst), LocNo(Loc) { }
314af732203SDimitry Andric
ValueIDNum(uint64_t Block,uint64_t Inst,LocIdx Loc)315af732203SDimitry Andric ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc)
316af732203SDimitry Andric : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) { }
317af732203SDimitry Andric
getBlock() const318af732203SDimitry Andric uint64_t getBlock() const { return BlockNo; }
getInst() const319af732203SDimitry Andric uint64_t getInst() const { return InstNo; }
getLoc() const320af732203SDimitry Andric uint64_t getLoc() const { return LocNo; }
isPHI() const321af732203SDimitry Andric bool isPHI() const { return InstNo == 0; }
322af732203SDimitry Andric
asU64() const323af732203SDimitry Andric uint64_t asU64() const {
324af732203SDimitry Andric uint64_t TmpBlock = BlockNo;
325af732203SDimitry Andric uint64_t TmpInst = InstNo;
326af732203SDimitry Andric return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo;
327af732203SDimitry Andric }
328af732203SDimitry Andric
fromU64(uint64_t v)329af732203SDimitry Andric static ValueIDNum fromU64(uint64_t v) {
330af732203SDimitry Andric uint64_t L = (v & 0x3FFF);
331af732203SDimitry Andric return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L};
332af732203SDimitry Andric }
333af732203SDimitry Andric
operator <(const ValueIDNum & Other) const334af732203SDimitry Andric bool operator<(const ValueIDNum &Other) const {
335af732203SDimitry Andric return asU64() < Other.asU64();
336af732203SDimitry Andric }
337af732203SDimitry Andric
operator ==(const ValueIDNum & Other) const338af732203SDimitry Andric bool operator==(const ValueIDNum &Other) const {
339af732203SDimitry Andric return std::tie(BlockNo, InstNo, LocNo) ==
340af732203SDimitry Andric std::tie(Other.BlockNo, Other.InstNo, Other.LocNo);
341af732203SDimitry Andric }
342af732203SDimitry Andric
operator !=(const ValueIDNum & Other) const343af732203SDimitry Andric bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
344af732203SDimitry Andric
asString(const std::string & mlocname) const345af732203SDimitry Andric std::string asString(const std::string &mlocname) const {
346af732203SDimitry Andric return Twine("Value{bb: ")
347af732203SDimitry Andric .concat(Twine(BlockNo).concat(
348af732203SDimitry Andric Twine(", inst: ")
349af732203SDimitry Andric .concat((InstNo ? Twine(InstNo) : Twine("live-in"))
350af732203SDimitry Andric .concat(Twine(", loc: ").concat(Twine(mlocname)))
351af732203SDimitry Andric .concat(Twine("}")))))
352af732203SDimitry Andric .str();
353af732203SDimitry Andric }
354af732203SDimitry Andric
355af732203SDimitry Andric static ValueIDNum EmptyValue;
356af732203SDimitry Andric };
357af732203SDimitry Andric
358af732203SDimitry Andric } // end anonymous namespace
359af732203SDimitry Andric
360af732203SDimitry Andric namespace {
361af732203SDimitry Andric
362af732203SDimitry Andric /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
363af732203SDimitry Andric /// the the value, and Boolean of whether or not it's indirect.
364af732203SDimitry Andric class DbgValueProperties {
365af732203SDimitry Andric public:
DbgValueProperties(const DIExpression * DIExpr,bool Indirect)366af732203SDimitry Andric DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
367af732203SDimitry Andric : DIExpr(DIExpr), Indirect(Indirect) {}
368af732203SDimitry Andric
369af732203SDimitry Andric /// Extract properties from an existing DBG_VALUE instruction.
DbgValueProperties(const MachineInstr & MI)370af732203SDimitry Andric DbgValueProperties(const MachineInstr &MI) {
371af732203SDimitry Andric assert(MI.isDebugValue());
372af732203SDimitry Andric DIExpr = MI.getDebugExpression();
373af732203SDimitry Andric Indirect = MI.getOperand(1).isImm();
374af732203SDimitry Andric }
375af732203SDimitry Andric
operator ==(const DbgValueProperties & Other) const376af732203SDimitry Andric bool operator==(const DbgValueProperties &Other) const {
377af732203SDimitry Andric return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
378af732203SDimitry Andric }
379af732203SDimitry Andric
operator !=(const DbgValueProperties & Other) const380af732203SDimitry Andric bool operator!=(const DbgValueProperties &Other) const {
381af732203SDimitry Andric return !(*this == Other);
382af732203SDimitry Andric }
383af732203SDimitry Andric
384af732203SDimitry Andric const DIExpression *DIExpr;
385af732203SDimitry Andric bool Indirect;
386af732203SDimitry Andric };
387af732203SDimitry Andric
388af732203SDimitry Andric /// Tracker for what values are in machine locations. Listens to the Things
389af732203SDimitry Andric /// being Done by various instructions, and maintains a table of what machine
390af732203SDimitry Andric /// locations have what values (as defined by a ValueIDNum).
391af732203SDimitry Andric ///
392af732203SDimitry Andric /// There are potentially a much larger number of machine locations on the
393af732203SDimitry Andric /// target machine than the actual working-set size of the function. On x86 for
394af732203SDimitry Andric /// example, we're extremely unlikely to want to track values through control
395af732203SDimitry Andric /// or debug registers. To avoid doing so, MLocTracker has several layers of
396af732203SDimitry Andric /// indirection going on, with two kinds of ``location'':
397af732203SDimitry Andric /// * A LocID uniquely identifies a register or spill location, with a
398af732203SDimitry Andric /// predictable value.
399af732203SDimitry Andric /// * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum.
400af732203SDimitry Andric /// Whenever a location is def'd or used by a MachineInstr, we automagically
401af732203SDimitry Andric /// create a new LocIdx for a location, but not otherwise. This ensures we only
402af732203SDimitry Andric /// account for locations that are actually used or defined. The cost is another
403af732203SDimitry Andric /// vector lookup (of LocID -> LocIdx) over any other implementation. This is
404af732203SDimitry Andric /// fairly cheap, and the compiler tries to reduce the working-set at any one
405af732203SDimitry Andric /// time in the function anyway.
406af732203SDimitry Andric ///
407af732203SDimitry Andric /// Register mask operands completely blow this out of the water; I've just
408af732203SDimitry Andric /// piled hacks on top of hacks to get around that.
409af732203SDimitry Andric class MLocTracker {
410af732203SDimitry Andric public:
411af732203SDimitry Andric MachineFunction &MF;
412af732203SDimitry Andric const TargetInstrInfo &TII;
413af732203SDimitry Andric const TargetRegisterInfo &TRI;
414af732203SDimitry Andric const TargetLowering &TLI;
415af732203SDimitry Andric
416af732203SDimitry Andric /// IndexedMap type, mapping from LocIdx to ValueIDNum.
417af732203SDimitry Andric using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
418af732203SDimitry Andric
419af732203SDimitry Andric /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
420af732203SDimitry Andric /// packed, entries only exist for locations that are being tracked.
421af732203SDimitry Andric LocToValueType LocIdxToIDNum;
422af732203SDimitry Andric
423af732203SDimitry Andric /// "Map" of machine location IDs (i.e., raw register or spill number) to the
424af732203SDimitry Andric /// LocIdx key / number for that location. There are always at least as many
425af732203SDimitry Andric /// as the number of registers on the target -- if the value in the register
426af732203SDimitry Andric /// is not being tracked, then the LocIdx value will be zero. New entries are
427af732203SDimitry Andric /// appended if a new spill slot begins being tracked.
428af732203SDimitry Andric /// This, and the corresponding reverse map persist for the analysis of the
429af732203SDimitry Andric /// whole function, and is necessarying for decoding various vectors of
430af732203SDimitry Andric /// values.
431af732203SDimitry Andric std::vector<LocIdx> LocIDToLocIdx;
432af732203SDimitry Andric
433af732203SDimitry Andric /// Inverse map of LocIDToLocIdx.
434af732203SDimitry Andric IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
435af732203SDimitry Andric
436af732203SDimitry Andric /// Unique-ification of spill slots. Used to number them -- their LocID
437af732203SDimitry Andric /// number is the index in SpillLocs minus one plus NumRegs.
438af732203SDimitry Andric UniqueVector<SpillLoc> SpillLocs;
439af732203SDimitry Andric
440af732203SDimitry Andric // If we discover a new machine location, assign it an mphi with this
441af732203SDimitry Andric // block number.
442af732203SDimitry Andric unsigned CurBB;
443af732203SDimitry Andric
444af732203SDimitry Andric /// Cached local copy of the number of registers the target has.
445af732203SDimitry Andric unsigned NumRegs;
446af732203SDimitry Andric
447af732203SDimitry Andric /// Collection of register mask operands that have been observed. Second part
448af732203SDimitry Andric /// of pair indicates the instruction that they happened in. Used to
449af732203SDimitry Andric /// reconstruct where defs happened if we start tracking a location later
450af732203SDimitry Andric /// on.
451af732203SDimitry Andric SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
452af732203SDimitry Andric
453af732203SDimitry Andric /// Iterator for locations and the values they contain. Dereferencing
454af732203SDimitry Andric /// produces a struct/pair containing the LocIdx key for this location,
455af732203SDimitry Andric /// and a reference to the value currently stored. Simplifies the process
456af732203SDimitry Andric /// of seeking a particular location.
457af732203SDimitry Andric class MLocIterator {
458af732203SDimitry Andric LocToValueType &ValueMap;
459af732203SDimitry Andric LocIdx Idx;
460af732203SDimitry Andric
461af732203SDimitry Andric public:
462af732203SDimitry Andric class value_type {
463af732203SDimitry Andric public:
value_type(LocIdx Idx,ValueIDNum & Value)464af732203SDimitry Andric value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) { }
465af732203SDimitry Andric const LocIdx Idx; /// Read-only index of this location.
466af732203SDimitry Andric ValueIDNum &Value; /// Reference to the stored value at this location.
467af732203SDimitry Andric };
468af732203SDimitry Andric
MLocIterator(LocToValueType & ValueMap,LocIdx Idx)469af732203SDimitry Andric MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
470af732203SDimitry Andric : ValueMap(ValueMap), Idx(Idx) { }
471af732203SDimitry Andric
operator ==(const MLocIterator & Other) const472af732203SDimitry Andric bool operator==(const MLocIterator &Other) const {
473af732203SDimitry Andric assert(&ValueMap == &Other.ValueMap);
474af732203SDimitry Andric return Idx == Other.Idx;
475af732203SDimitry Andric }
476af732203SDimitry Andric
operator !=(const MLocIterator & Other) const477af732203SDimitry Andric bool operator!=(const MLocIterator &Other) const {
478af732203SDimitry Andric return !(*this == Other);
479af732203SDimitry Andric }
480af732203SDimitry Andric
operator ++()481af732203SDimitry Andric void operator++() {
482af732203SDimitry Andric Idx = LocIdx(Idx.asU64() + 1);
483af732203SDimitry Andric }
484af732203SDimitry Andric
operator *()485af732203SDimitry Andric value_type operator*() {
486af732203SDimitry Andric return value_type(Idx, ValueMap[LocIdx(Idx)]);
487af732203SDimitry Andric }
488af732203SDimitry Andric };
489af732203SDimitry Andric
MLocTracker(MachineFunction & MF,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const TargetLowering & TLI)490af732203SDimitry Andric MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
491af732203SDimitry Andric const TargetRegisterInfo &TRI, const TargetLowering &TLI)
492af732203SDimitry Andric : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
493af732203SDimitry Andric LocIdxToIDNum(ValueIDNum::EmptyValue),
494af732203SDimitry Andric LocIdxToLocID(0) {
495af732203SDimitry Andric NumRegs = TRI.getNumRegs();
496af732203SDimitry Andric reset();
497af732203SDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
498af732203SDimitry Andric assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
499af732203SDimitry Andric
500af732203SDimitry Andric // Always track SP. This avoids the implicit clobbering caused by regmasks
501af732203SDimitry Andric // from affectings its values. (LiveDebugValues disbelieves calls and
502af732203SDimitry Andric // regmasks that claim to clobber SP).
503af732203SDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore();
504af732203SDimitry Andric if (SP) {
505af732203SDimitry Andric unsigned ID = getLocID(SP, false);
506af732203SDimitry Andric (void)lookupOrTrackRegister(ID);
507af732203SDimitry Andric }
508af732203SDimitry Andric }
509af732203SDimitry Andric
510af732203SDimitry Andric /// Produce location ID number for indexing LocIDToLocIdx. Takes the register
511af732203SDimitry Andric /// or spill number, and flag for whether it's a spill or not.
getLocID(Register RegOrSpill,bool isSpill)512af732203SDimitry Andric unsigned getLocID(Register RegOrSpill, bool isSpill) {
513af732203SDimitry Andric return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id();
514af732203SDimitry Andric }
515af732203SDimitry Andric
516af732203SDimitry Andric /// Accessor for reading the value at Idx.
getNumAtPos(LocIdx Idx) const517af732203SDimitry Andric ValueIDNum getNumAtPos(LocIdx Idx) const {
518af732203SDimitry Andric assert(Idx.asU64() < LocIdxToIDNum.size());
519af732203SDimitry Andric return LocIdxToIDNum[Idx];
520af732203SDimitry Andric }
521af732203SDimitry Andric
getNumLocs(void) const522af732203SDimitry Andric unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); }
523af732203SDimitry Andric
524af732203SDimitry Andric /// Reset all locations to contain a PHI value at the designated block. Used
525af732203SDimitry Andric /// sometimes for actual PHI values, othertimes to indicate the block entry
526af732203SDimitry Andric /// value (before any more information is known).
setMPhis(unsigned NewCurBB)527af732203SDimitry Andric void setMPhis(unsigned NewCurBB) {
528af732203SDimitry Andric CurBB = NewCurBB;
529af732203SDimitry Andric for (auto Location : locations())
530af732203SDimitry Andric Location.Value = {CurBB, 0, Location.Idx};
531af732203SDimitry Andric }
532af732203SDimitry Andric
533af732203SDimitry Andric /// Load values for each location from array of ValueIDNums. Take current
534af732203SDimitry Andric /// bbnum just in case we read a value from a hitherto untouched register.
loadFromArray(ValueIDNum * Locs,unsigned NewCurBB)535af732203SDimitry Andric void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
536af732203SDimitry Andric CurBB = NewCurBB;
537af732203SDimitry Andric // Iterate over all tracked locations, and load each locations live-in
538af732203SDimitry Andric // value into our local index.
539af732203SDimitry Andric for (auto Location : locations())
540af732203SDimitry Andric Location.Value = Locs[Location.Idx.asU64()];
541af732203SDimitry Andric }
542af732203SDimitry Andric
543af732203SDimitry Andric /// Wipe any un-necessary location records after traversing a block.
reset(void)544af732203SDimitry Andric void reset(void) {
545af732203SDimitry Andric // We could reset all the location values too; however either loadFromArray
546af732203SDimitry Andric // or setMPhis should be called before this object is re-used. Just
547af732203SDimitry Andric // clear Masks, they're definitely not needed.
548af732203SDimitry Andric Masks.clear();
549af732203SDimitry Andric }
550af732203SDimitry Andric
551af732203SDimitry Andric /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
552af732203SDimitry Andric /// the information in this pass uninterpretable.
clear(void)553af732203SDimitry Andric void clear(void) {
554af732203SDimitry Andric reset();
555af732203SDimitry Andric LocIDToLocIdx.clear();
556af732203SDimitry Andric LocIdxToLocID.clear();
557af732203SDimitry Andric LocIdxToIDNum.clear();
558af732203SDimitry Andric //SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 0
559af732203SDimitry Andric SpillLocs = decltype(SpillLocs)();
560af732203SDimitry Andric
561af732203SDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
562af732203SDimitry Andric }
563af732203SDimitry Andric
564af732203SDimitry Andric /// Set a locaiton to a certain value.
setMLoc(LocIdx L,ValueIDNum Num)565af732203SDimitry Andric void setMLoc(LocIdx L, ValueIDNum Num) {
566af732203SDimitry Andric assert(L.asU64() < LocIdxToIDNum.size());
567af732203SDimitry Andric LocIdxToIDNum[L] = Num;
568af732203SDimitry Andric }
569af732203SDimitry Andric
570af732203SDimitry Andric /// Create a LocIdx for an untracked register ID. Initialize it to either an
571af732203SDimitry Andric /// mphi value representing a live-in, or a recent register mask clobber.
trackRegister(unsigned ID)572af732203SDimitry Andric LocIdx trackRegister(unsigned ID) {
573af732203SDimitry Andric assert(ID != 0);
574af732203SDimitry Andric LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
575af732203SDimitry Andric LocIdxToIDNum.grow(NewIdx);
576af732203SDimitry Andric LocIdxToLocID.grow(NewIdx);
577af732203SDimitry Andric
578af732203SDimitry Andric // Default: it's an mphi.
579af732203SDimitry Andric ValueIDNum ValNum = {CurBB, 0, NewIdx};
580af732203SDimitry Andric // Was this reg ever touched by a regmask?
581af732203SDimitry Andric for (const auto &MaskPair : reverse(Masks)) {
582af732203SDimitry Andric if (MaskPair.first->clobbersPhysReg(ID)) {
583af732203SDimitry Andric // There was an earlier def we skipped.
584af732203SDimitry Andric ValNum = {CurBB, MaskPair.second, NewIdx};
585af732203SDimitry Andric break;
586af732203SDimitry Andric }
587af732203SDimitry Andric }
588af732203SDimitry Andric
589af732203SDimitry Andric LocIdxToIDNum[NewIdx] = ValNum;
590af732203SDimitry Andric LocIdxToLocID[NewIdx] = ID;
591af732203SDimitry Andric return NewIdx;
592af732203SDimitry Andric }
593af732203SDimitry Andric
lookupOrTrackRegister(unsigned ID)594af732203SDimitry Andric LocIdx lookupOrTrackRegister(unsigned ID) {
595af732203SDimitry Andric LocIdx &Index = LocIDToLocIdx[ID];
596af732203SDimitry Andric if (Index.isIllegal())
597af732203SDimitry Andric Index = trackRegister(ID);
598af732203SDimitry Andric return Index;
599af732203SDimitry Andric }
600af732203SDimitry Andric
601af732203SDimitry Andric /// Record a definition of the specified register at the given block / inst.
602af732203SDimitry Andric /// This doesn't take a ValueIDNum, because the definition and its location
603af732203SDimitry Andric /// are synonymous.
defReg(Register R,unsigned BB,unsigned Inst)604af732203SDimitry Andric void defReg(Register R, unsigned BB, unsigned Inst) {
605af732203SDimitry Andric unsigned ID = getLocID(R, false);
606af732203SDimitry Andric LocIdx Idx = lookupOrTrackRegister(ID);
607af732203SDimitry Andric ValueIDNum ValueID = {BB, Inst, Idx};
608af732203SDimitry Andric LocIdxToIDNum[Idx] = ValueID;
609af732203SDimitry Andric }
610af732203SDimitry Andric
611af732203SDimitry Andric /// Set a register to a value number. To be used if the value number is
612af732203SDimitry Andric /// known in advance.
setReg(Register R,ValueIDNum ValueID)613af732203SDimitry Andric void setReg(Register R, ValueIDNum ValueID) {
614af732203SDimitry Andric unsigned ID = getLocID(R, false);
615af732203SDimitry Andric LocIdx Idx = lookupOrTrackRegister(ID);
616af732203SDimitry Andric LocIdxToIDNum[Idx] = ValueID;
617af732203SDimitry Andric }
618af732203SDimitry Andric
readReg(Register R)619af732203SDimitry Andric ValueIDNum readReg(Register R) {
620af732203SDimitry Andric unsigned ID = getLocID(R, false);
621af732203SDimitry Andric LocIdx Idx = lookupOrTrackRegister(ID);
622af732203SDimitry Andric return LocIdxToIDNum[Idx];
623af732203SDimitry Andric }
624af732203SDimitry Andric
625af732203SDimitry Andric /// Reset a register value to zero / empty. Needed to replicate the
626af732203SDimitry Andric /// VarLoc implementation where a copy to/from a register effectively
627af732203SDimitry Andric /// clears the contents of the source register. (Values can only have one
628af732203SDimitry Andric /// machine location in VarLocBasedImpl).
wipeRegister(Register R)629af732203SDimitry Andric void wipeRegister(Register R) {
630af732203SDimitry Andric unsigned ID = getLocID(R, false);
631af732203SDimitry Andric LocIdx Idx = LocIDToLocIdx[ID];
632af732203SDimitry Andric LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
633af732203SDimitry Andric }
634af732203SDimitry Andric
635af732203SDimitry Andric /// Determine the LocIdx of an existing register.
getRegMLoc(Register R)636af732203SDimitry Andric LocIdx getRegMLoc(Register R) {
637af732203SDimitry Andric unsigned ID = getLocID(R, false);
638af732203SDimitry Andric return LocIDToLocIdx[ID];
639af732203SDimitry Andric }
640af732203SDimitry Andric
641af732203SDimitry Andric /// Record a RegMask operand being executed. Defs any register we currently
642af732203SDimitry Andric /// track, stores a pointer to the mask in case we have to account for it
643af732203SDimitry Andric /// later.
writeRegMask(const MachineOperand * MO,unsigned CurBB,unsigned InstID)644af732203SDimitry Andric void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID) {
645af732203SDimitry Andric // Ensure SP exists, so that we don't override it later.
646af732203SDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore();
647af732203SDimitry Andric
648af732203SDimitry Andric // Def any register we track have that isn't preserved. The regmask
649af732203SDimitry Andric // terminates the liveness of a register, meaning its value can't be
650af732203SDimitry Andric // relied upon -- we represent this by giving it a new value.
651af732203SDimitry Andric for (auto Location : locations()) {
652af732203SDimitry Andric unsigned ID = LocIdxToLocID[Location.Idx];
653af732203SDimitry Andric // Don't clobber SP, even if the mask says it's clobbered.
654af732203SDimitry Andric if (ID < NumRegs && ID != SP && MO->clobbersPhysReg(ID))
655af732203SDimitry Andric defReg(ID, CurBB, InstID);
656af732203SDimitry Andric }
657af732203SDimitry Andric Masks.push_back(std::make_pair(MO, InstID));
658af732203SDimitry Andric }
659af732203SDimitry Andric
660af732203SDimitry Andric /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
getOrTrackSpillLoc(SpillLoc L)661af732203SDimitry Andric LocIdx getOrTrackSpillLoc(SpillLoc L) {
662af732203SDimitry Andric unsigned SpillID = SpillLocs.idFor(L);
663af732203SDimitry Andric if (SpillID == 0) {
664af732203SDimitry Andric SpillID = SpillLocs.insert(L);
665af732203SDimitry Andric unsigned L = getLocID(SpillID, true);
666af732203SDimitry Andric LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
667af732203SDimitry Andric LocIdxToIDNum.grow(Idx);
668af732203SDimitry Andric LocIdxToLocID.grow(Idx);
669af732203SDimitry Andric LocIDToLocIdx.push_back(Idx);
670af732203SDimitry Andric LocIdxToLocID[Idx] = L;
671af732203SDimitry Andric return Idx;
672af732203SDimitry Andric } else {
673af732203SDimitry Andric unsigned L = getLocID(SpillID, true);
674af732203SDimitry Andric LocIdx Idx = LocIDToLocIdx[L];
675af732203SDimitry Andric return Idx;
676af732203SDimitry Andric }
677af732203SDimitry Andric }
678af732203SDimitry Andric
679af732203SDimitry Andric /// Set the value stored in a spill slot.
setSpill(SpillLoc L,ValueIDNum ValueID)680af732203SDimitry Andric void setSpill(SpillLoc L, ValueIDNum ValueID) {
681af732203SDimitry Andric LocIdx Idx = getOrTrackSpillLoc(L);
682af732203SDimitry Andric LocIdxToIDNum[Idx] = ValueID;
683af732203SDimitry Andric }
684af732203SDimitry Andric
685af732203SDimitry Andric /// Read whatever value is in a spill slot, or None if it isn't tracked.
readSpill(SpillLoc L)686af732203SDimitry Andric Optional<ValueIDNum> readSpill(SpillLoc L) {
687af732203SDimitry Andric unsigned SpillID = SpillLocs.idFor(L);
688af732203SDimitry Andric if (SpillID == 0)
689af732203SDimitry Andric return None;
690af732203SDimitry Andric
691af732203SDimitry Andric unsigned LocID = getLocID(SpillID, true);
692af732203SDimitry Andric LocIdx Idx = LocIDToLocIdx[LocID];
693af732203SDimitry Andric return LocIdxToIDNum[Idx];
694af732203SDimitry Andric }
695af732203SDimitry Andric
696af732203SDimitry Andric /// Determine the LocIdx of a spill slot. Return None if it previously
697af732203SDimitry Andric /// hasn't had a value assigned.
getSpillMLoc(SpillLoc L)698af732203SDimitry Andric Optional<LocIdx> getSpillMLoc(SpillLoc L) {
699af732203SDimitry Andric unsigned SpillID = SpillLocs.idFor(L);
700af732203SDimitry Andric if (SpillID == 0)
701af732203SDimitry Andric return None;
702af732203SDimitry Andric unsigned LocNo = getLocID(SpillID, true);
703af732203SDimitry Andric return LocIDToLocIdx[LocNo];
704af732203SDimitry Andric }
705af732203SDimitry Andric
706af732203SDimitry Andric /// Return true if Idx is a spill machine location.
isSpill(LocIdx Idx) const707af732203SDimitry Andric bool isSpill(LocIdx Idx) const {
708af732203SDimitry Andric return LocIdxToLocID[Idx] >= NumRegs;
709af732203SDimitry Andric }
710af732203SDimitry Andric
begin()711af732203SDimitry Andric MLocIterator begin() {
712af732203SDimitry Andric return MLocIterator(LocIdxToIDNum, 0);
713af732203SDimitry Andric }
714af732203SDimitry Andric
end()715af732203SDimitry Andric MLocIterator end() {
716af732203SDimitry Andric return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
717af732203SDimitry Andric }
718af732203SDimitry Andric
719af732203SDimitry Andric /// Return a range over all locations currently tracked.
locations()720af732203SDimitry Andric iterator_range<MLocIterator> locations() {
721af732203SDimitry Andric return llvm::make_range(begin(), end());
722af732203SDimitry Andric }
723af732203SDimitry Andric
LocIdxToName(LocIdx Idx) const724af732203SDimitry Andric std::string LocIdxToName(LocIdx Idx) const {
725af732203SDimitry Andric unsigned ID = LocIdxToLocID[Idx];
726af732203SDimitry Andric if (ID >= NumRegs)
727af732203SDimitry Andric return Twine("slot ").concat(Twine(ID - NumRegs)).str();
728af732203SDimitry Andric else
729af732203SDimitry Andric return TRI.getRegAsmName(ID).str();
730af732203SDimitry Andric }
731af732203SDimitry Andric
IDAsString(const ValueIDNum & Num) const732af732203SDimitry Andric std::string IDAsString(const ValueIDNum &Num) const {
733af732203SDimitry Andric std::string DefName = LocIdxToName(Num.getLoc());
734af732203SDimitry Andric return Num.asString(DefName);
735af732203SDimitry Andric }
736af732203SDimitry Andric
737af732203SDimitry Andric LLVM_DUMP_METHOD
dump()738af732203SDimitry Andric void dump() {
739af732203SDimitry Andric for (auto Location : locations()) {
740af732203SDimitry Andric std::string MLocName = LocIdxToName(Location.Value.getLoc());
741af732203SDimitry Andric std::string DefName = Location.Value.asString(MLocName);
742af732203SDimitry Andric dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
743af732203SDimitry Andric }
744af732203SDimitry Andric }
745af732203SDimitry Andric
746af732203SDimitry Andric LLVM_DUMP_METHOD
dump_mloc_map()747af732203SDimitry Andric void dump_mloc_map() {
748af732203SDimitry Andric for (auto Location : locations()) {
749af732203SDimitry Andric std::string foo = LocIdxToName(Location.Idx);
750af732203SDimitry Andric dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
751af732203SDimitry Andric }
752af732203SDimitry Andric }
753af732203SDimitry Andric
754af732203SDimitry Andric /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the
755af732203SDimitry Andric /// information in \pProperties, for variable Var. Don't insert it anywhere,
756af732203SDimitry Andric /// just return the builder for it.
emitLoc(Optional<LocIdx> MLoc,const DebugVariable & Var,const DbgValueProperties & Properties)757af732203SDimitry Andric MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
758af732203SDimitry Andric const DbgValueProperties &Properties) {
759af732203SDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
760af732203SDimitry Andric Var.getVariable()->getScope(),
761af732203SDimitry Andric const_cast<DILocation *>(Var.getInlinedAt()));
762af732203SDimitry Andric auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
763af732203SDimitry Andric
764af732203SDimitry Andric const DIExpression *Expr = Properties.DIExpr;
765af732203SDimitry Andric if (!MLoc) {
766af732203SDimitry Andric // No location -> DBG_VALUE $noreg
767af732203SDimitry Andric MIB.addReg(0, RegState::Debug);
768af732203SDimitry Andric MIB.addReg(0, RegState::Debug);
769af732203SDimitry Andric } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
770af732203SDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc];
771af732203SDimitry Andric const SpillLoc &Spill = SpillLocs[LocID - NumRegs + 1];
772af732203SDimitry Andric
773af732203SDimitry Andric auto *TRI = MF.getSubtarget().getRegisterInfo();
774af732203SDimitry Andric Expr = TRI->prependOffsetExpression(Expr, DIExpression::ApplyOffset,
775af732203SDimitry Andric Spill.SpillOffset);
776af732203SDimitry Andric unsigned Base = Spill.SpillBase;
777af732203SDimitry Andric MIB.addReg(Base, RegState::Debug);
778af732203SDimitry Andric MIB.addImm(0);
779af732203SDimitry Andric } else {
780af732203SDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc];
781af732203SDimitry Andric MIB.addReg(LocID, RegState::Debug);
782af732203SDimitry Andric if (Properties.Indirect)
783af732203SDimitry Andric MIB.addImm(0);
784af732203SDimitry Andric else
785af732203SDimitry Andric MIB.addReg(0, RegState::Debug);
786af732203SDimitry Andric }
787af732203SDimitry Andric
788af732203SDimitry Andric MIB.addMetadata(Var.getVariable());
789af732203SDimitry Andric MIB.addMetadata(Expr);
790af732203SDimitry Andric return MIB;
791af732203SDimitry Andric }
792af732203SDimitry Andric };
793af732203SDimitry Andric
794af732203SDimitry Andric /// Class recording the (high level) _value_ of a variable. Identifies either
795af732203SDimitry Andric /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
796af732203SDimitry Andric /// This class also stores meta-information about how the value is qualified.
797af732203SDimitry Andric /// Used to reason about variable values when performing the second
798af732203SDimitry Andric /// (DebugVariable specific) dataflow analysis.
799af732203SDimitry Andric class DbgValue {
800af732203SDimitry Andric public:
801af732203SDimitry Andric union {
802af732203SDimitry Andric /// If Kind is Def, the value number that this value is based on.
803af732203SDimitry Andric ValueIDNum ID;
804af732203SDimitry Andric /// If Kind is Const, the MachineOperand defining this value.
805af732203SDimitry Andric MachineOperand MO;
806af732203SDimitry Andric /// For a NoVal DbgValue, which block it was generated in.
807af732203SDimitry Andric unsigned BlockNo;
808af732203SDimitry Andric };
809af732203SDimitry Andric /// Qualifiers for the ValueIDNum above.
810af732203SDimitry Andric DbgValueProperties Properties;
811af732203SDimitry Andric
812af732203SDimitry Andric typedef enum {
813af732203SDimitry Andric Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
814af732203SDimitry Andric Def, // This value is defined by an inst, or is a PHI value.
815af732203SDimitry Andric Const, // A constant value contained in the MachineOperand field.
816af732203SDimitry Andric Proposed, // This is a tentative PHI value, which may be confirmed or
817af732203SDimitry Andric // invalidated later.
818af732203SDimitry Andric NoVal // Empty DbgValue, generated during dataflow. BlockNo stores
819af732203SDimitry Andric // which block this was generated in.
820af732203SDimitry Andric } KindT;
821af732203SDimitry Andric /// Discriminator for whether this is a constant or an in-program value.
822af732203SDimitry Andric KindT Kind;
823af732203SDimitry Andric
DbgValue(const ValueIDNum & Val,const DbgValueProperties & Prop,KindT Kind)824af732203SDimitry Andric DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
825af732203SDimitry Andric : ID(Val), Properties(Prop), Kind(Kind) {
826af732203SDimitry Andric assert(Kind == Def || Kind == Proposed);
827af732203SDimitry Andric }
828af732203SDimitry Andric
DbgValue(unsigned BlockNo,const DbgValueProperties & Prop,KindT Kind)829af732203SDimitry Andric DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
830af732203SDimitry Andric : BlockNo(BlockNo), Properties(Prop), Kind(Kind) {
831af732203SDimitry Andric assert(Kind == NoVal);
832af732203SDimitry Andric }
833af732203SDimitry Andric
DbgValue(const MachineOperand & MO,const DbgValueProperties & Prop,KindT Kind)834af732203SDimitry Andric DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
835af732203SDimitry Andric : MO(MO), Properties(Prop), Kind(Kind) {
836af732203SDimitry Andric assert(Kind == Const);
837af732203SDimitry Andric }
838af732203SDimitry Andric
DbgValue(const DbgValueProperties & Prop,KindT Kind)839af732203SDimitry Andric DbgValue(const DbgValueProperties &Prop, KindT Kind)
840af732203SDimitry Andric : Properties(Prop), Kind(Kind) {
841af732203SDimitry Andric assert(Kind == Undef &&
842af732203SDimitry Andric "Empty DbgValue constructor must pass in Undef kind");
843af732203SDimitry Andric }
844af732203SDimitry Andric
dump(const MLocTracker * MTrack) const845af732203SDimitry Andric void dump(const MLocTracker *MTrack) const {
846af732203SDimitry Andric if (Kind == Const) {
847af732203SDimitry Andric MO.dump();
848af732203SDimitry Andric } else if (Kind == NoVal) {
849af732203SDimitry Andric dbgs() << "NoVal(" << BlockNo << ")";
850af732203SDimitry Andric } else if (Kind == Proposed) {
851af732203SDimitry Andric dbgs() << "VPHI(" << MTrack->IDAsString(ID) << ")";
852af732203SDimitry Andric } else {
853af732203SDimitry Andric assert(Kind == Def);
854af732203SDimitry Andric dbgs() << MTrack->IDAsString(ID);
855af732203SDimitry Andric }
856af732203SDimitry Andric if (Properties.Indirect)
857af732203SDimitry Andric dbgs() << " indir";
858af732203SDimitry Andric if (Properties.DIExpr)
859af732203SDimitry Andric dbgs() << " " << *Properties.DIExpr;
860af732203SDimitry Andric }
861af732203SDimitry Andric
operator ==(const DbgValue & Other) const862af732203SDimitry Andric bool operator==(const DbgValue &Other) const {
863af732203SDimitry Andric if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
864af732203SDimitry Andric return false;
865af732203SDimitry Andric else if (Kind == Proposed && ID != Other.ID)
866af732203SDimitry Andric return false;
867af732203SDimitry Andric else if (Kind == Def && ID != Other.ID)
868af732203SDimitry Andric return false;
869af732203SDimitry Andric else if (Kind == NoVal && BlockNo != Other.BlockNo)
870af732203SDimitry Andric return false;
871af732203SDimitry Andric else if (Kind == Const)
872af732203SDimitry Andric return MO.isIdenticalTo(Other.MO);
873af732203SDimitry Andric
874af732203SDimitry Andric return true;
875af732203SDimitry Andric }
876af732203SDimitry Andric
operator !=(const DbgValue & Other) const877af732203SDimitry Andric bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
878af732203SDimitry Andric };
879af732203SDimitry Andric
880af732203SDimitry Andric /// Types for recording sets of variable fragments that overlap. For a given
881af732203SDimitry Andric /// local variable, we record all other fragments of that variable that could
882af732203SDimitry Andric /// overlap it, to reduce search time.
883af732203SDimitry Andric using FragmentOfVar =
884af732203SDimitry Andric std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
885af732203SDimitry Andric using OverlapMap =
886af732203SDimitry Andric DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
887af732203SDimitry Andric
888af732203SDimitry Andric /// Collection of DBG_VALUEs observed when traversing a block. Records each
889af732203SDimitry Andric /// variable and the value the DBG_VALUE refers to. Requires the machine value
890af732203SDimitry Andric /// location dataflow algorithm to have run already, so that values can be
891af732203SDimitry Andric /// identified.
892af732203SDimitry Andric class VLocTracker {
893af732203SDimitry Andric public:
894af732203SDimitry Andric /// Map DebugVariable to the latest Value it's defined to have.
895af732203SDimitry Andric /// Needs to be a MapVector because we determine order-in-the-input-MIR from
896af732203SDimitry Andric /// the order in this container.
897af732203SDimitry Andric /// We only retain the last DbgValue in each block for each variable, to
898af732203SDimitry Andric /// determine the blocks live-out variable value. The Vars container forms the
899af732203SDimitry Andric /// transfer function for this block, as part of the dataflow analysis. The
900af732203SDimitry Andric /// movement of values between locations inside of a block is handled at a
901af732203SDimitry Andric /// much later stage, in the TransferTracker class.
902af732203SDimitry Andric MapVector<DebugVariable, DbgValue> Vars;
903af732203SDimitry Andric DenseMap<DebugVariable, const DILocation *> Scopes;
904af732203SDimitry Andric MachineBasicBlock *MBB;
905af732203SDimitry Andric
906af732203SDimitry Andric public:
VLocTracker()907af732203SDimitry Andric VLocTracker() {}
908af732203SDimitry Andric
defVar(const MachineInstr & MI,const DbgValueProperties & Properties,Optional<ValueIDNum> ID)909af732203SDimitry Andric void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
910af732203SDimitry Andric Optional<ValueIDNum> ID) {
911af732203SDimitry Andric assert(MI.isDebugValue() || MI.isDebugRef());
912af732203SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
913af732203SDimitry Andric MI.getDebugLoc()->getInlinedAt());
914af732203SDimitry Andric DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
915af732203SDimitry Andric : DbgValue(Properties, DbgValue::Undef);
916af732203SDimitry Andric
917af732203SDimitry Andric // Attempt insertion; overwrite if it's already mapped.
918af732203SDimitry Andric auto Result = Vars.insert(std::make_pair(Var, Rec));
919af732203SDimitry Andric if (!Result.second)
920af732203SDimitry Andric Result.first->second = Rec;
921af732203SDimitry Andric Scopes[Var] = MI.getDebugLoc().get();
922af732203SDimitry Andric }
923af732203SDimitry Andric
defVar(const MachineInstr & MI,const MachineOperand & MO)924af732203SDimitry Andric void defVar(const MachineInstr &MI, const MachineOperand &MO) {
925af732203SDimitry Andric // Only DBG_VALUEs can define constant-valued variables.
926af732203SDimitry Andric assert(MI.isDebugValue());
927af732203SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
928af732203SDimitry Andric MI.getDebugLoc()->getInlinedAt());
929af732203SDimitry Andric DbgValueProperties Properties(MI);
930af732203SDimitry Andric DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
931af732203SDimitry Andric
932af732203SDimitry Andric // Attempt insertion; overwrite if it's already mapped.
933af732203SDimitry Andric auto Result = Vars.insert(std::make_pair(Var, Rec));
934af732203SDimitry Andric if (!Result.second)
935af732203SDimitry Andric Result.first->second = Rec;
936af732203SDimitry Andric Scopes[Var] = MI.getDebugLoc().get();
937af732203SDimitry Andric }
938af732203SDimitry Andric };
939af732203SDimitry Andric
940af732203SDimitry Andric /// Tracker for converting machine value locations and variable values into
941af732203SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
942af732203SDimitry Andric /// specifying block live-in locations and transfers within blocks.
943af732203SDimitry Andric ///
944af732203SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
945af732203SDimitry Andric /// and must be initialized with the set of variable values that are live-in to
946af732203SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks
947af732203SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a
948af732203SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
949af732203SDimitry Andric /// stepped through, transfers of values between machine locations are
950af732203SDimitry Andric /// identified and if profitable, a DBG_VALUE created.
951af732203SDimitry Andric ///
952af732203SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an
953af732203SDimitry Andric /// unavailable value could materialize in the middle of a block, when the
954af732203SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the
955af732203SDimitry Andric /// variable in a backup location. (XXX these are unimplemented).
956af732203SDimitry Andric class TransferTracker {
957af732203SDimitry Andric public:
958af732203SDimitry Andric const TargetInstrInfo *TII;
959*5f7ddb14SDimitry Andric const TargetLowering *TLI;
960af732203SDimitry Andric /// This machine location tracker is assumed to always contain the up-to-date
961af732203SDimitry Andric /// value mapping for all machine locations. TransferTracker only reads
962af732203SDimitry Andric /// information from it. (XXX make it const?)
963af732203SDimitry Andric MLocTracker *MTracker;
964af732203SDimitry Andric MachineFunction &MF;
965*5f7ddb14SDimitry Andric bool ShouldEmitDebugEntryValues;
966af732203SDimitry Andric
967af732203SDimitry Andric /// Record of all changes in variable locations at a block position. Awkwardly
968af732203SDimitry Andric /// we allow inserting either before or after the point: MBB != nullptr
969af732203SDimitry Andric /// indicates it's before, otherwise after.
970af732203SDimitry Andric struct Transfer {
971*5f7ddb14SDimitry Andric MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
972af732203SDimitry Andric MachineBasicBlock *MBB; /// non-null if we should insert after.
973af732203SDimitry Andric SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
974af732203SDimitry Andric };
975af732203SDimitry Andric
976*5f7ddb14SDimitry Andric struct LocAndProperties {
977af732203SDimitry Andric LocIdx Loc;
978af732203SDimitry Andric DbgValueProperties Properties;
979*5f7ddb14SDimitry Andric };
980af732203SDimitry Andric
981af732203SDimitry Andric /// Collection of transfers (DBG_VALUEs) to be inserted.
982af732203SDimitry Andric SmallVector<Transfer, 32> Transfers;
983af732203SDimitry Andric
984af732203SDimitry Andric /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
985af732203SDimitry Andric /// between TransferTrackers view of variable locations and MLocTrackers. For
986af732203SDimitry Andric /// example, MLocTracker observes all clobbers, but TransferTracker lazily
987af732203SDimitry Andric /// does not.
988af732203SDimitry Andric std::vector<ValueIDNum> VarLocs;
989af732203SDimitry Andric
990af732203SDimitry Andric /// Map from LocIdxes to which DebugVariables are based that location.
991af732203SDimitry Andric /// Mantained while stepping through the block. Not accurate if
992af732203SDimitry Andric /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
993af732203SDimitry Andric std::map<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
994af732203SDimitry Andric
995af732203SDimitry Andric /// Map from DebugVariable to it's current location and qualifying meta
996af732203SDimitry Andric /// information. To be used in conjunction with ActiveMLocs to construct
997af732203SDimitry Andric /// enough information for the DBG_VALUEs for a particular LocIdx.
998af732203SDimitry Andric DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
999af732203SDimitry Andric
1000af732203SDimitry Andric /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
1001af732203SDimitry Andric SmallVector<MachineInstr *, 4> PendingDbgValues;
1002af732203SDimitry Andric
1003af732203SDimitry Andric /// Record of a use-before-def: created when a value that's live-in to the
1004af732203SDimitry Andric /// current block isn't available in any machine location, but it will be
1005af732203SDimitry Andric /// defined in this block.
1006af732203SDimitry Andric struct UseBeforeDef {
1007af732203SDimitry Andric /// Value of this variable, def'd in block.
1008af732203SDimitry Andric ValueIDNum ID;
1009af732203SDimitry Andric /// Identity of this variable.
1010af732203SDimitry Andric DebugVariable Var;
1011af732203SDimitry Andric /// Additional variable properties.
1012af732203SDimitry Andric DbgValueProperties Properties;
1013af732203SDimitry Andric };
1014af732203SDimitry Andric
1015af732203SDimitry Andric /// Map from instruction index (within the block) to the set of UseBeforeDefs
1016af732203SDimitry Andric /// that become defined at that instruction.
1017af732203SDimitry Andric DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
1018af732203SDimitry Andric
1019af732203SDimitry Andric /// The set of variables that are in UseBeforeDefs and can become a location
1020af732203SDimitry Andric /// once the relevant value is defined. An element being erased from this
1021af732203SDimitry Andric /// collection prevents the use-before-def materializing.
1022af732203SDimitry Andric DenseSet<DebugVariable> UseBeforeDefVariables;
1023af732203SDimitry Andric
1024af732203SDimitry Andric const TargetRegisterInfo &TRI;
1025af732203SDimitry Andric const BitVector &CalleeSavedRegs;
1026af732203SDimitry Andric
TransferTracker(const TargetInstrInfo * TII,MLocTracker * MTracker,MachineFunction & MF,const TargetRegisterInfo & TRI,const BitVector & CalleeSavedRegs,const TargetPassConfig & TPC)1027af732203SDimitry Andric TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
1028af732203SDimitry Andric MachineFunction &MF, const TargetRegisterInfo &TRI,
1029*5f7ddb14SDimitry Andric const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
1030af732203SDimitry Andric : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
1031*5f7ddb14SDimitry Andric CalleeSavedRegs(CalleeSavedRegs) {
1032*5f7ddb14SDimitry Andric TLI = MF.getSubtarget().getTargetLowering();
1033*5f7ddb14SDimitry Andric auto &TM = TPC.getTM<TargetMachine>();
1034*5f7ddb14SDimitry Andric ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
1035*5f7ddb14SDimitry Andric }
1036af732203SDimitry Andric
1037af732203SDimitry Andric /// Load object with live-in variable values. \p mlocs contains the live-in
1038af732203SDimitry Andric /// values in each machine location, while \p vlocs the live-in variable
1039af732203SDimitry Andric /// values. This method picks variable locations for the live-in variables,
1040af732203SDimitry Andric /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
1041af732203SDimitry Andric /// object fields to track variable locations as we step through the block.
1042af732203SDimitry Andric /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
loadInlocs(MachineBasicBlock & MBB,ValueIDNum * MLocs,SmallVectorImpl<std::pair<DebugVariable,DbgValue>> & VLocs,unsigned NumLocs)1043af732203SDimitry Andric void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs,
1044af732203SDimitry Andric SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
1045af732203SDimitry Andric unsigned NumLocs) {
1046af732203SDimitry Andric ActiveMLocs.clear();
1047af732203SDimitry Andric ActiveVLocs.clear();
1048af732203SDimitry Andric VarLocs.clear();
1049af732203SDimitry Andric VarLocs.reserve(NumLocs);
1050af732203SDimitry Andric UseBeforeDefs.clear();
1051af732203SDimitry Andric UseBeforeDefVariables.clear();
1052af732203SDimitry Andric
1053af732203SDimitry Andric auto isCalleeSaved = [&](LocIdx L) {
1054af732203SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L];
1055af732203SDimitry Andric if (Reg >= MTracker->NumRegs)
1056af732203SDimitry Andric return false;
1057af732203SDimitry Andric for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
1058af732203SDimitry Andric if (CalleeSavedRegs.test(*RAI))
1059af732203SDimitry Andric return true;
1060af732203SDimitry Andric return false;
1061af732203SDimitry Andric };
1062af732203SDimitry Andric
1063af732203SDimitry Andric // Map of the preferred location for each value.
1064af732203SDimitry Andric std::map<ValueIDNum, LocIdx> ValueToLoc;
1065af732203SDimitry Andric
1066af732203SDimitry Andric // Produce a map of value numbers to the current machine locs they live
1067af732203SDimitry Andric // in. When emulating VarLocBasedImpl, there should only be one
1068af732203SDimitry Andric // location; when not, we get to pick.
1069af732203SDimitry Andric for (auto Location : MTracker->locations()) {
1070af732203SDimitry Andric LocIdx Idx = Location.Idx;
1071af732203SDimitry Andric ValueIDNum &VNum = MLocs[Idx.asU64()];
1072af732203SDimitry Andric VarLocs.push_back(VNum);
1073af732203SDimitry Andric auto it = ValueToLoc.find(VNum);
1074af732203SDimitry Andric // In order of preference, pick:
1075af732203SDimitry Andric // * Callee saved registers,
1076af732203SDimitry Andric // * Other registers,
1077af732203SDimitry Andric // * Spill slots.
1078af732203SDimitry Andric if (it == ValueToLoc.end() || MTracker->isSpill(it->second) ||
1079af732203SDimitry Andric (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) {
1080af732203SDimitry Andric // Insert, or overwrite if insertion failed.
1081af732203SDimitry Andric auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx));
1082af732203SDimitry Andric if (!PrefLocRes.second)
1083af732203SDimitry Andric PrefLocRes.first->second = Idx;
1084af732203SDimitry Andric }
1085af732203SDimitry Andric }
1086af732203SDimitry Andric
1087af732203SDimitry Andric // Now map variables to their picked LocIdxes.
1088af732203SDimitry Andric for (auto Var : VLocs) {
1089af732203SDimitry Andric if (Var.second.Kind == DbgValue::Const) {
1090af732203SDimitry Andric PendingDbgValues.push_back(
1091af732203SDimitry Andric emitMOLoc(Var.second.MO, Var.first, Var.second.Properties));
1092af732203SDimitry Andric continue;
1093af732203SDimitry Andric }
1094af732203SDimitry Andric
1095af732203SDimitry Andric // If the value has no location, we can't make a variable location.
1096af732203SDimitry Andric const ValueIDNum &Num = Var.second.ID;
1097af732203SDimitry Andric auto ValuesPreferredLoc = ValueToLoc.find(Num);
1098af732203SDimitry Andric if (ValuesPreferredLoc == ValueToLoc.end()) {
1099af732203SDimitry Andric // If it's a def that occurs in this block, register it as a
1100af732203SDimitry Andric // use-before-def to be resolved as we step through the block.
1101af732203SDimitry Andric if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
1102af732203SDimitry Andric addUseBeforeDef(Var.first, Var.second.Properties, Num);
1103*5f7ddb14SDimitry Andric else
1104*5f7ddb14SDimitry Andric recoverAsEntryValue(Var.first, Var.second.Properties, Num);
1105af732203SDimitry Andric continue;
1106af732203SDimitry Andric }
1107af732203SDimitry Andric
1108af732203SDimitry Andric LocIdx M = ValuesPreferredLoc->second;
1109af732203SDimitry Andric auto NewValue = LocAndProperties{M, Var.second.Properties};
1110af732203SDimitry Andric auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
1111af732203SDimitry Andric if (!Result.second)
1112af732203SDimitry Andric Result.first->second = NewValue;
1113af732203SDimitry Andric ActiveMLocs[M].insert(Var.first);
1114af732203SDimitry Andric PendingDbgValues.push_back(
1115af732203SDimitry Andric MTracker->emitLoc(M, Var.first, Var.second.Properties));
1116af732203SDimitry Andric }
1117af732203SDimitry Andric flushDbgValues(MBB.begin(), &MBB);
1118af732203SDimitry Andric }
1119af732203SDimitry Andric
1120af732203SDimitry Andric /// Record that \p Var has value \p ID, a value that becomes available
1121af732203SDimitry Andric /// later in the function.
addUseBeforeDef(const DebugVariable & Var,const DbgValueProperties & Properties,ValueIDNum ID)1122af732203SDimitry Andric void addUseBeforeDef(const DebugVariable &Var,
1123af732203SDimitry Andric const DbgValueProperties &Properties, ValueIDNum ID) {
1124af732203SDimitry Andric UseBeforeDef UBD = {ID, Var, Properties};
1125af732203SDimitry Andric UseBeforeDefs[ID.getInst()].push_back(UBD);
1126af732203SDimitry Andric UseBeforeDefVariables.insert(Var);
1127af732203SDimitry Andric }
1128af732203SDimitry Andric
1129af732203SDimitry Andric /// After the instruction at index \p Inst and position \p pos has been
1130af732203SDimitry Andric /// processed, check whether it defines a variable value in a use-before-def.
1131af732203SDimitry Andric /// If so, and the variable value hasn't changed since the start of the
1132af732203SDimitry Andric /// block, create a DBG_VALUE.
checkInstForNewValues(unsigned Inst,MachineBasicBlock::iterator pos)1133af732203SDimitry Andric void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
1134af732203SDimitry Andric auto MIt = UseBeforeDefs.find(Inst);
1135af732203SDimitry Andric if (MIt == UseBeforeDefs.end())
1136af732203SDimitry Andric return;
1137af732203SDimitry Andric
1138af732203SDimitry Andric for (auto &Use : MIt->second) {
1139af732203SDimitry Andric LocIdx L = Use.ID.getLoc();
1140af732203SDimitry Andric
1141af732203SDimitry Andric // If something goes very wrong, we might end up labelling a COPY
1142af732203SDimitry Andric // instruction or similar with an instruction number, where it doesn't
1143af732203SDimitry Andric // actually define a new value, instead it moves a value. In case this
1144af732203SDimitry Andric // happens, discard.
1145af732203SDimitry Andric if (MTracker->LocIdxToIDNum[L] != Use.ID)
1146af732203SDimitry Andric continue;
1147af732203SDimitry Andric
1148af732203SDimitry Andric // If a different debug instruction defined the variable value / location
1149af732203SDimitry Andric // since the start of the block, don't materialize this use-before-def.
1150af732203SDimitry Andric if (!UseBeforeDefVariables.count(Use.Var))
1151af732203SDimitry Andric continue;
1152af732203SDimitry Andric
1153af732203SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
1154af732203SDimitry Andric }
1155af732203SDimitry Andric flushDbgValues(pos, nullptr);
1156af732203SDimitry Andric }
1157af732203SDimitry Andric
1158af732203SDimitry Andric /// Helper to move created DBG_VALUEs into Transfers collection.
flushDbgValues(MachineBasicBlock::iterator Pos,MachineBasicBlock * MBB)1159af732203SDimitry Andric void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
1160*5f7ddb14SDimitry Andric if (PendingDbgValues.size() == 0)
1161*5f7ddb14SDimitry Andric return;
1162*5f7ddb14SDimitry Andric
1163*5f7ddb14SDimitry Andric // Pick out the instruction start position.
1164*5f7ddb14SDimitry Andric MachineBasicBlock::instr_iterator BundleStart;
1165*5f7ddb14SDimitry Andric if (MBB && Pos == MBB->begin())
1166*5f7ddb14SDimitry Andric BundleStart = MBB->instr_begin();
1167*5f7ddb14SDimitry Andric else
1168*5f7ddb14SDimitry Andric BundleStart = getBundleStart(Pos->getIterator());
1169*5f7ddb14SDimitry Andric
1170*5f7ddb14SDimitry Andric Transfers.push_back({BundleStart, MBB, PendingDbgValues});
1171af732203SDimitry Andric PendingDbgValues.clear();
1172af732203SDimitry Andric }
1173*5f7ddb14SDimitry Andric
isEntryValueVariable(const DebugVariable & Var,const DIExpression * Expr) const1174*5f7ddb14SDimitry Andric bool isEntryValueVariable(const DebugVariable &Var,
1175*5f7ddb14SDimitry Andric const DIExpression *Expr) const {
1176*5f7ddb14SDimitry Andric if (!Var.getVariable()->isParameter())
1177*5f7ddb14SDimitry Andric return false;
1178*5f7ddb14SDimitry Andric
1179*5f7ddb14SDimitry Andric if (Var.getInlinedAt())
1180*5f7ddb14SDimitry Andric return false;
1181*5f7ddb14SDimitry Andric
1182*5f7ddb14SDimitry Andric if (Expr->getNumElements() > 0)
1183*5f7ddb14SDimitry Andric return false;
1184*5f7ddb14SDimitry Andric
1185*5f7ddb14SDimitry Andric return true;
1186*5f7ddb14SDimitry Andric }
1187*5f7ddb14SDimitry Andric
isEntryValueValue(const ValueIDNum & Val) const1188*5f7ddb14SDimitry Andric bool isEntryValueValue(const ValueIDNum &Val) const {
1189*5f7ddb14SDimitry Andric // Must be in entry block (block number zero), and be a PHI / live-in value.
1190*5f7ddb14SDimitry Andric if (Val.getBlock() || !Val.isPHI())
1191*5f7ddb14SDimitry Andric return false;
1192*5f7ddb14SDimitry Andric
1193*5f7ddb14SDimitry Andric // Entry values must enter in a register.
1194*5f7ddb14SDimitry Andric if (MTracker->isSpill(Val.getLoc()))
1195*5f7ddb14SDimitry Andric return false;
1196*5f7ddb14SDimitry Andric
1197*5f7ddb14SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore();
1198*5f7ddb14SDimitry Andric Register FP = TRI.getFrameRegister(MF);
1199*5f7ddb14SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
1200*5f7ddb14SDimitry Andric return Reg != SP && Reg != FP;
1201*5f7ddb14SDimitry Andric }
1202*5f7ddb14SDimitry Andric
recoverAsEntryValue(const DebugVariable & Var,DbgValueProperties & Prop,const ValueIDNum & Num)1203*5f7ddb14SDimitry Andric bool recoverAsEntryValue(const DebugVariable &Var, DbgValueProperties &Prop,
1204*5f7ddb14SDimitry Andric const ValueIDNum &Num) {
1205*5f7ddb14SDimitry Andric // Is this variable location a candidate to be an entry value. First,
1206*5f7ddb14SDimitry Andric // should we be trying this at all?
1207*5f7ddb14SDimitry Andric if (!ShouldEmitDebugEntryValues)
1208*5f7ddb14SDimitry Andric return false;
1209*5f7ddb14SDimitry Andric
1210*5f7ddb14SDimitry Andric // Is the variable appropriate for entry values (i.e., is a parameter).
1211*5f7ddb14SDimitry Andric if (!isEntryValueVariable(Var, Prop.DIExpr))
1212*5f7ddb14SDimitry Andric return false;
1213*5f7ddb14SDimitry Andric
1214*5f7ddb14SDimitry Andric // Is the value assigned to this variable still the entry value?
1215*5f7ddb14SDimitry Andric if (!isEntryValueValue(Num))
1216*5f7ddb14SDimitry Andric return false;
1217*5f7ddb14SDimitry Andric
1218*5f7ddb14SDimitry Andric // Emit a variable location using an entry value expression.
1219*5f7ddb14SDimitry Andric DIExpression *NewExpr =
1220*5f7ddb14SDimitry Andric DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue);
1221*5f7ddb14SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
1222*5f7ddb14SDimitry Andric MachineOperand MO = MachineOperand::CreateReg(Reg, false);
1223*5f7ddb14SDimitry Andric MO.setIsDebug(true);
1224*5f7ddb14SDimitry Andric
1225*5f7ddb14SDimitry Andric PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect}));
1226*5f7ddb14SDimitry Andric return true;
1227af732203SDimitry Andric }
1228af732203SDimitry Andric
1229af732203SDimitry Andric /// Change a variable value after encountering a DBG_VALUE inside a block.
redefVar(const MachineInstr & MI)1230af732203SDimitry Andric void redefVar(const MachineInstr &MI) {
1231af732203SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1232af732203SDimitry Andric MI.getDebugLoc()->getInlinedAt());
1233af732203SDimitry Andric DbgValueProperties Properties(MI);
1234af732203SDimitry Andric
1235af732203SDimitry Andric const MachineOperand &MO = MI.getOperand(0);
1236af732203SDimitry Andric
1237af732203SDimitry Andric // Ignore non-register locations, we don't transfer those.
1238af732203SDimitry Andric if (!MO.isReg() || MO.getReg() == 0) {
1239af732203SDimitry Andric auto It = ActiveVLocs.find(Var);
1240af732203SDimitry Andric if (It != ActiveVLocs.end()) {
1241af732203SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var);
1242af732203SDimitry Andric ActiveVLocs.erase(It);
1243af732203SDimitry Andric }
1244af732203SDimitry Andric // Any use-before-defs no longer apply.
1245af732203SDimitry Andric UseBeforeDefVariables.erase(Var);
1246af732203SDimitry Andric return;
1247af732203SDimitry Andric }
1248af732203SDimitry Andric
1249af732203SDimitry Andric Register Reg = MO.getReg();
1250af732203SDimitry Andric LocIdx NewLoc = MTracker->getRegMLoc(Reg);
1251af732203SDimitry Andric redefVar(MI, Properties, NewLoc);
1252af732203SDimitry Andric }
1253af732203SDimitry Andric
1254af732203SDimitry Andric /// Handle a change in variable location within a block. Terminate the
1255af732203SDimitry Andric /// variables current location, and record the value it now refers to, so
1256af732203SDimitry Andric /// that we can detect location transfers later on.
redefVar(const MachineInstr & MI,const DbgValueProperties & Properties,Optional<LocIdx> OptNewLoc)1257af732203SDimitry Andric void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
1258af732203SDimitry Andric Optional<LocIdx> OptNewLoc) {
1259af732203SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1260af732203SDimitry Andric MI.getDebugLoc()->getInlinedAt());
1261af732203SDimitry Andric // Any use-before-defs no longer apply.
1262af732203SDimitry Andric UseBeforeDefVariables.erase(Var);
1263af732203SDimitry Andric
1264af732203SDimitry Andric // Erase any previous location,
1265af732203SDimitry Andric auto It = ActiveVLocs.find(Var);
1266af732203SDimitry Andric if (It != ActiveVLocs.end())
1267af732203SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var);
1268af732203SDimitry Andric
1269af732203SDimitry Andric // If there _is_ no new location, all we had to do was erase.
1270af732203SDimitry Andric if (!OptNewLoc)
1271af732203SDimitry Andric return;
1272af732203SDimitry Andric LocIdx NewLoc = *OptNewLoc;
1273af732203SDimitry Andric
1274af732203SDimitry Andric // Check whether our local copy of values-by-location in #VarLocs is out of
1275af732203SDimitry Andric // date. Wipe old tracking data for the location if it's been clobbered in
1276af732203SDimitry Andric // the meantime.
1277af732203SDimitry Andric if (MTracker->getNumAtPos(NewLoc) != VarLocs[NewLoc.asU64()]) {
1278af732203SDimitry Andric for (auto &P : ActiveMLocs[NewLoc]) {
1279af732203SDimitry Andric ActiveVLocs.erase(P);
1280af732203SDimitry Andric }
1281af732203SDimitry Andric ActiveMLocs[NewLoc.asU64()].clear();
1282af732203SDimitry Andric VarLocs[NewLoc.asU64()] = MTracker->getNumAtPos(NewLoc);
1283af732203SDimitry Andric }
1284af732203SDimitry Andric
1285af732203SDimitry Andric ActiveMLocs[NewLoc].insert(Var);
1286af732203SDimitry Andric if (It == ActiveVLocs.end()) {
1287af732203SDimitry Andric ActiveVLocs.insert(
1288af732203SDimitry Andric std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
1289af732203SDimitry Andric } else {
1290af732203SDimitry Andric It->second.Loc = NewLoc;
1291af732203SDimitry Andric It->second.Properties = Properties;
1292af732203SDimitry Andric }
1293af732203SDimitry Andric }
1294af732203SDimitry Andric
1295*5f7ddb14SDimitry Andric /// Account for a location \p mloc being clobbered. Examine the variable
1296*5f7ddb14SDimitry Andric /// locations that will be terminated: and try to recover them by using
1297*5f7ddb14SDimitry Andric /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
1298*5f7ddb14SDimitry Andric /// explicitly terminate a location if it can't be recovered.
clobberMloc(LocIdx MLoc,MachineBasicBlock::iterator Pos,bool MakeUndef=true)1299*5f7ddb14SDimitry Andric void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
1300*5f7ddb14SDimitry Andric bool MakeUndef = true) {
1301af732203SDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc);
1302af732203SDimitry Andric if (ActiveMLocIt == ActiveMLocs.end())
1303af732203SDimitry Andric return;
1304af732203SDimitry Andric
1305*5f7ddb14SDimitry Andric // What was the old variable value?
1306*5f7ddb14SDimitry Andric ValueIDNum OldValue = VarLocs[MLoc.asU64()];
1307af732203SDimitry Andric VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
1308af732203SDimitry Andric
1309*5f7ddb14SDimitry Andric // Examine the remaining variable locations: if we can find the same value
1310*5f7ddb14SDimitry Andric // again, we can recover the location.
1311*5f7ddb14SDimitry Andric Optional<LocIdx> NewLoc = None;
1312*5f7ddb14SDimitry Andric for (auto Loc : MTracker->locations())
1313*5f7ddb14SDimitry Andric if (Loc.Value == OldValue)
1314*5f7ddb14SDimitry Andric NewLoc = Loc.Idx;
1315*5f7ddb14SDimitry Andric
1316*5f7ddb14SDimitry Andric // If there is no location, and we weren't asked to make the variable
1317*5f7ddb14SDimitry Andric // explicitly undef, then stop here.
1318*5f7ddb14SDimitry Andric if (!NewLoc && !MakeUndef) {
1319*5f7ddb14SDimitry Andric // Try and recover a few more locations with entry values.
1320*5f7ddb14SDimitry Andric for (auto &Var : ActiveMLocIt->second) {
1321*5f7ddb14SDimitry Andric auto &Prop = ActiveVLocs.find(Var)->second.Properties;
1322*5f7ddb14SDimitry Andric recoverAsEntryValue(Var, Prop, OldValue);
1323*5f7ddb14SDimitry Andric }
1324*5f7ddb14SDimitry Andric flushDbgValues(Pos, nullptr);
1325*5f7ddb14SDimitry Andric return;
1326*5f7ddb14SDimitry Andric }
1327*5f7ddb14SDimitry Andric
1328*5f7ddb14SDimitry Andric // Examine all the variables based on this location.
1329*5f7ddb14SDimitry Andric DenseSet<DebugVariable> NewMLocs;
1330af732203SDimitry Andric for (auto &Var : ActiveMLocIt->second) {
1331af732203SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var);
1332*5f7ddb14SDimitry Andric // Re-state the variable location: if there's no replacement then NewLoc
1333*5f7ddb14SDimitry Andric // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE
1334*5f7ddb14SDimitry Andric // identifying the alternative location will be emitted.
1335af732203SDimitry Andric const DIExpression *Expr = ActiveVLocIt->second.Properties.DIExpr;
1336af732203SDimitry Andric DbgValueProperties Properties(Expr, false);
1337*5f7ddb14SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties));
1338*5f7ddb14SDimitry Andric
1339*5f7ddb14SDimitry Andric // Update machine locations <=> variable locations maps. Defer updating
1340*5f7ddb14SDimitry Andric // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator.
1341*5f7ddb14SDimitry Andric if (!NewLoc) {
1342af732203SDimitry Andric ActiveVLocs.erase(ActiveVLocIt);
1343*5f7ddb14SDimitry Andric } else {
1344*5f7ddb14SDimitry Andric ActiveVLocIt->second.Loc = *NewLoc;
1345*5f7ddb14SDimitry Andric NewMLocs.insert(Var);
1346af732203SDimitry Andric }
1347*5f7ddb14SDimitry Andric }
1348*5f7ddb14SDimitry Andric
1349*5f7ddb14SDimitry Andric // Commit any deferred ActiveMLoc changes.
1350*5f7ddb14SDimitry Andric if (!NewMLocs.empty())
1351*5f7ddb14SDimitry Andric for (auto &Var : NewMLocs)
1352*5f7ddb14SDimitry Andric ActiveMLocs[*NewLoc].insert(Var);
1353*5f7ddb14SDimitry Andric
1354*5f7ddb14SDimitry Andric // We lazily track what locations have which values; if we've found a new
1355*5f7ddb14SDimitry Andric // location for the clobbered value, remember it.
1356*5f7ddb14SDimitry Andric if (NewLoc)
1357*5f7ddb14SDimitry Andric VarLocs[NewLoc->asU64()] = OldValue;
1358*5f7ddb14SDimitry Andric
1359af732203SDimitry Andric flushDbgValues(Pos, nullptr);
1360af732203SDimitry Andric
1361af732203SDimitry Andric ActiveMLocIt->second.clear();
1362af732203SDimitry Andric }
1363af732203SDimitry Andric
1364af732203SDimitry Andric /// Transfer variables based on \p Src to be based on \p Dst. This handles
1365af732203SDimitry Andric /// both register copies as well as spills and restores. Creates DBG_VALUEs
1366af732203SDimitry Andric /// describing the movement.
transferMlocs(LocIdx Src,LocIdx Dst,MachineBasicBlock::iterator Pos)1367af732203SDimitry Andric void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
1368af732203SDimitry Andric // Does Src still contain the value num we expect? If not, it's been
1369af732203SDimitry Andric // clobbered in the meantime, and our variable locations are stale.
1370af732203SDimitry Andric if (VarLocs[Src.asU64()] != MTracker->getNumAtPos(Src))
1371af732203SDimitry Andric return;
1372af732203SDimitry Andric
1373af732203SDimitry Andric // assert(ActiveMLocs[Dst].size() == 0);
1374af732203SDimitry Andric //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
1375af732203SDimitry Andric ActiveMLocs[Dst] = ActiveMLocs[Src];
1376af732203SDimitry Andric VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
1377af732203SDimitry Andric
1378af732203SDimitry Andric // For each variable based on Src; create a location at Dst.
1379af732203SDimitry Andric for (auto &Var : ActiveMLocs[Src]) {
1380af732203SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var);
1381af732203SDimitry Andric assert(ActiveVLocIt != ActiveVLocs.end());
1382af732203SDimitry Andric ActiveVLocIt->second.Loc = Dst;
1383af732203SDimitry Andric
1384af732203SDimitry Andric assert(Dst != 0);
1385af732203SDimitry Andric MachineInstr *MI =
1386af732203SDimitry Andric MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
1387af732203SDimitry Andric PendingDbgValues.push_back(MI);
1388af732203SDimitry Andric }
1389af732203SDimitry Andric ActiveMLocs[Src].clear();
1390af732203SDimitry Andric flushDbgValues(Pos, nullptr);
1391af732203SDimitry Andric
1392af732203SDimitry Andric // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
1393af732203SDimitry Andric // about the old location.
1394af732203SDimitry Andric if (EmulateOldLDV)
1395af732203SDimitry Andric VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
1396af732203SDimitry Andric }
1397af732203SDimitry Andric
emitMOLoc(const MachineOperand & MO,const DebugVariable & Var,const DbgValueProperties & Properties)1398af732203SDimitry Andric MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
1399af732203SDimitry Andric const DebugVariable &Var,
1400af732203SDimitry Andric const DbgValueProperties &Properties) {
1401af732203SDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
1402af732203SDimitry Andric Var.getVariable()->getScope(),
1403af732203SDimitry Andric const_cast<DILocation *>(Var.getInlinedAt()));
1404af732203SDimitry Andric auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
1405af732203SDimitry Andric MIB.add(MO);
1406af732203SDimitry Andric if (Properties.Indirect)
1407af732203SDimitry Andric MIB.addImm(0);
1408af732203SDimitry Andric else
1409af732203SDimitry Andric MIB.addReg(0);
1410af732203SDimitry Andric MIB.addMetadata(Var.getVariable());
1411af732203SDimitry Andric MIB.addMetadata(Properties.DIExpr);
1412af732203SDimitry Andric return MIB;
1413af732203SDimitry Andric }
1414af732203SDimitry Andric };
1415af732203SDimitry Andric
1416af732203SDimitry Andric class InstrRefBasedLDV : public LDVImpl {
1417af732203SDimitry Andric private:
1418af732203SDimitry Andric using FragmentInfo = DIExpression::FragmentInfo;
1419af732203SDimitry Andric using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
1420af732203SDimitry Andric
1421af732203SDimitry Andric // Helper while building OverlapMap, a map of all fragments seen for a given
1422af732203SDimitry Andric // DILocalVariable.
1423af732203SDimitry Andric using VarToFragments =
1424af732203SDimitry Andric DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
1425af732203SDimitry Andric
1426af732203SDimitry Andric /// Machine location/value transfer function, a mapping of which locations
1427af732203SDimitry Andric /// are assigned which new values.
1428af732203SDimitry Andric using MLocTransferMap = std::map<LocIdx, ValueIDNum>;
1429af732203SDimitry Andric
1430af732203SDimitry Andric /// Live in/out structure for the variable values: a per-block map of
1431af732203SDimitry Andric /// variables to their values. XXX, better name?
1432af732203SDimitry Andric using LiveIdxT =
1433af732203SDimitry Andric DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>;
1434af732203SDimitry Andric
1435af732203SDimitry Andric using VarAndLoc = std::pair<DebugVariable, DbgValue>;
1436af732203SDimitry Andric
1437af732203SDimitry Andric /// Type for a live-in value: the predecessor block, and its value.
1438af732203SDimitry Andric using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
1439af732203SDimitry Andric
1440af732203SDimitry Andric /// Vector (per block) of a collection (inner smallvector) of live-ins.
1441af732203SDimitry Andric /// Used as the result type for the variable value dataflow problem.
1442af732203SDimitry Andric using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
1443af732203SDimitry Andric
1444af732203SDimitry Andric const TargetRegisterInfo *TRI;
1445af732203SDimitry Andric const TargetInstrInfo *TII;
1446af732203SDimitry Andric const TargetFrameLowering *TFI;
1447*5f7ddb14SDimitry Andric const MachineFrameInfo *MFI;
1448af732203SDimitry Andric BitVector CalleeSavedRegs;
1449af732203SDimitry Andric LexicalScopes LS;
1450af732203SDimitry Andric TargetPassConfig *TPC;
1451af732203SDimitry Andric
1452af732203SDimitry Andric /// Object to track machine locations as we step through a block. Could
1453af732203SDimitry Andric /// probably be a field rather than a pointer, as it's always used.
1454af732203SDimitry Andric MLocTracker *MTracker;
1455af732203SDimitry Andric
1456af732203SDimitry Andric /// Number of the current block LiveDebugValues is stepping through.
1457af732203SDimitry Andric unsigned CurBB;
1458af732203SDimitry Andric
1459af732203SDimitry Andric /// Number of the current instruction LiveDebugValues is evaluating.
1460af732203SDimitry Andric unsigned CurInst;
1461af732203SDimitry Andric
1462af732203SDimitry Andric /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
1463af732203SDimitry Andric /// steps through a block. Reads the values at each location from the
1464af732203SDimitry Andric /// MLocTracker object.
1465af732203SDimitry Andric VLocTracker *VTracker;
1466af732203SDimitry Andric
1467af732203SDimitry Andric /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
1468af732203SDimitry Andric /// between locations during stepping, creates new DBG_VALUEs when values move
1469af732203SDimitry Andric /// location.
1470af732203SDimitry Andric TransferTracker *TTracker;
1471af732203SDimitry Andric
1472af732203SDimitry Andric /// Blocks which are artificial, i.e. blocks which exclusively contain
1473af732203SDimitry Andric /// instructions without DebugLocs, or with line 0 locations.
1474af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1475af732203SDimitry Andric
1476af732203SDimitry Andric // Mapping of blocks to and from their RPOT order.
1477af732203SDimitry Andric DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1478af732203SDimitry Andric DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1479af732203SDimitry Andric DenseMap<unsigned, unsigned> BBNumToRPO;
1480af732203SDimitry Andric
1481af732203SDimitry Andric /// Pair of MachineInstr, and its 1-based offset into the containing block.
1482af732203SDimitry Andric using InstAndNum = std::pair<const MachineInstr *, unsigned>;
1483af732203SDimitry Andric /// Map from debug instruction number to the MachineInstr labelled with that
1484af732203SDimitry Andric /// number, and its location within the function. Used to transform
1485af732203SDimitry Andric /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
1486af732203SDimitry Andric std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
1487af732203SDimitry Andric
1488*5f7ddb14SDimitry Andric /// Record of where we observed a DBG_PHI instruction.
1489*5f7ddb14SDimitry Andric class DebugPHIRecord {
1490*5f7ddb14SDimitry Andric public:
1491*5f7ddb14SDimitry Andric uint64_t InstrNum; ///< Instruction number of this DBG_PHI.
1492*5f7ddb14SDimitry Andric MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred.
1493*5f7ddb14SDimitry Andric ValueIDNum ValueRead; ///< The value number read by the DBG_PHI.
1494*5f7ddb14SDimitry Andric LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads.
1495*5f7ddb14SDimitry Andric
operator unsigned() const1496*5f7ddb14SDimitry Andric operator unsigned() const { return InstrNum; }
1497*5f7ddb14SDimitry Andric };
1498*5f7ddb14SDimitry Andric
1499*5f7ddb14SDimitry Andric /// Map from instruction numbers defined by DBG_PHIs to a record of what that
1500*5f7ddb14SDimitry Andric /// DBG_PHI read and where. Populated and edited during the machine value
1501*5f7ddb14SDimitry Andric /// location problem -- we use LLVMs SSA Updater to fix changes by
1502*5f7ddb14SDimitry Andric /// optimizations that destroy PHI instructions.
1503*5f7ddb14SDimitry Andric SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
1504*5f7ddb14SDimitry Andric
1505af732203SDimitry Andric // Map of overlapping variable fragments.
1506af732203SDimitry Andric OverlapMap OverlapFragments;
1507af732203SDimitry Andric VarToFragments SeenFragments;
1508af732203SDimitry Andric
1509af732203SDimitry Andric /// Tests whether this instruction is a spill to a stack slot.
1510af732203SDimitry Andric bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
1511af732203SDimitry Andric
1512af732203SDimitry Andric /// Decide if @MI is a spill instruction and return true if it is. We use 2
1513af732203SDimitry Andric /// criteria to make this decision:
1514af732203SDimitry Andric /// - Is this instruction a store to a spill slot?
1515af732203SDimitry Andric /// - Is there a register operand that is both used and killed?
1516af732203SDimitry Andric /// TODO: Store optimization can fold spills into other stores (including
1517af732203SDimitry Andric /// other spills). We do not handle this yet (more than one memory operand).
1518af732203SDimitry Andric bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
1519af732203SDimitry Andric unsigned &Reg);
1520af732203SDimitry Andric
1521af732203SDimitry Andric /// If a given instruction is identified as a spill, return the spill slot
1522af732203SDimitry Andric /// and set \p Reg to the spilled register.
1523af732203SDimitry Andric Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI,
1524af732203SDimitry Andric MachineFunction *MF, unsigned &Reg);
1525af732203SDimitry Andric
1526af732203SDimitry Andric /// Given a spill instruction, extract the register and offset used to
1527af732203SDimitry Andric /// address the spill slot in a target independent way.
1528af732203SDimitry Andric SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
1529af732203SDimitry Andric
1530af732203SDimitry Andric /// Observe a single instruction while stepping through a block.
1531*5f7ddb14SDimitry Andric void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr,
1532*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns = nullptr);
1533af732203SDimitry Andric
1534af732203SDimitry Andric /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
1535af732203SDimitry Andric /// \returns true if MI was recognized and processed.
1536af732203SDimitry Andric bool transferDebugValue(const MachineInstr &MI);
1537af732203SDimitry Andric
1538af732203SDimitry Andric /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
1539af732203SDimitry Andric /// \returns true if MI was recognized and processed.
1540*5f7ddb14SDimitry Andric bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts,
1541*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns);
1542*5f7ddb14SDimitry Andric
1543*5f7ddb14SDimitry Andric /// Stores value-information about where this PHI occurred, and what
1544*5f7ddb14SDimitry Andric /// instruction number is associated with it.
1545*5f7ddb14SDimitry Andric /// \returns true if MI was recognized and processed.
1546*5f7ddb14SDimitry Andric bool transferDebugPHI(MachineInstr &MI);
1547af732203SDimitry Andric
1548af732203SDimitry Andric /// Examines whether \p MI is copy instruction, and notifies trackers.
1549af732203SDimitry Andric /// \returns true if MI was recognized and processed.
1550af732203SDimitry Andric bool transferRegisterCopy(MachineInstr &MI);
1551af732203SDimitry Andric
1552af732203SDimitry Andric /// Examines whether \p MI is stack spill or restore instruction, and
1553af732203SDimitry Andric /// notifies trackers. \returns true if MI was recognized and processed.
1554af732203SDimitry Andric bool transferSpillOrRestoreInst(MachineInstr &MI);
1555af732203SDimitry Andric
1556af732203SDimitry Andric /// Examines \p MI for any registers that it defines, and notifies trackers.
1557af732203SDimitry Andric void transferRegisterDef(MachineInstr &MI);
1558af732203SDimitry Andric
1559af732203SDimitry Andric /// Copy one location to the other, accounting for movement of subregisters
1560af732203SDimitry Andric /// too.
1561af732203SDimitry Andric void performCopy(Register Src, Register Dst);
1562af732203SDimitry Andric
1563af732203SDimitry Andric void accumulateFragmentMap(MachineInstr &MI);
1564af732203SDimitry Andric
1565*5f7ddb14SDimitry Andric /// Determine the machine value number referred to by (potentially several)
1566*5f7ddb14SDimitry Andric /// DBG_PHI instructions. Block duplication and tail folding can duplicate
1567*5f7ddb14SDimitry Andric /// DBG_PHIs, shifting the position where values in registers merge, and
1568*5f7ddb14SDimitry Andric /// forming another mini-ssa problem to solve.
1569*5f7ddb14SDimitry Andric /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
1570*5f7ddb14SDimitry Andric /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
1571*5f7ddb14SDimitry Andric /// \returns The machine value number at position Here, or None.
1572*5f7ddb14SDimitry Andric Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
1573*5f7ddb14SDimitry Andric ValueIDNum **MLiveOuts,
1574*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns, MachineInstr &Here,
1575*5f7ddb14SDimitry Andric uint64_t InstrNum);
1576*5f7ddb14SDimitry Andric
1577af732203SDimitry Andric /// Step through the function, recording register definitions and movements
1578af732203SDimitry Andric /// in an MLocTracker. Convert the observations into a per-block transfer
1579af732203SDimitry Andric /// function in \p MLocTransfer, suitable for using with the machine value
1580af732203SDimitry Andric /// location dataflow problem.
1581af732203SDimitry Andric void
1582af732203SDimitry Andric produceMLocTransferFunction(MachineFunction &MF,
1583af732203SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1584af732203SDimitry Andric unsigned MaxNumBlocks);
1585af732203SDimitry Andric
1586af732203SDimitry Andric /// Solve the machine value location dataflow problem. Takes as input the
1587af732203SDimitry Andric /// transfer functions in \p MLocTransfer. Writes the output live-in and
1588af732203SDimitry Andric /// live-out arrays to the (initialized to zero) multidimensional arrays in
1589af732203SDimitry Andric /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
1590af732203SDimitry Andric /// number, the inner by LocIdx.
1591af732203SDimitry Andric void mlocDataflow(ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
1592af732203SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer);
1593af732203SDimitry Andric
1594af732203SDimitry Andric /// Perform a control flow join (lattice value meet) of the values in machine
1595af732203SDimitry Andric /// locations at \p MBB. Follows the algorithm described in the file-comment,
1596af732203SDimitry Andric /// reading live-outs of predecessors from \p OutLocs, the current live ins
1597af732203SDimitry Andric /// from \p InLocs, and assigning the newly computed live ins back into
1598af732203SDimitry Andric /// \p InLocs. \returns two bools -- the first indicates whether a change
1599af732203SDimitry Andric /// was made, the second whether a lattice downgrade occurred. If the latter
1600af732203SDimitry Andric /// is true, revisiting this block is necessary.
1601af732203SDimitry Andric std::tuple<bool, bool>
1602af732203SDimitry Andric mlocJoin(MachineBasicBlock &MBB,
1603af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1604af732203SDimitry Andric ValueIDNum **OutLocs, ValueIDNum *InLocs);
1605af732203SDimitry Andric
1606af732203SDimitry Andric /// Solve the variable value dataflow problem, for a single lexical scope.
1607af732203SDimitry Andric /// Uses the algorithm from the file comment to resolve control flow joins,
1608af732203SDimitry Andric /// although there are extra hacks, see vlocJoin. Reads the
1609af732203SDimitry Andric /// locations of values from the \p MInLocs and \p MOutLocs arrays (see
1610af732203SDimitry Andric /// mlocDataflow) and reads the variable values transfer function from
1611af732203SDimitry Andric /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally,
1612af732203SDimitry Andric /// with the live-ins permanently stored to \p Output once the fixedpoint is
1613af732203SDimitry Andric /// reached.
1614af732203SDimitry Andric /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
1615af732203SDimitry Andric /// that we should be tracking.
1616af732203SDimitry Andric /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but
1617af732203SDimitry Andric /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations
1618af732203SDimitry Andric /// through.
1619af732203SDimitry Andric void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc,
1620af732203SDimitry Andric const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
1621af732203SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
1622af732203SDimitry Andric LiveInsT &Output, ValueIDNum **MOutLocs,
1623af732203SDimitry Andric ValueIDNum **MInLocs,
1624af732203SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs);
1625af732203SDimitry Andric
1626af732203SDimitry Andric /// Compute the live-ins to a block, considering control flow merges according
1627af732203SDimitry Andric /// to the method in the file comment. Live out and live in variable values
1628af732203SDimitry Andric /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB
1629af732203SDimitry Andric /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins
1630af732203SDimitry Andric /// are modified.
1631af732203SDimitry Andric /// \p InLocsT Output argument, storage for calculated live-ins.
1632af732203SDimitry Andric /// \returns two bools -- the first indicates whether a change
1633af732203SDimitry Andric /// was made, the second whether a lattice downgrade occurred. If the latter
1634af732203SDimitry Andric /// is true, revisiting this block is necessary.
1635af732203SDimitry Andric std::tuple<bool, bool>
1636af732203SDimitry Andric vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
1637af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited,
1638af732203SDimitry Andric unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars,
1639af732203SDimitry Andric ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
1640af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
1641af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
1642af732203SDimitry Andric DenseMap<DebugVariable, DbgValue> &InLocsT);
1643af732203SDimitry Andric
1644af732203SDimitry Andric /// Continue exploration of the variable-value lattice, as explained in the
1645af732203SDimitry Andric /// file-level comment. \p OldLiveInLocation contains the current
1646af732203SDimitry Andric /// exploration position, from which we need to descend further. \p Values
1647af732203SDimitry Andric /// contains the set of live-in values, \p CurBlockRPONum the RPO number of
1648af732203SDimitry Andric /// the current block, and \p CandidateLocations a set of locations that
1649af732203SDimitry Andric /// should be considered as PHI locations, if we reach the bottom of the
1650af732203SDimitry Andric /// lattice. \returns true if we should downgrade; the value is the agreeing
1651af732203SDimitry Andric /// value number in a non-backedge predecessor.
1652af732203SDimitry Andric bool vlocDowngradeLattice(const MachineBasicBlock &MBB,
1653af732203SDimitry Andric const DbgValue &OldLiveInLocation,
1654af732203SDimitry Andric const SmallVectorImpl<InValueT> &Values,
1655af732203SDimitry Andric unsigned CurBlockRPONum);
1656af732203SDimitry Andric
1657af732203SDimitry Andric /// For the given block and live-outs feeding into it, try to find a
1658af732203SDimitry Andric /// machine location where they all join. If a solution for all predecessors
1659af732203SDimitry Andric /// can't be found, a location where all non-backedge-predecessors join
1660af732203SDimitry Andric /// will be returned instead. While this method finds a join location, this
1661af732203SDimitry Andric /// says nothing as to whether it should be used.
1662af732203SDimitry Andric /// \returns Pair of value ID if found, and true when the correct value
1663af732203SDimitry Andric /// is available on all predecessor edges, or false if it's only available
1664af732203SDimitry Andric /// for non-backedge predecessors.
1665af732203SDimitry Andric std::tuple<Optional<ValueIDNum>, bool>
1666af732203SDimitry Andric pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var,
1667af732203SDimitry Andric const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
1668af732203SDimitry Andric ValueIDNum **MInLocs,
1669af732203SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &BlockOrders);
1670af732203SDimitry Andric
1671af732203SDimitry Andric /// Given the solutions to the two dataflow problems, machine value locations
1672af732203SDimitry Andric /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the
1673af732203SDimitry Andric /// TransferTracker class over the function to produce live-in and transfer
1674af732203SDimitry Andric /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the
1675af732203SDimitry Andric /// order given by AllVarsNumbering -- this could be any stable order, but
1676af732203SDimitry Andric /// right now "order of appearence in function, when explored in RPO", so
1677af732203SDimitry Andric /// that we can compare explictly against VarLocBasedImpl.
1678af732203SDimitry Andric void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns,
1679*5f7ddb14SDimitry Andric ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
1680*5f7ddb14SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
1681*5f7ddb14SDimitry Andric const TargetPassConfig &TPC);
1682af732203SDimitry Andric
1683af732203SDimitry Andric /// Boilerplate computation of some initial sets, artifical blocks and
1684af732203SDimitry Andric /// RPOT block ordering.
1685af732203SDimitry Andric void initialSetup(MachineFunction &MF);
1686af732203SDimitry Andric
1687af732203SDimitry Andric bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override;
1688af732203SDimitry Andric
1689af732203SDimitry Andric public:
1690af732203SDimitry Andric /// Default construct and initialize the pass.
1691af732203SDimitry Andric InstrRefBasedLDV();
1692af732203SDimitry Andric
1693af732203SDimitry Andric LLVM_DUMP_METHOD
1694af732203SDimitry Andric void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
1695af732203SDimitry Andric
isCalleeSaved(LocIdx L)1696af732203SDimitry Andric bool isCalleeSaved(LocIdx L) {
1697af732203SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L];
1698af732203SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1699af732203SDimitry Andric if (CalleeSavedRegs.test(*RAI))
1700af732203SDimitry Andric return true;
1701af732203SDimitry Andric return false;
1702af732203SDimitry Andric }
1703af732203SDimitry Andric };
1704af732203SDimitry Andric
1705af732203SDimitry Andric } // end anonymous namespace
1706af732203SDimitry Andric
1707af732203SDimitry Andric //===----------------------------------------------------------------------===//
1708af732203SDimitry Andric // Implementation
1709af732203SDimitry Andric //===----------------------------------------------------------------------===//
1710af732203SDimitry Andric
1711af732203SDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
1712af732203SDimitry Andric
1713af732203SDimitry Andric /// Default construct and initialize the pass.
InstrRefBasedLDV()1714af732203SDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() {}
1715af732203SDimitry Andric
1716af732203SDimitry Andric //===----------------------------------------------------------------------===//
1717af732203SDimitry Andric // Debug Range Extension Implementation
1718af732203SDimitry Andric //===----------------------------------------------------------------------===//
1719af732203SDimitry Andric
1720af732203SDimitry Andric #ifndef NDEBUG
1721af732203SDimitry Andric // Something to restore in the future.
1722af732203SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..)
1723af732203SDimitry Andric #endif
1724af732203SDimitry Andric
1725af732203SDimitry Andric SpillLoc
extractSpillBaseRegAndOffset(const MachineInstr & MI)1726af732203SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1727af732203SDimitry Andric assert(MI.hasOneMemOperand() &&
1728af732203SDimitry Andric "Spill instruction does not have exactly one memory operand?");
1729af732203SDimitry Andric auto MMOI = MI.memoperands_begin();
1730af732203SDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1731af732203SDimitry Andric assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1732af732203SDimitry Andric "Inconsistent memory operand in spill instruction");
1733af732203SDimitry Andric int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1734af732203SDimitry Andric const MachineBasicBlock *MBB = MI.getParent();
1735af732203SDimitry Andric Register Reg;
1736af732203SDimitry Andric StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1737af732203SDimitry Andric return {Reg, Offset};
1738af732203SDimitry Andric }
1739af732203SDimitry Andric
1740af732203SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI
1741af732203SDimitry Andric /// if it is a DBG_VALUE instr.
transferDebugValue(const MachineInstr & MI)1742af732203SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1743af732203SDimitry Andric if (!MI.isDebugValue())
1744af732203SDimitry Andric return false;
1745af732203SDimitry Andric
1746af732203SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable();
1747af732203SDimitry Andric const DIExpression *Expr = MI.getDebugExpression();
1748af732203SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc();
1749af732203SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1750af732203SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1751af732203SDimitry Andric "Expected inlined-at fields to agree");
1752af732203SDimitry Andric
1753af732203SDimitry Andric DebugVariable V(Var, Expr, InlinedAt);
1754af732203SDimitry Andric DbgValueProperties Properties(MI);
1755af732203SDimitry Andric
1756af732203SDimitry Andric // If there are no instructions in this lexical scope, do no location tracking
1757af732203SDimitry Andric // at all, this variable shouldn't get a legitimate location range.
1758af732203SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1759af732203SDimitry Andric if (Scope == nullptr)
1760af732203SDimitry Andric return true; // handled it; by doing nothing
1761af732203SDimitry Andric
1762af732203SDimitry Andric const MachineOperand &MO = MI.getOperand(0);
1763af732203SDimitry Andric
1764af732203SDimitry Andric // MLocTracker needs to know that this register is read, even if it's only
1765af732203SDimitry Andric // read by a debug inst.
1766af732203SDimitry Andric if (MO.isReg() && MO.getReg() != 0)
1767af732203SDimitry Andric (void)MTracker->readReg(MO.getReg());
1768af732203SDimitry Andric
1769af732203SDimitry Andric // If we're preparing for the second analysis (variables), the machine value
1770af732203SDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value
1771af732203SDimitry Andric // it refers to to VLocTracker.
1772af732203SDimitry Andric if (VTracker) {
1773af732203SDimitry Andric if (MO.isReg()) {
1774af732203SDimitry Andric // Feed defVar the new variable location, or if this is a
1775af732203SDimitry Andric // DBG_VALUE $noreg, feed defVar None.
1776af732203SDimitry Andric if (MO.getReg())
1777af732203SDimitry Andric VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1778af732203SDimitry Andric else
1779af732203SDimitry Andric VTracker->defVar(MI, Properties, None);
1780af732203SDimitry Andric } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1781af732203SDimitry Andric MI.getOperand(0).isCImm()) {
1782af732203SDimitry Andric VTracker->defVar(MI, MI.getOperand(0));
1783af732203SDimitry Andric }
1784af732203SDimitry Andric }
1785af732203SDimitry Andric
1786af732203SDimitry Andric // If performing final tracking of transfers, report this variable definition
1787af732203SDimitry Andric // to the TransferTracker too.
1788af732203SDimitry Andric if (TTracker)
1789af732203SDimitry Andric TTracker->redefVar(MI);
1790af732203SDimitry Andric return true;
1791af732203SDimitry Andric }
1792af732203SDimitry Andric
transferDebugInstrRef(MachineInstr & MI,ValueIDNum ** MLiveOuts,ValueIDNum ** MLiveIns)1793*5f7ddb14SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1794*5f7ddb14SDimitry Andric ValueIDNum **MLiveOuts,
1795*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns) {
1796af732203SDimitry Andric if (!MI.isDebugRef())
1797af732203SDimitry Andric return false;
1798af732203SDimitry Andric
1799af732203SDimitry Andric // Only handle this instruction when we are building the variable value
1800af732203SDimitry Andric // transfer function.
1801af732203SDimitry Andric if (!VTracker)
1802af732203SDimitry Andric return false;
1803af732203SDimitry Andric
1804af732203SDimitry Andric unsigned InstNo = MI.getOperand(0).getImm();
1805af732203SDimitry Andric unsigned OpNo = MI.getOperand(1).getImm();
1806af732203SDimitry Andric
1807af732203SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable();
1808af732203SDimitry Andric const DIExpression *Expr = MI.getDebugExpression();
1809af732203SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc();
1810af732203SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1811af732203SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1812af732203SDimitry Andric "Expected inlined-at fields to agree");
1813af732203SDimitry Andric
1814af732203SDimitry Andric DebugVariable V(Var, Expr, InlinedAt);
1815af732203SDimitry Andric
1816af732203SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1817af732203SDimitry Andric if (Scope == nullptr)
1818af732203SDimitry Andric return true; // Handled by doing nothing. This variable is never in scope.
1819af732203SDimitry Andric
1820af732203SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent();
1821af732203SDimitry Andric
1822af732203SDimitry Andric // Various optimizations may have happened to the value during codegen,
1823af732203SDimitry Andric // recorded in the value substitution table. Apply any substitutions to
1824*5f7ddb14SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect
1825*5f7ddb14SDimitry Andric // any subregister extractions performed during optimization.
1826*5f7ddb14SDimitry Andric
1827*5f7ddb14SDimitry Andric // Create dummy substitution with Src set, for lookup.
1828*5f7ddb14SDimitry Andric auto SoughtSub =
1829*5f7ddb14SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1830*5f7ddb14SDimitry Andric
1831*5f7ddb14SDimitry Andric SmallVector<unsigned, 4> SeenSubregs;
1832*5f7ddb14SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1833*5f7ddb14SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1834*5f7ddb14SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) {
1835*5f7ddb14SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1836*5f7ddb14SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest;
1837*5f7ddb14SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg)
1838*5f7ddb14SDimitry Andric SeenSubregs.push_back(Subreg);
1839*5f7ddb14SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1840af732203SDimitry Andric }
1841af732203SDimitry Andric
1842af732203SDimitry Andric // Default machine value number is <None> -- if no instruction defines
1843af732203SDimitry Andric // the corresponding value, it must have been optimized out.
1844af732203SDimitry Andric Optional<ValueIDNum> NewID = None;
1845af732203SDimitry Andric
1846af732203SDimitry Andric // Try to lookup the instruction number, and find the machine value number
1847*5f7ddb14SDimitry Andric // that it defines. It could be an instruction, or a PHI.
1848af732203SDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1849*5f7ddb14SDimitry Andric auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(),
1850*5f7ddb14SDimitry Andric DebugPHINumToValue.end(), InstNo);
1851af732203SDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) {
1852af732203SDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first;
1853af732203SDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1854af732203SDimitry Andric
1855af732203SDimitry Andric // Pick out the designated operand.
1856af732203SDimitry Andric assert(OpNo < TargetInstr.getNumOperands());
1857af732203SDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1858af732203SDimitry Andric
1859af732203SDimitry Andric // Today, this can only be a register.
1860af732203SDimitry Andric assert(MO.isReg() && MO.isDef());
1861af732203SDimitry Andric
1862af732203SDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg(), false);
1863af732203SDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID];
1864af732203SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1865*5f7ddb14SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1866*5f7ddb14SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use
1867*5f7ddb14SDimitry Andric // the resolver helper to find out.
1868*5f7ddb14SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
1869*5f7ddb14SDimitry Andric MI, InstNo);
1870*5f7ddb14SDimitry Andric }
1871*5f7ddb14SDimitry Andric
1872*5f7ddb14SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code
1873*5f7ddb14SDimitry Andric // like this:
1874*5f7ddb14SDimitry Andric // CALL64 @foo, implicit-def $rax
1875*5f7ddb14SDimitry Andric // %0:gr64 = COPY $rax
1876*5f7ddb14SDimitry Andric // %1:gr32 = COPY %0.sub_32bit
1877*5f7ddb14SDimitry Andric // %2:gr16 = COPY %1.sub_16bit
1878*5f7ddb14SDimitry Andric // %3:gr8 = COPY %2.sub_8bit
1879*5f7ddb14SDimitry Andric // In which case each copy would have been recorded as a substitution with
1880*5f7ddb14SDimitry Andric // a subregister qualifier. Apply those qualifiers now.
1881*5f7ddb14SDimitry Andric if (NewID && !SeenSubregs.empty()) {
1882*5f7ddb14SDimitry Andric unsigned Offset = 0;
1883*5f7ddb14SDimitry Andric unsigned Size = 0;
1884*5f7ddb14SDimitry Andric
1885*5f7ddb14SDimitry Andric // Look at each subregister that we passed through, and progressively
1886*5f7ddb14SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should
1887*5f7ddb14SDimitry Andric // only ever be the same or narrower width than what they read from;
1888*5f7ddb14SDimitry Andric // iterate in reverse order so that we go from wide to small.
1889*5f7ddb14SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) {
1890*5f7ddb14SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1891*5f7ddb14SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1892*5f7ddb14SDimitry Andric Offset += ThisOffset;
1893*5f7ddb14SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1894*5f7ddb14SDimitry Andric }
1895*5f7ddb14SDimitry Andric
1896*5f7ddb14SDimitry Andric // If that worked, look for an appropriate subregister with the register
1897*5f7ddb14SDimitry Andric // where the define happens. Don't look at values that were defined during
1898*5f7ddb14SDimitry Andric // a stack write: we can't currently express register locations within
1899*5f7ddb14SDimitry Andric // spills.
1900*5f7ddb14SDimitry Andric LocIdx L = NewID->getLoc();
1901*5f7ddb14SDimitry Andric if (NewID && !MTracker->isSpill(L)) {
1902*5f7ddb14SDimitry Andric // Find the register class for the register where this def happened.
1903*5f7ddb14SDimitry Andric // FIXME: no index for this?
1904*5f7ddb14SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L];
1905*5f7ddb14SDimitry Andric const TargetRegisterClass *TRC = nullptr;
1906*5f7ddb14SDimitry Andric for (auto *TRCI : TRI->regclasses())
1907*5f7ddb14SDimitry Andric if (TRCI->contains(Reg))
1908*5f7ddb14SDimitry Andric TRC = TRCI;
1909*5f7ddb14SDimitry Andric assert(TRC && "Couldn't find target register class?");
1910*5f7ddb14SDimitry Andric
1911*5f7ddb14SDimitry Andric // If the register we have isn't the right size or in the right place,
1912*5f7ddb14SDimitry Andric // Try to find a subregister inside it.
1913*5f7ddb14SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1914*5f7ddb14SDimitry Andric if (Size != MainRegSize || Offset) {
1915*5f7ddb14SDimitry Andric // Enumerate all subregisters, searching.
1916*5f7ddb14SDimitry Andric Register NewReg = 0;
1917*5f7ddb14SDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1918*5f7ddb14SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1919*5f7ddb14SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1920*5f7ddb14SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1921*5f7ddb14SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) {
1922*5f7ddb14SDimitry Andric NewReg = *SRI;
1923*5f7ddb14SDimitry Andric break;
1924*5f7ddb14SDimitry Andric }
1925*5f7ddb14SDimitry Andric }
1926*5f7ddb14SDimitry Andric
1927*5f7ddb14SDimitry Andric // If we didn't find anything: there's no way to express our value.
1928*5f7ddb14SDimitry Andric if (!NewReg) {
1929*5f7ddb14SDimitry Andric NewID = None;
1930*5f7ddb14SDimitry Andric } else {
1931*5f7ddb14SDimitry Andric // Re-state the value as being defined within the subregister
1932*5f7ddb14SDimitry Andric // that we found.
1933*5f7ddb14SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1934*5f7ddb14SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1935*5f7ddb14SDimitry Andric }
1936*5f7ddb14SDimitry Andric }
1937*5f7ddb14SDimitry Andric } else {
1938*5f7ddb14SDimitry Andric // If we can't handle subregisters, unset the new value.
1939*5f7ddb14SDimitry Andric NewID = None;
1940*5f7ddb14SDimitry Andric }
1941af732203SDimitry Andric }
1942af732203SDimitry Andric
1943af732203SDimitry Andric // We, we have a value number or None. Tell the variable value tracker about
1944af732203SDimitry Andric // it. The rest of this LiveDebugValues implementation acts exactly the same
1945af732203SDimitry Andric // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1946af732203SDimitry Andric // aren't immediately available).
1947af732203SDimitry Andric DbgValueProperties Properties(Expr, false);
1948af732203SDimitry Andric VTracker->defVar(MI, Properties, NewID);
1949af732203SDimitry Andric
1950af732203SDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF
1951af732203SDimitry Andric // into a plain DBG_VALUE.
1952af732203SDimitry Andric if (!TTracker)
1953af732203SDimitry Andric return true;
1954af732203SDimitry Andric
1955af732203SDimitry Andric // Pick a location for the machine value number, if such a location exists.
1956af732203SDimitry Andric // (This information could be stored in TransferTracker to make it faster).
1957af732203SDimitry Andric Optional<LocIdx> FoundLoc = None;
1958af732203SDimitry Andric for (auto Location : MTracker->locations()) {
1959af732203SDimitry Andric LocIdx CurL = Location.Idx;
1960af732203SDimitry Andric ValueIDNum ID = MTracker->LocIdxToIDNum[CurL];
1961af732203SDimitry Andric if (NewID && ID == NewID) {
1962af732203SDimitry Andric // If this is the first location with that value, pick it. Otherwise,
1963af732203SDimitry Andric // consider whether it's a "longer term" location.
1964af732203SDimitry Andric if (!FoundLoc) {
1965af732203SDimitry Andric FoundLoc = CurL;
1966af732203SDimitry Andric continue;
1967af732203SDimitry Andric }
1968af732203SDimitry Andric
1969af732203SDimitry Andric if (MTracker->isSpill(CurL))
1970af732203SDimitry Andric FoundLoc = CurL; // Spills are a longer term location.
1971af732203SDimitry Andric else if (!MTracker->isSpill(*FoundLoc) &&
1972af732203SDimitry Andric !MTracker->isSpill(CurL) &&
1973af732203SDimitry Andric !isCalleeSaved(*FoundLoc) &&
1974af732203SDimitry Andric isCalleeSaved(CurL))
1975af732203SDimitry Andric FoundLoc = CurL; // Callee saved regs are longer term than normal.
1976af732203SDimitry Andric }
1977af732203SDimitry Andric }
1978af732203SDimitry Andric
1979af732203SDimitry Andric // Tell transfer tracker that the variable value has changed.
1980af732203SDimitry Andric TTracker->redefVar(MI, Properties, FoundLoc);
1981af732203SDimitry Andric
1982af732203SDimitry Andric // If there was a value with no location; but the value is defined in a
1983af732203SDimitry Andric // later instruction in this block, this is a block-local use-before-def.
1984af732203SDimitry Andric if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1985af732203SDimitry Andric NewID->getInst() > CurInst)
1986af732203SDimitry Andric TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1987af732203SDimitry Andric
1988af732203SDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1989af732203SDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if
1990af732203SDimitry Andric // FoundLoc is None.
1991af732203SDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future).
1992af732203SDimitry Andric MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1993af732203SDimitry Andric TTracker->PendingDbgValues.push_back(DbgMI);
1994af732203SDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr);
1995*5f7ddb14SDimitry Andric return true;
1996*5f7ddb14SDimitry Andric }
1997*5f7ddb14SDimitry Andric
transferDebugPHI(MachineInstr & MI)1998*5f7ddb14SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1999*5f7ddb14SDimitry Andric if (!MI.isDebugPHI())
2000*5f7ddb14SDimitry Andric return false;
2001*5f7ddb14SDimitry Andric
2002*5f7ddb14SDimitry Andric // Analyse these only when solving the machine value location problem.
2003*5f7ddb14SDimitry Andric if (VTracker || TTracker)
2004*5f7ddb14SDimitry Andric return true;
2005*5f7ddb14SDimitry Andric
2006*5f7ddb14SDimitry Andric // First operand is the value location, either a stack slot or register.
2007*5f7ddb14SDimitry Andric // Second is the debug instruction number of the original PHI.
2008*5f7ddb14SDimitry Andric const MachineOperand &MO = MI.getOperand(0);
2009*5f7ddb14SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm();
2010*5f7ddb14SDimitry Andric
2011*5f7ddb14SDimitry Andric if (MO.isReg()) {
2012*5f7ddb14SDimitry Andric // The value is whatever's currently in the register. Read and record it,
2013*5f7ddb14SDimitry Andric // to be analysed later.
2014*5f7ddb14SDimitry Andric Register Reg = MO.getReg();
2015*5f7ddb14SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg);
2016*5f7ddb14SDimitry Andric auto PHIRec = DebugPHIRecord(
2017*5f7ddb14SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
2018*5f7ddb14SDimitry Andric DebugPHINumToValue.push_back(PHIRec);
2019*5f7ddb14SDimitry Andric } else {
2020*5f7ddb14SDimitry Andric // The value is whatever's in this stack slot.
2021*5f7ddb14SDimitry Andric assert(MO.isFI());
2022*5f7ddb14SDimitry Andric unsigned FI = MO.getIndex();
2023*5f7ddb14SDimitry Andric
2024*5f7ddb14SDimitry Andric // If the stack slot is dead, then this was optimized away.
2025*5f7ddb14SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged.
2026*5f7ddb14SDimitry Andric if (MFI->isDeadObjectIndex(FI))
2027*5f7ddb14SDimitry Andric return true;
2028*5f7ddb14SDimitry Andric
2029*5f7ddb14SDimitry Andric // Identify this spill slot.
2030*5f7ddb14SDimitry Andric Register Base;
2031*5f7ddb14SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
2032*5f7ddb14SDimitry Andric SpillLoc SL = {Base, Offs};
2033*5f7ddb14SDimitry Andric Optional<ValueIDNum> Num = MTracker->readSpill(SL);
2034*5f7ddb14SDimitry Andric
2035*5f7ddb14SDimitry Andric if (!Num)
2036*5f7ddb14SDimitry Andric // Nothing ever writes to this slot. Curious, but nothing we can do.
2037*5f7ddb14SDimitry Andric return true;
2038*5f7ddb14SDimitry Andric
2039*5f7ddb14SDimitry Andric // Record this DBG_PHI for later analysis.
2040*5f7ddb14SDimitry Andric auto DbgPHI = DebugPHIRecord(
2041*5f7ddb14SDimitry Andric {InstrNum, MI.getParent(), *Num, *MTracker->getSpillMLoc(SL)});
2042*5f7ddb14SDimitry Andric DebugPHINumToValue.push_back(DbgPHI);
2043*5f7ddb14SDimitry Andric }
2044af732203SDimitry Andric
2045af732203SDimitry Andric return true;
2046af732203SDimitry Andric }
2047af732203SDimitry Andric
transferRegisterDef(MachineInstr & MI)2048af732203SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
2049af732203SDimitry Andric // Meta Instructions do not affect the debug liveness of any register they
2050af732203SDimitry Andric // define.
2051af732203SDimitry Andric if (MI.isImplicitDef()) {
2052af732203SDimitry Andric // Except when there's an implicit def, and the location it's defining has
2053af732203SDimitry Andric // no value number. The whole point of an implicit def is to announce that
2054af732203SDimitry Andric // the register is live, without be specific about it's value. So define
2055af732203SDimitry Andric // a value if there isn't one already.
2056af732203SDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
2057af732203SDimitry Andric // Has a legitimate value -> ignore the implicit def.
2058af732203SDimitry Andric if (Num.getLoc() != 0)
2059af732203SDimitry Andric return;
2060af732203SDimitry Andric // Otherwise, def it here.
2061af732203SDimitry Andric } else if (MI.isMetaInstruction())
2062af732203SDimitry Andric return;
2063af732203SDimitry Andric
2064af732203SDimitry Andric MachineFunction *MF = MI.getMF();
2065af732203SDimitry Andric const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2066af732203SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore();
2067af732203SDimitry Andric
2068af732203SDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs.
2069af732203SDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this
2070af732203SDimitry Andric // prevents fallback to std::set::count() operations.
2071af732203SDimitry Andric SmallSet<uint32_t, 32> DeadRegs;
2072af732203SDimitry Andric SmallVector<const uint32_t *, 4> RegMasks;
2073af732203SDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs;
2074af732203SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
2075af732203SDimitry Andric // Determine whether the operand is a register def.
2076af732203SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() &&
2077af732203SDimitry Andric Register::isPhysicalRegister(MO.getReg()) &&
2078af732203SDimitry Andric !(MI.isCall() && MO.getReg() == SP)) {
2079af732203SDimitry Andric // Remove ranges of all aliased registers.
2080af732203SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
2081af732203SDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs?
2082af732203SDimitry Andric DeadRegs.insert(*RAI);
2083af732203SDimitry Andric } else if (MO.isRegMask()) {
2084af732203SDimitry Andric RegMasks.push_back(MO.getRegMask());
2085af732203SDimitry Andric RegMaskPtrs.push_back(&MO);
2086af732203SDimitry Andric }
2087af732203SDimitry Andric }
2088af732203SDimitry Andric
2089af732203SDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise.
2090af732203SDimitry Andric for (uint32_t DeadReg : DeadRegs)
2091af732203SDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst);
2092af732203SDimitry Andric
2093af732203SDimitry Andric for (auto *MO : RegMaskPtrs)
2094af732203SDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst);
2095*5f7ddb14SDimitry Andric
2096*5f7ddb14SDimitry Andric if (!TTracker)
2097*5f7ddb14SDimitry Andric return;
2098*5f7ddb14SDimitry Andric
2099*5f7ddb14SDimitry Andric // When committing variable values to locations: tell transfer tracker that
2100*5f7ddb14SDimitry Andric // we've clobbered things. It may be able to recover the variable from a
2101*5f7ddb14SDimitry Andric // different location.
2102*5f7ddb14SDimitry Andric
2103*5f7ddb14SDimitry Andric // Inform TTracker about any direct clobbers.
2104*5f7ddb14SDimitry Andric for (uint32_t DeadReg : DeadRegs) {
2105*5f7ddb14SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
2106*5f7ddb14SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false);
2107*5f7ddb14SDimitry Andric }
2108*5f7ddb14SDimitry Andric
2109*5f7ddb14SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations
2110*5f7ddb14SDimitry Andric // that are actually being tracked.
2111*5f7ddb14SDimitry Andric for (auto L : MTracker->locations()) {
2112*5f7ddb14SDimitry Andric // Stack locations can't be clobbered by regmasks.
2113*5f7ddb14SDimitry Andric if (MTracker->isSpill(L.Idx))
2114*5f7ddb14SDimitry Andric continue;
2115*5f7ddb14SDimitry Andric
2116*5f7ddb14SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx];
2117*5f7ddb14SDimitry Andric for (auto *MO : RegMaskPtrs)
2118*5f7ddb14SDimitry Andric if (MO->clobbersPhysReg(Reg))
2119*5f7ddb14SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
2120*5f7ddb14SDimitry Andric }
2121af732203SDimitry Andric }
2122af732203SDimitry Andric
performCopy(Register SrcRegNum,Register DstRegNum)2123af732203SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
2124af732203SDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
2125af732203SDimitry Andric
2126af732203SDimitry Andric MTracker->setReg(DstRegNum, SrcValue);
2127af732203SDimitry Andric
2128af732203SDimitry Andric // In all circumstances, re-def the super registers. It's definitely a new
2129af732203SDimitry Andric // value now. This doesn't uniquely identify the composition of subregs, for
2130af732203SDimitry Andric // example, two identical values in subregisters composed in different
2131af732203SDimitry Andric // places would not get equal value numbers.
2132af732203SDimitry Andric for (MCSuperRegIterator SRI(DstRegNum, TRI); SRI.isValid(); ++SRI)
2133af732203SDimitry Andric MTracker->defReg(*SRI, CurBB, CurInst);
2134af732203SDimitry Andric
2135af732203SDimitry Andric // If we're emulating VarLocBasedImpl, just define all the subregisters.
2136af732203SDimitry Andric // DBG_VALUEs of them will expect to be tracked from the DBG_VALUE, not
2137af732203SDimitry Andric // through prior copies.
2138af732203SDimitry Andric if (EmulateOldLDV) {
2139af732203SDimitry Andric for (MCSubRegIndexIterator DRI(DstRegNum, TRI); DRI.isValid(); ++DRI)
2140af732203SDimitry Andric MTracker->defReg(DRI.getSubReg(), CurBB, CurInst);
2141af732203SDimitry Andric return;
2142af732203SDimitry Andric }
2143af732203SDimitry Andric
2144af732203SDimitry Andric // Otherwise, actually copy subregisters from one location to another.
2145af732203SDimitry Andric // XXX: in addition, any subregisters of DstRegNum that don't line up with
2146af732203SDimitry Andric // the source register should be def'd.
2147af732203SDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
2148af732203SDimitry Andric unsigned SrcSubReg = SRI.getSubReg();
2149af732203SDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex();
2150af732203SDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
2151af732203SDimitry Andric if (!DstSubReg)
2152af732203SDimitry Andric continue;
2153af732203SDimitry Andric
2154af732203SDimitry Andric // Do copy. There are two matching subregisters, the source value should
2155af732203SDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked
2156af732203SDimitry Andric // yet.
2157af732203SDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet.
2158af732203SDimitry Andric (void)MTracker->readReg(SrcSubReg);
2159af732203SDimitry Andric LocIdx SrcL = MTracker->getRegMLoc(SrcSubReg);
2160af732203SDimitry Andric assert(SrcL.asU64());
2161af732203SDimitry Andric (void)MTracker->readReg(DstSubReg);
2162af732203SDimitry Andric LocIdx DstL = MTracker->getRegMLoc(DstSubReg);
2163af732203SDimitry Andric assert(DstL.asU64());
2164af732203SDimitry Andric (void)DstL;
2165af732203SDimitry Andric ValueIDNum CpyValue = {SrcValue.getBlock(), SrcValue.getInst(), SrcL};
2166af732203SDimitry Andric
2167af732203SDimitry Andric MTracker->setReg(DstSubReg, CpyValue);
2168af732203SDimitry Andric }
2169af732203SDimitry Andric }
2170af732203SDimitry Andric
isSpillInstruction(const MachineInstr & MI,MachineFunction * MF)2171af732203SDimitry Andric bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
2172af732203SDimitry Andric MachineFunction *MF) {
2173af732203SDimitry Andric // TODO: Handle multiple stores folded into one.
2174af732203SDimitry Andric if (!MI.hasOneMemOperand())
2175af732203SDimitry Andric return false;
2176af732203SDimitry Andric
2177af732203SDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
2178af732203SDimitry Andric return false; // This is not a spill instruction, since no valid size was
2179af732203SDimitry Andric // returned from either function.
2180af732203SDimitry Andric
2181af732203SDimitry Andric return true;
2182af732203SDimitry Andric }
2183af732203SDimitry Andric
isLocationSpill(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)2184af732203SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
2185af732203SDimitry Andric MachineFunction *MF, unsigned &Reg) {
2186af732203SDimitry Andric if (!isSpillInstruction(MI, MF))
2187af732203SDimitry Andric return false;
2188af732203SDimitry Andric
2189af732203SDimitry Andric int FI;
2190af732203SDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI);
2191af732203SDimitry Andric return Reg != 0;
2192af732203SDimitry Andric }
2193af732203SDimitry Andric
2194af732203SDimitry Andric Optional<SpillLoc>
isRestoreInstruction(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)2195af732203SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
2196af732203SDimitry Andric MachineFunction *MF, unsigned &Reg) {
2197af732203SDimitry Andric if (!MI.hasOneMemOperand())
2198af732203SDimitry Andric return None;
2199af732203SDimitry Andric
2200af732203SDimitry Andric // FIXME: Handle folded restore instructions with more than one memory
2201af732203SDimitry Andric // operand.
2202af732203SDimitry Andric if (MI.getRestoreSize(TII)) {
2203af732203SDimitry Andric Reg = MI.getOperand(0).getReg();
2204af732203SDimitry Andric return extractSpillBaseRegAndOffset(MI);
2205af732203SDimitry Andric }
2206af732203SDimitry Andric return None;
2207af732203SDimitry Andric }
2208af732203SDimitry Andric
transferSpillOrRestoreInst(MachineInstr & MI)2209af732203SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
2210af732203SDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location
2211af732203SDimitry Andric // limitations under the new model. Therefore, when comparing them, compare
2212af732203SDimitry Andric // versions that don't attempt spills or restores at all.
2213af732203SDimitry Andric if (EmulateOldLDV)
2214af732203SDimitry Andric return false;
2215af732203SDimitry Andric
2216af732203SDimitry Andric MachineFunction *MF = MI.getMF();
2217af732203SDimitry Andric unsigned Reg;
2218af732203SDimitry Andric Optional<SpillLoc> Loc;
2219af732203SDimitry Andric
2220af732203SDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
2221af732203SDimitry Andric
2222af732203SDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is
2223af732203SDimitry Andric // written to, terminate that variable location. The value in memory
2224af732203SDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
2225af732203SDimitry Andric if (isSpillInstruction(MI, MF)) {
2226af732203SDimitry Andric Loc = extractSpillBaseRegAndOffset(MI);
2227af732203SDimitry Andric
2228af732203SDimitry Andric if (TTracker) {
2229af732203SDimitry Andric Optional<LocIdx> MLoc = MTracker->getSpillMLoc(*Loc);
2230*5f7ddb14SDimitry Andric if (MLoc) {
2231*5f7ddb14SDimitry Andric // Un-set this location before clobbering, so that we don't salvage
2232*5f7ddb14SDimitry Andric // the variable location back to the same place.
2233*5f7ddb14SDimitry Andric MTracker->setMLoc(*MLoc, ValueIDNum::EmptyValue);
2234af732203SDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator());
2235af732203SDimitry Andric }
2236af732203SDimitry Andric }
2237*5f7ddb14SDimitry Andric }
2238af732203SDimitry Andric
2239af732203SDimitry Andric // Try to recognise spill and restore instructions that may transfer a value.
2240af732203SDimitry Andric if (isLocationSpill(MI, MF, Reg)) {
2241af732203SDimitry Andric Loc = extractSpillBaseRegAndOffset(MI);
2242af732203SDimitry Andric auto ValueID = MTracker->readReg(Reg);
2243af732203SDimitry Andric
2244af732203SDimitry Andric // If the location is empty, produce a phi, signify it's the live-in value.
2245af732203SDimitry Andric if (ValueID.getLoc() == 0)
2246af732203SDimitry Andric ValueID = {CurBB, 0, MTracker->getRegMLoc(Reg)};
2247af732203SDimitry Andric
2248af732203SDimitry Andric MTracker->setSpill(*Loc, ValueID);
2249af732203SDimitry Andric auto OptSpillLocIdx = MTracker->getSpillMLoc(*Loc);
2250af732203SDimitry Andric assert(OptSpillLocIdx && "Spill slot set but has no LocIdx?");
2251af732203SDimitry Andric LocIdx SpillLocIdx = *OptSpillLocIdx;
2252af732203SDimitry Andric
2253af732203SDimitry Andric // Tell TransferTracker about this spill, produce DBG_VALUEs for it.
2254af732203SDimitry Andric if (TTracker)
2255af732203SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(Reg), SpillLocIdx,
2256af732203SDimitry Andric MI.getIterator());
2257af732203SDimitry Andric } else {
2258af732203SDimitry Andric if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
2259af732203SDimitry Andric return false;
2260af732203SDimitry Andric
2261af732203SDimitry Andric // Is there a value to be restored?
2262af732203SDimitry Andric auto OptValueID = MTracker->readSpill(*Loc);
2263af732203SDimitry Andric if (OptValueID) {
2264af732203SDimitry Andric ValueIDNum ValueID = *OptValueID;
2265af732203SDimitry Andric LocIdx SpillLocIdx = *MTracker->getSpillMLoc(*Loc);
2266af732203SDimitry Andric // XXX -- can we recover sub-registers of this value? Until we can, first
2267af732203SDimitry Andric // overwrite all defs of the register being restored to.
2268af732203SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2269af732203SDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst);
2270af732203SDimitry Andric
2271af732203SDimitry Andric // Now override the reg we're restoring to.
2272af732203SDimitry Andric MTracker->setReg(Reg, ValueID);
2273af732203SDimitry Andric
2274af732203SDimitry Andric // Report this restore to the transfer tracker too.
2275af732203SDimitry Andric if (TTracker)
2276af732203SDimitry Andric TTracker->transferMlocs(SpillLocIdx, MTracker->getRegMLoc(Reg),
2277af732203SDimitry Andric MI.getIterator());
2278af732203SDimitry Andric } else {
2279af732203SDimitry Andric // There isn't anything in the location; not clear if this is a code path
2280af732203SDimitry Andric // that still runs. Def this register anyway just in case.
2281af732203SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2282af732203SDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst);
2283af732203SDimitry Andric
2284af732203SDimitry Andric // Force the spill slot to be tracked.
2285af732203SDimitry Andric LocIdx L = MTracker->getOrTrackSpillLoc(*Loc);
2286af732203SDimitry Andric
2287af732203SDimitry Andric // Set the restored value to be a machine phi number, signifying that it's
2288af732203SDimitry Andric // whatever the spills live-in value is in this block. Definitely has
2289af732203SDimitry Andric // a LocIdx due to the setSpill above.
2290af732203SDimitry Andric ValueIDNum ValueID = {CurBB, 0, L};
2291af732203SDimitry Andric MTracker->setReg(Reg, ValueID);
2292af732203SDimitry Andric MTracker->setSpill(*Loc, ValueID);
2293af732203SDimitry Andric }
2294af732203SDimitry Andric }
2295af732203SDimitry Andric return true;
2296af732203SDimitry Andric }
2297af732203SDimitry Andric
transferRegisterCopy(MachineInstr & MI)2298af732203SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2299af732203SDimitry Andric auto DestSrc = TII->isCopyInstr(MI);
2300af732203SDimitry Andric if (!DestSrc)
2301af732203SDimitry Andric return false;
2302af732203SDimitry Andric
2303af732203SDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination;
2304af732203SDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source;
2305af732203SDimitry Andric
2306af732203SDimitry Andric auto isCalleeSavedReg = [&](unsigned Reg) {
2307af732203SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2308af732203SDimitry Andric if (CalleeSavedRegs.test(*RAI))
2309af732203SDimitry Andric return true;
2310af732203SDimitry Andric return false;
2311af732203SDimitry Andric };
2312af732203SDimitry Andric
2313af732203SDimitry Andric Register SrcReg = SrcRegOp->getReg();
2314af732203SDimitry Andric Register DestReg = DestRegOp->getReg();
2315af732203SDimitry Andric
2316af732203SDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2317af732203SDimitry Andric if (SrcReg == DestReg)
2318af732203SDimitry Andric return true;
2319af732203SDimitry Andric
2320af732203SDimitry Andric // For emulating VarLocBasedImpl:
2321af732203SDimitry Andric // We want to recognize instructions where destination register is callee
2322af732203SDimitry Andric // saved register. If register that could be clobbered by the call is
2323af732203SDimitry Andric // included, there would be a great chance that it is going to be clobbered
2324af732203SDimitry Andric // soon. It is more likely that previous register, which is callee saved, is
2325af732203SDimitry Andric // going to stay unclobbered longer, even if it is killed.
2326af732203SDimitry Andric //
2327af732203SDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so
2328af732203SDimitry Andric // ignore this condition.
2329af732203SDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
2330af732203SDimitry Andric return false;
2331af732203SDimitry Andric
2332af732203SDimitry Andric // InstrRefBasedImpl only followed killing copies.
2333af732203SDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill())
2334af732203SDimitry Andric return false;
2335af732203SDimitry Andric
2336af732203SDimitry Andric // Copy MTracker info, including subregs if available.
2337af732203SDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg);
2338af732203SDimitry Andric
2339af732203SDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV
2340af732203SDimitry Andric // would have. We might make use of the additional value tracking in some
2341af732203SDimitry Andric // other way, later.
2342af732203SDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
2343af732203SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
2344af732203SDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator());
2345af732203SDimitry Andric
2346af732203SDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying.
2347af732203SDimitry Andric if (EmulateOldLDV && SrcReg != DestReg)
2348af732203SDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst);
2349af732203SDimitry Andric
2350*5f7ddb14SDimitry Andric // Finally, the copy might have clobbered variables based on the destination
2351*5f7ddb14SDimitry Andric // register. Tell TTracker about it, in case a backup location exists.
2352*5f7ddb14SDimitry Andric if (TTracker) {
2353*5f7ddb14SDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
2354*5f7ddb14SDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
2355*5f7ddb14SDimitry Andric TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false);
2356*5f7ddb14SDimitry Andric }
2357*5f7ddb14SDimitry Andric }
2358*5f7ddb14SDimitry Andric
2359af732203SDimitry Andric return true;
2360af732203SDimitry Andric }
2361af732203SDimitry Andric
2362af732203SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
2363af732203SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
2364af732203SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
2365af732203SDimitry Andric /// known-to-overlap fragments are present".
2366af732203SDimitry Andric /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
2367af732203SDimitry Andric /// fragment usage.
accumulateFragmentMap(MachineInstr & MI)2368af732203SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2369af732203SDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2370af732203SDimitry Andric MI.getDebugLoc()->getInlinedAt());
2371af732203SDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2372af732203SDimitry Andric
2373af732203SDimitry Andric // If this is the first sighting of this variable, then we are guaranteed
2374af732203SDimitry Andric // there are currently no overlapping fragments either. Initialize the set
2375af732203SDimitry Andric // of seen fragments, record no overlaps for the current one, and return.
2376af732203SDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable());
2377af732203SDimitry Andric if (SeenIt == SeenFragments.end()) {
2378af732203SDimitry Andric SmallSet<FragmentInfo, 4> OneFragment;
2379af732203SDimitry Andric OneFragment.insert(ThisFragment);
2380af732203SDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment});
2381af732203SDimitry Andric
2382af732203SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2383af732203SDimitry Andric return;
2384af732203SDimitry Andric }
2385af732203SDimitry Andric
2386af732203SDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap
2387af732203SDimitry Andric // map, it has already been accounted for.
2388af732203SDimitry Andric auto IsInOLapMap =
2389af732203SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2390af732203SDimitry Andric if (!IsInOLapMap.second)
2391af732203SDimitry Andric return;
2392af732203SDimitry Andric
2393af732203SDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2394af732203SDimitry Andric auto &AllSeenFragments = SeenIt->second;
2395af732203SDimitry Andric
2396af732203SDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this"
2397af732203SDimitry Andric // fragment being a previously unseen fragment. Record any pair of
2398af732203SDimitry Andric // overlapping fragments.
2399af732203SDimitry Andric for (auto &ASeenFragment : AllSeenFragments) {
2400af732203SDimitry Andric // Does this previously seen fragment overlap?
2401af732203SDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
2402af732203SDimitry Andric // Yes: Mark the current fragment as being overlapped.
2403af732203SDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment);
2404af732203SDimitry Andric // Mark the previously seen fragment as being overlapped by the current
2405af732203SDimitry Andric // one.
2406af732203SDimitry Andric auto ASeenFragmentsOverlaps =
2407af732203SDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
2408af732203SDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2409af732203SDimitry Andric "Previously seen var fragment has no vector of overlaps");
2410af732203SDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment);
2411af732203SDimitry Andric }
2412af732203SDimitry Andric }
2413af732203SDimitry Andric
2414af732203SDimitry Andric AllSeenFragments.insert(ThisFragment);
2415af732203SDimitry Andric }
2416af732203SDimitry Andric
process(MachineInstr & MI,ValueIDNum ** MLiveOuts,ValueIDNum ** MLiveIns)2417*5f7ddb14SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, ValueIDNum **MLiveOuts,
2418*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns) {
2419af732203SDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's
2420af732203SDimitry Andric // none of these should we interpret it's register defs as new value
2421af732203SDimitry Andric // definitions.
2422af732203SDimitry Andric if (transferDebugValue(MI))
2423af732203SDimitry Andric return;
2424*5f7ddb14SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
2425*5f7ddb14SDimitry Andric return;
2426*5f7ddb14SDimitry Andric if (transferDebugPHI(MI))
2427af732203SDimitry Andric return;
2428af732203SDimitry Andric if (transferRegisterCopy(MI))
2429af732203SDimitry Andric return;
2430af732203SDimitry Andric if (transferSpillOrRestoreInst(MI))
2431af732203SDimitry Andric return;
2432af732203SDimitry Andric transferRegisterDef(MI);
2433af732203SDimitry Andric }
2434af732203SDimitry Andric
produceMLocTransferFunction(MachineFunction & MF,SmallVectorImpl<MLocTransferMap> & MLocTransfer,unsigned MaxNumBlocks)2435af732203SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction(
2436af732203SDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2437af732203SDimitry Andric unsigned MaxNumBlocks) {
2438af732203SDimitry Andric // Because we try to optimize around register mask operands by ignoring regs
2439af732203SDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask
2440af732203SDimitry Andric // operands that are seen earlier than the first use of a register, still need
2441af732203SDimitry Andric // to clobber that register in the transfer function. But this information
2442af732203SDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block,
2443af732203SDimitry Andric // and accumulated the clobbered but untracked registers in each block into
2444af732203SDimitry Andric // the following bitvector. Later, if new values are tracked, we can add
2445af732203SDimitry Andric // appropriate clobbers.
2446af732203SDimitry Andric SmallVector<BitVector, 32> BlockMasks;
2447af732203SDimitry Andric BlockMasks.resize(MaxNumBlocks);
2448af732203SDimitry Andric
2449af732203SDimitry Andric // Reserve one bit per register for the masks described above.
2450af732203SDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
2451af732203SDimitry Andric for (auto &BV : BlockMasks)
2452af732203SDimitry Andric BV.resize(TRI->getNumRegs(), true);
2453af732203SDimitry Andric
2454af732203SDimitry Andric // Step through all instructions and inhale the transfer function.
2455af732203SDimitry Andric for (auto &MBB : MF) {
2456af732203SDimitry Andric // Object fields that are read by trackers to know where we are in the
2457af732203SDimitry Andric // function.
2458af732203SDimitry Andric CurBB = MBB.getNumber();
2459af732203SDimitry Andric CurInst = 1;
2460af732203SDimitry Andric
2461af732203SDimitry Andric // Set all machine locations to a PHI value. For transfer function
2462af732203SDimitry Andric // production only, this signifies the live-in value to the block.
2463af732203SDimitry Andric MTracker->reset();
2464af732203SDimitry Andric MTracker->setMPhis(CurBB);
2465af732203SDimitry Andric
2466af732203SDimitry Andric // Step through each instruction in this block.
2467af732203SDimitry Andric for (auto &MI : MBB) {
2468af732203SDimitry Andric process(MI);
2469af732203SDimitry Andric // Also accumulate fragment map.
2470af732203SDimitry Andric if (MI.isDebugValue())
2471af732203SDimitry Andric accumulateFragmentMap(MI);
2472af732203SDimitry Andric
2473af732203SDimitry Andric // Create a map from the instruction number (if present) to the
2474af732203SDimitry Andric // MachineInstr and its position.
2475af732203SDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
2476af732203SDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst);
2477af732203SDimitry Andric auto InsertResult =
2478af732203SDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
2479af732203SDimitry Andric
2480af732203SDimitry Andric // There should never be duplicate instruction numbers.
2481af732203SDimitry Andric assert(InsertResult.second);
2482af732203SDimitry Andric (void)InsertResult;
2483af732203SDimitry Andric }
2484af732203SDimitry Andric
2485af732203SDimitry Andric ++CurInst;
2486af732203SDimitry Andric }
2487af732203SDimitry Andric
2488af732203SDimitry Andric // Produce the transfer function, a map of machine location to new value. If
2489af732203SDimitry Andric // any machine location has the live-in phi value from the start of the
2490af732203SDimitry Andric // block, it's live-through and doesn't need recording in the transfer
2491af732203SDimitry Andric // function.
2492af732203SDimitry Andric for (auto Location : MTracker->locations()) {
2493af732203SDimitry Andric LocIdx Idx = Location.Idx;
2494af732203SDimitry Andric ValueIDNum &P = Location.Value;
2495af732203SDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64())
2496af732203SDimitry Andric continue;
2497af732203SDimitry Andric
2498af732203SDimitry Andric // Insert-or-update.
2499af732203SDimitry Andric auto &TransferMap = MLocTransfer[CurBB];
2500af732203SDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
2501af732203SDimitry Andric if (!Result.second)
2502af732203SDimitry Andric Result.first->second = P;
2503af732203SDimitry Andric }
2504af732203SDimitry Andric
2505af732203SDimitry Andric // Accumulate any bitmask operands into the clobberred reg mask for this
2506af732203SDimitry Andric // block.
2507af732203SDimitry Andric for (auto &P : MTracker->Masks) {
2508af732203SDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
2509af732203SDimitry Andric }
2510af732203SDimitry Andric }
2511af732203SDimitry Andric
2512af732203SDimitry Andric // Compute a bitvector of all the registers that are tracked in this block.
2513af732203SDimitry Andric const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2514af732203SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore();
2515af732203SDimitry Andric BitVector UsedRegs(TRI->getNumRegs());
2516af732203SDimitry Andric for (auto Location : MTracker->locations()) {
2517af732203SDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2518af732203SDimitry Andric if (ID >= TRI->getNumRegs() || ID == SP)
2519af732203SDimitry Andric continue;
2520af732203SDimitry Andric UsedRegs.set(ID);
2521af732203SDimitry Andric }
2522af732203SDimitry Andric
2523af732203SDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not
2524af732203SDimitry Andric // live-through in the transfer function. It needs to be clobbered at the
2525af732203SDimitry Andric // very least.
2526af732203SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2527af732203SDimitry Andric BitVector &BV = BlockMasks[I];
2528af732203SDimitry Andric BV.flip();
2529af732203SDimitry Andric BV &= UsedRegs;
2530af732203SDimitry Andric // This produces all the bits that we clobber, but also use. Check that
2531af732203SDimitry Andric // they're all clobbered or at least set in the designated transfer
2532af732203SDimitry Andric // elem.
2533af732203SDimitry Andric for (unsigned Bit : BV.set_bits()) {
2534af732203SDimitry Andric unsigned ID = MTracker->getLocID(Bit, false);
2535af732203SDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2536af732203SDimitry Andric auto &TransferMap = MLocTransfer[I];
2537af732203SDimitry Andric
2538af732203SDimitry Andric // Install a value representing the fact that this location is effectively
2539af732203SDimitry Andric // written to in this block. As there's no reserved value, instead use
2540af732203SDimitry Andric // a value number that is never generated. Pick the value number for the
2541af732203SDimitry Andric // first instruction in the block, def'ing this location, which we know
2542af732203SDimitry Andric // this block never used anyway.
2543af732203SDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2544af732203SDimitry Andric auto Result =
2545af732203SDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
2546af732203SDimitry Andric if (!Result.second) {
2547af732203SDimitry Andric ValueIDNum &ValueID = Result.first->second;
2548af732203SDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI())
2549af732203SDimitry Andric // It was left as live-through. Set it to clobbered.
2550af732203SDimitry Andric ValueID = NotGeneratedNum;
2551af732203SDimitry Andric }
2552af732203SDimitry Andric }
2553af732203SDimitry Andric }
2554af732203SDimitry Andric }
2555af732203SDimitry Andric
2556af732203SDimitry Andric std::tuple<bool, bool>
mlocJoin(MachineBasicBlock & MBB,SmallPtrSet<const MachineBasicBlock *,16> & Visited,ValueIDNum ** OutLocs,ValueIDNum * InLocs)2557af732203SDimitry Andric InstrRefBasedLDV::mlocJoin(MachineBasicBlock &MBB,
2558af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
2559af732203SDimitry Andric ValueIDNum **OutLocs, ValueIDNum *InLocs) {
2560af732203SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2561af732203SDimitry Andric bool Changed = false;
2562af732203SDimitry Andric bool DowngradeOccurred = false;
2563af732203SDimitry Andric
2564af732203SDimitry Andric // Collect predecessors that have been visited. Anything that hasn't been
2565af732203SDimitry Andric // visited yet is a backedge on the first iteration, and the meet of it's
2566af732203SDimitry Andric // lattice value for all locations will be unaffected.
2567af732203SDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders;
2568af732203SDimitry Andric for (auto Pred : MBB.predecessors()) {
2569af732203SDimitry Andric if (Visited.count(Pred)) {
2570af732203SDimitry Andric BlockOrders.push_back(Pred);
2571af732203SDimitry Andric }
2572af732203SDimitry Andric }
2573af732203SDimitry Andric
2574af732203SDimitry Andric // Visit predecessors in RPOT order.
2575af732203SDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2576af732203SDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2577af732203SDimitry Andric };
2578af732203SDimitry Andric llvm::sort(BlockOrders, Cmp);
2579af732203SDimitry Andric
2580af732203SDimitry Andric // Skip entry block.
2581af732203SDimitry Andric if (BlockOrders.size() == 0)
2582af732203SDimitry Andric return std::tuple<bool, bool>(false, false);
2583af732203SDimitry Andric
2584af732203SDimitry Andric // Step through all machine locations, then look at each predecessor and
2585af732203SDimitry Andric // detect disagreements.
2586af732203SDimitry Andric unsigned ThisBlockRPO = BBToOrder.find(&MBB)->second;
2587af732203SDimitry Andric for (auto Location : MTracker->locations()) {
2588af732203SDimitry Andric LocIdx Idx = Location.Idx;
2589af732203SDimitry Andric // Pick out the first predecessors live-out value for this location. It's
2590af732203SDimitry Andric // guaranteed to be not a backedge, as we order by RPO.
2591af732203SDimitry Andric ValueIDNum BaseVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
2592af732203SDimitry Andric
2593af732203SDimitry Andric // Some flags for whether there's a disagreement, and whether it's a
2594af732203SDimitry Andric // disagreement with a backedge or not.
2595af732203SDimitry Andric bool Disagree = false;
2596af732203SDimitry Andric bool NonBackEdgeDisagree = false;
2597af732203SDimitry Andric
2598af732203SDimitry Andric // Loop around everything that wasn't 'base'.
2599af732203SDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2600af732203SDimitry Andric auto *MBB = BlockOrders[I];
2601af732203SDimitry Andric if (BaseVal != OutLocs[MBB->getNumber()][Idx.asU64()]) {
2602af732203SDimitry Andric // Live-out of a predecessor disagrees with the first predecessor.
2603af732203SDimitry Andric Disagree = true;
2604af732203SDimitry Andric
2605af732203SDimitry Andric // Test whether it's a disagreemnt in the backedges or not.
2606af732203SDimitry Andric if (BBToOrder.find(MBB)->second < ThisBlockRPO) // might be self b/e
2607af732203SDimitry Andric NonBackEdgeDisagree = true;
2608af732203SDimitry Andric }
2609af732203SDimitry Andric }
2610af732203SDimitry Andric
2611af732203SDimitry Andric bool OverRide = false;
2612af732203SDimitry Andric if (Disagree && !NonBackEdgeDisagree) {
2613af732203SDimitry Andric // Only the backedges disagree. Consider demoting the livein
2614af732203SDimitry Andric // lattice value, as per the file level comment. The value we consider
2615af732203SDimitry Andric // demoting to is the value that the non-backedge predecessors agree on.
2616af732203SDimitry Andric // The order of values is that non-PHIs are \top, a PHI at this block
2617af732203SDimitry Andric // \bot, and phis between the two are ordered by their RPO number.
2618af732203SDimitry Andric // If there's no agreement, or we've already demoted to this PHI value
2619af732203SDimitry Andric // before, replace with a PHI value at this block.
2620af732203SDimitry Andric
2621af732203SDimitry Andric // Calculate order numbers: zero means normal def, nonzero means RPO
2622af732203SDimitry Andric // number.
2623af732203SDimitry Andric unsigned BaseBlockRPONum = BBNumToRPO[BaseVal.getBlock()] + 1;
2624af732203SDimitry Andric if (!BaseVal.isPHI())
2625af732203SDimitry Andric BaseBlockRPONum = 0;
2626af732203SDimitry Andric
2627af732203SDimitry Andric ValueIDNum &InLocID = InLocs[Idx.asU64()];
2628af732203SDimitry Andric unsigned InLocRPONum = BBNumToRPO[InLocID.getBlock()] + 1;
2629af732203SDimitry Andric if (!InLocID.isPHI())
2630af732203SDimitry Andric InLocRPONum = 0;
2631af732203SDimitry Andric
2632af732203SDimitry Andric // Should we ignore the disagreeing backedges, and override with the
2633af732203SDimitry Andric // value the other predecessors agree on (in "base")?
2634af732203SDimitry Andric unsigned ThisBlockRPONum = BBNumToRPO[MBB.getNumber()] + 1;
2635af732203SDimitry Andric if (BaseBlockRPONum > InLocRPONum && BaseBlockRPONum < ThisBlockRPONum) {
2636af732203SDimitry Andric // Override.
2637af732203SDimitry Andric OverRide = true;
2638af732203SDimitry Andric DowngradeOccurred = true;
2639af732203SDimitry Andric }
2640af732203SDimitry Andric }
2641af732203SDimitry Andric // else: if we disagree in the non-backedges, then this is definitely
2642af732203SDimitry Andric // a control flow merge where different values merge. Make it a PHI.
2643af732203SDimitry Andric
2644af732203SDimitry Andric // Generate a phi...
2645af732203SDimitry Andric ValueIDNum PHI = {(uint64_t)MBB.getNumber(), 0, Idx};
2646af732203SDimitry Andric ValueIDNum NewVal = (Disagree && !OverRide) ? PHI : BaseVal;
2647af732203SDimitry Andric if (InLocs[Idx.asU64()] != NewVal) {
2648af732203SDimitry Andric Changed |= true;
2649af732203SDimitry Andric InLocs[Idx.asU64()] = NewVal;
2650af732203SDimitry Andric }
2651af732203SDimitry Andric }
2652af732203SDimitry Andric
2653af732203SDimitry Andric // TODO: Reimplement NumInserted and NumRemoved.
2654af732203SDimitry Andric return std::tuple<bool, bool>(Changed, DowngradeOccurred);
2655af732203SDimitry Andric }
2656af732203SDimitry Andric
mlocDataflow(ValueIDNum ** MInLocs,ValueIDNum ** MOutLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)2657af732203SDimitry Andric void InstrRefBasedLDV::mlocDataflow(
2658af732203SDimitry Andric ValueIDNum **MInLocs, ValueIDNum **MOutLocs,
2659af732203SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2660af732203SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>,
2661af732203SDimitry Andric std::greater<unsigned int>>
2662af732203SDimitry Andric Worklist, Pending;
2663af732203SDimitry Andric
2664af732203SDimitry Andric // We track what is on the current and pending worklist to avoid inserting
2665af732203SDimitry Andric // the same thing twice. We could avoid this with a custom priority queue,
2666af732203SDimitry Andric // but this is probably not worth it.
2667af732203SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2668af732203SDimitry Andric
2669af732203SDimitry Andric // Initialize worklist with every block to be visited.
2670af732203SDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2671af732203SDimitry Andric Worklist.push(I);
2672af732203SDimitry Andric OnWorklist.insert(OrderToBB[I]);
2673af732203SDimitry Andric }
2674af732203SDimitry Andric
2675af732203SDimitry Andric MTracker->reset();
2676af732203SDimitry Andric
2677af732203SDimitry Andric // Set inlocs for entry block -- each as a PHI at the entry block. Represents
2678af732203SDimitry Andric // the incoming value to the function.
2679af732203SDimitry Andric MTracker->setMPhis(0);
2680af732203SDimitry Andric for (auto Location : MTracker->locations())
2681af732203SDimitry Andric MInLocs[0][Location.Idx.asU64()] = Location.Value;
2682af732203SDimitry Andric
2683af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2684af732203SDimitry Andric while (!Worklist.empty() || !Pending.empty()) {
2685af732203SDimitry Andric // Vector for storing the evaluated block transfer function.
2686af732203SDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2687af732203SDimitry Andric
2688af732203SDimitry Andric while (!Worklist.empty()) {
2689af732203SDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2690af732203SDimitry Andric CurBB = MBB->getNumber();
2691af732203SDimitry Andric Worklist.pop();
2692af732203SDimitry Andric
2693af732203SDimitry Andric // Join the values in all predecessor blocks.
2694af732203SDimitry Andric bool InLocsChanged, DowngradeOccurred;
2695af732203SDimitry Andric std::tie(InLocsChanged, DowngradeOccurred) =
2696af732203SDimitry Andric mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2697af732203SDimitry Andric InLocsChanged |= Visited.insert(MBB).second;
2698af732203SDimitry Andric
2699af732203SDimitry Andric // If a downgrade occurred, book us in for re-examination on the next
2700af732203SDimitry Andric // iteration.
2701af732203SDimitry Andric if (DowngradeOccurred && OnPending.insert(MBB).second)
2702af732203SDimitry Andric Pending.push(BBToOrder[MBB]);
2703af732203SDimitry Andric
2704af732203SDimitry Andric // Don't examine transfer function if we've visited this loc at least
2705af732203SDimitry Andric // once, and inlocs haven't changed.
2706af732203SDimitry Andric if (!InLocsChanged)
2707af732203SDimitry Andric continue;
2708af732203SDimitry Andric
2709af732203SDimitry Andric // Load the current set of live-ins into MLocTracker.
2710af732203SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2711af732203SDimitry Andric
2712af732203SDimitry Andric // Each element of the transfer function can be a new def, or a read of
2713af732203SDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap".
2714af732203SDimitry Andric ToRemap.clear();
2715af732203SDimitry Andric for (auto &P : MLocTransfer[CurBB]) {
2716af732203SDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2717af732203SDimitry Andric // This is a movement of whatever was live in. Read it.
2718af732203SDimitry Andric ValueIDNum NewID = MTracker->getNumAtPos(P.second.getLoc());
2719af732203SDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID));
2720af732203SDimitry Andric } else {
2721af732203SDimitry Andric // It's a def. Just set it.
2722af732203SDimitry Andric assert(P.second.getBlock() == CurBB);
2723af732203SDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second));
2724af732203SDimitry Andric }
2725af732203SDimitry Andric }
2726af732203SDimitry Andric
2727af732203SDimitry Andric // Commit the transfer function changes into mloc tracker, which
2728af732203SDimitry Andric // transforms the contents of the MLocTracker into the live-outs.
2729af732203SDimitry Andric for (auto &P : ToRemap)
2730af732203SDimitry Andric MTracker->setMLoc(P.first, P.second);
2731af732203SDimitry Andric
2732af732203SDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking
2733af732203SDimitry Andric // whether changes have occurred. These changes can have come from both
2734af732203SDimitry Andric // the transfer function, and mlocJoin.
2735af732203SDimitry Andric bool OLChanged = false;
2736af732203SDimitry Andric for (auto Location : MTracker->locations()) {
2737af732203SDimitry Andric OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2738af732203SDimitry Andric MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2739af732203SDimitry Andric }
2740af732203SDimitry Andric
2741af732203SDimitry Andric MTracker->reset();
2742af732203SDimitry Andric
2743af732203SDimitry Andric // No need to examine successors again if out-locs didn't change.
2744af732203SDimitry Andric if (!OLChanged)
2745af732203SDimitry Andric continue;
2746af732203SDimitry Andric
2747af732203SDimitry Andric // All successors should be visited: put any back-edges on the pending
2748af732203SDimitry Andric // list for the next dataflow iteration, and any other successors to be
2749af732203SDimitry Andric // visited this iteration, if they're not going to be already.
2750af732203SDimitry Andric for (auto s : MBB->successors()) {
2751af732203SDimitry Andric // Does branching to this successor represent a back-edge?
2752af732203SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) {
2753af732203SDimitry Andric // No: visit it during this dataflow iteration.
2754af732203SDimitry Andric if (OnWorklist.insert(s).second)
2755af732203SDimitry Andric Worklist.push(BBToOrder[s]);
2756af732203SDimitry Andric } else {
2757af732203SDimitry Andric // Yes: visit it on the next iteration.
2758af732203SDimitry Andric if (OnPending.insert(s).second)
2759af732203SDimitry Andric Pending.push(BBToOrder[s]);
2760af732203SDimitry Andric }
2761af732203SDimitry Andric }
2762af732203SDimitry Andric }
2763af732203SDimitry Andric
2764af732203SDimitry Andric Worklist.swap(Pending);
2765af732203SDimitry Andric std::swap(OnPending, OnWorklist);
2766af732203SDimitry Andric OnPending.clear();
2767af732203SDimitry Andric // At this point, pending must be empty, since it was just the empty
2768af732203SDimitry Andric // worklist
2769af732203SDimitry Andric assert(Pending.empty() && "Pending should be empty");
2770af732203SDimitry Andric }
2771af732203SDimitry Andric
2772af732203SDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've reached a
2773af732203SDimitry Andric // fixedpoint.
2774af732203SDimitry Andric }
2775af732203SDimitry Andric
vlocDowngradeLattice(const MachineBasicBlock & MBB,const DbgValue & OldLiveInLocation,const SmallVectorImpl<InValueT> & Values,unsigned CurBlockRPONum)2776af732203SDimitry Andric bool InstrRefBasedLDV::vlocDowngradeLattice(
2777af732203SDimitry Andric const MachineBasicBlock &MBB, const DbgValue &OldLiveInLocation,
2778af732203SDimitry Andric const SmallVectorImpl<InValueT> &Values, unsigned CurBlockRPONum) {
2779af732203SDimitry Andric // Ranking value preference: see file level comment, the highest rank is
2780af732203SDimitry Andric // a plain def, followed by PHI values in reverse post-order. Numerically,
2781af732203SDimitry Andric // we assign all defs the rank '0', all PHIs their blocks RPO number plus
2782af732203SDimitry Andric // one, and consider the lowest value the highest ranked.
2783af732203SDimitry Andric int OldLiveInRank = BBNumToRPO[OldLiveInLocation.ID.getBlock()] + 1;
2784af732203SDimitry Andric if (!OldLiveInLocation.ID.isPHI())
2785af732203SDimitry Andric OldLiveInRank = 0;
2786af732203SDimitry Andric
2787af732203SDimitry Andric // Allow any unresolvable conflict to be over-ridden.
2788af732203SDimitry Andric if (OldLiveInLocation.Kind == DbgValue::NoVal) {
2789af732203SDimitry Andric // Although if it was an unresolvable conflict from _this_ block, then
2790af732203SDimitry Andric // all other seeking of downgrades and PHIs must have failed before hand.
2791af732203SDimitry Andric if (OldLiveInLocation.BlockNo == (unsigned)MBB.getNumber())
2792af732203SDimitry Andric return false;
2793af732203SDimitry Andric OldLiveInRank = INT_MIN;
2794af732203SDimitry Andric }
2795af732203SDimitry Andric
2796af732203SDimitry Andric auto &InValue = *Values[0].second;
2797af732203SDimitry Andric
2798af732203SDimitry Andric if (InValue.Kind == DbgValue::Const || InValue.Kind == DbgValue::NoVal)
2799af732203SDimitry Andric return false;
2800af732203SDimitry Andric
2801af732203SDimitry Andric unsigned ThisRPO = BBNumToRPO[InValue.ID.getBlock()];
2802af732203SDimitry Andric int ThisRank = ThisRPO + 1;
2803af732203SDimitry Andric if (!InValue.ID.isPHI())
2804af732203SDimitry Andric ThisRank = 0;
2805af732203SDimitry Andric
2806af732203SDimitry Andric // Too far down the lattice?
2807af732203SDimitry Andric if (ThisRPO >= CurBlockRPONum)
2808af732203SDimitry Andric return false;
2809af732203SDimitry Andric
2810af732203SDimitry Andric // Higher in the lattice than what we've already explored?
2811af732203SDimitry Andric if (ThisRank <= OldLiveInRank)
2812af732203SDimitry Andric return false;
2813af732203SDimitry Andric
2814af732203SDimitry Andric return true;
2815af732203SDimitry Andric }
2816af732203SDimitry Andric
pickVPHILoc(MachineBasicBlock & MBB,const DebugVariable & Var,const LiveIdxT & LiveOuts,ValueIDNum ** MOutLocs,ValueIDNum ** MInLocs,const SmallVectorImpl<MachineBasicBlock * > & BlockOrders)2817af732203SDimitry Andric std::tuple<Optional<ValueIDNum>, bool> InstrRefBasedLDV::pickVPHILoc(
2818af732203SDimitry Andric MachineBasicBlock &MBB, const DebugVariable &Var, const LiveIdxT &LiveOuts,
2819af732203SDimitry Andric ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
2820af732203SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &BlockOrders) {
2821af732203SDimitry Andric // Collect a set of locations from predecessor where its live-out value can
2822af732203SDimitry Andric // be found.
2823af732203SDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2824af732203SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
2825af732203SDimitry Andric unsigned BackEdgesStart = 0;
2826af732203SDimitry Andric
2827af732203SDimitry Andric for (auto p : BlockOrders) {
2828af732203SDimitry Andric // Pick out where backedges start in the list of predecessors. Relies on
2829af732203SDimitry Andric // BlockOrders being sorted by RPO.
2830af732203SDimitry Andric if (BBToOrder[p] < BBToOrder[&MBB])
2831af732203SDimitry Andric ++BackEdgesStart;
2832af732203SDimitry Andric
2833af732203SDimitry Andric // For each predecessor, create a new set of locations.
2834af732203SDimitry Andric Locs.resize(Locs.size() + 1);
2835af732203SDimitry Andric unsigned ThisBBNum = p->getNumber();
2836af732203SDimitry Andric auto LiveOutMap = LiveOuts.find(p);
2837af732203SDimitry Andric if (LiveOutMap == LiveOuts.end())
2838af732203SDimitry Andric // This predecessor isn't in scope, it must have no live-in/live-out
2839af732203SDimitry Andric // locations.
2840af732203SDimitry Andric continue;
2841af732203SDimitry Andric
2842af732203SDimitry Andric auto It = LiveOutMap->second->find(Var);
2843af732203SDimitry Andric if (It == LiveOutMap->second->end())
2844af732203SDimitry Andric // There's no value recorded for this variable in this predecessor,
2845af732203SDimitry Andric // leave an empty set of locations.
2846af732203SDimitry Andric continue;
2847af732203SDimitry Andric
2848af732203SDimitry Andric const DbgValue &OutVal = It->second;
2849af732203SDimitry Andric
2850af732203SDimitry Andric if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2851af732203SDimitry Andric // Consts and no-values cannot have locations we can join on.
2852af732203SDimitry Andric continue;
2853af732203SDimitry Andric
2854af732203SDimitry Andric assert(OutVal.Kind == DbgValue::Proposed || OutVal.Kind == DbgValue::Def);
2855af732203SDimitry Andric ValueIDNum ValToLookFor = OutVal.ID;
2856af732203SDimitry Andric
2857af732203SDimitry Andric // Search the live-outs of the predecessor for the specified value.
2858af732203SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) {
2859af732203SDimitry Andric if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2860af732203SDimitry Andric Locs.back().push_back(LocIdx(I));
2861af732203SDimitry Andric }
2862af732203SDimitry Andric }
2863af732203SDimitry Andric
2864af732203SDimitry Andric // If there were no locations at all, return an empty result.
2865af732203SDimitry Andric if (Locs.empty())
2866af732203SDimitry Andric return std::tuple<Optional<ValueIDNum>, bool>(None, false);
2867af732203SDimitry Andric
2868af732203SDimitry Andric // Lambda for seeking a common location within a range of location-sets.
2869af732203SDimitry Andric using LocsIt = SmallVector<SmallVector<LocIdx, 4>, 8>::iterator;
2870af732203SDimitry Andric auto SeekLocation =
2871af732203SDimitry Andric [&Locs](llvm::iterator_range<LocsIt> SearchRange) -> Optional<LocIdx> {
2872af732203SDimitry Andric // Starting with the first set of locations, take the intersection with
2873af732203SDimitry Andric // subsequent sets.
2874af732203SDimitry Andric SmallVector<LocIdx, 4> base = Locs[0];
2875af732203SDimitry Andric for (auto &S : SearchRange) {
2876af732203SDimitry Andric SmallVector<LocIdx, 4> new_base;
2877af732203SDimitry Andric std::set_intersection(base.begin(), base.end(), S.begin(), S.end(),
2878af732203SDimitry Andric std::inserter(new_base, new_base.begin()));
2879af732203SDimitry Andric base = new_base;
2880af732203SDimitry Andric }
2881af732203SDimitry Andric if (base.empty())
2882af732203SDimitry Andric return None;
2883af732203SDimitry Andric
2884af732203SDimitry Andric // We now have a set of LocIdxes that contain the right output value in
2885af732203SDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc,
2886af732203SDimitry Andric // that'll be it.
2887af732203SDimitry Andric return *base.begin();
2888af732203SDimitry Andric };
2889af732203SDimitry Andric
2890af732203SDimitry Andric // Search for a common location for all predecessors. If we can't, then fall
2891af732203SDimitry Andric // back to only finding a common location between non-backedge predecessors.
2892af732203SDimitry Andric bool ValidForAllLocs = true;
2893af732203SDimitry Andric auto TheLoc = SeekLocation(Locs);
2894af732203SDimitry Andric if (!TheLoc) {
2895af732203SDimitry Andric ValidForAllLocs = false;
2896af732203SDimitry Andric TheLoc =
2897af732203SDimitry Andric SeekLocation(make_range(Locs.begin(), Locs.begin() + BackEdgesStart));
2898af732203SDimitry Andric }
2899af732203SDimitry Andric
2900af732203SDimitry Andric if (!TheLoc)
2901af732203SDimitry Andric return std::tuple<Optional<ValueIDNum>, bool>(None, false);
2902af732203SDimitry Andric
2903af732203SDimitry Andric // Return a PHI-value-number for the found location.
2904af732203SDimitry Andric LocIdx L = *TheLoc;
2905af732203SDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2906af732203SDimitry Andric return std::tuple<Optional<ValueIDNum>, bool>(PHIVal, ValidForAllLocs);
2907af732203SDimitry Andric }
2908af732203SDimitry Andric
vlocJoin(MachineBasicBlock & MBB,LiveIdxT & VLOCOutLocs,LiveIdxT & VLOCInLocs,SmallPtrSet<const MachineBasicBlock *,16> * VLOCVisited,unsigned BBNum,const SmallSet<DebugVariable,4> & AllVars,ValueIDNum ** MOutLocs,ValueIDNum ** MInLocs,SmallPtrSet<const MachineBasicBlock *,8> & InScopeBlocks,SmallPtrSet<const MachineBasicBlock *,8> & BlocksToExplore,DenseMap<DebugVariable,DbgValue> & InLocsT)2909af732203SDimitry Andric std::tuple<bool, bool> InstrRefBasedLDV::vlocJoin(
2910af732203SDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs,
2911af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, unsigned BBNum,
2912af732203SDimitry Andric const SmallSet<DebugVariable, 4> &AllVars, ValueIDNum **MOutLocs,
2913af732203SDimitry Andric ValueIDNum **MInLocs,
2914af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks,
2915af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2916af732203SDimitry Andric DenseMap<DebugVariable, DbgValue> &InLocsT) {
2917af732203SDimitry Andric bool DowngradeOccurred = false;
2918af732203SDimitry Andric
2919af732203SDimitry Andric // To emulate VarLocBasedImpl, process this block if it's not in scope but
2920af732203SDimitry Andric // _does_ assign a variable value. No live-ins for this scope are transferred
2921af732203SDimitry Andric // in though, so we can return immediately.
2922af732203SDimitry Andric if (InScopeBlocks.count(&MBB) == 0 && !ArtificialBlocks.count(&MBB)) {
2923af732203SDimitry Andric if (VLOCVisited)
2924af732203SDimitry Andric return std::tuple<bool, bool>(true, false);
2925af732203SDimitry Andric return std::tuple<bool, bool>(false, false);
2926af732203SDimitry Andric }
2927af732203SDimitry Andric
2928af732203SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2929af732203SDimitry Andric bool Changed = false;
2930af732203SDimitry Andric
2931af732203SDimitry Andric // Find any live-ins computed in a prior iteration.
2932af732203SDimitry Andric auto ILSIt = VLOCInLocs.find(&MBB);
2933af732203SDimitry Andric assert(ILSIt != VLOCInLocs.end());
2934af732203SDimitry Andric auto &ILS = *ILSIt->second;
2935af732203SDimitry Andric
2936af732203SDimitry Andric // Order predecessors by RPOT order, for exploring them in that order.
2937*5f7ddb14SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2938af732203SDimitry Andric
2939af732203SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2940af732203SDimitry Andric return BBToOrder[A] < BBToOrder[B];
2941af732203SDimitry Andric };
2942af732203SDimitry Andric
2943af732203SDimitry Andric llvm::sort(BlockOrders, Cmp);
2944af732203SDimitry Andric
2945af732203SDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB];
2946af732203SDimitry Andric
2947af732203SDimitry Andric // Force a re-visit to loop heads in the first dataflow iteration.
2948af732203SDimitry Andric // FIXME: if we could "propose" Const values this wouldn't be needed,
2949af732203SDimitry Andric // because they'd need to be confirmed before being emitted.
2950af732203SDimitry Andric if (!BlockOrders.empty() &&
2951af732203SDimitry Andric BBToOrder[BlockOrders[BlockOrders.size() - 1]] >= CurBlockRPONum &&
2952af732203SDimitry Andric VLOCVisited)
2953af732203SDimitry Andric DowngradeOccurred = true;
2954af732203SDimitry Andric
2955af732203SDimitry Andric auto ConfirmValue = [&InLocsT](const DebugVariable &DV, DbgValue VR) {
2956af732203SDimitry Andric auto Result = InLocsT.insert(std::make_pair(DV, VR));
2957af732203SDimitry Andric (void)Result;
2958af732203SDimitry Andric assert(Result.second);
2959af732203SDimitry Andric };
2960af732203SDimitry Andric
2961af732203SDimitry Andric auto ConfirmNoVal = [&ConfirmValue, &MBB](const DebugVariable &Var, const DbgValueProperties &Properties) {
2962af732203SDimitry Andric DbgValue NoLocPHIVal(MBB.getNumber(), Properties, DbgValue::NoVal);
2963af732203SDimitry Andric
2964af732203SDimitry Andric ConfirmValue(Var, NoLocPHIVal);
2965af732203SDimitry Andric };
2966af732203SDimitry Andric
2967af732203SDimitry Andric // Attempt to join the values for each variable.
2968af732203SDimitry Andric for (auto &Var : AllVars) {
2969af732203SDimitry Andric // Collect all the DbgValues for this variable.
2970af732203SDimitry Andric SmallVector<InValueT, 8> Values;
2971af732203SDimitry Andric bool Bail = false;
2972af732203SDimitry Andric unsigned BackEdgesStart = 0;
2973af732203SDimitry Andric for (auto p : BlockOrders) {
2974af732203SDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be
2975af732203SDimitry Andric // able to join any locations.
2976af732203SDimitry Andric if (!BlocksToExplore.contains(p)) {
2977af732203SDimitry Andric Bail = true;
2978af732203SDimitry Andric break;
2979af732203SDimitry Andric }
2980af732203SDimitry Andric
2981af732203SDimitry Andric // Don't attempt to handle unvisited predecessors: they're implicitly
2982af732203SDimitry Andric // "unknown"s in the lattice.
2983af732203SDimitry Andric if (VLOCVisited && !VLOCVisited->count(p))
2984af732203SDimitry Andric continue;
2985af732203SDimitry Andric
2986af732203SDimitry Andric // If the predecessors OutLocs is absent, there's not much we can do.
2987af732203SDimitry Andric auto OL = VLOCOutLocs.find(p);
2988af732203SDimitry Andric if (OL == VLOCOutLocs.end()) {
2989af732203SDimitry Andric Bail = true;
2990af732203SDimitry Andric break;
2991af732203SDimitry Andric }
2992af732203SDimitry Andric
2993af732203SDimitry Andric // No live-out value for this predecessor also means we can't produce
2994af732203SDimitry Andric // a joined value.
2995af732203SDimitry Andric auto VIt = OL->second->find(Var);
2996af732203SDimitry Andric if (VIt == OL->second->end()) {
2997af732203SDimitry Andric Bail = true;
2998af732203SDimitry Andric break;
2999af732203SDimitry Andric }
3000af732203SDimitry Andric
3001af732203SDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on
3002af732203SDimitry Andric // BlockOrders being sorted by RPO.
3003af732203SDimitry Andric unsigned ThisBBRPONum = BBToOrder[p];
3004af732203SDimitry Andric if (ThisBBRPONum < CurBlockRPONum)
3005af732203SDimitry Andric ++BackEdgesStart;
3006af732203SDimitry Andric
3007af732203SDimitry Andric Values.push_back(std::make_pair(p, &VIt->second));
3008af732203SDimitry Andric }
3009af732203SDimitry Andric
3010af732203SDimitry Andric // If there were no values, or one of the predecessors couldn't have a
3011af732203SDimitry Andric // value, then give up immediately. It's not safe to produce a live-in
3012af732203SDimitry Andric // value.
3013af732203SDimitry Andric if (Bail || Values.size() == 0)
3014af732203SDimitry Andric continue;
3015af732203SDimitry Andric
3016af732203SDimitry Andric // Enumeration identifying the current state of the predecessors values.
3017af732203SDimitry Andric enum {
3018af732203SDimitry Andric Unset = 0,
3019af732203SDimitry Andric Agreed, // All preds agree on the variable value.
3020af732203SDimitry Andric PropDisagree, // All preds agree, but the value kind is Proposed in some.
3021af732203SDimitry Andric BEDisagree, // Only back-edges disagree on variable value.
3022af732203SDimitry Andric PHINeeded, // Non-back-edge predecessors have conflicing values.
3023af732203SDimitry Andric NoSolution // Conflicting Value metadata makes solution impossible.
3024af732203SDimitry Andric } OurState = Unset;
3025af732203SDimitry Andric
3026af732203SDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor.
3027af732203SDimitry Andric // Pick the variable value from the first of these, to compare against
3028af732203SDimitry Andric // all others.
3029af732203SDimitry Andric const DbgValue &FirstVal = *Values[0].second;
3030af732203SDimitry Andric const ValueIDNum &FirstID = FirstVal.ID;
3031af732203SDimitry Andric
3032af732203SDimitry Andric // Scan for variable values that can't be resolved: if they have different
3033af732203SDimitry Andric // DIExpressions, different indirectness, or are mixed constants /
3034af732203SDimitry Andric // non-constants.
3035af732203SDimitry Andric for (auto &V : Values) {
3036af732203SDimitry Andric if (V.second->Properties != FirstVal.Properties)
3037af732203SDimitry Andric OurState = NoSolution;
3038af732203SDimitry Andric if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
3039af732203SDimitry Andric OurState = NoSolution;
3040af732203SDimitry Andric }
3041af732203SDimitry Andric
3042af732203SDimitry Andric // Flags diagnosing _how_ the values disagree.
3043af732203SDimitry Andric bool NonBackEdgeDisagree = false;
3044af732203SDimitry Andric bool DisagreeOnPHINess = false;
3045af732203SDimitry Andric bool IDDisagree = false;
3046af732203SDimitry Andric bool Disagree = false;
3047af732203SDimitry Andric if (OurState == Unset) {
3048af732203SDimitry Andric for (auto &V : Values) {
3049af732203SDimitry Andric if (*V.second == FirstVal)
3050af732203SDimitry Andric continue; // No disagreement.
3051af732203SDimitry Andric
3052af732203SDimitry Andric Disagree = true;
3053af732203SDimitry Andric
3054af732203SDimitry Andric // Flag whether the value number actually diagrees.
3055af732203SDimitry Andric if (V.second->ID != FirstID)
3056af732203SDimitry Andric IDDisagree = true;
3057af732203SDimitry Andric
3058af732203SDimitry Andric // Distinguish whether disagreement happens in backedges or not.
3059af732203SDimitry Andric // Relies on Values (and BlockOrders) being sorted by RPO.
3060af732203SDimitry Andric unsigned ThisBBRPONum = BBToOrder[V.first];
3061af732203SDimitry Andric if (ThisBBRPONum < CurBlockRPONum)
3062af732203SDimitry Andric NonBackEdgeDisagree = true;
3063af732203SDimitry Andric
3064af732203SDimitry Andric // Is there a difference in whether the value is definite or only
3065af732203SDimitry Andric // proposed?
3066af732203SDimitry Andric if (V.second->Kind != FirstVal.Kind &&
3067af732203SDimitry Andric (V.second->Kind == DbgValue::Proposed ||
3068af732203SDimitry Andric V.second->Kind == DbgValue::Def) &&
3069af732203SDimitry Andric (FirstVal.Kind == DbgValue::Proposed ||
3070af732203SDimitry Andric FirstVal.Kind == DbgValue::Def))
3071af732203SDimitry Andric DisagreeOnPHINess = true;
3072af732203SDimitry Andric }
3073af732203SDimitry Andric
3074af732203SDimitry Andric // Collect those flags together and determine an overall state for
3075af732203SDimitry Andric // what extend the predecessors agree on a live-in value.
3076af732203SDimitry Andric if (!Disagree)
3077af732203SDimitry Andric OurState = Agreed;
3078af732203SDimitry Andric else if (!IDDisagree && DisagreeOnPHINess)
3079af732203SDimitry Andric OurState = PropDisagree;
3080af732203SDimitry Andric else if (!NonBackEdgeDisagree)
3081af732203SDimitry Andric OurState = BEDisagree;
3082af732203SDimitry Andric else
3083af732203SDimitry Andric OurState = PHINeeded;
3084af732203SDimitry Andric }
3085af732203SDimitry Andric
3086af732203SDimitry Andric // An extra indicator: if we only disagree on whether the value is a
3087af732203SDimitry Andric // Def, or proposed, then also flag whether that disagreement happens
3088af732203SDimitry Andric // in backedges only.
3089af732203SDimitry Andric bool PropOnlyInBEs = Disagree && !IDDisagree && DisagreeOnPHINess &&
3090af732203SDimitry Andric !NonBackEdgeDisagree && FirstVal.Kind == DbgValue::Def;
3091af732203SDimitry Andric
3092af732203SDimitry Andric const auto &Properties = FirstVal.Properties;
3093af732203SDimitry Andric
3094af732203SDimitry Andric auto OldLiveInIt = ILS.find(Var);
3095af732203SDimitry Andric const DbgValue *OldLiveInLocation =
3096af732203SDimitry Andric (OldLiveInIt != ILS.end()) ? &OldLiveInIt->second : nullptr;
3097af732203SDimitry Andric
3098af732203SDimitry Andric bool OverRide = false;
3099af732203SDimitry Andric if (OurState == BEDisagree && OldLiveInLocation) {
3100af732203SDimitry Andric // Only backedges disagree: we can consider downgrading. If there was a
3101af732203SDimitry Andric // previous live-in value, use it to work out whether the current
3102af732203SDimitry Andric // incoming value represents a lattice downgrade or not.
3103af732203SDimitry Andric OverRide =
3104af732203SDimitry Andric vlocDowngradeLattice(MBB, *OldLiveInLocation, Values, CurBlockRPONum);
3105af732203SDimitry Andric }
3106af732203SDimitry Andric
3107af732203SDimitry Andric // Use the current state of predecessor agreement and other flags to work
3108af732203SDimitry Andric // out what to do next. Possibilities include:
3109af732203SDimitry Andric // * Accept a value all predecessors agree on, or accept one that
3110af732203SDimitry Andric // represents a step down the exploration lattice,
3111af732203SDimitry Andric // * Use a PHI value number, if one can be found,
3112af732203SDimitry Andric // * Propose a PHI value number, and see if it gets confirmed later,
3113af732203SDimitry Andric // * Emit a 'NoVal' value, indicating we couldn't resolve anything.
3114af732203SDimitry Andric if (OurState == Agreed) {
3115af732203SDimitry Andric // Easiest solution: all predecessors agree on the variable value.
3116af732203SDimitry Andric ConfirmValue(Var, FirstVal);
3117af732203SDimitry Andric } else if (OurState == BEDisagree && OverRide) {
3118af732203SDimitry Andric // Only backedges disagree, and the other predecessors have produced
3119af732203SDimitry Andric // a new live-in value further down the exploration lattice.
3120af732203SDimitry Andric DowngradeOccurred = true;
3121af732203SDimitry Andric ConfirmValue(Var, FirstVal);
3122af732203SDimitry Andric } else if (OurState == PropDisagree) {
3123af732203SDimitry Andric // Predecessors agree on value, but some say it's only a proposed value.
3124af732203SDimitry Andric // Propagate it as proposed: unless it was proposed in this block, in
3125af732203SDimitry Andric // which case we're able to confirm the value.
3126af732203SDimitry Andric if (FirstID.getBlock() == (uint64_t)MBB.getNumber() && FirstID.isPHI()) {
3127af732203SDimitry Andric ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def));
3128af732203SDimitry Andric } else if (PropOnlyInBEs) {
3129af732203SDimitry Andric // If only backedges disagree, a higher (in RPO) block confirmed this
3130af732203SDimitry Andric // location, and we need to propagate it into this loop.
3131af732203SDimitry Andric ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def));
3132af732203SDimitry Andric } else {
3133af732203SDimitry Andric // Otherwise; a Def meeting a Proposed is still a Proposed.
3134af732203SDimitry Andric ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Proposed));
3135af732203SDimitry Andric }
3136af732203SDimitry Andric } else if ((OurState == PHINeeded || OurState == BEDisagree)) {
3137af732203SDimitry Andric // Predecessors disagree and can't be downgraded: this can only be
3138af732203SDimitry Andric // solved with a PHI. Use pickVPHILoc to go look for one.
3139af732203SDimitry Andric Optional<ValueIDNum> VPHI;
3140af732203SDimitry Andric bool AllEdgesVPHI = false;
3141af732203SDimitry Andric std::tie(VPHI, AllEdgesVPHI) =
3142af732203SDimitry Andric pickVPHILoc(MBB, Var, VLOCOutLocs, MOutLocs, MInLocs, BlockOrders);
3143af732203SDimitry Andric
3144af732203SDimitry Andric if (VPHI && AllEdgesVPHI) {
3145af732203SDimitry Andric // There's a PHI value that's valid for all predecessors -- we can use
3146af732203SDimitry Andric // it. If any of the non-backedge predecessors have proposed values
3147af732203SDimitry Andric // though, this PHI is also only proposed, until the predecessors are
3148af732203SDimitry Andric // confirmed.
3149af732203SDimitry Andric DbgValue::KindT K = DbgValue::Def;
3150af732203SDimitry Andric for (unsigned int I = 0; I < BackEdgesStart; ++I)
3151af732203SDimitry Andric if (Values[I].second->Kind == DbgValue::Proposed)
3152af732203SDimitry Andric K = DbgValue::Proposed;
3153af732203SDimitry Andric
3154af732203SDimitry Andric ConfirmValue(Var, DbgValue(*VPHI, Properties, K));
3155af732203SDimitry Andric } else if (VPHI) {
3156af732203SDimitry Andric // There's a PHI value, but it's only legal for backedges. Leave this
3157af732203SDimitry Andric // as a proposed PHI value: it might come back on the backedges,
3158af732203SDimitry Andric // and allow us to confirm it in the future.
3159af732203SDimitry Andric DbgValue NoBEValue = DbgValue(*VPHI, Properties, DbgValue::Proposed);
3160af732203SDimitry Andric ConfirmValue(Var, NoBEValue);
3161af732203SDimitry Andric } else {
3162af732203SDimitry Andric ConfirmNoVal(Var, Properties);
3163af732203SDimitry Andric }
3164af732203SDimitry Andric } else {
3165af732203SDimitry Andric // Otherwise: we don't know. Emit a "phi but no real loc" phi.
3166af732203SDimitry Andric ConfirmNoVal(Var, Properties);
3167af732203SDimitry Andric }
3168af732203SDimitry Andric }
3169af732203SDimitry Andric
3170af732203SDimitry Andric // Store newly calculated in-locs into VLOCInLocs, if they've changed.
3171af732203SDimitry Andric Changed = ILS != InLocsT;
3172af732203SDimitry Andric if (Changed)
3173af732203SDimitry Andric ILS = InLocsT;
3174af732203SDimitry Andric
3175af732203SDimitry Andric return std::tuple<bool, bool>(Changed, DowngradeOccurred);
3176af732203SDimitry Andric }
3177af732203SDimitry Andric
vlocDataflow(const LexicalScope * Scope,const DILocation * DILoc,const SmallSet<DebugVariable,4> & VarsWeCareAbout,SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks,LiveInsT & Output,ValueIDNum ** MOutLocs,ValueIDNum ** MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs)3178af732203SDimitry Andric void InstrRefBasedLDV::vlocDataflow(
3179af732203SDimitry Andric const LexicalScope *Scope, const DILocation *DILoc,
3180af732203SDimitry Andric const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
3181af732203SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
3182af732203SDimitry Andric ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
3183af732203SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) {
3184af732203SDimitry Andric // This method is much like mlocDataflow: but focuses on a single
3185af732203SDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are
3186af732203SDimitry Andric // to have their value assignments solved, then run our dataflow algorithm
3187af732203SDimitry Andric // until a fixedpoint is reached.
3188af732203SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>,
3189af732203SDimitry Andric std::greater<unsigned int>>
3190af732203SDimitry Andric Worklist, Pending;
3191af732203SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
3192af732203SDimitry Andric
3193af732203SDimitry Andric // The set of blocks we'll be examining.
3194af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3195af732203SDimitry Andric
3196af732203SDimitry Andric // The order in which to examine them (RPO).
3197af732203SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders;
3198af732203SDimitry Andric
3199af732203SDimitry Andric // RPO ordering function.
3200af732203SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3201af732203SDimitry Andric return BBToOrder[A] < BBToOrder[B];
3202af732203SDimitry Andric };
3203af732203SDimitry Andric
3204af732203SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
3205af732203SDimitry Andric
3206af732203SDimitry Andric // A separate container to distinguish "blocks we're exploring" versus
3207af732203SDimitry Andric // "blocks that are potentially in scope. See comment at start of vlocJoin.
3208af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore;
3209af732203SDimitry Andric
3210af732203SDimitry Andric // Old LiveDebugValues tracks variable locations that come out of blocks
3211af732203SDimitry Andric // not in scope, where DBG_VALUEs occur. This is something we could
3212af732203SDimitry Andric // legitimately ignore, but lets allow it for now.
3213af732203SDimitry Andric if (EmulateOldLDV)
3214af732203SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
3215af732203SDimitry Andric
3216af732203SDimitry Andric // We also need to propagate variable values through any artificial blocks
3217af732203SDimitry Andric // that immediately follow blocks in scope.
3218af732203SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd;
3219af732203SDimitry Andric
3220af732203SDimitry Andric // Helper lambda: For a given block in scope, perform a depth first search
3221af732203SDimitry Andric // of all the artificial successors, adding them to the ToAdd collection.
3222af732203SDimitry Andric auto AccumulateArtificialBlocks =
3223af732203SDimitry Andric [this, &ToAdd, &BlocksToExplore,
3224af732203SDimitry Andric &InScopeBlocks](const MachineBasicBlock *MBB) {
3225af732203SDimitry Andric // Depth-first-search state: each node is a block and which successor
3226af732203SDimitry Andric // we're currently exploring.
3227af732203SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *,
3228af732203SDimitry Andric MachineBasicBlock::const_succ_iterator>,
3229af732203SDimitry Andric 8>
3230af732203SDimitry Andric DFS;
3231af732203SDimitry Andric
3232af732203SDimitry Andric // Find any artificial successors not already tracked.
3233af732203SDimitry Andric for (auto *succ : MBB->successors()) {
3234af732203SDimitry Andric if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ))
3235af732203SDimitry Andric continue;
3236af732203SDimitry Andric if (!ArtificialBlocks.count(succ))
3237af732203SDimitry Andric continue;
3238af732203SDimitry Andric DFS.push_back(std::make_pair(succ, succ->succ_begin()));
3239af732203SDimitry Andric ToAdd.insert(succ);
3240af732203SDimitry Andric }
3241af732203SDimitry Andric
3242af732203SDimitry Andric // Search all those blocks, depth first.
3243af732203SDimitry Andric while (!DFS.empty()) {
3244af732203SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first;
3245af732203SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
3246af732203SDimitry Andric // Walk back if we've explored this blocks successors to the end.
3247af732203SDimitry Andric if (CurSucc == CurBB->succ_end()) {
3248af732203SDimitry Andric DFS.pop_back();
3249af732203SDimitry Andric continue;
3250af732203SDimitry Andric }
3251af732203SDimitry Andric
3252af732203SDimitry Andric // If the current successor is artificial and unexplored, descend into
3253af732203SDimitry Andric // it.
3254af732203SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
3255af732203SDimitry Andric DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin()));
3256af732203SDimitry Andric ToAdd.insert(*CurSucc);
3257af732203SDimitry Andric continue;
3258af732203SDimitry Andric }
3259af732203SDimitry Andric
3260af732203SDimitry Andric ++CurSucc;
3261af732203SDimitry Andric }
3262af732203SDimitry Andric };
3263af732203SDimitry Andric
3264af732203SDimitry Andric // Search in-scope blocks and those containing a DBG_VALUE from this scope
3265af732203SDimitry Andric // for artificial successors.
3266af732203SDimitry Andric for (auto *MBB : BlocksToExplore)
3267af732203SDimitry Andric AccumulateArtificialBlocks(MBB);
3268af732203SDimitry Andric for (auto *MBB : InScopeBlocks)
3269af732203SDimitry Andric AccumulateArtificialBlocks(MBB);
3270af732203SDimitry Andric
3271af732203SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
3272af732203SDimitry Andric InScopeBlocks.insert(ToAdd.begin(), ToAdd.end());
3273af732203SDimitry Andric
3274af732203SDimitry Andric // Single block scope: not interesting! No propagation at all. Note that
3275af732203SDimitry Andric // this could probably go above ArtificialBlocks without damage, but
3276af732203SDimitry Andric // that then produces output differences from original-live-debug-values,
3277af732203SDimitry Andric // which propagates from a single block into many artificial ones.
3278af732203SDimitry Andric if (BlocksToExplore.size() == 1)
3279af732203SDimitry Andric return;
3280af732203SDimitry Andric
3281af732203SDimitry Andric // Picks out relevants blocks RPO order and sort them.
3282af732203SDimitry Andric for (auto *MBB : BlocksToExplore)
3283af732203SDimitry Andric BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
3284af732203SDimitry Andric
3285af732203SDimitry Andric llvm::sort(BlockOrders, Cmp);
3286af732203SDimitry Andric unsigned NumBlocks = BlockOrders.size();
3287af732203SDimitry Andric
3288af732203SDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large.
3289af732203SDimitry Andric SmallVector<DenseMap<DebugVariable, DbgValue>, 32> LiveIns, LiveOuts;
3290af732203SDimitry Andric LiveIns.resize(NumBlocks);
3291af732203SDimitry Andric LiveOuts.resize(NumBlocks);
3292af732203SDimitry Andric
3293af732203SDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3294af732203SDimitry Andric // vlocJoin.
3295af732203SDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx;
3296af732203SDimitry Andric LiveOutIdx.reserve(NumBlocks);
3297af732203SDimitry Andric LiveInIdx.reserve(NumBlocks);
3298af732203SDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) {
3299af732203SDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3300af732203SDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3301af732203SDimitry Andric }
3302af732203SDimitry Andric
3303af732203SDimitry Andric for (auto *MBB : BlockOrders) {
3304af732203SDimitry Andric Worklist.push(BBToOrder[MBB]);
3305af732203SDimitry Andric OnWorklist.insert(MBB);
3306af732203SDimitry Andric }
3307af732203SDimitry Andric
3308af732203SDimitry Andric // Iterate over all the blocks we selected, propagating variable values.
3309af732203SDimitry Andric bool FirstTrip = true;
3310af732203SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> VLOCVisited;
3311af732203SDimitry Andric while (!Worklist.empty() || !Pending.empty()) {
3312af732203SDimitry Andric while (!Worklist.empty()) {
3313af732203SDimitry Andric auto *MBB = OrderToBB[Worklist.top()];
3314af732203SDimitry Andric CurBB = MBB->getNumber();
3315af732203SDimitry Andric Worklist.pop();
3316af732203SDimitry Andric
3317af732203SDimitry Andric DenseMap<DebugVariable, DbgValue> JoinedInLocs;
3318af732203SDimitry Andric
3319af732203SDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output
3320af732203SDimitry Andric // into JoinedInLocs.
3321af732203SDimitry Andric bool InLocsChanged, DowngradeOccurred;
3322af732203SDimitry Andric std::tie(InLocsChanged, DowngradeOccurred) = vlocJoin(
3323af732203SDimitry Andric *MBB, LiveOutIdx, LiveInIdx, (FirstTrip) ? &VLOCVisited : nullptr,
3324af732203SDimitry Andric CurBB, VarsWeCareAbout, MOutLocs, MInLocs, InScopeBlocks,
3325af732203SDimitry Andric BlocksToExplore, JoinedInLocs);
3326af732203SDimitry Andric
3327af732203SDimitry Andric bool FirstVisit = VLOCVisited.insert(MBB).second;
3328af732203SDimitry Andric
3329af732203SDimitry Andric // Always explore transfer function if inlocs changed, or if we've not
3330af732203SDimitry Andric // visited this block before.
3331af732203SDimitry Andric InLocsChanged |= FirstVisit;
3332af732203SDimitry Andric
3333af732203SDimitry Andric // If a downgrade occurred, book us in for re-examination on the next
3334af732203SDimitry Andric // iteration.
3335af732203SDimitry Andric if (DowngradeOccurred && OnPending.insert(MBB).second)
3336af732203SDimitry Andric Pending.push(BBToOrder[MBB]);
3337af732203SDimitry Andric
3338af732203SDimitry Andric if (!InLocsChanged)
3339af732203SDimitry Andric continue;
3340af732203SDimitry Andric
3341af732203SDimitry Andric // Do transfer function.
3342af732203SDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()];
3343af732203SDimitry Andric for (auto &Transfer : VTracker.Vars) {
3344af732203SDimitry Andric // Is this var we're mangling in this scope?
3345af732203SDimitry Andric if (VarsWeCareAbout.count(Transfer.first)) {
3346af732203SDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg).
3347af732203SDimitry Andric if (Transfer.second.Kind == DbgValue::Undef) {
3348af732203SDimitry Andric JoinedInLocs.erase(Transfer.first);
3349af732203SDimitry Andric } else {
3350af732203SDimitry Andric // Insert new variable value; or overwrite.
3351af732203SDimitry Andric auto NewValuePair = std::make_pair(Transfer.first, Transfer.second);
3352af732203SDimitry Andric auto Result = JoinedInLocs.insert(NewValuePair);
3353af732203SDimitry Andric if (!Result.second)
3354af732203SDimitry Andric Result.first->second = Transfer.second;
3355af732203SDimitry Andric }
3356af732203SDimitry Andric }
3357af732203SDimitry Andric }
3358af732203SDimitry Andric
3359af732203SDimitry Andric // Did the live-out locations change?
3360af732203SDimitry Andric bool OLChanged = JoinedInLocs != *LiveOutIdx[MBB];
3361af732203SDimitry Andric
3362af732203SDimitry Andric // If they haven't changed, there's no need to explore further.
3363af732203SDimitry Andric if (!OLChanged)
3364af732203SDimitry Andric continue;
3365af732203SDimitry Andric
3366af732203SDimitry Andric // Commit to the live-out record.
3367af732203SDimitry Andric *LiveOutIdx[MBB] = JoinedInLocs;
3368af732203SDimitry Andric
3369af732203SDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge
3370af732203SDimitry Andric // successors during this dataflow iteration; book backedge successors
3371af732203SDimitry Andric // to be visited next time around.
3372af732203SDimitry Andric for (auto s : MBB->successors()) {
3373af732203SDimitry Andric // Ignore out of scope / not-to-be-explored successors.
3374af732203SDimitry Andric if (LiveInIdx.find(s) == LiveInIdx.end())
3375af732203SDimitry Andric continue;
3376af732203SDimitry Andric
3377af732203SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) {
3378af732203SDimitry Andric if (OnWorklist.insert(s).second)
3379af732203SDimitry Andric Worklist.push(BBToOrder[s]);
3380af732203SDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
3381af732203SDimitry Andric Pending.push(BBToOrder[s]);
3382af732203SDimitry Andric }
3383af732203SDimitry Andric }
3384af732203SDimitry Andric }
3385af732203SDimitry Andric Worklist.swap(Pending);
3386af732203SDimitry Andric std::swap(OnWorklist, OnPending);
3387af732203SDimitry Andric OnPending.clear();
3388af732203SDimitry Andric assert(Pending.empty());
3389af732203SDimitry Andric FirstTrip = false;
3390af732203SDimitry Andric }
3391af732203SDimitry Andric
3392af732203SDimitry Andric // Dataflow done. Now what? Save live-ins. Ignore any that are still marked
3393af732203SDimitry Andric // as being variable-PHIs, because those did not have their machine-PHI
3394af732203SDimitry Andric // value confirmed. Such variable values are places that could have been
3395af732203SDimitry Andric // PHIs, but are not.
3396af732203SDimitry Andric for (auto *MBB : BlockOrders) {
3397af732203SDimitry Andric auto &VarMap = *LiveInIdx[MBB];
3398af732203SDimitry Andric for (auto &P : VarMap) {
3399af732203SDimitry Andric if (P.second.Kind == DbgValue::Proposed ||
3400af732203SDimitry Andric P.second.Kind == DbgValue::NoVal)
3401af732203SDimitry Andric continue;
3402af732203SDimitry Andric Output[MBB->getNumber()].push_back(P);
3403af732203SDimitry Andric }
3404af732203SDimitry Andric }
3405af732203SDimitry Andric
3406af732203SDimitry Andric BlockOrders.clear();
3407af732203SDimitry Andric BlocksToExplore.clear();
3408af732203SDimitry Andric }
3409af732203SDimitry Andric
3410af732203SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump_mloc_transfer(const MLocTransferMap & mloc_transfer) const3411af732203SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer(
3412af732203SDimitry Andric const MLocTransferMap &mloc_transfer) const {
3413af732203SDimitry Andric for (auto &P : mloc_transfer) {
3414af732203SDimitry Andric std::string foo = MTracker->LocIdxToName(P.first);
3415af732203SDimitry Andric std::string bar = MTracker->IDAsString(P.second);
3416af732203SDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n";
3417af732203SDimitry Andric }
3418af732203SDimitry Andric }
3419af732203SDimitry Andric #endif
3420af732203SDimitry Andric
emitLocations(MachineFunction & MF,LiveInsT SavedLiveIns,ValueIDNum ** MOutLocs,ValueIDNum ** MInLocs,DenseMap<DebugVariable,unsigned> & AllVarsNumbering,const TargetPassConfig & TPC)3421af732203SDimitry Andric void InstrRefBasedLDV::emitLocations(
3422*5f7ddb14SDimitry Andric MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MOutLocs,
3423*5f7ddb14SDimitry Andric ValueIDNum **MInLocs, DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
3424*5f7ddb14SDimitry Andric const TargetPassConfig &TPC) {
3425*5f7ddb14SDimitry Andric TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
3426af732203SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
3427af732203SDimitry Andric
3428af732203SDimitry Andric // For each block, load in the machine value locations and variable value
3429af732203SDimitry Andric // live-ins, then step through each instruction in the block. New DBG_VALUEs
3430af732203SDimitry Andric // to be inserted will be created along the way.
3431af732203SDimitry Andric for (MachineBasicBlock &MBB : MF) {
3432af732203SDimitry Andric unsigned bbnum = MBB.getNumber();
3433af732203SDimitry Andric MTracker->reset();
3434af732203SDimitry Andric MTracker->loadFromArray(MInLocs[bbnum], bbnum);
3435af732203SDimitry Andric TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()],
3436af732203SDimitry Andric NumLocs);
3437af732203SDimitry Andric
3438af732203SDimitry Andric CurBB = bbnum;
3439af732203SDimitry Andric CurInst = 1;
3440af732203SDimitry Andric for (auto &MI : MBB) {
3441*5f7ddb14SDimitry Andric process(MI, MOutLocs, MInLocs);
3442af732203SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator());
3443af732203SDimitry Andric ++CurInst;
3444af732203SDimitry Andric }
3445af732203SDimitry Andric }
3446af732203SDimitry Andric
3447af732203SDimitry Andric // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer
3448af732203SDimitry Andric // in DWARF in different orders. Use the order that they appear when walking
3449af732203SDimitry Andric // through each block / each instruction, stored in AllVarsNumbering.
3450af732203SDimitry Andric auto OrderDbgValues = [&](const MachineInstr *A,
3451af732203SDimitry Andric const MachineInstr *B) -> bool {
3452af732203SDimitry Andric DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(),
3453af732203SDimitry Andric A->getDebugLoc()->getInlinedAt());
3454af732203SDimitry Andric DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(),
3455af732203SDimitry Andric B->getDebugLoc()->getInlinedAt());
3456af732203SDimitry Andric return AllVarsNumbering.find(VarA)->second <
3457af732203SDimitry Andric AllVarsNumbering.find(VarB)->second;
3458af732203SDimitry Andric };
3459af732203SDimitry Andric
3460af732203SDimitry Andric // Go through all the transfers recorded in the TransferTracker -- this is
3461af732203SDimitry Andric // both the live-ins to a block, and any movements of values that happen
3462af732203SDimitry Andric // in the middle.
3463af732203SDimitry Andric for (auto &P : TTracker->Transfers) {
3464af732203SDimitry Andric // Sort them according to appearance order.
3465af732203SDimitry Andric llvm::sort(P.Insts, OrderDbgValues);
3466af732203SDimitry Andric // Insert either before or after the designated point...
3467af732203SDimitry Andric if (P.MBB) {
3468af732203SDimitry Andric MachineBasicBlock &MBB = *P.MBB;
3469af732203SDimitry Andric for (auto *MI : P.Insts) {
3470af732203SDimitry Andric MBB.insert(P.Pos, MI);
3471af732203SDimitry Andric }
3472af732203SDimitry Andric } else {
3473*5f7ddb14SDimitry Andric // Terminators, like tail calls, can clobber things. Don't try and place
3474*5f7ddb14SDimitry Andric // transfers after them.
3475*5f7ddb14SDimitry Andric if (P.Pos->isTerminator())
3476*5f7ddb14SDimitry Andric continue;
3477*5f7ddb14SDimitry Andric
3478af732203SDimitry Andric MachineBasicBlock &MBB = *P.Pos->getParent();
3479af732203SDimitry Andric for (auto *MI : P.Insts) {
3480*5f7ddb14SDimitry Andric MBB.insertAfterBundle(P.Pos, MI);
3481af732203SDimitry Andric }
3482af732203SDimitry Andric }
3483af732203SDimitry Andric }
3484af732203SDimitry Andric }
3485af732203SDimitry Andric
initialSetup(MachineFunction & MF)3486af732203SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3487af732203SDimitry Andric // Build some useful data structures.
3488af732203SDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3489af732203SDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc())
3490af732203SDimitry Andric return DL.getLine() != 0;
3491af732203SDimitry Andric return false;
3492af732203SDimitry Andric };
3493af732203SDimitry Andric // Collect a set of all the artificial blocks.
3494af732203SDimitry Andric for (auto &MBB : MF)
3495af732203SDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation))
3496af732203SDimitry Andric ArtificialBlocks.insert(&MBB);
3497af732203SDimitry Andric
3498af732203SDimitry Andric // Compute mappings of block <=> RPO order.
3499af732203SDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3500af732203SDimitry Andric unsigned int RPONumber = 0;
3501*5f7ddb14SDimitry Andric for (MachineBasicBlock *MBB : RPOT) {
3502*5f7ddb14SDimitry Andric OrderToBB[RPONumber] = MBB;
3503*5f7ddb14SDimitry Andric BBToOrder[MBB] = RPONumber;
3504*5f7ddb14SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber;
3505af732203SDimitry Andric ++RPONumber;
3506af732203SDimitry Andric }
3507*5f7ddb14SDimitry Andric
3508*5f7ddb14SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup.
3509*5f7ddb14SDimitry Andric llvm::sort(MF.DebugValueSubstitutions);
3510*5f7ddb14SDimitry Andric
3511*5f7ddb14SDimitry Andric #ifdef EXPENSIVE_CHECKS
3512*5f7ddb14SDimitry Andric // As an expensive check, test whether there are any duplicate substitution
3513*5f7ddb14SDimitry Andric // sources in the collection.
3514*5f7ddb14SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) {
3515*5f7ddb14SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin();
3516*5f7ddb14SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
3517*5f7ddb14SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location "
3518*5f7ddb14SDimitry Andric "substitution seen");
3519*5f7ddb14SDimitry Andric }
3520*5f7ddb14SDimitry Andric }
3521*5f7ddb14SDimitry Andric #endif
3522af732203SDimitry Andric }
3523af732203SDimitry Andric
3524af732203SDimitry Andric /// Calculate the liveness information for the given machine function and
3525af732203SDimitry Andric /// extend ranges across basic blocks.
ExtendRanges(MachineFunction & MF,TargetPassConfig * TPC)3526af732203SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3527af732203SDimitry Andric TargetPassConfig *TPC) {
3528af732203SDimitry Andric // No subprogram means this function contains no debuginfo.
3529af732203SDimitry Andric if (!MF.getFunction().getSubprogram())
3530af732203SDimitry Andric return false;
3531af732203SDimitry Andric
3532af732203SDimitry Andric LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3533af732203SDimitry Andric this->TPC = TPC;
3534af732203SDimitry Andric
3535af732203SDimitry Andric TRI = MF.getSubtarget().getRegisterInfo();
3536af732203SDimitry Andric TII = MF.getSubtarget().getInstrInfo();
3537af732203SDimitry Andric TFI = MF.getSubtarget().getFrameLowering();
3538af732203SDimitry Andric TFI->getCalleeSaves(MF, CalleeSavedRegs);
3539*5f7ddb14SDimitry Andric MFI = &MF.getFrameInfo();
3540af732203SDimitry Andric LS.initialize(MF);
3541af732203SDimitry Andric
3542af732203SDimitry Andric MTracker =
3543af732203SDimitry Andric new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3544af732203SDimitry Andric VTracker = nullptr;
3545af732203SDimitry Andric TTracker = nullptr;
3546af732203SDimitry Andric
3547af732203SDimitry Andric SmallVector<MLocTransferMap, 32> MLocTransfer;
3548af732203SDimitry Andric SmallVector<VLocTracker, 8> vlocs;
3549af732203SDimitry Andric LiveInsT SavedLiveIns;
3550af732203SDimitry Andric
3551af732203SDimitry Andric int MaxNumBlocks = -1;
3552af732203SDimitry Andric for (auto &MBB : MF)
3553af732203SDimitry Andric MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3554af732203SDimitry Andric assert(MaxNumBlocks >= 0);
3555af732203SDimitry Andric ++MaxNumBlocks;
3556af732203SDimitry Andric
3557af732203SDimitry Andric MLocTransfer.resize(MaxNumBlocks);
3558af732203SDimitry Andric vlocs.resize(MaxNumBlocks);
3559af732203SDimitry Andric SavedLiveIns.resize(MaxNumBlocks);
3560af732203SDimitry Andric
3561af732203SDimitry Andric initialSetup(MF);
3562af732203SDimitry Andric
3563af732203SDimitry Andric produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3564af732203SDimitry Andric
3565af732203SDimitry Andric // Allocate and initialize two array-of-arrays for the live-in and live-out
3566af732203SDimitry Andric // machine values. The outer dimension is the block number; while the inner
3567af732203SDimitry Andric // dimension is a LocIdx from MLocTracker.
3568af732203SDimitry Andric ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks];
3569af732203SDimitry Andric ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks];
3570af732203SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
3571af732203SDimitry Andric for (int i = 0; i < MaxNumBlocks; ++i) {
3572af732203SDimitry Andric MOutLocs[i] = new ValueIDNum[NumLocs];
3573af732203SDimitry Andric MInLocs[i] = new ValueIDNum[NumLocs];
3574af732203SDimitry Andric }
3575af732203SDimitry Andric
3576af732203SDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function,
3577af732203SDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use
3578af732203SDimitry Andric // both live-ins and live-outs for decision making in the variable value
3579af732203SDimitry Andric // dataflow problem.
3580af732203SDimitry Andric mlocDataflow(MInLocs, MOutLocs, MLocTransfer);
3581af732203SDimitry Andric
3582*5f7ddb14SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into
3583*5f7ddb14SDimitry Andric // either live-through machine values, or PHIs.
3584*5f7ddb14SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) {
3585*5f7ddb14SDimitry Andric // Identify unresolved block-live-ins.
3586*5f7ddb14SDimitry Andric ValueIDNum &Num = DBG_PHI.ValueRead;
3587*5f7ddb14SDimitry Andric if (!Num.isPHI())
3588*5f7ddb14SDimitry Andric continue;
3589*5f7ddb14SDimitry Andric
3590*5f7ddb14SDimitry Andric unsigned BlockNo = Num.getBlock();
3591*5f7ddb14SDimitry Andric LocIdx LocNo = Num.getLoc();
3592*5f7ddb14SDimitry Andric Num = MInLocs[BlockNo][LocNo.asU64()];
3593*5f7ddb14SDimitry Andric }
3594*5f7ddb14SDimitry Andric // Later, we'll be looking up ranges of instruction numbers.
3595*5f7ddb14SDimitry Andric llvm::sort(DebugPHINumToValue);
3596*5f7ddb14SDimitry Andric
3597af732203SDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE
3598af732203SDimitry Andric // instructions and recording what machine value their operands refer to.
3599af732203SDimitry Andric for (auto &OrderPair : OrderToBB) {
3600af732203SDimitry Andric MachineBasicBlock &MBB = *OrderPair.second;
3601af732203SDimitry Andric CurBB = MBB.getNumber();
3602af732203SDimitry Andric VTracker = &vlocs[CurBB];
3603af732203SDimitry Andric VTracker->MBB = &MBB;
3604af732203SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3605af732203SDimitry Andric CurInst = 1;
3606af732203SDimitry Andric for (auto &MI : MBB) {
3607*5f7ddb14SDimitry Andric process(MI, MOutLocs, MInLocs);
3608af732203SDimitry Andric ++CurInst;
3609af732203SDimitry Andric }
3610af732203SDimitry Andric MTracker->reset();
3611af732203SDimitry Andric }
3612af732203SDimitry Andric
3613af732203SDimitry Andric // Number all variables in the order that they appear, to be used as a stable
3614af732203SDimitry Andric // insertion order later.
3615af732203SDimitry Andric DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3616af732203SDimitry Andric
3617af732203SDimitry Andric // Map from one LexicalScope to all the variables in that scope.
3618af732203SDimitry Andric DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars;
3619af732203SDimitry Andric
3620af732203SDimitry Andric // Map from One lexical scope to all blocks in that scope.
3621af732203SDimitry Andric DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>
3622af732203SDimitry Andric ScopeToBlocks;
3623af732203SDimitry Andric
3624af732203SDimitry Andric // Store a DILocation that describes a scope.
3625af732203SDimitry Andric DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation;
3626af732203SDimitry Andric
3627af732203SDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3628af732203SDimitry Andric // the order is unimportant, it just has to be stable.
3629af732203SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3630af732203SDimitry Andric auto *MBB = OrderToBB[I];
3631af732203SDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()];
3632af732203SDimitry Andric // Collect each variable with a DBG_VALUE in this block.
3633af732203SDimitry Andric for (auto &idx : VTracker->Vars) {
3634af732203SDimitry Andric const auto &Var = idx.first;
3635af732203SDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[Var];
3636af732203SDimitry Andric assert(ScopeLoc != nullptr);
3637af732203SDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc);
3638af732203SDimitry Andric
3639af732203SDimitry Andric // No insts in scope -> shouldn't have been recorded.
3640af732203SDimitry Andric assert(Scope != nullptr);
3641af732203SDimitry Andric
3642af732203SDimitry Andric AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3643af732203SDimitry Andric ScopeToVars[Scope].insert(Var);
3644af732203SDimitry Andric ScopeToBlocks[Scope].insert(VTracker->MBB);
3645af732203SDimitry Andric ScopeToDILocation[Scope] = ScopeLoc;
3646af732203SDimitry Andric }
3647af732203SDimitry Andric }
3648af732203SDimitry Andric
3649af732203SDimitry Andric // OK. Iterate over scopes: there might be something to be said for
3650af732203SDimitry Andric // ordering them by size/locality, but that's for the future. For each scope,
3651af732203SDimitry Andric // solve the variable value problem, producing a map of variables to values
3652af732203SDimitry Andric // in SavedLiveIns.
3653af732203SDimitry Andric for (auto &P : ScopeToVars) {
3654af732203SDimitry Andric vlocDataflow(P.first, ScopeToDILocation[P.first], P.second,
3655af732203SDimitry Andric ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs,
3656af732203SDimitry Andric vlocs);
3657af732203SDimitry Andric }
3658af732203SDimitry Andric
3659af732203SDimitry Andric // Using the computed value locations and variable values for each block,
3660af732203SDimitry Andric // create the DBG_VALUE instructions representing the extended variable
3661af732203SDimitry Andric // locations.
3662*5f7ddb14SDimitry Andric emitLocations(MF, SavedLiveIns, MOutLocs, MInLocs, AllVarsNumbering, *TPC);
3663af732203SDimitry Andric
3664af732203SDimitry Andric for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) {
3665af732203SDimitry Andric delete[] MOutLocs[Idx];
3666af732203SDimitry Andric delete[] MInLocs[Idx];
3667af732203SDimitry Andric }
3668af732203SDimitry Andric delete[] MOutLocs;
3669af732203SDimitry Andric delete[] MInLocs;
3670af732203SDimitry Andric
3671af732203SDimitry Andric // Did we actually make any changes? If we created any DBG_VALUEs, then yes.
3672af732203SDimitry Andric bool Changed = TTracker->Transfers.size() != 0;
3673af732203SDimitry Andric
3674af732203SDimitry Andric delete MTracker;
3675af732203SDimitry Andric delete TTracker;
3676af732203SDimitry Andric MTracker = nullptr;
3677af732203SDimitry Andric VTracker = nullptr;
3678af732203SDimitry Andric TTracker = nullptr;
3679af732203SDimitry Andric
3680af732203SDimitry Andric ArtificialBlocks.clear();
3681af732203SDimitry Andric OrderToBB.clear();
3682af732203SDimitry Andric BBToOrder.clear();
3683af732203SDimitry Andric BBNumToRPO.clear();
3684af732203SDimitry Andric DebugInstrNumToInstr.clear();
3685*5f7ddb14SDimitry Andric DebugPHINumToValue.clear();
3686af732203SDimitry Andric
3687af732203SDimitry Andric return Changed;
3688af732203SDimitry Andric }
3689af732203SDimitry Andric
makeInstrRefBasedLiveDebugValues()3690af732203SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3691af732203SDimitry Andric return new InstrRefBasedLDV();
3692af732203SDimitry Andric }
3693*5f7ddb14SDimitry Andric
3694*5f7ddb14SDimitry Andric namespace {
3695*5f7ddb14SDimitry Andric class LDVSSABlock;
3696*5f7ddb14SDimitry Andric class LDVSSAUpdater;
3697*5f7ddb14SDimitry Andric
3698*5f7ddb14SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We
3699*5f7ddb14SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater
3700*5f7ddb14SDimitry Andric // expects to zero-initialize the type.
3701*5f7ddb14SDimitry Andric typedef uint64_t BlockValueNum;
3702*5f7ddb14SDimitry Andric
3703*5f7ddb14SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block
3704*5f7ddb14SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming
3705*5f7ddb14SDimitry Andric /// values from parent blocks.
3706*5f7ddb14SDimitry Andric class LDVSSAPhi {
3707*5f7ddb14SDimitry Andric public:
3708*5f7ddb14SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3709*5f7ddb14SDimitry Andric LDVSSABlock *ParentBlock;
3710*5f7ddb14SDimitry Andric BlockValueNum PHIValNum;
LDVSSAPhi(BlockValueNum PHIValNum,LDVSSABlock * ParentBlock)3711*5f7ddb14SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3712*5f7ddb14SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3713*5f7ddb14SDimitry Andric
getParent()3714*5f7ddb14SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; }
3715*5f7ddb14SDimitry Andric };
3716*5f7ddb14SDimitry Andric
3717*5f7ddb14SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a
3718*5f7ddb14SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock.
3719*5f7ddb14SDimitry Andric class LDVSSABlockIterator {
3720*5f7ddb14SDimitry Andric public:
3721*5f7ddb14SDimitry Andric MachineBasicBlock::pred_iterator PredIt;
3722*5f7ddb14SDimitry Andric LDVSSAUpdater &Updater;
3723*5f7ddb14SDimitry Andric
LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,LDVSSAUpdater & Updater)3724*5f7ddb14SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3725*5f7ddb14SDimitry Andric LDVSSAUpdater &Updater)
3726*5f7ddb14SDimitry Andric : PredIt(PredIt), Updater(Updater) {}
3727*5f7ddb14SDimitry Andric
operator !=(const LDVSSABlockIterator & OtherIt) const3728*5f7ddb14SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3729*5f7ddb14SDimitry Andric return OtherIt.PredIt != PredIt;
3730*5f7ddb14SDimitry Andric }
3731*5f7ddb14SDimitry Andric
operator ++()3732*5f7ddb14SDimitry Andric LDVSSABlockIterator &operator++() {
3733*5f7ddb14SDimitry Andric ++PredIt;
3734*5f7ddb14SDimitry Andric return *this;
3735*5f7ddb14SDimitry Andric }
3736*5f7ddb14SDimitry Andric
3737*5f7ddb14SDimitry Andric LDVSSABlock *operator*();
3738*5f7ddb14SDimitry Andric };
3739*5f7ddb14SDimitry Andric
3740*5f7ddb14SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because
3741*5f7ddb14SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary
3742*5f7ddb14SDimitry Andric /// in this block.
3743*5f7ddb14SDimitry Andric class LDVSSABlock {
3744*5f7ddb14SDimitry Andric public:
3745*5f7ddb14SDimitry Andric MachineBasicBlock &BB;
3746*5f7ddb14SDimitry Andric LDVSSAUpdater &Updater;
3747*5f7ddb14SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>;
3748*5f7ddb14SDimitry Andric /// List of PHIs in this block. There should only ever be one.
3749*5f7ddb14SDimitry Andric PHIListT PHIList;
3750*5f7ddb14SDimitry Andric
LDVSSABlock(MachineBasicBlock & BB,LDVSSAUpdater & Updater)3751*5f7ddb14SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3752*5f7ddb14SDimitry Andric : BB(BB), Updater(Updater) {}
3753*5f7ddb14SDimitry Andric
succ_begin()3754*5f7ddb14SDimitry Andric LDVSSABlockIterator succ_begin() {
3755*5f7ddb14SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater);
3756*5f7ddb14SDimitry Andric }
3757*5f7ddb14SDimitry Andric
succ_end()3758*5f7ddb14SDimitry Andric LDVSSABlockIterator succ_end() {
3759*5f7ddb14SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater);
3760*5f7ddb14SDimitry Andric }
3761*5f7ddb14SDimitry Andric
3762*5f7ddb14SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record.
newPHI(BlockValueNum Value)3763*5f7ddb14SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) {
3764*5f7ddb14SDimitry Andric PHIList.emplace_back(Value, this);
3765*5f7ddb14SDimitry Andric return &PHIList.back();
3766*5f7ddb14SDimitry Andric }
3767*5f7ddb14SDimitry Andric
3768*5f7ddb14SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block.
phis()3769*5f7ddb14SDimitry Andric PHIListT &phis() { return PHIList; }
3770*5f7ddb14SDimitry Andric };
3771*5f7ddb14SDimitry Andric
3772*5f7ddb14SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3773*5f7ddb14SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3774*5f7ddb14SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>.
3775*5f7ddb14SDimitry Andric class LDVSSAUpdater {
3776*5f7ddb14SDimitry Andric public:
3777*5f7ddb14SDimitry Andric /// Map of value numbers to PHI records.
3778*5f7ddb14SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3779*5f7ddb14SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not
3780*5f7ddb14SDimitry Andric /// dominated by any Def.
3781*5f7ddb14SDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3782*5f7ddb14SDimitry Andric /// Map of machine blocks to our own records of them.
3783*5f7ddb14SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3784*5f7ddb14SDimitry Andric /// Machine location where any PHI must occur.
3785*5f7ddb14SDimitry Andric LocIdx Loc;
3786*5f7ddb14SDimitry Andric /// Table of live-in machine value numbers for blocks / locations.
3787*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns;
3788*5f7ddb14SDimitry Andric
LDVSSAUpdater(LocIdx L,ValueIDNum ** MLiveIns)3789*5f7ddb14SDimitry Andric LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {}
3790*5f7ddb14SDimitry Andric
reset()3791*5f7ddb14SDimitry Andric void reset() {
3792*5f7ddb14SDimitry Andric for (auto &Block : BlockMap)
3793*5f7ddb14SDimitry Andric delete Block.second;
3794*5f7ddb14SDimitry Andric
3795*5f7ddb14SDimitry Andric PHIs.clear();
3796*5f7ddb14SDimitry Andric UndefMap.clear();
3797*5f7ddb14SDimitry Andric BlockMap.clear();
3798*5f7ddb14SDimitry Andric }
3799*5f7ddb14SDimitry Andric
~LDVSSAUpdater()3800*5f7ddb14SDimitry Andric ~LDVSSAUpdater() { reset(); }
3801*5f7ddb14SDimitry Andric
3802*5f7ddb14SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the
3803*5f7ddb14SDimitry Andric /// LDVSSAUpdater block map.
getSSALDVBlock(MachineBasicBlock * BB)3804*5f7ddb14SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3805*5f7ddb14SDimitry Andric auto it = BlockMap.find(BB);
3806*5f7ddb14SDimitry Andric if (it == BlockMap.end()) {
3807*5f7ddb14SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this);
3808*5f7ddb14SDimitry Andric it = BlockMap.find(BB);
3809*5f7ddb14SDimitry Andric }
3810*5f7ddb14SDimitry Andric return it->second;
3811*5f7ddb14SDimitry Andric }
3812*5f7ddb14SDimitry Andric
3813*5f7ddb14SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at
3814*5f7ddb14SDimitry Andric /// the PHI location on entry.
getValue(LDVSSABlock * LDVBB)3815*5f7ddb14SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) {
3816*5f7ddb14SDimitry Andric return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3817*5f7ddb14SDimitry Andric }
3818*5f7ddb14SDimitry Andric };
3819*5f7ddb14SDimitry Andric
operator *()3820*5f7ddb14SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() {
3821*5f7ddb14SDimitry Andric return Updater.getSSALDVBlock(*PredIt);
3822*5f7ddb14SDimitry Andric }
3823*5f7ddb14SDimitry Andric
3824*5f7ddb14SDimitry Andric #ifndef NDEBUG
3825*5f7ddb14SDimitry Andric
operator <<(raw_ostream & out,const LDVSSAPhi & PHI)3826*5f7ddb14SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3827*5f7ddb14SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum;
3828*5f7ddb14SDimitry Andric return out;
3829*5f7ddb14SDimitry Andric }
3830*5f7ddb14SDimitry Andric
3831*5f7ddb14SDimitry Andric #endif
3832*5f7ddb14SDimitry Andric
3833*5f7ddb14SDimitry Andric } // namespace
3834*5f7ddb14SDimitry Andric
3835*5f7ddb14SDimitry Andric namespace llvm {
3836*5f7ddb14SDimitry Andric
3837*5f7ddb14SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value
3838*5f7ddb14SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the
3839*5f7ddb14SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define.
3840*5f7ddb14SDimitry Andric /// It also provides methods to create PHI nodes and track them.
3841*5f7ddb14SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3842*5f7ddb14SDimitry Andric public:
3843*5f7ddb14SDimitry Andric using BlkT = LDVSSABlock;
3844*5f7ddb14SDimitry Andric using ValT = BlockValueNum;
3845*5f7ddb14SDimitry Andric using PhiT = LDVSSAPhi;
3846*5f7ddb14SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator;
3847*5f7ddb14SDimitry Andric
3848*5f7ddb14SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class.
BlkSucc_begin(BlkT * BB)3849*5f7ddb14SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
BlkSucc_end(BlkT * BB)3850*5f7ddb14SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3851*5f7ddb14SDimitry Andric
3852*5f7ddb14SDimitry Andric /// Iterator for PHI operands.
3853*5f7ddb14SDimitry Andric class PHI_iterator {
3854*5f7ddb14SDimitry Andric private:
3855*5f7ddb14SDimitry Andric LDVSSAPhi *PHI;
3856*5f7ddb14SDimitry Andric unsigned Idx;
3857*5f7ddb14SDimitry Andric
3858*5f7ddb14SDimitry Andric public:
PHI_iterator(LDVSSAPhi * P)3859*5f7ddb14SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3860*5f7ddb14SDimitry Andric : PHI(P), Idx(0) {}
PHI_iterator(LDVSSAPhi * P,bool)3861*5f7ddb14SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3862*5f7ddb14SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {}
3863*5f7ddb14SDimitry Andric
operator ++()3864*5f7ddb14SDimitry Andric PHI_iterator &operator++() {
3865*5f7ddb14SDimitry Andric Idx++;
3866*5f7ddb14SDimitry Andric return *this;
3867*5f7ddb14SDimitry Andric }
operator ==(const PHI_iterator & X) const3868*5f7ddb14SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
operator !=(const PHI_iterator & X) const3869*5f7ddb14SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3870*5f7ddb14SDimitry Andric
getIncomingValue()3871*5f7ddb14SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
3872*5f7ddb14SDimitry Andric
getIncomingBlock()3873*5f7ddb14SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
3874*5f7ddb14SDimitry Andric };
3875*5f7ddb14SDimitry Andric
PHI_begin(PhiT * PHI)3876*5f7ddb14SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
3877*5f7ddb14SDimitry Andric
PHI_end(PhiT * PHI)3878*5f7ddb14SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) {
3879*5f7ddb14SDimitry Andric return PHI_iterator(PHI, true);
3880*5f7ddb14SDimitry Andric }
3881*5f7ddb14SDimitry Andric
3882*5f7ddb14SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
3883*5f7ddb14SDimitry Andric /// vector.
FindPredecessorBlocks(LDVSSABlock * BB,SmallVectorImpl<LDVSSABlock * > * Preds)3884*5f7ddb14SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB,
3885*5f7ddb14SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) {
3886*5f7ddb14SDimitry Andric for (MachineBasicBlock::pred_iterator PI = BB->BB.pred_begin(),
3887*5f7ddb14SDimitry Andric E = BB->BB.pred_end();
3888*5f7ddb14SDimitry Andric PI != E; ++PI)
3889*5f7ddb14SDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(*PI));
3890*5f7ddb14SDimitry Andric }
3891*5f7ddb14SDimitry Andric
3892*5f7ddb14SDimitry Andric /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
3893*5f7ddb14SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having
3894*5f7ddb14SDimitry Andric /// any DBG_PHI predecessors.
GetUndefVal(LDVSSABlock * BB,LDVSSAUpdater * Updater)3895*5f7ddb14SDimitry Andric static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
3896*5f7ddb14SDimitry Andric // Create a value number for this block -- it needs to be unique and in the
3897*5f7ddb14SDimitry Andric // "undef" collection, so that we know it's not real. Use a number
3898*5f7ddb14SDimitry Andric // representing a PHI into this block.
3899*5f7ddb14SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
3900*5f7ddb14SDimitry Andric Updater->UndefMap[&BB->BB] = Num;
3901*5f7ddb14SDimitry Andric return Num;
3902*5f7ddb14SDimitry Andric }
3903*5f7ddb14SDimitry Andric
3904*5f7ddb14SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
3905*5f7ddb14SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The
3906*5f7ddb14SDimitry Andric /// value number of this PHI is whatever the machine value number problem
3907*5f7ddb14SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater
3908*5f7ddb14SDimitry Andric /// tries to create a PHI where the incoming values are identical.
CreateEmptyPHI(LDVSSABlock * BB,unsigned NumPreds,LDVSSAUpdater * Updater)3909*5f7ddb14SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
3910*5f7ddb14SDimitry Andric LDVSSAUpdater *Updater) {
3911*5f7ddb14SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB);
3912*5f7ddb14SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
3913*5f7ddb14SDimitry Andric Updater->PHIs[PHIValNum] = PHI;
3914*5f7ddb14SDimitry Andric return PHIValNum;
3915*5f7ddb14SDimitry Andric }
3916*5f7ddb14SDimitry Andric
3917*5f7ddb14SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for
3918*5f7ddb14SDimitry Andric /// the specified predecessor block.
AddPHIOperand(LDVSSAPhi * PHI,BlockValueNum Val,LDVSSABlock * Pred)3919*5f7ddb14SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
3920*5f7ddb14SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
3921*5f7ddb14SDimitry Andric }
3922*5f7ddb14SDimitry Andric
3923*5f7ddb14SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value
3924*5f7ddb14SDimitry Andric /// is a PHI instruction.
ValueIsPHI(BlockValueNum Val,LDVSSAUpdater * Updater)3925*5f7ddb14SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3926*5f7ddb14SDimitry Andric auto PHIIt = Updater->PHIs.find(Val);
3927*5f7ddb14SDimitry Andric if (PHIIt == Updater->PHIs.end())
3928*5f7ddb14SDimitry Andric return nullptr;
3929*5f7ddb14SDimitry Andric return PHIIt->second;
3930*5f7ddb14SDimitry Andric }
3931*5f7ddb14SDimitry Andric
3932*5f7ddb14SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
3933*5f7ddb14SDimitry Andric /// operands, i.e., it was just added.
ValueIsNewPHI(BlockValueNum Val,LDVSSAUpdater * Updater)3934*5f7ddb14SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3935*5f7ddb14SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
3936*5f7ddb14SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0)
3937*5f7ddb14SDimitry Andric return PHI;
3938*5f7ddb14SDimitry Andric return nullptr;
3939*5f7ddb14SDimitry Andric }
3940*5f7ddb14SDimitry Andric
3941*5f7ddb14SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value
3942*5f7ddb14SDimitry Andric /// that it defines.
GetPHIValue(LDVSSAPhi * PHI)3943*5f7ddb14SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
3944*5f7ddb14SDimitry Andric };
3945*5f7ddb14SDimitry Andric
3946*5f7ddb14SDimitry Andric } // end namespace llvm
3947*5f7ddb14SDimitry Andric
resolveDbgPHIs(MachineFunction & MF,ValueIDNum ** MLiveOuts,ValueIDNum ** MLiveIns,MachineInstr & Here,uint64_t InstrNum)3948*5f7ddb14SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF,
3949*5f7ddb14SDimitry Andric ValueIDNum **MLiveOuts,
3950*5f7ddb14SDimitry Andric ValueIDNum **MLiveIns,
3951*5f7ddb14SDimitry Andric MachineInstr &Here,
3952*5f7ddb14SDimitry Andric uint64_t InstrNum) {
3953*5f7ddb14SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there
3954*5f7ddb14SDimitry Andric // are none, then we cannot compute a value number.
3955*5f7ddb14SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
3956*5f7ddb14SDimitry Andric DebugPHINumToValue.end(), InstrNum);
3957*5f7ddb14SDimitry Andric auto LowerIt = RangePair.first;
3958*5f7ddb14SDimitry Andric auto UpperIt = RangePair.second;
3959*5f7ddb14SDimitry Andric
3960*5f7ddb14SDimitry Andric // No DBG_PHI means there can be no location.
3961*5f7ddb14SDimitry Andric if (LowerIt == UpperIt)
3962*5f7ddb14SDimitry Andric return None;
3963*5f7ddb14SDimitry Andric
3964*5f7ddb14SDimitry Andric // If there's only one DBG_PHI, then that is our value number.
3965*5f7ddb14SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1)
3966*5f7ddb14SDimitry Andric return LowerIt->ValueRead;
3967*5f7ddb14SDimitry Andric
3968*5f7ddb14SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt);
3969*5f7ddb14SDimitry Andric
3970*5f7ddb14SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's
3971*5f7ddb14SDimitry Andric // technically possible for us to merge values in different registers in each
3972*5f7ddb14SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register
3973*5f7ddb14SDimitry Andric // allocation.
3974*5f7ddb14SDimitry Andric LocIdx Loc = LowerIt->ReadLoc;
3975*5f7ddb14SDimitry Andric
3976*5f7ddb14SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each
3977*5f7ddb14SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each
3978*5f7ddb14SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a
3979*5f7ddb14SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
3980*5f7ddb14SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along
3981*5f7ddb14SDimitry Andric // the way.
3982*5f7ddb14SDimitry Andric // Adapted LLVM SSA Updater:
3983*5f7ddb14SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns);
3984*5f7ddb14SDimitry Andric // Map of which Def or PHI is the current value in each block.
3985*5f7ddb14SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
3986*5f7ddb14SDimitry Andric // Set of PHIs that we have created along the way.
3987*5f7ddb14SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
3988*5f7ddb14SDimitry Andric
3989*5f7ddb14SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
3990*5f7ddb14SDimitry Andric // for the SSAUpdater.
3991*5f7ddb14SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) {
3992*5f7ddb14SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3993*5f7ddb14SDimitry Andric const ValueIDNum &Num = DBG_PHI.ValueRead;
3994*5f7ddb14SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64()));
3995*5f7ddb14SDimitry Andric }
3996*5f7ddb14SDimitry Andric
3997*5f7ddb14SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
3998*5f7ddb14SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock);
3999*5f7ddb14SDimitry Andric if (AvailIt != AvailableValues.end()) {
4000*5f7ddb14SDimitry Andric // Actually, we already know what the value is -- the Use is in the same
4001*5f7ddb14SDimitry Andric // block as the Def.
4002*5f7ddb14SDimitry Andric return ValueIDNum::fromU64(AvailIt->second);
4003*5f7ddb14SDimitry Andric }
4004*5f7ddb14SDimitry Andric
4005*5f7ddb14SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number
4006*5f7ddb14SDimitry Andric // that we are to use, and the PHIs that must happen along the way.
4007*5f7ddb14SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
4008*5f7ddb14SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
4009*5f7ddb14SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
4010*5f7ddb14SDimitry Andric
4011*5f7ddb14SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used
4012*5f7ddb14SDimitry Andric // at this Use. There are a number of things we have to check about it though:
4013*5f7ddb14SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
4014*5f7ddb14SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort.
4015*5f7ddb14SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
4016*5f7ddb14SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the
4017*5f7ddb14SDimitry Andric // expected values.
4018*5f7ddb14SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the
4019*5f7ddb14SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number?
4020*5f7ddb14SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the
4021*5f7ddb14SDimitry Andric // the ValidatedValues collection below to sort this out.
4022*5f7ddb14SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
4023*5f7ddb14SDimitry Andric
4024*5f7ddb14SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues.
4025*5f7ddb14SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) {
4026*5f7ddb14SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
4027*5f7ddb14SDimitry Andric const ValueIDNum &Num = DBG_PHI.ValueRead;
4028*5f7ddb14SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num));
4029*5f7ddb14SDimitry Andric }
4030*5f7ddb14SDimitry Andric
4031*5f7ddb14SDimitry Andric // Sort PHIs to validate into RPO-order.
4032*5f7ddb14SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs;
4033*5f7ddb14SDimitry Andric for (auto &PHI : CreatedPHIs)
4034*5f7ddb14SDimitry Andric SortedPHIs.push_back(PHI);
4035*5f7ddb14SDimitry Andric
4036*5f7ddb14SDimitry Andric std::sort(
4037*5f7ddb14SDimitry Andric SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) {
4038*5f7ddb14SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
4039*5f7ddb14SDimitry Andric });
4040*5f7ddb14SDimitry Andric
4041*5f7ddb14SDimitry Andric for (auto &PHI : SortedPHIs) {
4042*5f7ddb14SDimitry Andric ValueIDNum ThisBlockValueNum =
4043*5f7ddb14SDimitry Andric MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
4044*5f7ddb14SDimitry Andric
4045*5f7ddb14SDimitry Andric // Are all these things actually defined?
4046*5f7ddb14SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) {
4047*5f7ddb14SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point.
4048*5f7ddb14SDimitry Andric if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
4049*5f7ddb14SDimitry Andric return None;
4050*5f7ddb14SDimitry Andric
4051*5f7ddb14SDimitry Andric ValueIDNum ValueToCheck;
4052*5f7ddb14SDimitry Andric ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
4053*5f7ddb14SDimitry Andric
4054*5f7ddb14SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first);
4055*5f7ddb14SDimitry Andric if (VVal == ValidatedValues.end()) {
4056*5f7ddb14SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication
4057*5f7ddb14SDimitry Andric // happens so late that DBG_PHI instructions should not be able to
4058*5f7ddb14SDimitry Andric // migrate into loops -- meaning we can only be live-through this
4059*5f7ddb14SDimitry Andric // loop.
4060*5f7ddb14SDimitry Andric ValueToCheck = ThisBlockValueNum;
4061*5f7ddb14SDimitry Andric } else {
4062*5f7ddb14SDimitry Andric // Does the block have as a live-out, in the location we're examining,
4063*5f7ddb14SDimitry Andric // the value that we expect? If not, it's been moved or clobbered.
4064*5f7ddb14SDimitry Andric ValueToCheck = VVal->second;
4065*5f7ddb14SDimitry Andric }
4066*5f7ddb14SDimitry Andric
4067*5f7ddb14SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
4068*5f7ddb14SDimitry Andric return None;
4069*5f7ddb14SDimitry Andric }
4070*5f7ddb14SDimitry Andric
4071*5f7ddb14SDimitry Andric // Record this value as validated.
4072*5f7ddb14SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
4073*5f7ddb14SDimitry Andric }
4074*5f7ddb14SDimitry Andric
4075*5f7ddb14SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value
4076*5f7ddb14SDimitry Andric // number was.
4077*5f7ddb14SDimitry Andric return Result;
4078*5f7ddb14SDimitry Andric }
4079