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