1*9880d681SAndroid Build Coastguard Worker //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker /// \file
10*9880d681SAndroid Build Coastguard Worker /// This transformation implements the well known scalar replacement of
11*9880d681SAndroid Build Coastguard Worker /// aggregates transformation. It tries to identify promotable elements of an
12*9880d681SAndroid Build Coastguard Worker /// aggregate alloca, and promote them to registers. It will also try to
13*9880d681SAndroid Build Coastguard Worker /// convert uses of an element (or set of elements) of an alloca into a vector
14*9880d681SAndroid Build Coastguard Worker /// or bitfield-style integer scalar if appropriate.
15*9880d681SAndroid Build Coastguard Worker ///
16*9880d681SAndroid Build Coastguard Worker /// It works to do this with minimal slicing of the alloca so that regions
17*9880d681SAndroid Build Coastguard Worker /// which are merely transferred in and out of external memory remain unchanged
18*9880d681SAndroid Build Coastguard Worker /// and are not decomposed to scalar code.
19*9880d681SAndroid Build Coastguard Worker ///
20*9880d681SAndroid Build Coastguard Worker /// Because this also performs alloca promotion, it can be thought of as also
21*9880d681SAndroid Build Coastguard Worker /// serving the purpose of SSA formation. The algorithm iterates on the
22*9880d681SAndroid Build Coastguard Worker /// function until all opportunities for promotion have been realized.
23*9880d681SAndroid Build Coastguard Worker ///
24*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
25*9880d681SAndroid Build Coastguard Worker
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/SROA.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/Loads.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/PtrUseVisitor.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DIBuilder.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DebugInfo.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/InstVisitor.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Operator.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Compiler.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ErrorHandling.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/MathExtras.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/TimeValue.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57*9880d681SAndroid Build Coastguard Worker
58*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
59*9880d681SAndroid Build Coastguard Worker // We only use this for a debug check.
60*9880d681SAndroid Build Coastguard Worker #include <random>
61*9880d681SAndroid Build Coastguard Worker #endif
62*9880d681SAndroid Build Coastguard Worker
63*9880d681SAndroid Build Coastguard Worker using namespace llvm;
64*9880d681SAndroid Build Coastguard Worker using namespace llvm::sroa;
65*9880d681SAndroid Build Coastguard Worker
66*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "sroa"
67*9880d681SAndroid Build Coastguard Worker
68*9880d681SAndroid Build Coastguard Worker STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
69*9880d681SAndroid Build Coastguard Worker STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
70*9880d681SAndroid Build Coastguard Worker STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
71*9880d681SAndroid Build Coastguard Worker STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
72*9880d681SAndroid Build Coastguard Worker STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
73*9880d681SAndroid Build Coastguard Worker STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
74*9880d681SAndroid Build Coastguard Worker STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
75*9880d681SAndroid Build Coastguard Worker STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
76*9880d681SAndroid Build Coastguard Worker STATISTIC(NumDeleted, "Number of instructions deleted");
77*9880d681SAndroid Build Coastguard Worker STATISTIC(NumVectorized, "Number of vectorized aggregates");
78*9880d681SAndroid Build Coastguard Worker
79*9880d681SAndroid Build Coastguard Worker /// Hidden option to enable randomly shuffling the slices to help uncover
80*9880d681SAndroid Build Coastguard Worker /// instability in their order.
81*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
82*9880d681SAndroid Build Coastguard Worker cl::init(false), cl::Hidden);
83*9880d681SAndroid Build Coastguard Worker
84*9880d681SAndroid Build Coastguard Worker /// Hidden option to experiment with completely strict handling of inbounds
85*9880d681SAndroid Build Coastguard Worker /// GEPs.
86*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
87*9880d681SAndroid Build Coastguard Worker cl::Hidden);
88*9880d681SAndroid Build Coastguard Worker
89*9880d681SAndroid Build Coastguard Worker namespace {
90*9880d681SAndroid Build Coastguard Worker /// \brief A custom IRBuilder inserter which prefixes all names, but only in
91*9880d681SAndroid Build Coastguard Worker /// Assert builds.
92*9880d681SAndroid Build Coastguard Worker class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
93*9880d681SAndroid Build Coastguard Worker std::string Prefix;
getNameWithPrefix(const Twine & Name) const94*9880d681SAndroid Build Coastguard Worker const Twine getNameWithPrefix(const Twine &Name) const {
95*9880d681SAndroid Build Coastguard Worker return Name.isTriviallyEmpty() ? Name : Prefix + Name;
96*9880d681SAndroid Build Coastguard Worker }
97*9880d681SAndroid Build Coastguard Worker
98*9880d681SAndroid Build Coastguard Worker public:
SetNamePrefix(const Twine & P)99*9880d681SAndroid Build Coastguard Worker void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
100*9880d681SAndroid Build Coastguard Worker
101*9880d681SAndroid Build Coastguard Worker protected:
InsertHelper(Instruction * I,const Twine & Name,BasicBlock * BB,BasicBlock::iterator InsertPt) const102*9880d681SAndroid Build Coastguard Worker void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
103*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator InsertPt) const {
104*9880d681SAndroid Build Coastguard Worker IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
105*9880d681SAndroid Build Coastguard Worker InsertPt);
106*9880d681SAndroid Build Coastguard Worker }
107*9880d681SAndroid Build Coastguard Worker };
108*9880d681SAndroid Build Coastguard Worker
109*9880d681SAndroid Build Coastguard Worker /// \brief Provide a typedef for IRBuilder that drops names in release builds.
110*9880d681SAndroid Build Coastguard Worker using IRBuilderTy = llvm::IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
111*9880d681SAndroid Build Coastguard Worker }
112*9880d681SAndroid Build Coastguard Worker
113*9880d681SAndroid Build Coastguard Worker namespace {
114*9880d681SAndroid Build Coastguard Worker /// \brief A used slice of an alloca.
115*9880d681SAndroid Build Coastguard Worker ///
116*9880d681SAndroid Build Coastguard Worker /// This structure represents a slice of an alloca used by some instruction. It
117*9880d681SAndroid Build Coastguard Worker /// stores both the begin and end offsets of this use, a pointer to the use
118*9880d681SAndroid Build Coastguard Worker /// itself, and a flag indicating whether we can classify the use as splittable
119*9880d681SAndroid Build Coastguard Worker /// or not when forming partitions of the alloca.
120*9880d681SAndroid Build Coastguard Worker class Slice {
121*9880d681SAndroid Build Coastguard Worker /// \brief The beginning offset of the range.
122*9880d681SAndroid Build Coastguard Worker uint64_t BeginOffset;
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker /// \brief The ending offset, not included in the range.
125*9880d681SAndroid Build Coastguard Worker uint64_t EndOffset;
126*9880d681SAndroid Build Coastguard Worker
127*9880d681SAndroid Build Coastguard Worker /// \brief Storage for both the use of this slice and whether it can be
128*9880d681SAndroid Build Coastguard Worker /// split.
129*9880d681SAndroid Build Coastguard Worker PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
130*9880d681SAndroid Build Coastguard Worker
131*9880d681SAndroid Build Coastguard Worker public:
Slice()132*9880d681SAndroid Build Coastguard Worker Slice() : BeginOffset(), EndOffset() {}
Slice(uint64_t BeginOffset,uint64_t EndOffset,Use * U,bool IsSplittable)133*9880d681SAndroid Build Coastguard Worker Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
134*9880d681SAndroid Build Coastguard Worker : BeginOffset(BeginOffset), EndOffset(EndOffset),
135*9880d681SAndroid Build Coastguard Worker UseAndIsSplittable(U, IsSplittable) {}
136*9880d681SAndroid Build Coastguard Worker
beginOffset() const137*9880d681SAndroid Build Coastguard Worker uint64_t beginOffset() const { return BeginOffset; }
endOffset() const138*9880d681SAndroid Build Coastguard Worker uint64_t endOffset() const { return EndOffset; }
139*9880d681SAndroid Build Coastguard Worker
isSplittable() const140*9880d681SAndroid Build Coastguard Worker bool isSplittable() const { return UseAndIsSplittable.getInt(); }
makeUnsplittable()141*9880d681SAndroid Build Coastguard Worker void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
142*9880d681SAndroid Build Coastguard Worker
getUse() const143*9880d681SAndroid Build Coastguard Worker Use *getUse() const { return UseAndIsSplittable.getPointer(); }
144*9880d681SAndroid Build Coastguard Worker
isDead() const145*9880d681SAndroid Build Coastguard Worker bool isDead() const { return getUse() == nullptr; }
kill()146*9880d681SAndroid Build Coastguard Worker void kill() { UseAndIsSplittable.setPointer(nullptr); }
147*9880d681SAndroid Build Coastguard Worker
148*9880d681SAndroid Build Coastguard Worker /// \brief Support for ordering ranges.
149*9880d681SAndroid Build Coastguard Worker ///
150*9880d681SAndroid Build Coastguard Worker /// This provides an ordering over ranges such that start offsets are
151*9880d681SAndroid Build Coastguard Worker /// always increasing, and within equal start offsets, the end offsets are
152*9880d681SAndroid Build Coastguard Worker /// decreasing. Thus the spanning range comes first in a cluster with the
153*9880d681SAndroid Build Coastguard Worker /// same start position.
operator <(const Slice & RHS) const154*9880d681SAndroid Build Coastguard Worker bool operator<(const Slice &RHS) const {
155*9880d681SAndroid Build Coastguard Worker if (beginOffset() < RHS.beginOffset())
156*9880d681SAndroid Build Coastguard Worker return true;
157*9880d681SAndroid Build Coastguard Worker if (beginOffset() > RHS.beginOffset())
158*9880d681SAndroid Build Coastguard Worker return false;
159*9880d681SAndroid Build Coastguard Worker if (isSplittable() != RHS.isSplittable())
160*9880d681SAndroid Build Coastguard Worker return !isSplittable();
161*9880d681SAndroid Build Coastguard Worker if (endOffset() > RHS.endOffset())
162*9880d681SAndroid Build Coastguard Worker return true;
163*9880d681SAndroid Build Coastguard Worker return false;
164*9880d681SAndroid Build Coastguard Worker }
165*9880d681SAndroid Build Coastguard Worker
166*9880d681SAndroid Build Coastguard Worker /// \brief Support comparison with a single offset to allow binary searches.
operator <(const Slice & LHS,uint64_t RHSOffset)167*9880d681SAndroid Build Coastguard Worker friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
168*9880d681SAndroid Build Coastguard Worker uint64_t RHSOffset) {
169*9880d681SAndroid Build Coastguard Worker return LHS.beginOffset() < RHSOffset;
170*9880d681SAndroid Build Coastguard Worker }
operator <(uint64_t LHSOffset,const Slice & RHS)171*9880d681SAndroid Build Coastguard Worker friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
172*9880d681SAndroid Build Coastguard Worker const Slice &RHS) {
173*9880d681SAndroid Build Coastguard Worker return LHSOffset < RHS.beginOffset();
174*9880d681SAndroid Build Coastguard Worker }
175*9880d681SAndroid Build Coastguard Worker
operator ==(const Slice & RHS) const176*9880d681SAndroid Build Coastguard Worker bool operator==(const Slice &RHS) const {
177*9880d681SAndroid Build Coastguard Worker return isSplittable() == RHS.isSplittable() &&
178*9880d681SAndroid Build Coastguard Worker beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
179*9880d681SAndroid Build Coastguard Worker }
operator !=(const Slice & RHS) const180*9880d681SAndroid Build Coastguard Worker bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
181*9880d681SAndroid Build Coastguard Worker };
182*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
183*9880d681SAndroid Build Coastguard Worker
184*9880d681SAndroid Build Coastguard Worker namespace llvm {
185*9880d681SAndroid Build Coastguard Worker template <typename T> struct isPodLike;
186*9880d681SAndroid Build Coastguard Worker template <> struct isPodLike<Slice> { static const bool value = true; };
187*9880d681SAndroid Build Coastguard Worker }
188*9880d681SAndroid Build Coastguard Worker
189*9880d681SAndroid Build Coastguard Worker /// \brief Representation of the alloca slices.
190*9880d681SAndroid Build Coastguard Worker ///
191*9880d681SAndroid Build Coastguard Worker /// This class represents the slices of an alloca which are formed by its
192*9880d681SAndroid Build Coastguard Worker /// various uses. If a pointer escapes, we can't fully build a representation
193*9880d681SAndroid Build Coastguard Worker /// for the slices used and we reflect that in this structure. The uses are
194*9880d681SAndroid Build Coastguard Worker /// stored, sorted by increasing beginning offset and with unsplittable slices
195*9880d681SAndroid Build Coastguard Worker /// starting at a particular offset before splittable slices.
196*9880d681SAndroid Build Coastguard Worker class llvm::sroa::AllocaSlices {
197*9880d681SAndroid Build Coastguard Worker public:
198*9880d681SAndroid Build Coastguard Worker /// \brief Construct the slices of a particular alloca.
199*9880d681SAndroid Build Coastguard Worker AllocaSlices(const DataLayout &DL, AllocaInst &AI);
200*9880d681SAndroid Build Coastguard Worker
201*9880d681SAndroid Build Coastguard Worker /// \brief Test whether a pointer to the allocation escapes our analysis.
202*9880d681SAndroid Build Coastguard Worker ///
203*9880d681SAndroid Build Coastguard Worker /// If this is true, the slices are never fully built and should be
204*9880d681SAndroid Build Coastguard Worker /// ignored.
isEscaped() const205*9880d681SAndroid Build Coastguard Worker bool isEscaped() const { return PointerEscapingInstr; }
206*9880d681SAndroid Build Coastguard Worker
207*9880d681SAndroid Build Coastguard Worker /// \brief Support for iterating over the slices.
208*9880d681SAndroid Build Coastguard Worker /// @{
209*9880d681SAndroid Build Coastguard Worker typedef SmallVectorImpl<Slice>::iterator iterator;
210*9880d681SAndroid Build Coastguard Worker typedef iterator_range<iterator> range;
begin()211*9880d681SAndroid Build Coastguard Worker iterator begin() { return Slices.begin(); }
end()212*9880d681SAndroid Build Coastguard Worker iterator end() { return Slices.end(); }
213*9880d681SAndroid Build Coastguard Worker
214*9880d681SAndroid Build Coastguard Worker typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
215*9880d681SAndroid Build Coastguard Worker typedef iterator_range<const_iterator> const_range;
begin() const216*9880d681SAndroid Build Coastguard Worker const_iterator begin() const { return Slices.begin(); }
end() const217*9880d681SAndroid Build Coastguard Worker const_iterator end() const { return Slices.end(); }
218*9880d681SAndroid Build Coastguard Worker /// @}
219*9880d681SAndroid Build Coastguard Worker
220*9880d681SAndroid Build Coastguard Worker /// \brief Erase a range of slices.
erase(iterator Start,iterator Stop)221*9880d681SAndroid Build Coastguard Worker void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
222*9880d681SAndroid Build Coastguard Worker
223*9880d681SAndroid Build Coastguard Worker /// \brief Insert new slices for this alloca.
224*9880d681SAndroid Build Coastguard Worker ///
225*9880d681SAndroid Build Coastguard Worker /// This moves the slices into the alloca's slices collection, and re-sorts
226*9880d681SAndroid Build Coastguard Worker /// everything so that the usual ordering properties of the alloca's slices
227*9880d681SAndroid Build Coastguard Worker /// hold.
insert(ArrayRef<Slice> NewSlices)228*9880d681SAndroid Build Coastguard Worker void insert(ArrayRef<Slice> NewSlices) {
229*9880d681SAndroid Build Coastguard Worker int OldSize = Slices.size();
230*9880d681SAndroid Build Coastguard Worker Slices.append(NewSlices.begin(), NewSlices.end());
231*9880d681SAndroid Build Coastguard Worker auto SliceI = Slices.begin() + OldSize;
232*9880d681SAndroid Build Coastguard Worker std::sort(SliceI, Slices.end());
233*9880d681SAndroid Build Coastguard Worker std::inplace_merge(Slices.begin(), SliceI, Slices.end());
234*9880d681SAndroid Build Coastguard Worker }
235*9880d681SAndroid Build Coastguard Worker
236*9880d681SAndroid Build Coastguard Worker // Forward declare the iterator and range accessor for walking the
237*9880d681SAndroid Build Coastguard Worker // partitions.
238*9880d681SAndroid Build Coastguard Worker class partition_iterator;
239*9880d681SAndroid Build Coastguard Worker iterator_range<partition_iterator> partitions();
240*9880d681SAndroid Build Coastguard Worker
241*9880d681SAndroid Build Coastguard Worker /// \brief Access the dead users for this alloca.
getDeadUsers() const242*9880d681SAndroid Build Coastguard Worker ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
243*9880d681SAndroid Build Coastguard Worker
244*9880d681SAndroid Build Coastguard Worker /// \brief Access the dead operands referring to this alloca.
245*9880d681SAndroid Build Coastguard Worker ///
246*9880d681SAndroid Build Coastguard Worker /// These are operands which have cannot actually be used to refer to the
247*9880d681SAndroid Build Coastguard Worker /// alloca as they are outside its range and the user doesn't correct for
248*9880d681SAndroid Build Coastguard Worker /// that. These mostly consist of PHI node inputs and the like which we just
249*9880d681SAndroid Build Coastguard Worker /// need to replace with undef.
getDeadOperands() const250*9880d681SAndroid Build Coastguard Worker ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
251*9880d681SAndroid Build Coastguard Worker
252*9880d681SAndroid Build Coastguard Worker #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
253*9880d681SAndroid Build Coastguard Worker void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
254*9880d681SAndroid Build Coastguard Worker void printSlice(raw_ostream &OS, const_iterator I,
255*9880d681SAndroid Build Coastguard Worker StringRef Indent = " ") const;
256*9880d681SAndroid Build Coastguard Worker void printUse(raw_ostream &OS, const_iterator I,
257*9880d681SAndroid Build Coastguard Worker StringRef Indent = " ") const;
258*9880d681SAndroid Build Coastguard Worker void print(raw_ostream &OS) const;
259*9880d681SAndroid Build Coastguard Worker void dump(const_iterator I) const;
260*9880d681SAndroid Build Coastguard Worker void dump() const;
261*9880d681SAndroid Build Coastguard Worker #endif
262*9880d681SAndroid Build Coastguard Worker
263*9880d681SAndroid Build Coastguard Worker private:
264*9880d681SAndroid Build Coastguard Worker template <typename DerivedT, typename RetT = void> class BuilderBase;
265*9880d681SAndroid Build Coastguard Worker class SliceBuilder;
266*9880d681SAndroid Build Coastguard Worker friend class AllocaSlices::SliceBuilder;
267*9880d681SAndroid Build Coastguard Worker
268*9880d681SAndroid Build Coastguard Worker #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
269*9880d681SAndroid Build Coastguard Worker /// \brief Handle to alloca instruction to simplify method interfaces.
270*9880d681SAndroid Build Coastguard Worker AllocaInst &AI;
271*9880d681SAndroid Build Coastguard Worker #endif
272*9880d681SAndroid Build Coastguard Worker
273*9880d681SAndroid Build Coastguard Worker /// \brief The instruction responsible for this alloca not having a known set
274*9880d681SAndroid Build Coastguard Worker /// of slices.
275*9880d681SAndroid Build Coastguard Worker ///
276*9880d681SAndroid Build Coastguard Worker /// When an instruction (potentially) escapes the pointer to the alloca, we
277*9880d681SAndroid Build Coastguard Worker /// store a pointer to that here and abort trying to form slices of the
278*9880d681SAndroid Build Coastguard Worker /// alloca. This will be null if the alloca slices are analyzed successfully.
279*9880d681SAndroid Build Coastguard Worker Instruction *PointerEscapingInstr;
280*9880d681SAndroid Build Coastguard Worker
281*9880d681SAndroid Build Coastguard Worker /// \brief The slices of the alloca.
282*9880d681SAndroid Build Coastguard Worker ///
283*9880d681SAndroid Build Coastguard Worker /// We store a vector of the slices formed by uses of the alloca here. This
284*9880d681SAndroid Build Coastguard Worker /// vector is sorted by increasing begin offset, and then the unsplittable
285*9880d681SAndroid Build Coastguard Worker /// slices before the splittable ones. See the Slice inner class for more
286*9880d681SAndroid Build Coastguard Worker /// details.
287*9880d681SAndroid Build Coastguard Worker SmallVector<Slice, 8> Slices;
288*9880d681SAndroid Build Coastguard Worker
289*9880d681SAndroid Build Coastguard Worker /// \brief Instructions which will become dead if we rewrite the alloca.
290*9880d681SAndroid Build Coastguard Worker ///
291*9880d681SAndroid Build Coastguard Worker /// Note that these are not separated by slice. This is because we expect an
292*9880d681SAndroid Build Coastguard Worker /// alloca to be completely rewritten or not rewritten at all. If rewritten,
293*9880d681SAndroid Build Coastguard Worker /// all these instructions can simply be removed and replaced with undef as
294*9880d681SAndroid Build Coastguard Worker /// they come from outside of the allocated space.
295*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction *, 8> DeadUsers;
296*9880d681SAndroid Build Coastguard Worker
297*9880d681SAndroid Build Coastguard Worker /// \brief Operands which will become dead if we rewrite the alloca.
298*9880d681SAndroid Build Coastguard Worker ///
299*9880d681SAndroid Build Coastguard Worker /// These are operands that in their particular use can be replaced with
300*9880d681SAndroid Build Coastguard Worker /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
301*9880d681SAndroid Build Coastguard Worker /// to PHI nodes and the like. They aren't entirely dead (there might be
302*9880d681SAndroid Build Coastguard Worker /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
303*9880d681SAndroid Build Coastguard Worker /// want to swap this particular input for undef to simplify the use lists of
304*9880d681SAndroid Build Coastguard Worker /// the alloca.
305*9880d681SAndroid Build Coastguard Worker SmallVector<Use *, 8> DeadOperands;
306*9880d681SAndroid Build Coastguard Worker };
307*9880d681SAndroid Build Coastguard Worker
308*9880d681SAndroid Build Coastguard Worker /// \brief A partition of the slices.
309*9880d681SAndroid Build Coastguard Worker ///
310*9880d681SAndroid Build Coastguard Worker /// An ephemeral representation for a range of slices which can be viewed as
311*9880d681SAndroid Build Coastguard Worker /// a partition of the alloca. This range represents a span of the alloca's
312*9880d681SAndroid Build Coastguard Worker /// memory which cannot be split, and provides access to all of the slices
313*9880d681SAndroid Build Coastguard Worker /// overlapping some part of the partition.
314*9880d681SAndroid Build Coastguard Worker ///
315*9880d681SAndroid Build Coastguard Worker /// Objects of this type are produced by traversing the alloca's slices, but
316*9880d681SAndroid Build Coastguard Worker /// are only ephemeral and not persistent.
317*9880d681SAndroid Build Coastguard Worker class llvm::sroa::Partition {
318*9880d681SAndroid Build Coastguard Worker private:
319*9880d681SAndroid Build Coastguard Worker friend class AllocaSlices;
320*9880d681SAndroid Build Coastguard Worker friend class AllocaSlices::partition_iterator;
321*9880d681SAndroid Build Coastguard Worker
322*9880d681SAndroid Build Coastguard Worker typedef AllocaSlices::iterator iterator;
323*9880d681SAndroid Build Coastguard Worker
324*9880d681SAndroid Build Coastguard Worker /// \brief The beginning and ending offsets of the alloca for this
325*9880d681SAndroid Build Coastguard Worker /// partition.
326*9880d681SAndroid Build Coastguard Worker uint64_t BeginOffset, EndOffset;
327*9880d681SAndroid Build Coastguard Worker
328*9880d681SAndroid Build Coastguard Worker /// \brief The start end end iterators of this partition.
329*9880d681SAndroid Build Coastguard Worker iterator SI, SJ;
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard Worker /// \brief A collection of split slice tails overlapping the partition.
332*9880d681SAndroid Build Coastguard Worker SmallVector<Slice *, 4> SplitTails;
333*9880d681SAndroid Build Coastguard Worker
334*9880d681SAndroid Build Coastguard Worker /// \brief Raw constructor builds an empty partition starting and ending at
335*9880d681SAndroid Build Coastguard Worker /// the given iterator.
Partition(iterator SI)336*9880d681SAndroid Build Coastguard Worker Partition(iterator SI) : SI(SI), SJ(SI) {}
337*9880d681SAndroid Build Coastguard Worker
338*9880d681SAndroid Build Coastguard Worker public:
339*9880d681SAndroid Build Coastguard Worker /// \brief The start offset of this partition.
340*9880d681SAndroid Build Coastguard Worker ///
341*9880d681SAndroid Build Coastguard Worker /// All of the contained slices start at or after this offset.
beginOffset() const342*9880d681SAndroid Build Coastguard Worker uint64_t beginOffset() const { return BeginOffset; }
343*9880d681SAndroid Build Coastguard Worker
344*9880d681SAndroid Build Coastguard Worker /// \brief The end offset of this partition.
345*9880d681SAndroid Build Coastguard Worker ///
346*9880d681SAndroid Build Coastguard Worker /// All of the contained slices end at or before this offset.
endOffset() const347*9880d681SAndroid Build Coastguard Worker uint64_t endOffset() const { return EndOffset; }
348*9880d681SAndroid Build Coastguard Worker
349*9880d681SAndroid Build Coastguard Worker /// \brief The size of the partition.
350*9880d681SAndroid Build Coastguard Worker ///
351*9880d681SAndroid Build Coastguard Worker /// Note that this can never be zero.
size() const352*9880d681SAndroid Build Coastguard Worker uint64_t size() const {
353*9880d681SAndroid Build Coastguard Worker assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
354*9880d681SAndroid Build Coastguard Worker return EndOffset - BeginOffset;
355*9880d681SAndroid Build Coastguard Worker }
356*9880d681SAndroid Build Coastguard Worker
357*9880d681SAndroid Build Coastguard Worker /// \brief Test whether this partition contains no slices, and merely spans
358*9880d681SAndroid Build Coastguard Worker /// a region occupied by split slices.
empty() const359*9880d681SAndroid Build Coastguard Worker bool empty() const { return SI == SJ; }
360*9880d681SAndroid Build Coastguard Worker
361*9880d681SAndroid Build Coastguard Worker /// \name Iterate slices that start within the partition.
362*9880d681SAndroid Build Coastguard Worker /// These may be splittable or unsplittable. They have a begin offset >= the
363*9880d681SAndroid Build Coastguard Worker /// partition begin offset.
364*9880d681SAndroid Build Coastguard Worker /// @{
365*9880d681SAndroid Build Coastguard Worker // FIXME: We should probably define a "concat_iterator" helper and use that
366*9880d681SAndroid Build Coastguard Worker // to stitch together pointee_iterators over the split tails and the
367*9880d681SAndroid Build Coastguard Worker // contiguous iterators of the partition. That would give a much nicer
368*9880d681SAndroid Build Coastguard Worker // interface here. We could then additionally expose filtered iterators for
369*9880d681SAndroid Build Coastguard Worker // split, unsplit, and unsplittable splices based on the usage patterns.
begin() const370*9880d681SAndroid Build Coastguard Worker iterator begin() const { return SI; }
end() const371*9880d681SAndroid Build Coastguard Worker iterator end() const { return SJ; }
372*9880d681SAndroid Build Coastguard Worker /// @}
373*9880d681SAndroid Build Coastguard Worker
374*9880d681SAndroid Build Coastguard Worker /// \brief Get the sequence of split slice tails.
375*9880d681SAndroid Build Coastguard Worker ///
376*9880d681SAndroid Build Coastguard Worker /// These tails are of slices which start before this partition but are
377*9880d681SAndroid Build Coastguard Worker /// split and overlap into the partition. We accumulate these while forming
378*9880d681SAndroid Build Coastguard Worker /// partitions.
splitSliceTails() const379*9880d681SAndroid Build Coastguard Worker ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
380*9880d681SAndroid Build Coastguard Worker };
381*9880d681SAndroid Build Coastguard Worker
382*9880d681SAndroid Build Coastguard Worker /// \brief An iterator over partitions of the alloca's slices.
383*9880d681SAndroid Build Coastguard Worker ///
384*9880d681SAndroid Build Coastguard Worker /// This iterator implements the core algorithm for partitioning the alloca's
385*9880d681SAndroid Build Coastguard Worker /// slices. It is a forward iterator as we don't support backtracking for
386*9880d681SAndroid Build Coastguard Worker /// efficiency reasons, and re-use a single storage area to maintain the
387*9880d681SAndroid Build Coastguard Worker /// current set of split slices.
388*9880d681SAndroid Build Coastguard Worker ///
389*9880d681SAndroid Build Coastguard Worker /// It is templated on the slice iterator type to use so that it can operate
390*9880d681SAndroid Build Coastguard Worker /// with either const or non-const slice iterators.
391*9880d681SAndroid Build Coastguard Worker class AllocaSlices::partition_iterator
392*9880d681SAndroid Build Coastguard Worker : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
393*9880d681SAndroid Build Coastguard Worker Partition> {
394*9880d681SAndroid Build Coastguard Worker friend class AllocaSlices;
395*9880d681SAndroid Build Coastguard Worker
396*9880d681SAndroid Build Coastguard Worker /// \brief Most of the state for walking the partitions is held in a class
397*9880d681SAndroid Build Coastguard Worker /// with a nice interface for examining them.
398*9880d681SAndroid Build Coastguard Worker Partition P;
399*9880d681SAndroid Build Coastguard Worker
400*9880d681SAndroid Build Coastguard Worker /// \brief We need to keep the end of the slices to know when to stop.
401*9880d681SAndroid Build Coastguard Worker AllocaSlices::iterator SE;
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker /// \brief We also need to keep track of the maximum split end offset seen.
404*9880d681SAndroid Build Coastguard Worker /// FIXME: Do we really?
405*9880d681SAndroid Build Coastguard Worker uint64_t MaxSplitSliceEndOffset;
406*9880d681SAndroid Build Coastguard Worker
407*9880d681SAndroid Build Coastguard Worker /// \brief Sets the partition to be empty at given iterator, and sets the
408*9880d681SAndroid Build Coastguard Worker /// end iterator.
partition_iterator(AllocaSlices::iterator SI,AllocaSlices::iterator SE)409*9880d681SAndroid Build Coastguard Worker partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
410*9880d681SAndroid Build Coastguard Worker : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
411*9880d681SAndroid Build Coastguard Worker // If not already at the end, advance our state to form the initial
412*9880d681SAndroid Build Coastguard Worker // partition.
413*9880d681SAndroid Build Coastguard Worker if (SI != SE)
414*9880d681SAndroid Build Coastguard Worker advance();
415*9880d681SAndroid Build Coastguard Worker }
416*9880d681SAndroid Build Coastguard Worker
417*9880d681SAndroid Build Coastguard Worker /// \brief Advance the iterator to the next partition.
418*9880d681SAndroid Build Coastguard Worker ///
419*9880d681SAndroid Build Coastguard Worker /// Requires that the iterator not be at the end of the slices.
advance()420*9880d681SAndroid Build Coastguard Worker void advance() {
421*9880d681SAndroid Build Coastguard Worker assert((P.SI != SE || !P.SplitTails.empty()) &&
422*9880d681SAndroid Build Coastguard Worker "Cannot advance past the end of the slices!");
423*9880d681SAndroid Build Coastguard Worker
424*9880d681SAndroid Build Coastguard Worker // Clear out any split uses which have ended.
425*9880d681SAndroid Build Coastguard Worker if (!P.SplitTails.empty()) {
426*9880d681SAndroid Build Coastguard Worker if (P.EndOffset >= MaxSplitSliceEndOffset) {
427*9880d681SAndroid Build Coastguard Worker // If we've finished all splits, this is easy.
428*9880d681SAndroid Build Coastguard Worker P.SplitTails.clear();
429*9880d681SAndroid Build Coastguard Worker MaxSplitSliceEndOffset = 0;
430*9880d681SAndroid Build Coastguard Worker } else {
431*9880d681SAndroid Build Coastguard Worker // Remove the uses which have ended in the prior partition. This
432*9880d681SAndroid Build Coastguard Worker // cannot change the max split slice end because we just checked that
433*9880d681SAndroid Build Coastguard Worker // the prior partition ended prior to that max.
434*9880d681SAndroid Build Coastguard Worker P.SplitTails.erase(
435*9880d681SAndroid Build Coastguard Worker std::remove_if(
436*9880d681SAndroid Build Coastguard Worker P.SplitTails.begin(), P.SplitTails.end(),
437*9880d681SAndroid Build Coastguard Worker [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
438*9880d681SAndroid Build Coastguard Worker P.SplitTails.end());
439*9880d681SAndroid Build Coastguard Worker assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
440*9880d681SAndroid Build Coastguard Worker [&](Slice *S) {
441*9880d681SAndroid Build Coastguard Worker return S->endOffset() == MaxSplitSliceEndOffset;
442*9880d681SAndroid Build Coastguard Worker }) &&
443*9880d681SAndroid Build Coastguard Worker "Could not find the current max split slice offset!");
444*9880d681SAndroid Build Coastguard Worker assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
445*9880d681SAndroid Build Coastguard Worker [&](Slice *S) {
446*9880d681SAndroid Build Coastguard Worker return S->endOffset() <= MaxSplitSliceEndOffset;
447*9880d681SAndroid Build Coastguard Worker }) &&
448*9880d681SAndroid Build Coastguard Worker "Max split slice end offset is not actually the max!");
449*9880d681SAndroid Build Coastguard Worker }
450*9880d681SAndroid Build Coastguard Worker }
451*9880d681SAndroid Build Coastguard Worker
452*9880d681SAndroid Build Coastguard Worker // If P.SI is already at the end, then we've cleared the split tail and
453*9880d681SAndroid Build Coastguard Worker // now have an end iterator.
454*9880d681SAndroid Build Coastguard Worker if (P.SI == SE) {
455*9880d681SAndroid Build Coastguard Worker assert(P.SplitTails.empty() && "Failed to clear the split slices!");
456*9880d681SAndroid Build Coastguard Worker return;
457*9880d681SAndroid Build Coastguard Worker }
458*9880d681SAndroid Build Coastguard Worker
459*9880d681SAndroid Build Coastguard Worker // If we had a non-empty partition previously, set up the state for
460*9880d681SAndroid Build Coastguard Worker // subsequent partitions.
461*9880d681SAndroid Build Coastguard Worker if (P.SI != P.SJ) {
462*9880d681SAndroid Build Coastguard Worker // Accumulate all the splittable slices which started in the old
463*9880d681SAndroid Build Coastguard Worker // partition into the split list.
464*9880d681SAndroid Build Coastguard Worker for (Slice &S : P)
465*9880d681SAndroid Build Coastguard Worker if (S.isSplittable() && S.endOffset() > P.EndOffset) {
466*9880d681SAndroid Build Coastguard Worker P.SplitTails.push_back(&S);
467*9880d681SAndroid Build Coastguard Worker MaxSplitSliceEndOffset =
468*9880d681SAndroid Build Coastguard Worker std::max(S.endOffset(), MaxSplitSliceEndOffset);
469*9880d681SAndroid Build Coastguard Worker }
470*9880d681SAndroid Build Coastguard Worker
471*9880d681SAndroid Build Coastguard Worker // Start from the end of the previous partition.
472*9880d681SAndroid Build Coastguard Worker P.SI = P.SJ;
473*9880d681SAndroid Build Coastguard Worker
474*9880d681SAndroid Build Coastguard Worker // If P.SI is now at the end, we at most have a tail of split slices.
475*9880d681SAndroid Build Coastguard Worker if (P.SI == SE) {
476*9880d681SAndroid Build Coastguard Worker P.BeginOffset = P.EndOffset;
477*9880d681SAndroid Build Coastguard Worker P.EndOffset = MaxSplitSliceEndOffset;
478*9880d681SAndroid Build Coastguard Worker return;
479*9880d681SAndroid Build Coastguard Worker }
480*9880d681SAndroid Build Coastguard Worker
481*9880d681SAndroid Build Coastguard Worker // If the we have split slices and the next slice is after a gap and is
482*9880d681SAndroid Build Coastguard Worker // not splittable immediately form an empty partition for the split
483*9880d681SAndroid Build Coastguard Worker // slices up until the next slice begins.
484*9880d681SAndroid Build Coastguard Worker if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
485*9880d681SAndroid Build Coastguard Worker !P.SI->isSplittable()) {
486*9880d681SAndroid Build Coastguard Worker P.BeginOffset = P.EndOffset;
487*9880d681SAndroid Build Coastguard Worker P.EndOffset = P.SI->beginOffset();
488*9880d681SAndroid Build Coastguard Worker return;
489*9880d681SAndroid Build Coastguard Worker }
490*9880d681SAndroid Build Coastguard Worker }
491*9880d681SAndroid Build Coastguard Worker
492*9880d681SAndroid Build Coastguard Worker // OK, we need to consume new slices. Set the end offset based on the
493*9880d681SAndroid Build Coastguard Worker // current slice, and step SJ past it. The beginning offset of the
494*9880d681SAndroid Build Coastguard Worker // partition is the beginning offset of the next slice unless we have
495*9880d681SAndroid Build Coastguard Worker // pre-existing split slices that are continuing, in which case we begin
496*9880d681SAndroid Build Coastguard Worker // at the prior end offset.
497*9880d681SAndroid Build Coastguard Worker P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
498*9880d681SAndroid Build Coastguard Worker P.EndOffset = P.SI->endOffset();
499*9880d681SAndroid Build Coastguard Worker ++P.SJ;
500*9880d681SAndroid Build Coastguard Worker
501*9880d681SAndroid Build Coastguard Worker // There are two strategies to form a partition based on whether the
502*9880d681SAndroid Build Coastguard Worker // partition starts with an unsplittable slice or a splittable slice.
503*9880d681SAndroid Build Coastguard Worker if (!P.SI->isSplittable()) {
504*9880d681SAndroid Build Coastguard Worker // When we're forming an unsplittable region, it must always start at
505*9880d681SAndroid Build Coastguard Worker // the first slice and will extend through its end.
506*9880d681SAndroid Build Coastguard Worker assert(P.BeginOffset == P.SI->beginOffset());
507*9880d681SAndroid Build Coastguard Worker
508*9880d681SAndroid Build Coastguard Worker // Form a partition including all of the overlapping slices with this
509*9880d681SAndroid Build Coastguard Worker // unsplittable slice.
510*9880d681SAndroid Build Coastguard Worker while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
511*9880d681SAndroid Build Coastguard Worker if (!P.SJ->isSplittable())
512*9880d681SAndroid Build Coastguard Worker P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
513*9880d681SAndroid Build Coastguard Worker ++P.SJ;
514*9880d681SAndroid Build Coastguard Worker }
515*9880d681SAndroid Build Coastguard Worker
516*9880d681SAndroid Build Coastguard Worker // We have a partition across a set of overlapping unsplittable
517*9880d681SAndroid Build Coastguard Worker // partitions.
518*9880d681SAndroid Build Coastguard Worker return;
519*9880d681SAndroid Build Coastguard Worker }
520*9880d681SAndroid Build Coastguard Worker
521*9880d681SAndroid Build Coastguard Worker // If we're starting with a splittable slice, then we need to form
522*9880d681SAndroid Build Coastguard Worker // a synthetic partition spanning it and any other overlapping splittable
523*9880d681SAndroid Build Coastguard Worker // splices.
524*9880d681SAndroid Build Coastguard Worker assert(P.SI->isSplittable() && "Forming a splittable partition!");
525*9880d681SAndroid Build Coastguard Worker
526*9880d681SAndroid Build Coastguard Worker // Collect all of the overlapping splittable slices.
527*9880d681SAndroid Build Coastguard Worker while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
528*9880d681SAndroid Build Coastguard Worker P.SJ->isSplittable()) {
529*9880d681SAndroid Build Coastguard Worker P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
530*9880d681SAndroid Build Coastguard Worker ++P.SJ;
531*9880d681SAndroid Build Coastguard Worker }
532*9880d681SAndroid Build Coastguard Worker
533*9880d681SAndroid Build Coastguard Worker // Back upiP.EndOffset if we ended the span early when encountering an
534*9880d681SAndroid Build Coastguard Worker // unsplittable slice. This synthesizes the early end offset of
535*9880d681SAndroid Build Coastguard Worker // a partition spanning only splittable slices.
536*9880d681SAndroid Build Coastguard Worker if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
537*9880d681SAndroid Build Coastguard Worker assert(!P.SJ->isSplittable());
538*9880d681SAndroid Build Coastguard Worker P.EndOffset = P.SJ->beginOffset();
539*9880d681SAndroid Build Coastguard Worker }
540*9880d681SAndroid Build Coastguard Worker }
541*9880d681SAndroid Build Coastguard Worker
542*9880d681SAndroid Build Coastguard Worker public:
operator ==(const partition_iterator & RHS) const543*9880d681SAndroid Build Coastguard Worker bool operator==(const partition_iterator &RHS) const {
544*9880d681SAndroid Build Coastguard Worker assert(SE == RHS.SE &&
545*9880d681SAndroid Build Coastguard Worker "End iterators don't match between compared partition iterators!");
546*9880d681SAndroid Build Coastguard Worker
547*9880d681SAndroid Build Coastguard Worker // The observed positions of partitions is marked by the P.SI iterator and
548*9880d681SAndroid Build Coastguard Worker // the emptiness of the split slices. The latter is only relevant when
549*9880d681SAndroid Build Coastguard Worker // P.SI == SE, as the end iterator will additionally have an empty split
550*9880d681SAndroid Build Coastguard Worker // slices list, but the prior may have the same P.SI and a tail of split
551*9880d681SAndroid Build Coastguard Worker // slices.
552*9880d681SAndroid Build Coastguard Worker if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
553*9880d681SAndroid Build Coastguard Worker assert(P.SJ == RHS.P.SJ &&
554*9880d681SAndroid Build Coastguard Worker "Same set of slices formed two different sized partitions!");
555*9880d681SAndroid Build Coastguard Worker assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
556*9880d681SAndroid Build Coastguard Worker "Same slice position with differently sized non-empty split "
557*9880d681SAndroid Build Coastguard Worker "slice tails!");
558*9880d681SAndroid Build Coastguard Worker return true;
559*9880d681SAndroid Build Coastguard Worker }
560*9880d681SAndroid Build Coastguard Worker return false;
561*9880d681SAndroid Build Coastguard Worker }
562*9880d681SAndroid Build Coastguard Worker
operator ++()563*9880d681SAndroid Build Coastguard Worker partition_iterator &operator++() {
564*9880d681SAndroid Build Coastguard Worker advance();
565*9880d681SAndroid Build Coastguard Worker return *this;
566*9880d681SAndroid Build Coastguard Worker }
567*9880d681SAndroid Build Coastguard Worker
operator *()568*9880d681SAndroid Build Coastguard Worker Partition &operator*() { return P; }
569*9880d681SAndroid Build Coastguard Worker };
570*9880d681SAndroid Build Coastguard Worker
571*9880d681SAndroid Build Coastguard Worker /// \brief A forward range over the partitions of the alloca's slices.
572*9880d681SAndroid Build Coastguard Worker ///
573*9880d681SAndroid Build Coastguard Worker /// This accesses an iterator range over the partitions of the alloca's
574*9880d681SAndroid Build Coastguard Worker /// slices. It computes these partitions on the fly based on the overlapping
575*9880d681SAndroid Build Coastguard Worker /// offsets of the slices and the ability to split them. It will visit "empty"
576*9880d681SAndroid Build Coastguard Worker /// partitions to cover regions of the alloca only accessed via split
577*9880d681SAndroid Build Coastguard Worker /// slices.
partitions()578*9880d681SAndroid Build Coastguard Worker iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
579*9880d681SAndroid Build Coastguard Worker return make_range(partition_iterator(begin(), end()),
580*9880d681SAndroid Build Coastguard Worker partition_iterator(end(), end()));
581*9880d681SAndroid Build Coastguard Worker }
582*9880d681SAndroid Build Coastguard Worker
foldSelectInst(SelectInst & SI)583*9880d681SAndroid Build Coastguard Worker static Value *foldSelectInst(SelectInst &SI) {
584*9880d681SAndroid Build Coastguard Worker // If the condition being selected on is a constant or the same value is
585*9880d681SAndroid Build Coastguard Worker // being selected between, fold the select. Yes this does (rarely) happen
586*9880d681SAndroid Build Coastguard Worker // early on.
587*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
588*9880d681SAndroid Build Coastguard Worker return SI.getOperand(1 + CI->isZero());
589*9880d681SAndroid Build Coastguard Worker if (SI.getOperand(1) == SI.getOperand(2))
590*9880d681SAndroid Build Coastguard Worker return SI.getOperand(1);
591*9880d681SAndroid Build Coastguard Worker
592*9880d681SAndroid Build Coastguard Worker return nullptr;
593*9880d681SAndroid Build Coastguard Worker }
594*9880d681SAndroid Build Coastguard Worker
595*9880d681SAndroid Build Coastguard Worker /// \brief A helper that folds a PHI node or a select.
foldPHINodeOrSelectInst(Instruction & I)596*9880d681SAndroid Build Coastguard Worker static Value *foldPHINodeOrSelectInst(Instruction &I) {
597*9880d681SAndroid Build Coastguard Worker if (PHINode *PN = dyn_cast<PHINode>(&I)) {
598*9880d681SAndroid Build Coastguard Worker // If PN merges together the same value, return that value.
599*9880d681SAndroid Build Coastguard Worker return PN->hasConstantValue();
600*9880d681SAndroid Build Coastguard Worker }
601*9880d681SAndroid Build Coastguard Worker return foldSelectInst(cast<SelectInst>(I));
602*9880d681SAndroid Build Coastguard Worker }
603*9880d681SAndroid Build Coastguard Worker
604*9880d681SAndroid Build Coastguard Worker /// \brief Builder for the alloca slices.
605*9880d681SAndroid Build Coastguard Worker ///
606*9880d681SAndroid Build Coastguard Worker /// This class builds a set of alloca slices by recursively visiting the uses
607*9880d681SAndroid Build Coastguard Worker /// of an alloca and making a slice for each load and store at each offset.
608*9880d681SAndroid Build Coastguard Worker class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
609*9880d681SAndroid Build Coastguard Worker friend class PtrUseVisitor<SliceBuilder>;
610*9880d681SAndroid Build Coastguard Worker friend class InstVisitor<SliceBuilder>;
611*9880d681SAndroid Build Coastguard Worker typedef PtrUseVisitor<SliceBuilder> Base;
612*9880d681SAndroid Build Coastguard Worker
613*9880d681SAndroid Build Coastguard Worker const uint64_t AllocSize;
614*9880d681SAndroid Build Coastguard Worker AllocaSlices &AS;
615*9880d681SAndroid Build Coastguard Worker
616*9880d681SAndroid Build Coastguard Worker SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
617*9880d681SAndroid Build Coastguard Worker SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
618*9880d681SAndroid Build Coastguard Worker
619*9880d681SAndroid Build Coastguard Worker /// \brief Set to de-duplicate dead instructions found in the use walk.
620*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
621*9880d681SAndroid Build Coastguard Worker
622*9880d681SAndroid Build Coastguard Worker public:
SliceBuilder(const DataLayout & DL,AllocaInst & AI,AllocaSlices & AS)623*9880d681SAndroid Build Coastguard Worker SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
624*9880d681SAndroid Build Coastguard Worker : PtrUseVisitor<SliceBuilder>(DL),
625*9880d681SAndroid Build Coastguard Worker AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
626*9880d681SAndroid Build Coastguard Worker
627*9880d681SAndroid Build Coastguard Worker private:
markAsDead(Instruction & I)628*9880d681SAndroid Build Coastguard Worker void markAsDead(Instruction &I) {
629*9880d681SAndroid Build Coastguard Worker if (VisitedDeadInsts.insert(&I).second)
630*9880d681SAndroid Build Coastguard Worker AS.DeadUsers.push_back(&I);
631*9880d681SAndroid Build Coastguard Worker }
632*9880d681SAndroid Build Coastguard Worker
insertUse(Instruction & I,const APInt & Offset,uint64_t Size,bool IsSplittable=false)633*9880d681SAndroid Build Coastguard Worker void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
634*9880d681SAndroid Build Coastguard Worker bool IsSplittable = false) {
635*9880d681SAndroid Build Coastguard Worker // Completely skip uses which have a zero size or start either before or
636*9880d681SAndroid Build Coastguard Worker // past the end of the allocation.
637*9880d681SAndroid Build Coastguard Worker if (Size == 0 || Offset.uge(AllocSize)) {
638*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
639*9880d681SAndroid Build Coastguard Worker << " which has zero size or starts outside of the "
640*9880d681SAndroid Build Coastguard Worker << AllocSize << " byte alloca:\n"
641*9880d681SAndroid Build Coastguard Worker << " alloca: " << AS.AI << "\n"
642*9880d681SAndroid Build Coastguard Worker << " use: " << I << "\n");
643*9880d681SAndroid Build Coastguard Worker return markAsDead(I);
644*9880d681SAndroid Build Coastguard Worker }
645*9880d681SAndroid Build Coastguard Worker
646*9880d681SAndroid Build Coastguard Worker uint64_t BeginOffset = Offset.getZExtValue();
647*9880d681SAndroid Build Coastguard Worker uint64_t EndOffset = BeginOffset + Size;
648*9880d681SAndroid Build Coastguard Worker
649*9880d681SAndroid Build Coastguard Worker // Clamp the end offset to the end of the allocation. Note that this is
650*9880d681SAndroid Build Coastguard Worker // formulated to handle even the case where "BeginOffset + Size" overflows.
651*9880d681SAndroid Build Coastguard Worker // This may appear superficially to be something we could ignore entirely,
652*9880d681SAndroid Build Coastguard Worker // but that is not so! There may be widened loads or PHI-node uses where
653*9880d681SAndroid Build Coastguard Worker // some instructions are dead but not others. We can't completely ignore
654*9880d681SAndroid Build Coastguard Worker // them, and so have to record at least the information here.
655*9880d681SAndroid Build Coastguard Worker assert(AllocSize >= BeginOffset); // Established above.
656*9880d681SAndroid Build Coastguard Worker if (Size > AllocSize - BeginOffset) {
657*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
658*9880d681SAndroid Build Coastguard Worker << " to remain within the " << AllocSize << " byte alloca:\n"
659*9880d681SAndroid Build Coastguard Worker << " alloca: " << AS.AI << "\n"
660*9880d681SAndroid Build Coastguard Worker << " use: " << I << "\n");
661*9880d681SAndroid Build Coastguard Worker EndOffset = AllocSize;
662*9880d681SAndroid Build Coastguard Worker }
663*9880d681SAndroid Build Coastguard Worker
664*9880d681SAndroid Build Coastguard Worker AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
665*9880d681SAndroid Build Coastguard Worker }
666*9880d681SAndroid Build Coastguard Worker
visitBitCastInst(BitCastInst & BC)667*9880d681SAndroid Build Coastguard Worker void visitBitCastInst(BitCastInst &BC) {
668*9880d681SAndroid Build Coastguard Worker if (BC.use_empty())
669*9880d681SAndroid Build Coastguard Worker return markAsDead(BC);
670*9880d681SAndroid Build Coastguard Worker
671*9880d681SAndroid Build Coastguard Worker return Base::visitBitCastInst(BC);
672*9880d681SAndroid Build Coastguard Worker }
673*9880d681SAndroid Build Coastguard Worker
visitGetElementPtrInst(GetElementPtrInst & GEPI)674*9880d681SAndroid Build Coastguard Worker void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
675*9880d681SAndroid Build Coastguard Worker if (GEPI.use_empty())
676*9880d681SAndroid Build Coastguard Worker return markAsDead(GEPI);
677*9880d681SAndroid Build Coastguard Worker
678*9880d681SAndroid Build Coastguard Worker if (SROAStrictInbounds && GEPI.isInBounds()) {
679*9880d681SAndroid Build Coastguard Worker // FIXME: This is a manually un-factored variant of the basic code inside
680*9880d681SAndroid Build Coastguard Worker // of GEPs with checking of the inbounds invariant specified in the
681*9880d681SAndroid Build Coastguard Worker // langref in a very strict sense. If we ever want to enable
682*9880d681SAndroid Build Coastguard Worker // SROAStrictInbounds, this code should be factored cleanly into
683*9880d681SAndroid Build Coastguard Worker // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
684*9880d681SAndroid Build Coastguard Worker // by writing out the code here where we have the underlying allocation
685*9880d681SAndroid Build Coastguard Worker // size readily available.
686*9880d681SAndroid Build Coastguard Worker APInt GEPOffset = Offset;
687*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = GEPI.getModule()->getDataLayout();
688*9880d681SAndroid Build Coastguard Worker for (gep_type_iterator GTI = gep_type_begin(GEPI),
689*9880d681SAndroid Build Coastguard Worker GTE = gep_type_end(GEPI);
690*9880d681SAndroid Build Coastguard Worker GTI != GTE; ++GTI) {
691*9880d681SAndroid Build Coastguard Worker ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
692*9880d681SAndroid Build Coastguard Worker if (!OpC)
693*9880d681SAndroid Build Coastguard Worker break;
694*9880d681SAndroid Build Coastguard Worker
695*9880d681SAndroid Build Coastguard Worker // Handle a struct index, which adds its field offset to the pointer.
696*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(*GTI)) {
697*9880d681SAndroid Build Coastguard Worker unsigned ElementIdx = OpC->getZExtValue();
698*9880d681SAndroid Build Coastguard Worker const StructLayout *SL = DL.getStructLayout(STy);
699*9880d681SAndroid Build Coastguard Worker GEPOffset +=
700*9880d681SAndroid Build Coastguard Worker APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
701*9880d681SAndroid Build Coastguard Worker } else {
702*9880d681SAndroid Build Coastguard Worker // For array or vector indices, scale the index by the size of the
703*9880d681SAndroid Build Coastguard Worker // type.
704*9880d681SAndroid Build Coastguard Worker APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
705*9880d681SAndroid Build Coastguard Worker GEPOffset += Index * APInt(Offset.getBitWidth(),
706*9880d681SAndroid Build Coastguard Worker DL.getTypeAllocSize(GTI.getIndexedType()));
707*9880d681SAndroid Build Coastguard Worker }
708*9880d681SAndroid Build Coastguard Worker
709*9880d681SAndroid Build Coastguard Worker // If this index has computed an intermediate pointer which is not
710*9880d681SAndroid Build Coastguard Worker // inbounds, then the result of the GEP is a poison value and we can
711*9880d681SAndroid Build Coastguard Worker // delete it and all uses.
712*9880d681SAndroid Build Coastguard Worker if (GEPOffset.ugt(AllocSize))
713*9880d681SAndroid Build Coastguard Worker return markAsDead(GEPI);
714*9880d681SAndroid Build Coastguard Worker }
715*9880d681SAndroid Build Coastguard Worker }
716*9880d681SAndroid Build Coastguard Worker
717*9880d681SAndroid Build Coastguard Worker return Base::visitGetElementPtrInst(GEPI);
718*9880d681SAndroid Build Coastguard Worker }
719*9880d681SAndroid Build Coastguard Worker
handleLoadOrStore(Type * Ty,Instruction & I,const APInt & Offset,uint64_t Size,bool IsVolatile)720*9880d681SAndroid Build Coastguard Worker void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
721*9880d681SAndroid Build Coastguard Worker uint64_t Size, bool IsVolatile) {
722*9880d681SAndroid Build Coastguard Worker // We allow splitting of non-volatile loads and stores where the type is an
723*9880d681SAndroid Build Coastguard Worker // integer type. These may be used to implement 'memcpy' or other "transfer
724*9880d681SAndroid Build Coastguard Worker // of bits" patterns.
725*9880d681SAndroid Build Coastguard Worker bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
726*9880d681SAndroid Build Coastguard Worker
727*9880d681SAndroid Build Coastguard Worker insertUse(I, Offset, Size, IsSplittable);
728*9880d681SAndroid Build Coastguard Worker }
729*9880d681SAndroid Build Coastguard Worker
visitLoadInst(LoadInst & LI)730*9880d681SAndroid Build Coastguard Worker void visitLoadInst(LoadInst &LI) {
731*9880d681SAndroid Build Coastguard Worker assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
732*9880d681SAndroid Build Coastguard Worker "All simple FCA loads should have been pre-split");
733*9880d681SAndroid Build Coastguard Worker
734*9880d681SAndroid Build Coastguard Worker if (!IsOffsetKnown)
735*9880d681SAndroid Build Coastguard Worker return PI.setAborted(&LI);
736*9880d681SAndroid Build Coastguard Worker
737*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = LI.getModule()->getDataLayout();
738*9880d681SAndroid Build Coastguard Worker uint64_t Size = DL.getTypeStoreSize(LI.getType());
739*9880d681SAndroid Build Coastguard Worker return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
740*9880d681SAndroid Build Coastguard Worker }
741*9880d681SAndroid Build Coastguard Worker
visitStoreInst(StoreInst & SI)742*9880d681SAndroid Build Coastguard Worker void visitStoreInst(StoreInst &SI) {
743*9880d681SAndroid Build Coastguard Worker Value *ValOp = SI.getValueOperand();
744*9880d681SAndroid Build Coastguard Worker if (ValOp == *U)
745*9880d681SAndroid Build Coastguard Worker return PI.setEscapedAndAborted(&SI);
746*9880d681SAndroid Build Coastguard Worker if (!IsOffsetKnown)
747*9880d681SAndroid Build Coastguard Worker return PI.setAborted(&SI);
748*9880d681SAndroid Build Coastguard Worker
749*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = SI.getModule()->getDataLayout();
750*9880d681SAndroid Build Coastguard Worker uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
751*9880d681SAndroid Build Coastguard Worker
752*9880d681SAndroid Build Coastguard Worker // If this memory access can be shown to *statically* extend outside the
753*9880d681SAndroid Build Coastguard Worker // bounds of of the allocation, it's behavior is undefined, so simply
754*9880d681SAndroid Build Coastguard Worker // ignore it. Note that this is more strict than the generic clamping
755*9880d681SAndroid Build Coastguard Worker // behavior of insertUse. We also try to handle cases which might run the
756*9880d681SAndroid Build Coastguard Worker // risk of overflow.
757*9880d681SAndroid Build Coastguard Worker // FIXME: We should instead consider the pointer to have escaped if this
758*9880d681SAndroid Build Coastguard Worker // function is being instrumented for addressing bugs or race conditions.
759*9880d681SAndroid Build Coastguard Worker if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
760*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
761*9880d681SAndroid Build Coastguard Worker << " which extends past the end of the " << AllocSize
762*9880d681SAndroid Build Coastguard Worker << " byte alloca:\n"
763*9880d681SAndroid Build Coastguard Worker << " alloca: " << AS.AI << "\n"
764*9880d681SAndroid Build Coastguard Worker << " use: " << SI << "\n");
765*9880d681SAndroid Build Coastguard Worker return markAsDead(SI);
766*9880d681SAndroid Build Coastguard Worker }
767*9880d681SAndroid Build Coastguard Worker
768*9880d681SAndroid Build Coastguard Worker assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
769*9880d681SAndroid Build Coastguard Worker "All simple FCA stores should have been pre-split");
770*9880d681SAndroid Build Coastguard Worker handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
771*9880d681SAndroid Build Coastguard Worker }
772*9880d681SAndroid Build Coastguard Worker
visitMemSetInst(MemSetInst & II)773*9880d681SAndroid Build Coastguard Worker void visitMemSetInst(MemSetInst &II) {
774*9880d681SAndroid Build Coastguard Worker assert(II.getRawDest() == *U && "Pointer use is not the destination?");
775*9880d681SAndroid Build Coastguard Worker ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
776*9880d681SAndroid Build Coastguard Worker if ((Length && Length->getValue() == 0) ||
777*9880d681SAndroid Build Coastguard Worker (IsOffsetKnown && Offset.uge(AllocSize)))
778*9880d681SAndroid Build Coastguard Worker // Zero-length mem transfer intrinsics can be ignored entirely.
779*9880d681SAndroid Build Coastguard Worker return markAsDead(II);
780*9880d681SAndroid Build Coastguard Worker
781*9880d681SAndroid Build Coastguard Worker if (!IsOffsetKnown)
782*9880d681SAndroid Build Coastguard Worker return PI.setAborted(&II);
783*9880d681SAndroid Build Coastguard Worker
784*9880d681SAndroid Build Coastguard Worker insertUse(II, Offset, Length ? Length->getLimitedValue()
785*9880d681SAndroid Build Coastguard Worker : AllocSize - Offset.getLimitedValue(),
786*9880d681SAndroid Build Coastguard Worker (bool)Length);
787*9880d681SAndroid Build Coastguard Worker }
788*9880d681SAndroid Build Coastguard Worker
visitMemTransferInst(MemTransferInst & II)789*9880d681SAndroid Build Coastguard Worker void visitMemTransferInst(MemTransferInst &II) {
790*9880d681SAndroid Build Coastguard Worker ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
791*9880d681SAndroid Build Coastguard Worker if (Length && Length->getValue() == 0)
792*9880d681SAndroid Build Coastguard Worker // Zero-length mem transfer intrinsics can be ignored entirely.
793*9880d681SAndroid Build Coastguard Worker return markAsDead(II);
794*9880d681SAndroid Build Coastguard Worker
795*9880d681SAndroid Build Coastguard Worker // Because we can visit these intrinsics twice, also check to see if the
796*9880d681SAndroid Build Coastguard Worker // first time marked this instruction as dead. If so, skip it.
797*9880d681SAndroid Build Coastguard Worker if (VisitedDeadInsts.count(&II))
798*9880d681SAndroid Build Coastguard Worker return;
799*9880d681SAndroid Build Coastguard Worker
800*9880d681SAndroid Build Coastguard Worker if (!IsOffsetKnown)
801*9880d681SAndroid Build Coastguard Worker return PI.setAborted(&II);
802*9880d681SAndroid Build Coastguard Worker
803*9880d681SAndroid Build Coastguard Worker // This side of the transfer is completely out-of-bounds, and so we can
804*9880d681SAndroid Build Coastguard Worker // nuke the entire transfer. However, we also need to nuke the other side
805*9880d681SAndroid Build Coastguard Worker // if already added to our partitions.
806*9880d681SAndroid Build Coastguard Worker // FIXME: Yet another place we really should bypass this when
807*9880d681SAndroid Build Coastguard Worker // instrumenting for ASan.
808*9880d681SAndroid Build Coastguard Worker if (Offset.uge(AllocSize)) {
809*9880d681SAndroid Build Coastguard Worker SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
810*9880d681SAndroid Build Coastguard Worker MemTransferSliceMap.find(&II);
811*9880d681SAndroid Build Coastguard Worker if (MTPI != MemTransferSliceMap.end())
812*9880d681SAndroid Build Coastguard Worker AS.Slices[MTPI->second].kill();
813*9880d681SAndroid Build Coastguard Worker return markAsDead(II);
814*9880d681SAndroid Build Coastguard Worker }
815*9880d681SAndroid Build Coastguard Worker
816*9880d681SAndroid Build Coastguard Worker uint64_t RawOffset = Offset.getLimitedValue();
817*9880d681SAndroid Build Coastguard Worker uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
818*9880d681SAndroid Build Coastguard Worker
819*9880d681SAndroid Build Coastguard Worker // Check for the special case where the same exact value is used for both
820*9880d681SAndroid Build Coastguard Worker // source and dest.
821*9880d681SAndroid Build Coastguard Worker if (*U == II.getRawDest() && *U == II.getRawSource()) {
822*9880d681SAndroid Build Coastguard Worker // For non-volatile transfers this is a no-op.
823*9880d681SAndroid Build Coastguard Worker if (!II.isVolatile())
824*9880d681SAndroid Build Coastguard Worker return markAsDead(II);
825*9880d681SAndroid Build Coastguard Worker
826*9880d681SAndroid Build Coastguard Worker return insertUse(II, Offset, Size, /*IsSplittable=*/false);
827*9880d681SAndroid Build Coastguard Worker }
828*9880d681SAndroid Build Coastguard Worker
829*9880d681SAndroid Build Coastguard Worker // If we have seen both source and destination for a mem transfer, then
830*9880d681SAndroid Build Coastguard Worker // they both point to the same alloca.
831*9880d681SAndroid Build Coastguard Worker bool Inserted;
832*9880d681SAndroid Build Coastguard Worker SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
833*9880d681SAndroid Build Coastguard Worker std::tie(MTPI, Inserted) =
834*9880d681SAndroid Build Coastguard Worker MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
835*9880d681SAndroid Build Coastguard Worker unsigned PrevIdx = MTPI->second;
836*9880d681SAndroid Build Coastguard Worker if (!Inserted) {
837*9880d681SAndroid Build Coastguard Worker Slice &PrevP = AS.Slices[PrevIdx];
838*9880d681SAndroid Build Coastguard Worker
839*9880d681SAndroid Build Coastguard Worker // Check if the begin offsets match and this is a non-volatile transfer.
840*9880d681SAndroid Build Coastguard Worker // In that case, we can completely elide the transfer.
841*9880d681SAndroid Build Coastguard Worker if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
842*9880d681SAndroid Build Coastguard Worker PrevP.kill();
843*9880d681SAndroid Build Coastguard Worker return markAsDead(II);
844*9880d681SAndroid Build Coastguard Worker }
845*9880d681SAndroid Build Coastguard Worker
846*9880d681SAndroid Build Coastguard Worker // Otherwise we have an offset transfer within the same alloca. We can't
847*9880d681SAndroid Build Coastguard Worker // split those.
848*9880d681SAndroid Build Coastguard Worker PrevP.makeUnsplittable();
849*9880d681SAndroid Build Coastguard Worker }
850*9880d681SAndroid Build Coastguard Worker
851*9880d681SAndroid Build Coastguard Worker // Insert the use now that we've fixed up the splittable nature.
852*9880d681SAndroid Build Coastguard Worker insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
853*9880d681SAndroid Build Coastguard Worker
854*9880d681SAndroid Build Coastguard Worker // Check that we ended up with a valid index in the map.
855*9880d681SAndroid Build Coastguard Worker assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
856*9880d681SAndroid Build Coastguard Worker "Map index doesn't point back to a slice with this user.");
857*9880d681SAndroid Build Coastguard Worker }
858*9880d681SAndroid Build Coastguard Worker
859*9880d681SAndroid Build Coastguard Worker // Disable SRoA for any intrinsics except for lifetime invariants.
860*9880d681SAndroid Build Coastguard Worker // FIXME: What about debug intrinsics? This matches old behavior, but
861*9880d681SAndroid Build Coastguard Worker // doesn't make sense.
visitIntrinsicInst(IntrinsicInst & II)862*9880d681SAndroid Build Coastguard Worker void visitIntrinsicInst(IntrinsicInst &II) {
863*9880d681SAndroid Build Coastguard Worker if (!IsOffsetKnown)
864*9880d681SAndroid Build Coastguard Worker return PI.setAborted(&II);
865*9880d681SAndroid Build Coastguard Worker
866*9880d681SAndroid Build Coastguard Worker if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
867*9880d681SAndroid Build Coastguard Worker II.getIntrinsicID() == Intrinsic::lifetime_end) {
868*9880d681SAndroid Build Coastguard Worker ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
869*9880d681SAndroid Build Coastguard Worker uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
870*9880d681SAndroid Build Coastguard Worker Length->getLimitedValue());
871*9880d681SAndroid Build Coastguard Worker insertUse(II, Offset, Size, true);
872*9880d681SAndroid Build Coastguard Worker return;
873*9880d681SAndroid Build Coastguard Worker }
874*9880d681SAndroid Build Coastguard Worker
875*9880d681SAndroid Build Coastguard Worker Base::visitIntrinsicInst(II);
876*9880d681SAndroid Build Coastguard Worker }
877*9880d681SAndroid Build Coastguard Worker
hasUnsafePHIOrSelectUse(Instruction * Root,uint64_t & Size)878*9880d681SAndroid Build Coastguard Worker Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
879*9880d681SAndroid Build Coastguard Worker // We consider any PHI or select that results in a direct load or store of
880*9880d681SAndroid Build Coastguard Worker // the same offset to be a viable use for slicing purposes. These uses
881*9880d681SAndroid Build Coastguard Worker // are considered unsplittable and the size is the maximum loaded or stored
882*9880d681SAndroid Build Coastguard Worker // size.
883*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Instruction *, 4> Visited;
884*9880d681SAndroid Build Coastguard Worker SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
885*9880d681SAndroid Build Coastguard Worker Visited.insert(Root);
886*9880d681SAndroid Build Coastguard Worker Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
887*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = Root->getModule()->getDataLayout();
888*9880d681SAndroid Build Coastguard Worker // If there are no loads or stores, the access is dead. We mark that as
889*9880d681SAndroid Build Coastguard Worker // a size zero access.
890*9880d681SAndroid Build Coastguard Worker Size = 0;
891*9880d681SAndroid Build Coastguard Worker do {
892*9880d681SAndroid Build Coastguard Worker Instruction *I, *UsedI;
893*9880d681SAndroid Build Coastguard Worker std::tie(UsedI, I) = Uses.pop_back_val();
894*9880d681SAndroid Build Coastguard Worker
895*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
896*9880d681SAndroid Build Coastguard Worker Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
897*9880d681SAndroid Build Coastguard Worker continue;
898*9880d681SAndroid Build Coastguard Worker }
899*9880d681SAndroid Build Coastguard Worker if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
900*9880d681SAndroid Build Coastguard Worker Value *Op = SI->getOperand(0);
901*9880d681SAndroid Build Coastguard Worker if (Op == UsedI)
902*9880d681SAndroid Build Coastguard Worker return SI;
903*9880d681SAndroid Build Coastguard Worker Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
904*9880d681SAndroid Build Coastguard Worker continue;
905*9880d681SAndroid Build Coastguard Worker }
906*9880d681SAndroid Build Coastguard Worker
907*9880d681SAndroid Build Coastguard Worker if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
908*9880d681SAndroid Build Coastguard Worker if (!GEP->hasAllZeroIndices())
909*9880d681SAndroid Build Coastguard Worker return GEP;
910*9880d681SAndroid Build Coastguard Worker } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
911*9880d681SAndroid Build Coastguard Worker !isa<SelectInst>(I)) {
912*9880d681SAndroid Build Coastguard Worker return I;
913*9880d681SAndroid Build Coastguard Worker }
914*9880d681SAndroid Build Coastguard Worker
915*9880d681SAndroid Build Coastguard Worker for (User *U : I->users())
916*9880d681SAndroid Build Coastguard Worker if (Visited.insert(cast<Instruction>(U)).second)
917*9880d681SAndroid Build Coastguard Worker Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
918*9880d681SAndroid Build Coastguard Worker } while (!Uses.empty());
919*9880d681SAndroid Build Coastguard Worker
920*9880d681SAndroid Build Coastguard Worker return nullptr;
921*9880d681SAndroid Build Coastguard Worker }
922*9880d681SAndroid Build Coastguard Worker
visitPHINodeOrSelectInst(Instruction & I)923*9880d681SAndroid Build Coastguard Worker void visitPHINodeOrSelectInst(Instruction &I) {
924*9880d681SAndroid Build Coastguard Worker assert(isa<PHINode>(I) || isa<SelectInst>(I));
925*9880d681SAndroid Build Coastguard Worker if (I.use_empty())
926*9880d681SAndroid Build Coastguard Worker return markAsDead(I);
927*9880d681SAndroid Build Coastguard Worker
928*9880d681SAndroid Build Coastguard Worker // TODO: We could use SimplifyInstruction here to fold PHINodes and
929*9880d681SAndroid Build Coastguard Worker // SelectInsts. However, doing so requires to change the current
930*9880d681SAndroid Build Coastguard Worker // dead-operand-tracking mechanism. For instance, suppose neither loading
931*9880d681SAndroid Build Coastguard Worker // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
932*9880d681SAndroid Build Coastguard Worker // trap either. However, if we simply replace %U with undef using the
933*9880d681SAndroid Build Coastguard Worker // current dead-operand-tracking mechanism, "load (select undef, undef,
934*9880d681SAndroid Build Coastguard Worker // %other)" may trap because the select may return the first operand
935*9880d681SAndroid Build Coastguard Worker // "undef".
936*9880d681SAndroid Build Coastguard Worker if (Value *Result = foldPHINodeOrSelectInst(I)) {
937*9880d681SAndroid Build Coastguard Worker if (Result == *U)
938*9880d681SAndroid Build Coastguard Worker // If the result of the constant fold will be the pointer, recurse
939*9880d681SAndroid Build Coastguard Worker // through the PHI/select as if we had RAUW'ed it.
940*9880d681SAndroid Build Coastguard Worker enqueueUsers(I);
941*9880d681SAndroid Build Coastguard Worker else
942*9880d681SAndroid Build Coastguard Worker // Otherwise the operand to the PHI/select is dead, and we can replace
943*9880d681SAndroid Build Coastguard Worker // it with undef.
944*9880d681SAndroid Build Coastguard Worker AS.DeadOperands.push_back(U);
945*9880d681SAndroid Build Coastguard Worker
946*9880d681SAndroid Build Coastguard Worker return;
947*9880d681SAndroid Build Coastguard Worker }
948*9880d681SAndroid Build Coastguard Worker
949*9880d681SAndroid Build Coastguard Worker if (!IsOffsetKnown)
950*9880d681SAndroid Build Coastguard Worker return PI.setAborted(&I);
951*9880d681SAndroid Build Coastguard Worker
952*9880d681SAndroid Build Coastguard Worker // See if we already have computed info on this node.
953*9880d681SAndroid Build Coastguard Worker uint64_t &Size = PHIOrSelectSizes[&I];
954*9880d681SAndroid Build Coastguard Worker if (!Size) {
955*9880d681SAndroid Build Coastguard Worker // This is a new PHI/Select, check for an unsafe use of it.
956*9880d681SAndroid Build Coastguard Worker if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
957*9880d681SAndroid Build Coastguard Worker return PI.setAborted(UnsafeI);
958*9880d681SAndroid Build Coastguard Worker }
959*9880d681SAndroid Build Coastguard Worker
960*9880d681SAndroid Build Coastguard Worker // For PHI and select operands outside the alloca, we can't nuke the entire
961*9880d681SAndroid Build Coastguard Worker // phi or select -- the other side might still be relevant, so we special
962*9880d681SAndroid Build Coastguard Worker // case them here and use a separate structure to track the operands
963*9880d681SAndroid Build Coastguard Worker // themselves which should be replaced with undef.
964*9880d681SAndroid Build Coastguard Worker // FIXME: This should instead be escaped in the event we're instrumenting
965*9880d681SAndroid Build Coastguard Worker // for address sanitization.
966*9880d681SAndroid Build Coastguard Worker if (Offset.uge(AllocSize)) {
967*9880d681SAndroid Build Coastguard Worker AS.DeadOperands.push_back(U);
968*9880d681SAndroid Build Coastguard Worker return;
969*9880d681SAndroid Build Coastguard Worker }
970*9880d681SAndroid Build Coastguard Worker
971*9880d681SAndroid Build Coastguard Worker insertUse(I, Offset, Size);
972*9880d681SAndroid Build Coastguard Worker }
973*9880d681SAndroid Build Coastguard Worker
visitPHINode(PHINode & PN)974*9880d681SAndroid Build Coastguard Worker void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
975*9880d681SAndroid Build Coastguard Worker
visitSelectInst(SelectInst & SI)976*9880d681SAndroid Build Coastguard Worker void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
977*9880d681SAndroid Build Coastguard Worker
978*9880d681SAndroid Build Coastguard Worker /// \brief Disable SROA entirely if there are unhandled users of the alloca.
visitInstruction(Instruction & I)979*9880d681SAndroid Build Coastguard Worker void visitInstruction(Instruction &I) { PI.setAborted(&I); }
980*9880d681SAndroid Build Coastguard Worker };
981*9880d681SAndroid Build Coastguard Worker
AllocaSlices(const DataLayout & DL,AllocaInst & AI)982*9880d681SAndroid Build Coastguard Worker AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
983*9880d681SAndroid Build Coastguard Worker :
984*9880d681SAndroid Build Coastguard Worker #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
985*9880d681SAndroid Build Coastguard Worker AI(AI),
986*9880d681SAndroid Build Coastguard Worker #endif
987*9880d681SAndroid Build Coastguard Worker PointerEscapingInstr(nullptr) {
988*9880d681SAndroid Build Coastguard Worker SliceBuilder PB(DL, AI, *this);
989*9880d681SAndroid Build Coastguard Worker SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
990*9880d681SAndroid Build Coastguard Worker if (PtrI.isEscaped() || PtrI.isAborted()) {
991*9880d681SAndroid Build Coastguard Worker // FIXME: We should sink the escape vs. abort info into the caller nicely,
992*9880d681SAndroid Build Coastguard Worker // possibly by just storing the PtrInfo in the AllocaSlices.
993*9880d681SAndroid Build Coastguard Worker PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
994*9880d681SAndroid Build Coastguard Worker : PtrI.getAbortingInst();
995*9880d681SAndroid Build Coastguard Worker assert(PointerEscapingInstr && "Did not track a bad instruction");
996*9880d681SAndroid Build Coastguard Worker return;
997*9880d681SAndroid Build Coastguard Worker }
998*9880d681SAndroid Build Coastguard Worker
999*9880d681SAndroid Build Coastguard Worker Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
1000*9880d681SAndroid Build Coastguard Worker [](const Slice &S) {
1001*9880d681SAndroid Build Coastguard Worker return S.isDead();
1002*9880d681SAndroid Build Coastguard Worker }),
1003*9880d681SAndroid Build Coastguard Worker Slices.end());
1004*9880d681SAndroid Build Coastguard Worker
1005*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
1006*9880d681SAndroid Build Coastguard Worker if (SROARandomShuffleSlices) {
1007*9880d681SAndroid Build Coastguard Worker std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1008*9880d681SAndroid Build Coastguard Worker std::shuffle(Slices.begin(), Slices.end(), MT);
1009*9880d681SAndroid Build Coastguard Worker }
1010*9880d681SAndroid Build Coastguard Worker #endif
1011*9880d681SAndroid Build Coastguard Worker
1012*9880d681SAndroid Build Coastguard Worker // Sort the uses. This arranges for the offsets to be in ascending order,
1013*9880d681SAndroid Build Coastguard Worker // and the sizes to be in descending order.
1014*9880d681SAndroid Build Coastguard Worker std::sort(Slices.begin(), Slices.end());
1015*9880d681SAndroid Build Coastguard Worker }
1016*9880d681SAndroid Build Coastguard Worker
1017*9880d681SAndroid Build Coastguard Worker #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1018*9880d681SAndroid Build Coastguard Worker
print(raw_ostream & OS,const_iterator I,StringRef Indent) const1019*9880d681SAndroid Build Coastguard Worker void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1020*9880d681SAndroid Build Coastguard Worker StringRef Indent) const {
1021*9880d681SAndroid Build Coastguard Worker printSlice(OS, I, Indent);
1022*9880d681SAndroid Build Coastguard Worker OS << "\n";
1023*9880d681SAndroid Build Coastguard Worker printUse(OS, I, Indent);
1024*9880d681SAndroid Build Coastguard Worker }
1025*9880d681SAndroid Build Coastguard Worker
printSlice(raw_ostream & OS,const_iterator I,StringRef Indent) const1026*9880d681SAndroid Build Coastguard Worker void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1027*9880d681SAndroid Build Coastguard Worker StringRef Indent) const {
1028*9880d681SAndroid Build Coastguard Worker OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1029*9880d681SAndroid Build Coastguard Worker << " slice #" << (I - begin())
1030*9880d681SAndroid Build Coastguard Worker << (I->isSplittable() ? " (splittable)" : "");
1031*9880d681SAndroid Build Coastguard Worker }
1032*9880d681SAndroid Build Coastguard Worker
printUse(raw_ostream & OS,const_iterator I,StringRef Indent) const1033*9880d681SAndroid Build Coastguard Worker void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1034*9880d681SAndroid Build Coastguard Worker StringRef Indent) const {
1035*9880d681SAndroid Build Coastguard Worker OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1036*9880d681SAndroid Build Coastguard Worker }
1037*9880d681SAndroid Build Coastguard Worker
print(raw_ostream & OS) const1038*9880d681SAndroid Build Coastguard Worker void AllocaSlices::print(raw_ostream &OS) const {
1039*9880d681SAndroid Build Coastguard Worker if (PointerEscapingInstr) {
1040*9880d681SAndroid Build Coastguard Worker OS << "Can't analyze slices for alloca: " << AI << "\n"
1041*9880d681SAndroid Build Coastguard Worker << " A pointer to this alloca escaped by:\n"
1042*9880d681SAndroid Build Coastguard Worker << " " << *PointerEscapingInstr << "\n";
1043*9880d681SAndroid Build Coastguard Worker return;
1044*9880d681SAndroid Build Coastguard Worker }
1045*9880d681SAndroid Build Coastguard Worker
1046*9880d681SAndroid Build Coastguard Worker OS << "Slices of alloca: " << AI << "\n";
1047*9880d681SAndroid Build Coastguard Worker for (const_iterator I = begin(), E = end(); I != E; ++I)
1048*9880d681SAndroid Build Coastguard Worker print(OS, I);
1049*9880d681SAndroid Build Coastguard Worker }
1050*9880d681SAndroid Build Coastguard Worker
dump(const_iterator I) const1051*9880d681SAndroid Build Coastguard Worker LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1052*9880d681SAndroid Build Coastguard Worker print(dbgs(), I);
1053*9880d681SAndroid Build Coastguard Worker }
dump() const1054*9880d681SAndroid Build Coastguard Worker LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1055*9880d681SAndroid Build Coastguard Worker
1056*9880d681SAndroid Build Coastguard Worker #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1057*9880d681SAndroid Build Coastguard Worker
1058*9880d681SAndroid Build Coastguard Worker /// Walk the range of a partitioning looking for a common type to cover this
1059*9880d681SAndroid Build Coastguard Worker /// sequence of slices.
findCommonType(AllocaSlices::const_iterator B,AllocaSlices::const_iterator E,uint64_t EndOffset)1060*9880d681SAndroid Build Coastguard Worker static Type *findCommonType(AllocaSlices::const_iterator B,
1061*9880d681SAndroid Build Coastguard Worker AllocaSlices::const_iterator E,
1062*9880d681SAndroid Build Coastguard Worker uint64_t EndOffset) {
1063*9880d681SAndroid Build Coastguard Worker Type *Ty = nullptr;
1064*9880d681SAndroid Build Coastguard Worker bool TyIsCommon = true;
1065*9880d681SAndroid Build Coastguard Worker IntegerType *ITy = nullptr;
1066*9880d681SAndroid Build Coastguard Worker
1067*9880d681SAndroid Build Coastguard Worker // Note that we need to look at *every* alloca slice's Use to ensure we
1068*9880d681SAndroid Build Coastguard Worker // always get consistent results regardless of the order of slices.
1069*9880d681SAndroid Build Coastguard Worker for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1070*9880d681SAndroid Build Coastguard Worker Use *U = I->getUse();
1071*9880d681SAndroid Build Coastguard Worker if (isa<IntrinsicInst>(*U->getUser()))
1072*9880d681SAndroid Build Coastguard Worker continue;
1073*9880d681SAndroid Build Coastguard Worker if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1074*9880d681SAndroid Build Coastguard Worker continue;
1075*9880d681SAndroid Build Coastguard Worker
1076*9880d681SAndroid Build Coastguard Worker Type *UserTy = nullptr;
1077*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1078*9880d681SAndroid Build Coastguard Worker UserTy = LI->getType();
1079*9880d681SAndroid Build Coastguard Worker } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1080*9880d681SAndroid Build Coastguard Worker UserTy = SI->getValueOperand()->getType();
1081*9880d681SAndroid Build Coastguard Worker }
1082*9880d681SAndroid Build Coastguard Worker
1083*9880d681SAndroid Build Coastguard Worker if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1084*9880d681SAndroid Build Coastguard Worker // If the type is larger than the partition, skip it. We only encounter
1085*9880d681SAndroid Build Coastguard Worker // this for split integer operations where we want to use the type of the
1086*9880d681SAndroid Build Coastguard Worker // entity causing the split. Also skip if the type is not a byte width
1087*9880d681SAndroid Build Coastguard Worker // multiple.
1088*9880d681SAndroid Build Coastguard Worker if (UserITy->getBitWidth() % 8 != 0 ||
1089*9880d681SAndroid Build Coastguard Worker UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1090*9880d681SAndroid Build Coastguard Worker continue;
1091*9880d681SAndroid Build Coastguard Worker
1092*9880d681SAndroid Build Coastguard Worker // Track the largest bitwidth integer type used in this way in case there
1093*9880d681SAndroid Build Coastguard Worker // is no common type.
1094*9880d681SAndroid Build Coastguard Worker if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1095*9880d681SAndroid Build Coastguard Worker ITy = UserITy;
1096*9880d681SAndroid Build Coastguard Worker }
1097*9880d681SAndroid Build Coastguard Worker
1098*9880d681SAndroid Build Coastguard Worker // To avoid depending on the order of slices, Ty and TyIsCommon must not
1099*9880d681SAndroid Build Coastguard Worker // depend on types skipped above.
1100*9880d681SAndroid Build Coastguard Worker if (!UserTy || (Ty && Ty != UserTy))
1101*9880d681SAndroid Build Coastguard Worker TyIsCommon = false; // Give up on anything but an iN type.
1102*9880d681SAndroid Build Coastguard Worker else
1103*9880d681SAndroid Build Coastguard Worker Ty = UserTy;
1104*9880d681SAndroid Build Coastguard Worker }
1105*9880d681SAndroid Build Coastguard Worker
1106*9880d681SAndroid Build Coastguard Worker return TyIsCommon ? Ty : ITy;
1107*9880d681SAndroid Build Coastguard Worker }
1108*9880d681SAndroid Build Coastguard Worker
1109*9880d681SAndroid Build Coastguard Worker /// PHI instructions that use an alloca and are subsequently loaded can be
1110*9880d681SAndroid Build Coastguard Worker /// rewritten to load both input pointers in the pred blocks and then PHI the
1111*9880d681SAndroid Build Coastguard Worker /// results, allowing the load of the alloca to be promoted.
1112*9880d681SAndroid Build Coastguard Worker /// From this:
1113*9880d681SAndroid Build Coastguard Worker /// %P2 = phi [i32* %Alloca, i32* %Other]
1114*9880d681SAndroid Build Coastguard Worker /// %V = load i32* %P2
1115*9880d681SAndroid Build Coastguard Worker /// to:
1116*9880d681SAndroid Build Coastguard Worker /// %V1 = load i32* %Alloca -> will be mem2reg'd
1117*9880d681SAndroid Build Coastguard Worker /// ...
1118*9880d681SAndroid Build Coastguard Worker /// %V2 = load i32* %Other
1119*9880d681SAndroid Build Coastguard Worker /// ...
1120*9880d681SAndroid Build Coastguard Worker /// %V = phi [i32 %V1, i32 %V2]
1121*9880d681SAndroid Build Coastguard Worker ///
1122*9880d681SAndroid Build Coastguard Worker /// We can do this to a select if its only uses are loads and if the operands
1123*9880d681SAndroid Build Coastguard Worker /// to the select can be loaded unconditionally.
1124*9880d681SAndroid Build Coastguard Worker ///
1125*9880d681SAndroid Build Coastguard Worker /// FIXME: This should be hoisted into a generic utility, likely in
1126*9880d681SAndroid Build Coastguard Worker /// Transforms/Util/Local.h
isSafePHIToSpeculate(PHINode & PN)1127*9880d681SAndroid Build Coastguard Worker static bool isSafePHIToSpeculate(PHINode &PN) {
1128*9880d681SAndroid Build Coastguard Worker // For now, we can only do this promotion if the load is in the same block
1129*9880d681SAndroid Build Coastguard Worker // as the PHI, and if there are no stores between the phi and load.
1130*9880d681SAndroid Build Coastguard Worker // TODO: Allow recursive phi users.
1131*9880d681SAndroid Build Coastguard Worker // TODO: Allow stores.
1132*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = PN.getParent();
1133*9880d681SAndroid Build Coastguard Worker unsigned MaxAlign = 0;
1134*9880d681SAndroid Build Coastguard Worker bool HaveLoad = false;
1135*9880d681SAndroid Build Coastguard Worker for (User *U : PN.users()) {
1136*9880d681SAndroid Build Coastguard Worker LoadInst *LI = dyn_cast<LoadInst>(U);
1137*9880d681SAndroid Build Coastguard Worker if (!LI || !LI->isSimple())
1138*9880d681SAndroid Build Coastguard Worker return false;
1139*9880d681SAndroid Build Coastguard Worker
1140*9880d681SAndroid Build Coastguard Worker // For now we only allow loads in the same block as the PHI. This is
1141*9880d681SAndroid Build Coastguard Worker // a common case that happens when instcombine merges two loads through
1142*9880d681SAndroid Build Coastguard Worker // a PHI.
1143*9880d681SAndroid Build Coastguard Worker if (LI->getParent() != BB)
1144*9880d681SAndroid Build Coastguard Worker return false;
1145*9880d681SAndroid Build Coastguard Worker
1146*9880d681SAndroid Build Coastguard Worker // Ensure that there are no instructions between the PHI and the load that
1147*9880d681SAndroid Build Coastguard Worker // could store.
1148*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1149*9880d681SAndroid Build Coastguard Worker if (BBI->mayWriteToMemory())
1150*9880d681SAndroid Build Coastguard Worker return false;
1151*9880d681SAndroid Build Coastguard Worker
1152*9880d681SAndroid Build Coastguard Worker MaxAlign = std::max(MaxAlign, LI->getAlignment());
1153*9880d681SAndroid Build Coastguard Worker HaveLoad = true;
1154*9880d681SAndroid Build Coastguard Worker }
1155*9880d681SAndroid Build Coastguard Worker
1156*9880d681SAndroid Build Coastguard Worker if (!HaveLoad)
1157*9880d681SAndroid Build Coastguard Worker return false;
1158*9880d681SAndroid Build Coastguard Worker
1159*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = PN.getModule()->getDataLayout();
1160*9880d681SAndroid Build Coastguard Worker
1161*9880d681SAndroid Build Coastguard Worker // We can only transform this if it is safe to push the loads into the
1162*9880d681SAndroid Build Coastguard Worker // predecessor blocks. The only thing to watch out for is that we can't put
1163*9880d681SAndroid Build Coastguard Worker // a possibly trapping load in the predecessor if it is a critical edge.
1164*9880d681SAndroid Build Coastguard Worker for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1165*9880d681SAndroid Build Coastguard Worker TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1166*9880d681SAndroid Build Coastguard Worker Value *InVal = PN.getIncomingValue(Idx);
1167*9880d681SAndroid Build Coastguard Worker
1168*9880d681SAndroid Build Coastguard Worker // If the value is produced by the terminator of the predecessor (an
1169*9880d681SAndroid Build Coastguard Worker // invoke) or it has side-effects, there is no valid place to put a load
1170*9880d681SAndroid Build Coastguard Worker // in the predecessor.
1171*9880d681SAndroid Build Coastguard Worker if (TI == InVal || TI->mayHaveSideEffects())
1172*9880d681SAndroid Build Coastguard Worker return false;
1173*9880d681SAndroid Build Coastguard Worker
1174*9880d681SAndroid Build Coastguard Worker // If the predecessor has a single successor, then the edge isn't
1175*9880d681SAndroid Build Coastguard Worker // critical.
1176*9880d681SAndroid Build Coastguard Worker if (TI->getNumSuccessors() == 1)
1177*9880d681SAndroid Build Coastguard Worker continue;
1178*9880d681SAndroid Build Coastguard Worker
1179*9880d681SAndroid Build Coastguard Worker // If this pointer is always safe to load, or if we can prove that there
1180*9880d681SAndroid Build Coastguard Worker // is already a load in the block, then we can move the load to the pred
1181*9880d681SAndroid Build Coastguard Worker // block.
1182*9880d681SAndroid Build Coastguard Worker if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
1183*9880d681SAndroid Build Coastguard Worker continue;
1184*9880d681SAndroid Build Coastguard Worker
1185*9880d681SAndroid Build Coastguard Worker return false;
1186*9880d681SAndroid Build Coastguard Worker }
1187*9880d681SAndroid Build Coastguard Worker
1188*9880d681SAndroid Build Coastguard Worker return true;
1189*9880d681SAndroid Build Coastguard Worker }
1190*9880d681SAndroid Build Coastguard Worker
speculatePHINodeLoads(PHINode & PN)1191*9880d681SAndroid Build Coastguard Worker static void speculatePHINodeLoads(PHINode &PN) {
1192*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << PN << "\n");
1193*9880d681SAndroid Build Coastguard Worker
1194*9880d681SAndroid Build Coastguard Worker Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1195*9880d681SAndroid Build Coastguard Worker IRBuilderTy PHIBuilder(&PN);
1196*9880d681SAndroid Build Coastguard Worker PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1197*9880d681SAndroid Build Coastguard Worker PN.getName() + ".sroa.speculated");
1198*9880d681SAndroid Build Coastguard Worker
1199*9880d681SAndroid Build Coastguard Worker // Get the AA tags and alignment to use from one of the loads. It doesn't
1200*9880d681SAndroid Build Coastguard Worker // matter which one we get and if any differ.
1201*9880d681SAndroid Build Coastguard Worker LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1202*9880d681SAndroid Build Coastguard Worker
1203*9880d681SAndroid Build Coastguard Worker AAMDNodes AATags;
1204*9880d681SAndroid Build Coastguard Worker SomeLoad->getAAMetadata(AATags);
1205*9880d681SAndroid Build Coastguard Worker unsigned Align = SomeLoad->getAlignment();
1206*9880d681SAndroid Build Coastguard Worker
1207*9880d681SAndroid Build Coastguard Worker // Rewrite all loads of the PN to use the new PHI.
1208*9880d681SAndroid Build Coastguard Worker while (!PN.use_empty()) {
1209*9880d681SAndroid Build Coastguard Worker LoadInst *LI = cast<LoadInst>(PN.user_back());
1210*9880d681SAndroid Build Coastguard Worker LI->replaceAllUsesWith(NewPN);
1211*9880d681SAndroid Build Coastguard Worker LI->eraseFromParent();
1212*9880d681SAndroid Build Coastguard Worker }
1213*9880d681SAndroid Build Coastguard Worker
1214*9880d681SAndroid Build Coastguard Worker // Inject loads into all of the pred blocks.
1215*9880d681SAndroid Build Coastguard Worker for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1216*9880d681SAndroid Build Coastguard Worker BasicBlock *Pred = PN.getIncomingBlock(Idx);
1217*9880d681SAndroid Build Coastguard Worker TerminatorInst *TI = Pred->getTerminator();
1218*9880d681SAndroid Build Coastguard Worker Value *InVal = PN.getIncomingValue(Idx);
1219*9880d681SAndroid Build Coastguard Worker IRBuilderTy PredBuilder(TI);
1220*9880d681SAndroid Build Coastguard Worker
1221*9880d681SAndroid Build Coastguard Worker LoadInst *Load = PredBuilder.CreateLoad(
1222*9880d681SAndroid Build Coastguard Worker InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1223*9880d681SAndroid Build Coastguard Worker ++NumLoadsSpeculated;
1224*9880d681SAndroid Build Coastguard Worker Load->setAlignment(Align);
1225*9880d681SAndroid Build Coastguard Worker if (AATags)
1226*9880d681SAndroid Build Coastguard Worker Load->setAAMetadata(AATags);
1227*9880d681SAndroid Build Coastguard Worker NewPN->addIncoming(Load, Pred);
1228*9880d681SAndroid Build Coastguard Worker }
1229*9880d681SAndroid Build Coastguard Worker
1230*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1231*9880d681SAndroid Build Coastguard Worker PN.eraseFromParent();
1232*9880d681SAndroid Build Coastguard Worker }
1233*9880d681SAndroid Build Coastguard Worker
1234*9880d681SAndroid Build Coastguard Worker /// Select instructions that use an alloca and are subsequently loaded can be
1235*9880d681SAndroid Build Coastguard Worker /// rewritten to load both input pointers and then select between the result,
1236*9880d681SAndroid Build Coastguard Worker /// allowing the load of the alloca to be promoted.
1237*9880d681SAndroid Build Coastguard Worker /// From this:
1238*9880d681SAndroid Build Coastguard Worker /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1239*9880d681SAndroid Build Coastguard Worker /// %V = load i32* %P2
1240*9880d681SAndroid Build Coastguard Worker /// to:
1241*9880d681SAndroid Build Coastguard Worker /// %V1 = load i32* %Alloca -> will be mem2reg'd
1242*9880d681SAndroid Build Coastguard Worker /// %V2 = load i32* %Other
1243*9880d681SAndroid Build Coastguard Worker /// %V = select i1 %cond, i32 %V1, i32 %V2
1244*9880d681SAndroid Build Coastguard Worker ///
1245*9880d681SAndroid Build Coastguard Worker /// We can do this to a select if its only uses are loads and if the operand
1246*9880d681SAndroid Build Coastguard Worker /// to the select can be loaded unconditionally.
isSafeSelectToSpeculate(SelectInst & SI)1247*9880d681SAndroid Build Coastguard Worker static bool isSafeSelectToSpeculate(SelectInst &SI) {
1248*9880d681SAndroid Build Coastguard Worker Value *TValue = SI.getTrueValue();
1249*9880d681SAndroid Build Coastguard Worker Value *FValue = SI.getFalseValue();
1250*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = SI.getModule()->getDataLayout();
1251*9880d681SAndroid Build Coastguard Worker
1252*9880d681SAndroid Build Coastguard Worker for (User *U : SI.users()) {
1253*9880d681SAndroid Build Coastguard Worker LoadInst *LI = dyn_cast<LoadInst>(U);
1254*9880d681SAndroid Build Coastguard Worker if (!LI || !LI->isSimple())
1255*9880d681SAndroid Build Coastguard Worker return false;
1256*9880d681SAndroid Build Coastguard Worker
1257*9880d681SAndroid Build Coastguard Worker // Both operands to the select need to be dereferencable, either
1258*9880d681SAndroid Build Coastguard Worker // absolutely (e.g. allocas) or at this point because we can see other
1259*9880d681SAndroid Build Coastguard Worker // accesses to it.
1260*9880d681SAndroid Build Coastguard Worker if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
1261*9880d681SAndroid Build Coastguard Worker return false;
1262*9880d681SAndroid Build Coastguard Worker if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
1263*9880d681SAndroid Build Coastguard Worker return false;
1264*9880d681SAndroid Build Coastguard Worker }
1265*9880d681SAndroid Build Coastguard Worker
1266*9880d681SAndroid Build Coastguard Worker return true;
1267*9880d681SAndroid Build Coastguard Worker }
1268*9880d681SAndroid Build Coastguard Worker
speculateSelectInstLoads(SelectInst & SI)1269*9880d681SAndroid Build Coastguard Worker static void speculateSelectInstLoads(SelectInst &SI) {
1270*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << SI << "\n");
1271*9880d681SAndroid Build Coastguard Worker
1272*9880d681SAndroid Build Coastguard Worker IRBuilderTy IRB(&SI);
1273*9880d681SAndroid Build Coastguard Worker Value *TV = SI.getTrueValue();
1274*9880d681SAndroid Build Coastguard Worker Value *FV = SI.getFalseValue();
1275*9880d681SAndroid Build Coastguard Worker // Replace the loads of the select with a select of two loads.
1276*9880d681SAndroid Build Coastguard Worker while (!SI.use_empty()) {
1277*9880d681SAndroid Build Coastguard Worker LoadInst *LI = cast<LoadInst>(SI.user_back());
1278*9880d681SAndroid Build Coastguard Worker assert(LI->isSimple() && "We only speculate simple loads");
1279*9880d681SAndroid Build Coastguard Worker
1280*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(LI);
1281*9880d681SAndroid Build Coastguard Worker LoadInst *TL =
1282*9880d681SAndroid Build Coastguard Worker IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1283*9880d681SAndroid Build Coastguard Worker LoadInst *FL =
1284*9880d681SAndroid Build Coastguard Worker IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1285*9880d681SAndroid Build Coastguard Worker NumLoadsSpeculated += 2;
1286*9880d681SAndroid Build Coastguard Worker
1287*9880d681SAndroid Build Coastguard Worker // Transfer alignment and AA info if present.
1288*9880d681SAndroid Build Coastguard Worker TL->setAlignment(LI->getAlignment());
1289*9880d681SAndroid Build Coastguard Worker FL->setAlignment(LI->getAlignment());
1290*9880d681SAndroid Build Coastguard Worker
1291*9880d681SAndroid Build Coastguard Worker AAMDNodes Tags;
1292*9880d681SAndroid Build Coastguard Worker LI->getAAMetadata(Tags);
1293*9880d681SAndroid Build Coastguard Worker if (Tags) {
1294*9880d681SAndroid Build Coastguard Worker TL->setAAMetadata(Tags);
1295*9880d681SAndroid Build Coastguard Worker FL->setAAMetadata(Tags);
1296*9880d681SAndroid Build Coastguard Worker }
1297*9880d681SAndroid Build Coastguard Worker
1298*9880d681SAndroid Build Coastguard Worker Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1299*9880d681SAndroid Build Coastguard Worker LI->getName() + ".sroa.speculated");
1300*9880d681SAndroid Build Coastguard Worker
1301*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " speculated to: " << *V << "\n");
1302*9880d681SAndroid Build Coastguard Worker LI->replaceAllUsesWith(V);
1303*9880d681SAndroid Build Coastguard Worker LI->eraseFromParent();
1304*9880d681SAndroid Build Coastguard Worker }
1305*9880d681SAndroid Build Coastguard Worker SI.eraseFromParent();
1306*9880d681SAndroid Build Coastguard Worker }
1307*9880d681SAndroid Build Coastguard Worker
1308*9880d681SAndroid Build Coastguard Worker /// \brief Build a GEP out of a base pointer and indices.
1309*9880d681SAndroid Build Coastguard Worker ///
1310*9880d681SAndroid Build Coastguard Worker /// This will return the BasePtr if that is valid, or build a new GEP
1311*9880d681SAndroid Build Coastguard Worker /// instruction using the IRBuilder if GEP-ing is needed.
buildGEP(IRBuilderTy & IRB,Value * BasePtr,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1312*9880d681SAndroid Build Coastguard Worker static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1313*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1314*9880d681SAndroid Build Coastguard Worker if (Indices.empty())
1315*9880d681SAndroid Build Coastguard Worker return BasePtr;
1316*9880d681SAndroid Build Coastguard Worker
1317*9880d681SAndroid Build Coastguard Worker // A single zero index is a no-op, so check for this and avoid building a GEP
1318*9880d681SAndroid Build Coastguard Worker // in that case.
1319*9880d681SAndroid Build Coastguard Worker if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1320*9880d681SAndroid Build Coastguard Worker return BasePtr;
1321*9880d681SAndroid Build Coastguard Worker
1322*9880d681SAndroid Build Coastguard Worker return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1323*9880d681SAndroid Build Coastguard Worker NamePrefix + "sroa_idx");
1324*9880d681SAndroid Build Coastguard Worker }
1325*9880d681SAndroid Build Coastguard Worker
1326*9880d681SAndroid Build Coastguard Worker /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1327*9880d681SAndroid Build Coastguard Worker /// TargetTy without changing the offset of the pointer.
1328*9880d681SAndroid Build Coastguard Worker ///
1329*9880d681SAndroid Build Coastguard Worker /// This routine assumes we've already established a properly offset GEP with
1330*9880d681SAndroid Build Coastguard Worker /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1331*9880d681SAndroid Build Coastguard Worker /// zero-indices down through type layers until we find one the same as
1332*9880d681SAndroid Build Coastguard Worker /// TargetTy. If we can't find one with the same type, we at least try to use
1333*9880d681SAndroid Build Coastguard Worker /// one with the same size. If none of that works, we just produce the GEP as
1334*9880d681SAndroid Build Coastguard Worker /// indicated by Indices to have the correct offset.
getNaturalGEPWithType(IRBuilderTy & IRB,const DataLayout & DL,Value * BasePtr,Type * Ty,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1335*9880d681SAndroid Build Coastguard Worker static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1336*9880d681SAndroid Build Coastguard Worker Value *BasePtr, Type *Ty, Type *TargetTy,
1337*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Value *> &Indices,
1338*9880d681SAndroid Build Coastguard Worker Twine NamePrefix) {
1339*9880d681SAndroid Build Coastguard Worker if (Ty == TargetTy)
1340*9880d681SAndroid Build Coastguard Worker return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1341*9880d681SAndroid Build Coastguard Worker
1342*9880d681SAndroid Build Coastguard Worker // Pointer size to use for the indices.
1343*9880d681SAndroid Build Coastguard Worker unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1344*9880d681SAndroid Build Coastguard Worker
1345*9880d681SAndroid Build Coastguard Worker // See if we can descend into a struct and locate a field with the correct
1346*9880d681SAndroid Build Coastguard Worker // type.
1347*9880d681SAndroid Build Coastguard Worker unsigned NumLayers = 0;
1348*9880d681SAndroid Build Coastguard Worker Type *ElementTy = Ty;
1349*9880d681SAndroid Build Coastguard Worker do {
1350*9880d681SAndroid Build Coastguard Worker if (ElementTy->isPointerTy())
1351*9880d681SAndroid Build Coastguard Worker break;
1352*9880d681SAndroid Build Coastguard Worker
1353*9880d681SAndroid Build Coastguard Worker if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1354*9880d681SAndroid Build Coastguard Worker ElementTy = ArrayTy->getElementType();
1355*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getIntN(PtrSize, 0));
1356*9880d681SAndroid Build Coastguard Worker } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1357*9880d681SAndroid Build Coastguard Worker ElementTy = VectorTy->getElementType();
1358*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getInt32(0));
1359*9880d681SAndroid Build Coastguard Worker } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1360*9880d681SAndroid Build Coastguard Worker if (STy->element_begin() == STy->element_end())
1361*9880d681SAndroid Build Coastguard Worker break; // Nothing left to descend into.
1362*9880d681SAndroid Build Coastguard Worker ElementTy = *STy->element_begin();
1363*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getInt32(0));
1364*9880d681SAndroid Build Coastguard Worker } else {
1365*9880d681SAndroid Build Coastguard Worker break;
1366*9880d681SAndroid Build Coastguard Worker }
1367*9880d681SAndroid Build Coastguard Worker ++NumLayers;
1368*9880d681SAndroid Build Coastguard Worker } while (ElementTy != TargetTy);
1369*9880d681SAndroid Build Coastguard Worker if (ElementTy != TargetTy)
1370*9880d681SAndroid Build Coastguard Worker Indices.erase(Indices.end() - NumLayers, Indices.end());
1371*9880d681SAndroid Build Coastguard Worker
1372*9880d681SAndroid Build Coastguard Worker return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1373*9880d681SAndroid Build Coastguard Worker }
1374*9880d681SAndroid Build Coastguard Worker
1375*9880d681SAndroid Build Coastguard Worker /// \brief Recursively compute indices for a natural GEP.
1376*9880d681SAndroid Build Coastguard Worker ///
1377*9880d681SAndroid Build Coastguard Worker /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1378*9880d681SAndroid Build Coastguard Worker /// element types adding appropriate indices for the GEP.
getNaturalGEPRecursively(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,Type * Ty,APInt & Offset,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1379*9880d681SAndroid Build Coastguard Worker static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1380*9880d681SAndroid Build Coastguard Worker Value *Ptr, Type *Ty, APInt &Offset,
1381*9880d681SAndroid Build Coastguard Worker Type *TargetTy,
1382*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Value *> &Indices,
1383*9880d681SAndroid Build Coastguard Worker Twine NamePrefix) {
1384*9880d681SAndroid Build Coastguard Worker if (Offset == 0)
1385*9880d681SAndroid Build Coastguard Worker return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1386*9880d681SAndroid Build Coastguard Worker NamePrefix);
1387*9880d681SAndroid Build Coastguard Worker
1388*9880d681SAndroid Build Coastguard Worker // We can't recurse through pointer types.
1389*9880d681SAndroid Build Coastguard Worker if (Ty->isPointerTy())
1390*9880d681SAndroid Build Coastguard Worker return nullptr;
1391*9880d681SAndroid Build Coastguard Worker
1392*9880d681SAndroid Build Coastguard Worker // We try to analyze GEPs over vectors here, but note that these GEPs are
1393*9880d681SAndroid Build Coastguard Worker // extremely poorly defined currently. The long-term goal is to remove GEPing
1394*9880d681SAndroid Build Coastguard Worker // over a vector from the IR completely.
1395*9880d681SAndroid Build Coastguard Worker if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1396*9880d681SAndroid Build Coastguard Worker unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1397*9880d681SAndroid Build Coastguard Worker if (ElementSizeInBits % 8 != 0) {
1398*9880d681SAndroid Build Coastguard Worker // GEPs over non-multiple of 8 size vector elements are invalid.
1399*9880d681SAndroid Build Coastguard Worker return nullptr;
1400*9880d681SAndroid Build Coastguard Worker }
1401*9880d681SAndroid Build Coastguard Worker APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1402*9880d681SAndroid Build Coastguard Worker APInt NumSkippedElements = Offset.sdiv(ElementSize);
1403*9880d681SAndroid Build Coastguard Worker if (NumSkippedElements.ugt(VecTy->getNumElements()))
1404*9880d681SAndroid Build Coastguard Worker return nullptr;
1405*9880d681SAndroid Build Coastguard Worker Offset -= NumSkippedElements * ElementSize;
1406*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getInt(NumSkippedElements));
1407*9880d681SAndroid Build Coastguard Worker return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1408*9880d681SAndroid Build Coastguard Worker Offset, TargetTy, Indices, NamePrefix);
1409*9880d681SAndroid Build Coastguard Worker }
1410*9880d681SAndroid Build Coastguard Worker
1411*9880d681SAndroid Build Coastguard Worker if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1412*9880d681SAndroid Build Coastguard Worker Type *ElementTy = ArrTy->getElementType();
1413*9880d681SAndroid Build Coastguard Worker APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1414*9880d681SAndroid Build Coastguard Worker APInt NumSkippedElements = Offset.sdiv(ElementSize);
1415*9880d681SAndroid Build Coastguard Worker if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1416*9880d681SAndroid Build Coastguard Worker return nullptr;
1417*9880d681SAndroid Build Coastguard Worker
1418*9880d681SAndroid Build Coastguard Worker Offset -= NumSkippedElements * ElementSize;
1419*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getInt(NumSkippedElements));
1420*9880d681SAndroid Build Coastguard Worker return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1421*9880d681SAndroid Build Coastguard Worker Indices, NamePrefix);
1422*9880d681SAndroid Build Coastguard Worker }
1423*9880d681SAndroid Build Coastguard Worker
1424*9880d681SAndroid Build Coastguard Worker StructType *STy = dyn_cast<StructType>(Ty);
1425*9880d681SAndroid Build Coastguard Worker if (!STy)
1426*9880d681SAndroid Build Coastguard Worker return nullptr;
1427*9880d681SAndroid Build Coastguard Worker
1428*9880d681SAndroid Build Coastguard Worker const StructLayout *SL = DL.getStructLayout(STy);
1429*9880d681SAndroid Build Coastguard Worker uint64_t StructOffset = Offset.getZExtValue();
1430*9880d681SAndroid Build Coastguard Worker if (StructOffset >= SL->getSizeInBytes())
1431*9880d681SAndroid Build Coastguard Worker return nullptr;
1432*9880d681SAndroid Build Coastguard Worker unsigned Index = SL->getElementContainingOffset(StructOffset);
1433*9880d681SAndroid Build Coastguard Worker Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1434*9880d681SAndroid Build Coastguard Worker Type *ElementTy = STy->getElementType(Index);
1435*9880d681SAndroid Build Coastguard Worker if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1436*9880d681SAndroid Build Coastguard Worker return nullptr; // The offset points into alignment padding.
1437*9880d681SAndroid Build Coastguard Worker
1438*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getInt32(Index));
1439*9880d681SAndroid Build Coastguard Worker return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1440*9880d681SAndroid Build Coastguard Worker Indices, NamePrefix);
1441*9880d681SAndroid Build Coastguard Worker }
1442*9880d681SAndroid Build Coastguard Worker
1443*9880d681SAndroid Build Coastguard Worker /// \brief Get a natural GEP from a base pointer to a particular offset and
1444*9880d681SAndroid Build Coastguard Worker /// resulting in a particular type.
1445*9880d681SAndroid Build Coastguard Worker ///
1446*9880d681SAndroid Build Coastguard Worker /// The goal is to produce a "natural" looking GEP that works with the existing
1447*9880d681SAndroid Build Coastguard Worker /// composite types to arrive at the appropriate offset and element type for
1448*9880d681SAndroid Build Coastguard Worker /// a pointer. TargetTy is the element type the returned GEP should point-to if
1449*9880d681SAndroid Build Coastguard Worker /// possible. We recurse by decreasing Offset, adding the appropriate index to
1450*9880d681SAndroid Build Coastguard Worker /// Indices, and setting Ty to the result subtype.
1451*9880d681SAndroid Build Coastguard Worker ///
1452*9880d681SAndroid Build Coastguard Worker /// If no natural GEP can be constructed, this function returns null.
getNaturalGEPWithOffset(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * TargetTy,SmallVectorImpl<Value * > & Indices,Twine NamePrefix)1453*9880d681SAndroid Build Coastguard Worker static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1454*9880d681SAndroid Build Coastguard Worker Value *Ptr, APInt Offset, Type *TargetTy,
1455*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Value *> &Indices,
1456*9880d681SAndroid Build Coastguard Worker Twine NamePrefix) {
1457*9880d681SAndroid Build Coastguard Worker PointerType *Ty = cast<PointerType>(Ptr->getType());
1458*9880d681SAndroid Build Coastguard Worker
1459*9880d681SAndroid Build Coastguard Worker // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1460*9880d681SAndroid Build Coastguard Worker // an i8.
1461*9880d681SAndroid Build Coastguard Worker if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1462*9880d681SAndroid Build Coastguard Worker return nullptr;
1463*9880d681SAndroid Build Coastguard Worker
1464*9880d681SAndroid Build Coastguard Worker Type *ElementTy = Ty->getElementType();
1465*9880d681SAndroid Build Coastguard Worker if (!ElementTy->isSized())
1466*9880d681SAndroid Build Coastguard Worker return nullptr; // We can't GEP through an unsized element.
1467*9880d681SAndroid Build Coastguard Worker APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1468*9880d681SAndroid Build Coastguard Worker if (ElementSize == 0)
1469*9880d681SAndroid Build Coastguard Worker return nullptr; // Zero-length arrays can't help us build a natural GEP.
1470*9880d681SAndroid Build Coastguard Worker APInt NumSkippedElements = Offset.sdiv(ElementSize);
1471*9880d681SAndroid Build Coastguard Worker
1472*9880d681SAndroid Build Coastguard Worker Offset -= NumSkippedElements * ElementSize;
1473*9880d681SAndroid Build Coastguard Worker Indices.push_back(IRB.getInt(NumSkippedElements));
1474*9880d681SAndroid Build Coastguard Worker return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1475*9880d681SAndroid Build Coastguard Worker Indices, NamePrefix);
1476*9880d681SAndroid Build Coastguard Worker }
1477*9880d681SAndroid Build Coastguard Worker
1478*9880d681SAndroid Build Coastguard Worker /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1479*9880d681SAndroid Build Coastguard Worker /// resulting pointer has PointerTy.
1480*9880d681SAndroid Build Coastguard Worker ///
1481*9880d681SAndroid Build Coastguard Worker /// This tries very hard to compute a "natural" GEP which arrives at the offset
1482*9880d681SAndroid Build Coastguard Worker /// and produces the pointer type desired. Where it cannot, it will try to use
1483*9880d681SAndroid Build Coastguard Worker /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1484*9880d681SAndroid Build Coastguard Worker /// fails, it will try to use an existing i8* and GEP to the byte offset and
1485*9880d681SAndroid Build Coastguard Worker /// bitcast to the type.
1486*9880d681SAndroid Build Coastguard Worker ///
1487*9880d681SAndroid Build Coastguard Worker /// The strategy for finding the more natural GEPs is to peel off layers of the
1488*9880d681SAndroid Build Coastguard Worker /// pointer, walking back through bit casts and GEPs, searching for a base
1489*9880d681SAndroid Build Coastguard Worker /// pointer from which we can compute a natural GEP with the desired
1490*9880d681SAndroid Build Coastguard Worker /// properties. The algorithm tries to fold as many constant indices into
1491*9880d681SAndroid Build Coastguard Worker /// a single GEP as possible, thus making each GEP more independent of the
1492*9880d681SAndroid Build Coastguard Worker /// surrounding code.
getAdjustedPtr(IRBuilderTy & IRB,const DataLayout & DL,Value * Ptr,APInt Offset,Type * PointerTy,Twine NamePrefix)1493*9880d681SAndroid Build Coastguard Worker static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1494*9880d681SAndroid Build Coastguard Worker APInt Offset, Type *PointerTy, Twine NamePrefix) {
1495*9880d681SAndroid Build Coastguard Worker // Even though we don't look through PHI nodes, we could be called on an
1496*9880d681SAndroid Build Coastguard Worker // instruction in an unreachable block, which may be on a cycle.
1497*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Value *, 4> Visited;
1498*9880d681SAndroid Build Coastguard Worker Visited.insert(Ptr);
1499*9880d681SAndroid Build Coastguard Worker SmallVector<Value *, 4> Indices;
1500*9880d681SAndroid Build Coastguard Worker
1501*9880d681SAndroid Build Coastguard Worker // We may end up computing an offset pointer that has the wrong type. If we
1502*9880d681SAndroid Build Coastguard Worker // never are able to compute one directly that has the correct type, we'll
1503*9880d681SAndroid Build Coastguard Worker // fall back to it, so keep it and the base it was computed from around here.
1504*9880d681SAndroid Build Coastguard Worker Value *OffsetPtr = nullptr;
1505*9880d681SAndroid Build Coastguard Worker Value *OffsetBasePtr;
1506*9880d681SAndroid Build Coastguard Worker
1507*9880d681SAndroid Build Coastguard Worker // Remember any i8 pointer we come across to re-use if we need to do a raw
1508*9880d681SAndroid Build Coastguard Worker // byte offset.
1509*9880d681SAndroid Build Coastguard Worker Value *Int8Ptr = nullptr;
1510*9880d681SAndroid Build Coastguard Worker APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1511*9880d681SAndroid Build Coastguard Worker
1512*9880d681SAndroid Build Coastguard Worker Type *TargetTy = PointerTy->getPointerElementType();
1513*9880d681SAndroid Build Coastguard Worker
1514*9880d681SAndroid Build Coastguard Worker do {
1515*9880d681SAndroid Build Coastguard Worker // First fold any existing GEPs into the offset.
1516*9880d681SAndroid Build Coastguard Worker while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1517*9880d681SAndroid Build Coastguard Worker APInt GEPOffset(Offset.getBitWidth(), 0);
1518*9880d681SAndroid Build Coastguard Worker if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1519*9880d681SAndroid Build Coastguard Worker break;
1520*9880d681SAndroid Build Coastguard Worker Offset += GEPOffset;
1521*9880d681SAndroid Build Coastguard Worker Ptr = GEP->getPointerOperand();
1522*9880d681SAndroid Build Coastguard Worker if (!Visited.insert(Ptr).second)
1523*9880d681SAndroid Build Coastguard Worker break;
1524*9880d681SAndroid Build Coastguard Worker }
1525*9880d681SAndroid Build Coastguard Worker
1526*9880d681SAndroid Build Coastguard Worker // See if we can perform a natural GEP here.
1527*9880d681SAndroid Build Coastguard Worker Indices.clear();
1528*9880d681SAndroid Build Coastguard Worker if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1529*9880d681SAndroid Build Coastguard Worker Indices, NamePrefix)) {
1530*9880d681SAndroid Build Coastguard Worker // If we have a new natural pointer at the offset, clear out any old
1531*9880d681SAndroid Build Coastguard Worker // offset pointer we computed. Unless it is the base pointer or
1532*9880d681SAndroid Build Coastguard Worker // a non-instruction, we built a GEP we don't need. Zap it.
1533*9880d681SAndroid Build Coastguard Worker if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1534*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1535*9880d681SAndroid Build Coastguard Worker assert(I->use_empty() && "Built a GEP with uses some how!");
1536*9880d681SAndroid Build Coastguard Worker I->eraseFromParent();
1537*9880d681SAndroid Build Coastguard Worker }
1538*9880d681SAndroid Build Coastguard Worker OffsetPtr = P;
1539*9880d681SAndroid Build Coastguard Worker OffsetBasePtr = Ptr;
1540*9880d681SAndroid Build Coastguard Worker // If we also found a pointer of the right type, we're done.
1541*9880d681SAndroid Build Coastguard Worker if (P->getType() == PointerTy)
1542*9880d681SAndroid Build Coastguard Worker return P;
1543*9880d681SAndroid Build Coastguard Worker }
1544*9880d681SAndroid Build Coastguard Worker
1545*9880d681SAndroid Build Coastguard Worker // Stash this pointer if we've found an i8*.
1546*9880d681SAndroid Build Coastguard Worker if (Ptr->getType()->isIntegerTy(8)) {
1547*9880d681SAndroid Build Coastguard Worker Int8Ptr = Ptr;
1548*9880d681SAndroid Build Coastguard Worker Int8PtrOffset = Offset;
1549*9880d681SAndroid Build Coastguard Worker }
1550*9880d681SAndroid Build Coastguard Worker
1551*9880d681SAndroid Build Coastguard Worker // Peel off a layer of the pointer and update the offset appropriately.
1552*9880d681SAndroid Build Coastguard Worker if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1553*9880d681SAndroid Build Coastguard Worker Ptr = cast<Operator>(Ptr)->getOperand(0);
1554*9880d681SAndroid Build Coastguard Worker } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1555*9880d681SAndroid Build Coastguard Worker if (GA->isInterposable())
1556*9880d681SAndroid Build Coastguard Worker break;
1557*9880d681SAndroid Build Coastguard Worker Ptr = GA->getAliasee();
1558*9880d681SAndroid Build Coastguard Worker } else {
1559*9880d681SAndroid Build Coastguard Worker break;
1560*9880d681SAndroid Build Coastguard Worker }
1561*9880d681SAndroid Build Coastguard Worker assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1562*9880d681SAndroid Build Coastguard Worker } while (Visited.insert(Ptr).second);
1563*9880d681SAndroid Build Coastguard Worker
1564*9880d681SAndroid Build Coastguard Worker if (!OffsetPtr) {
1565*9880d681SAndroid Build Coastguard Worker if (!Int8Ptr) {
1566*9880d681SAndroid Build Coastguard Worker Int8Ptr = IRB.CreateBitCast(
1567*9880d681SAndroid Build Coastguard Worker Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1568*9880d681SAndroid Build Coastguard Worker NamePrefix + "sroa_raw_cast");
1569*9880d681SAndroid Build Coastguard Worker Int8PtrOffset = Offset;
1570*9880d681SAndroid Build Coastguard Worker }
1571*9880d681SAndroid Build Coastguard Worker
1572*9880d681SAndroid Build Coastguard Worker OffsetPtr = Int8PtrOffset == 0
1573*9880d681SAndroid Build Coastguard Worker ? Int8Ptr
1574*9880d681SAndroid Build Coastguard Worker : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1575*9880d681SAndroid Build Coastguard Worker IRB.getInt(Int8PtrOffset),
1576*9880d681SAndroid Build Coastguard Worker NamePrefix + "sroa_raw_idx");
1577*9880d681SAndroid Build Coastguard Worker }
1578*9880d681SAndroid Build Coastguard Worker Ptr = OffsetPtr;
1579*9880d681SAndroid Build Coastguard Worker
1580*9880d681SAndroid Build Coastguard Worker // On the off chance we were targeting i8*, guard the bitcast here.
1581*9880d681SAndroid Build Coastguard Worker if (Ptr->getType() != PointerTy)
1582*9880d681SAndroid Build Coastguard Worker Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1583*9880d681SAndroid Build Coastguard Worker
1584*9880d681SAndroid Build Coastguard Worker return Ptr;
1585*9880d681SAndroid Build Coastguard Worker }
1586*9880d681SAndroid Build Coastguard Worker
1587*9880d681SAndroid Build Coastguard Worker /// \brief Compute the adjusted alignment for a load or store from an offset.
getAdjustedAlignment(Instruction * I,uint64_t Offset,const DataLayout & DL)1588*9880d681SAndroid Build Coastguard Worker static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1589*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
1590*9880d681SAndroid Build Coastguard Worker unsigned Alignment;
1591*9880d681SAndroid Build Coastguard Worker Type *Ty;
1592*9880d681SAndroid Build Coastguard Worker if (auto *LI = dyn_cast<LoadInst>(I)) {
1593*9880d681SAndroid Build Coastguard Worker Alignment = LI->getAlignment();
1594*9880d681SAndroid Build Coastguard Worker Ty = LI->getType();
1595*9880d681SAndroid Build Coastguard Worker } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1596*9880d681SAndroid Build Coastguard Worker Alignment = SI->getAlignment();
1597*9880d681SAndroid Build Coastguard Worker Ty = SI->getValueOperand()->getType();
1598*9880d681SAndroid Build Coastguard Worker } else {
1599*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Only loads and stores are allowed!");
1600*9880d681SAndroid Build Coastguard Worker }
1601*9880d681SAndroid Build Coastguard Worker
1602*9880d681SAndroid Build Coastguard Worker if (!Alignment)
1603*9880d681SAndroid Build Coastguard Worker Alignment = DL.getABITypeAlignment(Ty);
1604*9880d681SAndroid Build Coastguard Worker
1605*9880d681SAndroid Build Coastguard Worker return MinAlign(Alignment, Offset);
1606*9880d681SAndroid Build Coastguard Worker }
1607*9880d681SAndroid Build Coastguard Worker
1608*9880d681SAndroid Build Coastguard Worker /// \brief Test whether we can convert a value from the old to the new type.
1609*9880d681SAndroid Build Coastguard Worker ///
1610*9880d681SAndroid Build Coastguard Worker /// This predicate should be used to guard calls to convertValue in order to
1611*9880d681SAndroid Build Coastguard Worker /// ensure that we only try to convert viable values. The strategy is that we
1612*9880d681SAndroid Build Coastguard Worker /// will peel off single element struct and array wrappings to get to an
1613*9880d681SAndroid Build Coastguard Worker /// underlying value, and convert that value.
canConvertValue(const DataLayout & DL,Type * OldTy,Type * NewTy)1614*9880d681SAndroid Build Coastguard Worker static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1615*9880d681SAndroid Build Coastguard Worker if (OldTy == NewTy)
1616*9880d681SAndroid Build Coastguard Worker return true;
1617*9880d681SAndroid Build Coastguard Worker
1618*9880d681SAndroid Build Coastguard Worker // For integer types, we can't handle any bit-width differences. This would
1619*9880d681SAndroid Build Coastguard Worker // break both vector conversions with extension and introduce endianness
1620*9880d681SAndroid Build Coastguard Worker // issues when in conjunction with loads and stores.
1621*9880d681SAndroid Build Coastguard Worker if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1622*9880d681SAndroid Build Coastguard Worker assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1623*9880d681SAndroid Build Coastguard Worker cast<IntegerType>(NewTy)->getBitWidth() &&
1624*9880d681SAndroid Build Coastguard Worker "We can't have the same bitwidth for different int types");
1625*9880d681SAndroid Build Coastguard Worker return false;
1626*9880d681SAndroid Build Coastguard Worker }
1627*9880d681SAndroid Build Coastguard Worker
1628*9880d681SAndroid Build Coastguard Worker if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1629*9880d681SAndroid Build Coastguard Worker return false;
1630*9880d681SAndroid Build Coastguard Worker if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1631*9880d681SAndroid Build Coastguard Worker return false;
1632*9880d681SAndroid Build Coastguard Worker
1633*9880d681SAndroid Build Coastguard Worker // We can convert pointers to integers and vice-versa. Same for vectors
1634*9880d681SAndroid Build Coastguard Worker // of pointers and integers.
1635*9880d681SAndroid Build Coastguard Worker OldTy = OldTy->getScalarType();
1636*9880d681SAndroid Build Coastguard Worker NewTy = NewTy->getScalarType();
1637*9880d681SAndroid Build Coastguard Worker if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1638*9880d681SAndroid Build Coastguard Worker if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1639*9880d681SAndroid Build Coastguard Worker return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1640*9880d681SAndroid Build Coastguard Worker cast<PointerType>(OldTy)->getPointerAddressSpace();
1641*9880d681SAndroid Build Coastguard Worker }
1642*9880d681SAndroid Build Coastguard Worker if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1643*9880d681SAndroid Build Coastguard Worker return true;
1644*9880d681SAndroid Build Coastguard Worker return false;
1645*9880d681SAndroid Build Coastguard Worker }
1646*9880d681SAndroid Build Coastguard Worker
1647*9880d681SAndroid Build Coastguard Worker return true;
1648*9880d681SAndroid Build Coastguard Worker }
1649*9880d681SAndroid Build Coastguard Worker
1650*9880d681SAndroid Build Coastguard Worker /// \brief Generic routine to convert an SSA value to a value of a different
1651*9880d681SAndroid Build Coastguard Worker /// type.
1652*9880d681SAndroid Build Coastguard Worker ///
1653*9880d681SAndroid Build Coastguard Worker /// This will try various different casting techniques, such as bitcasts,
1654*9880d681SAndroid Build Coastguard Worker /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1655*9880d681SAndroid Build Coastguard Worker /// two types for viability with this routine.
convertValue(const DataLayout & DL,IRBuilderTy & IRB,Value * V,Type * NewTy)1656*9880d681SAndroid Build Coastguard Worker static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1657*9880d681SAndroid Build Coastguard Worker Type *NewTy) {
1658*9880d681SAndroid Build Coastguard Worker Type *OldTy = V->getType();
1659*9880d681SAndroid Build Coastguard Worker assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1660*9880d681SAndroid Build Coastguard Worker
1661*9880d681SAndroid Build Coastguard Worker if (OldTy == NewTy)
1662*9880d681SAndroid Build Coastguard Worker return V;
1663*9880d681SAndroid Build Coastguard Worker
1664*9880d681SAndroid Build Coastguard Worker assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1665*9880d681SAndroid Build Coastguard Worker "Integer types must be the exact same to convert.");
1666*9880d681SAndroid Build Coastguard Worker
1667*9880d681SAndroid Build Coastguard Worker // See if we need inttoptr for this type pair. A cast involving both scalars
1668*9880d681SAndroid Build Coastguard Worker // and vectors requires and additional bitcast.
1669*9880d681SAndroid Build Coastguard Worker if (OldTy->getScalarType()->isIntegerTy() &&
1670*9880d681SAndroid Build Coastguard Worker NewTy->getScalarType()->isPointerTy()) {
1671*9880d681SAndroid Build Coastguard Worker // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1672*9880d681SAndroid Build Coastguard Worker if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1673*9880d681SAndroid Build Coastguard Worker return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1674*9880d681SAndroid Build Coastguard Worker NewTy);
1675*9880d681SAndroid Build Coastguard Worker
1676*9880d681SAndroid Build Coastguard Worker // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1677*9880d681SAndroid Build Coastguard Worker if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1678*9880d681SAndroid Build Coastguard Worker return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1679*9880d681SAndroid Build Coastguard Worker NewTy);
1680*9880d681SAndroid Build Coastguard Worker
1681*9880d681SAndroid Build Coastguard Worker return IRB.CreateIntToPtr(V, NewTy);
1682*9880d681SAndroid Build Coastguard Worker }
1683*9880d681SAndroid Build Coastguard Worker
1684*9880d681SAndroid Build Coastguard Worker // See if we need ptrtoint for this type pair. A cast involving both scalars
1685*9880d681SAndroid Build Coastguard Worker // and vectors requires and additional bitcast.
1686*9880d681SAndroid Build Coastguard Worker if (OldTy->getScalarType()->isPointerTy() &&
1687*9880d681SAndroid Build Coastguard Worker NewTy->getScalarType()->isIntegerTy()) {
1688*9880d681SAndroid Build Coastguard Worker // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1689*9880d681SAndroid Build Coastguard Worker if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1690*9880d681SAndroid Build Coastguard Worker return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1691*9880d681SAndroid Build Coastguard Worker NewTy);
1692*9880d681SAndroid Build Coastguard Worker
1693*9880d681SAndroid Build Coastguard Worker // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1694*9880d681SAndroid Build Coastguard Worker if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1695*9880d681SAndroid Build Coastguard Worker return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1696*9880d681SAndroid Build Coastguard Worker NewTy);
1697*9880d681SAndroid Build Coastguard Worker
1698*9880d681SAndroid Build Coastguard Worker return IRB.CreatePtrToInt(V, NewTy);
1699*9880d681SAndroid Build Coastguard Worker }
1700*9880d681SAndroid Build Coastguard Worker
1701*9880d681SAndroid Build Coastguard Worker return IRB.CreateBitCast(V, NewTy);
1702*9880d681SAndroid Build Coastguard Worker }
1703*9880d681SAndroid Build Coastguard Worker
1704*9880d681SAndroid Build Coastguard Worker /// \brief Test whether the given slice use can be promoted to a vector.
1705*9880d681SAndroid Build Coastguard Worker ///
1706*9880d681SAndroid Build Coastguard Worker /// This function is called to test each entry in a partition which is slated
1707*9880d681SAndroid Build Coastguard Worker /// for a single slice.
isVectorPromotionViableForSlice(Partition & P,const Slice & S,VectorType * Ty,uint64_t ElementSize,const DataLayout & DL)1708*9880d681SAndroid Build Coastguard Worker static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1709*9880d681SAndroid Build Coastguard Worker VectorType *Ty,
1710*9880d681SAndroid Build Coastguard Worker uint64_t ElementSize,
1711*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
1712*9880d681SAndroid Build Coastguard Worker // First validate the slice offsets.
1713*9880d681SAndroid Build Coastguard Worker uint64_t BeginOffset =
1714*9880d681SAndroid Build Coastguard Worker std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1715*9880d681SAndroid Build Coastguard Worker uint64_t BeginIndex = BeginOffset / ElementSize;
1716*9880d681SAndroid Build Coastguard Worker if (BeginIndex * ElementSize != BeginOffset ||
1717*9880d681SAndroid Build Coastguard Worker BeginIndex >= Ty->getNumElements())
1718*9880d681SAndroid Build Coastguard Worker return false;
1719*9880d681SAndroid Build Coastguard Worker uint64_t EndOffset =
1720*9880d681SAndroid Build Coastguard Worker std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1721*9880d681SAndroid Build Coastguard Worker uint64_t EndIndex = EndOffset / ElementSize;
1722*9880d681SAndroid Build Coastguard Worker if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1723*9880d681SAndroid Build Coastguard Worker return false;
1724*9880d681SAndroid Build Coastguard Worker
1725*9880d681SAndroid Build Coastguard Worker assert(EndIndex > BeginIndex && "Empty vector!");
1726*9880d681SAndroid Build Coastguard Worker uint64_t NumElements = EndIndex - BeginIndex;
1727*9880d681SAndroid Build Coastguard Worker Type *SliceTy = (NumElements == 1)
1728*9880d681SAndroid Build Coastguard Worker ? Ty->getElementType()
1729*9880d681SAndroid Build Coastguard Worker : VectorType::get(Ty->getElementType(), NumElements);
1730*9880d681SAndroid Build Coastguard Worker
1731*9880d681SAndroid Build Coastguard Worker Type *SplitIntTy =
1732*9880d681SAndroid Build Coastguard Worker Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1733*9880d681SAndroid Build Coastguard Worker
1734*9880d681SAndroid Build Coastguard Worker Use *U = S.getUse();
1735*9880d681SAndroid Build Coastguard Worker
1736*9880d681SAndroid Build Coastguard Worker if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1737*9880d681SAndroid Build Coastguard Worker if (MI->isVolatile())
1738*9880d681SAndroid Build Coastguard Worker return false;
1739*9880d681SAndroid Build Coastguard Worker if (!S.isSplittable())
1740*9880d681SAndroid Build Coastguard Worker return false; // Skip any unsplittable intrinsics.
1741*9880d681SAndroid Build Coastguard Worker } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1742*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1743*9880d681SAndroid Build Coastguard Worker II->getIntrinsicID() != Intrinsic::lifetime_end)
1744*9880d681SAndroid Build Coastguard Worker return false;
1745*9880d681SAndroid Build Coastguard Worker } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1746*9880d681SAndroid Build Coastguard Worker // Disable vector promotion when there are loads or stores of an FCA.
1747*9880d681SAndroid Build Coastguard Worker return false;
1748*9880d681SAndroid Build Coastguard Worker } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1749*9880d681SAndroid Build Coastguard Worker if (LI->isVolatile())
1750*9880d681SAndroid Build Coastguard Worker return false;
1751*9880d681SAndroid Build Coastguard Worker Type *LTy = LI->getType();
1752*9880d681SAndroid Build Coastguard Worker if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1753*9880d681SAndroid Build Coastguard Worker assert(LTy->isIntegerTy());
1754*9880d681SAndroid Build Coastguard Worker LTy = SplitIntTy;
1755*9880d681SAndroid Build Coastguard Worker }
1756*9880d681SAndroid Build Coastguard Worker if (!canConvertValue(DL, SliceTy, LTy))
1757*9880d681SAndroid Build Coastguard Worker return false;
1758*9880d681SAndroid Build Coastguard Worker } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1759*9880d681SAndroid Build Coastguard Worker if (SI->isVolatile())
1760*9880d681SAndroid Build Coastguard Worker return false;
1761*9880d681SAndroid Build Coastguard Worker Type *STy = SI->getValueOperand()->getType();
1762*9880d681SAndroid Build Coastguard Worker if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1763*9880d681SAndroid Build Coastguard Worker assert(STy->isIntegerTy());
1764*9880d681SAndroid Build Coastguard Worker STy = SplitIntTy;
1765*9880d681SAndroid Build Coastguard Worker }
1766*9880d681SAndroid Build Coastguard Worker if (!canConvertValue(DL, STy, SliceTy))
1767*9880d681SAndroid Build Coastguard Worker return false;
1768*9880d681SAndroid Build Coastguard Worker } else {
1769*9880d681SAndroid Build Coastguard Worker return false;
1770*9880d681SAndroid Build Coastguard Worker }
1771*9880d681SAndroid Build Coastguard Worker
1772*9880d681SAndroid Build Coastguard Worker return true;
1773*9880d681SAndroid Build Coastguard Worker }
1774*9880d681SAndroid Build Coastguard Worker
1775*9880d681SAndroid Build Coastguard Worker /// \brief Test whether the given alloca partitioning and range of slices can be
1776*9880d681SAndroid Build Coastguard Worker /// promoted to a vector.
1777*9880d681SAndroid Build Coastguard Worker ///
1778*9880d681SAndroid Build Coastguard Worker /// This is a quick test to check whether we can rewrite a particular alloca
1779*9880d681SAndroid Build Coastguard Worker /// partition (and its newly formed alloca) into a vector alloca with only
1780*9880d681SAndroid Build Coastguard Worker /// whole-vector loads and stores such that it could be promoted to a vector
1781*9880d681SAndroid Build Coastguard Worker /// SSA value. We only can ensure this for a limited set of operations, and we
1782*9880d681SAndroid Build Coastguard Worker /// don't want to do the rewrites unless we are confident that the result will
1783*9880d681SAndroid Build Coastguard Worker /// be promotable, so we have an early test here.
isVectorPromotionViable(Partition & P,const DataLayout & DL)1784*9880d681SAndroid Build Coastguard Worker static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
1785*9880d681SAndroid Build Coastguard Worker // Collect the candidate types for vector-based promotion. Also track whether
1786*9880d681SAndroid Build Coastguard Worker // we have different element types.
1787*9880d681SAndroid Build Coastguard Worker SmallVector<VectorType *, 4> CandidateTys;
1788*9880d681SAndroid Build Coastguard Worker Type *CommonEltTy = nullptr;
1789*9880d681SAndroid Build Coastguard Worker bool HaveCommonEltTy = true;
1790*9880d681SAndroid Build Coastguard Worker auto CheckCandidateType = [&](Type *Ty) {
1791*9880d681SAndroid Build Coastguard Worker if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1792*9880d681SAndroid Build Coastguard Worker CandidateTys.push_back(VTy);
1793*9880d681SAndroid Build Coastguard Worker if (!CommonEltTy)
1794*9880d681SAndroid Build Coastguard Worker CommonEltTy = VTy->getElementType();
1795*9880d681SAndroid Build Coastguard Worker else if (CommonEltTy != VTy->getElementType())
1796*9880d681SAndroid Build Coastguard Worker HaveCommonEltTy = false;
1797*9880d681SAndroid Build Coastguard Worker }
1798*9880d681SAndroid Build Coastguard Worker };
1799*9880d681SAndroid Build Coastguard Worker // Consider any loads or stores that are the exact size of the slice.
1800*9880d681SAndroid Build Coastguard Worker for (const Slice &S : P)
1801*9880d681SAndroid Build Coastguard Worker if (S.beginOffset() == P.beginOffset() &&
1802*9880d681SAndroid Build Coastguard Worker S.endOffset() == P.endOffset()) {
1803*9880d681SAndroid Build Coastguard Worker if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1804*9880d681SAndroid Build Coastguard Worker CheckCandidateType(LI->getType());
1805*9880d681SAndroid Build Coastguard Worker else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1806*9880d681SAndroid Build Coastguard Worker CheckCandidateType(SI->getValueOperand()->getType());
1807*9880d681SAndroid Build Coastguard Worker }
1808*9880d681SAndroid Build Coastguard Worker
1809*9880d681SAndroid Build Coastguard Worker // If we didn't find a vector type, nothing to do here.
1810*9880d681SAndroid Build Coastguard Worker if (CandidateTys.empty())
1811*9880d681SAndroid Build Coastguard Worker return nullptr;
1812*9880d681SAndroid Build Coastguard Worker
1813*9880d681SAndroid Build Coastguard Worker // Remove non-integer vector types if we had multiple common element types.
1814*9880d681SAndroid Build Coastguard Worker // FIXME: It'd be nice to replace them with integer vector types, but we can't
1815*9880d681SAndroid Build Coastguard Worker // do that until all the backends are known to produce good code for all
1816*9880d681SAndroid Build Coastguard Worker // integer vector types.
1817*9880d681SAndroid Build Coastguard Worker if (!HaveCommonEltTy) {
1818*9880d681SAndroid Build Coastguard Worker CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1819*9880d681SAndroid Build Coastguard Worker [](VectorType *VTy) {
1820*9880d681SAndroid Build Coastguard Worker return !VTy->getElementType()->isIntegerTy();
1821*9880d681SAndroid Build Coastguard Worker }),
1822*9880d681SAndroid Build Coastguard Worker CandidateTys.end());
1823*9880d681SAndroid Build Coastguard Worker
1824*9880d681SAndroid Build Coastguard Worker // If there were no integer vector types, give up.
1825*9880d681SAndroid Build Coastguard Worker if (CandidateTys.empty())
1826*9880d681SAndroid Build Coastguard Worker return nullptr;
1827*9880d681SAndroid Build Coastguard Worker
1828*9880d681SAndroid Build Coastguard Worker // Rank the remaining candidate vector types. This is easy because we know
1829*9880d681SAndroid Build Coastguard Worker // they're all integer vectors. We sort by ascending number of elements.
1830*9880d681SAndroid Build Coastguard Worker auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1831*9880d681SAndroid Build Coastguard Worker assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1832*9880d681SAndroid Build Coastguard Worker "Cannot have vector types of different sizes!");
1833*9880d681SAndroid Build Coastguard Worker assert(RHSTy->getElementType()->isIntegerTy() &&
1834*9880d681SAndroid Build Coastguard Worker "All non-integer types eliminated!");
1835*9880d681SAndroid Build Coastguard Worker assert(LHSTy->getElementType()->isIntegerTy() &&
1836*9880d681SAndroid Build Coastguard Worker "All non-integer types eliminated!");
1837*9880d681SAndroid Build Coastguard Worker return RHSTy->getNumElements() < LHSTy->getNumElements();
1838*9880d681SAndroid Build Coastguard Worker };
1839*9880d681SAndroid Build Coastguard Worker std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1840*9880d681SAndroid Build Coastguard Worker CandidateTys.erase(
1841*9880d681SAndroid Build Coastguard Worker std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1842*9880d681SAndroid Build Coastguard Worker CandidateTys.end());
1843*9880d681SAndroid Build Coastguard Worker } else {
1844*9880d681SAndroid Build Coastguard Worker // The only way to have the same element type in every vector type is to
1845*9880d681SAndroid Build Coastguard Worker // have the same vector type. Check that and remove all but one.
1846*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
1847*9880d681SAndroid Build Coastguard Worker for (VectorType *VTy : CandidateTys) {
1848*9880d681SAndroid Build Coastguard Worker assert(VTy->getElementType() == CommonEltTy &&
1849*9880d681SAndroid Build Coastguard Worker "Unaccounted for element type!");
1850*9880d681SAndroid Build Coastguard Worker assert(VTy == CandidateTys[0] &&
1851*9880d681SAndroid Build Coastguard Worker "Different vector types with the same element type!");
1852*9880d681SAndroid Build Coastguard Worker }
1853*9880d681SAndroid Build Coastguard Worker #endif
1854*9880d681SAndroid Build Coastguard Worker CandidateTys.resize(1);
1855*9880d681SAndroid Build Coastguard Worker }
1856*9880d681SAndroid Build Coastguard Worker
1857*9880d681SAndroid Build Coastguard Worker // Try each vector type, and return the one which works.
1858*9880d681SAndroid Build Coastguard Worker auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1859*9880d681SAndroid Build Coastguard Worker uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1860*9880d681SAndroid Build Coastguard Worker
1861*9880d681SAndroid Build Coastguard Worker // While the definition of LLVM vectors is bitpacked, we don't support sizes
1862*9880d681SAndroid Build Coastguard Worker // that aren't byte sized.
1863*9880d681SAndroid Build Coastguard Worker if (ElementSize % 8)
1864*9880d681SAndroid Build Coastguard Worker return false;
1865*9880d681SAndroid Build Coastguard Worker assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1866*9880d681SAndroid Build Coastguard Worker "vector size not a multiple of element size?");
1867*9880d681SAndroid Build Coastguard Worker ElementSize /= 8;
1868*9880d681SAndroid Build Coastguard Worker
1869*9880d681SAndroid Build Coastguard Worker for (const Slice &S : P)
1870*9880d681SAndroid Build Coastguard Worker if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
1871*9880d681SAndroid Build Coastguard Worker return false;
1872*9880d681SAndroid Build Coastguard Worker
1873*9880d681SAndroid Build Coastguard Worker for (const Slice *S : P.splitSliceTails())
1874*9880d681SAndroid Build Coastguard Worker if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
1875*9880d681SAndroid Build Coastguard Worker return false;
1876*9880d681SAndroid Build Coastguard Worker
1877*9880d681SAndroid Build Coastguard Worker return true;
1878*9880d681SAndroid Build Coastguard Worker };
1879*9880d681SAndroid Build Coastguard Worker for (VectorType *VTy : CandidateTys)
1880*9880d681SAndroid Build Coastguard Worker if (CheckVectorTypeForPromotion(VTy))
1881*9880d681SAndroid Build Coastguard Worker return VTy;
1882*9880d681SAndroid Build Coastguard Worker
1883*9880d681SAndroid Build Coastguard Worker return nullptr;
1884*9880d681SAndroid Build Coastguard Worker }
1885*9880d681SAndroid Build Coastguard Worker
1886*9880d681SAndroid Build Coastguard Worker /// \brief Test whether a slice of an alloca is valid for integer widening.
1887*9880d681SAndroid Build Coastguard Worker ///
1888*9880d681SAndroid Build Coastguard Worker /// This implements the necessary checking for the \c isIntegerWideningViable
1889*9880d681SAndroid Build Coastguard Worker /// test below on a single slice of the alloca.
isIntegerWideningViableForSlice(const Slice & S,uint64_t AllocBeginOffset,Type * AllocaTy,const DataLayout & DL,bool & WholeAllocaOp)1890*9880d681SAndroid Build Coastguard Worker static bool isIntegerWideningViableForSlice(const Slice &S,
1891*9880d681SAndroid Build Coastguard Worker uint64_t AllocBeginOffset,
1892*9880d681SAndroid Build Coastguard Worker Type *AllocaTy,
1893*9880d681SAndroid Build Coastguard Worker const DataLayout &DL,
1894*9880d681SAndroid Build Coastguard Worker bool &WholeAllocaOp) {
1895*9880d681SAndroid Build Coastguard Worker uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1896*9880d681SAndroid Build Coastguard Worker
1897*9880d681SAndroid Build Coastguard Worker uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1898*9880d681SAndroid Build Coastguard Worker uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1899*9880d681SAndroid Build Coastguard Worker
1900*9880d681SAndroid Build Coastguard Worker // We can't reasonably handle cases where the load or store extends past
1901*9880d681SAndroid Build Coastguard Worker // the end of the alloca's type and into its padding.
1902*9880d681SAndroid Build Coastguard Worker if (RelEnd > Size)
1903*9880d681SAndroid Build Coastguard Worker return false;
1904*9880d681SAndroid Build Coastguard Worker
1905*9880d681SAndroid Build Coastguard Worker Use *U = S.getUse();
1906*9880d681SAndroid Build Coastguard Worker
1907*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1908*9880d681SAndroid Build Coastguard Worker if (LI->isVolatile())
1909*9880d681SAndroid Build Coastguard Worker return false;
1910*9880d681SAndroid Build Coastguard Worker // We can't handle loads that extend past the allocated memory.
1911*9880d681SAndroid Build Coastguard Worker if (DL.getTypeStoreSize(LI->getType()) > Size)
1912*9880d681SAndroid Build Coastguard Worker return false;
1913*9880d681SAndroid Build Coastguard Worker // Note that we don't count vector loads or stores as whole-alloca
1914*9880d681SAndroid Build Coastguard Worker // operations which enable integer widening because we would prefer to use
1915*9880d681SAndroid Build Coastguard Worker // vector widening instead.
1916*9880d681SAndroid Build Coastguard Worker if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
1917*9880d681SAndroid Build Coastguard Worker WholeAllocaOp = true;
1918*9880d681SAndroid Build Coastguard Worker if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1919*9880d681SAndroid Build Coastguard Worker if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1920*9880d681SAndroid Build Coastguard Worker return false;
1921*9880d681SAndroid Build Coastguard Worker } else if (RelBegin != 0 || RelEnd != Size ||
1922*9880d681SAndroid Build Coastguard Worker !canConvertValue(DL, AllocaTy, LI->getType())) {
1923*9880d681SAndroid Build Coastguard Worker // Non-integer loads need to be convertible from the alloca type so that
1924*9880d681SAndroid Build Coastguard Worker // they are promotable.
1925*9880d681SAndroid Build Coastguard Worker return false;
1926*9880d681SAndroid Build Coastguard Worker }
1927*9880d681SAndroid Build Coastguard Worker } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1928*9880d681SAndroid Build Coastguard Worker Type *ValueTy = SI->getValueOperand()->getType();
1929*9880d681SAndroid Build Coastguard Worker if (SI->isVolatile())
1930*9880d681SAndroid Build Coastguard Worker return false;
1931*9880d681SAndroid Build Coastguard Worker // We can't handle stores that extend past the allocated memory.
1932*9880d681SAndroid Build Coastguard Worker if (DL.getTypeStoreSize(ValueTy) > Size)
1933*9880d681SAndroid Build Coastguard Worker return false;
1934*9880d681SAndroid Build Coastguard Worker // Note that we don't count vector loads or stores as whole-alloca
1935*9880d681SAndroid Build Coastguard Worker // operations which enable integer widening because we would prefer to use
1936*9880d681SAndroid Build Coastguard Worker // vector widening instead.
1937*9880d681SAndroid Build Coastguard Worker if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
1938*9880d681SAndroid Build Coastguard Worker WholeAllocaOp = true;
1939*9880d681SAndroid Build Coastguard Worker if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1940*9880d681SAndroid Build Coastguard Worker if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1941*9880d681SAndroid Build Coastguard Worker return false;
1942*9880d681SAndroid Build Coastguard Worker } else if (RelBegin != 0 || RelEnd != Size ||
1943*9880d681SAndroid Build Coastguard Worker !canConvertValue(DL, ValueTy, AllocaTy)) {
1944*9880d681SAndroid Build Coastguard Worker // Non-integer stores need to be convertible to the alloca type so that
1945*9880d681SAndroid Build Coastguard Worker // they are promotable.
1946*9880d681SAndroid Build Coastguard Worker return false;
1947*9880d681SAndroid Build Coastguard Worker }
1948*9880d681SAndroid Build Coastguard Worker } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1949*9880d681SAndroid Build Coastguard Worker if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1950*9880d681SAndroid Build Coastguard Worker return false;
1951*9880d681SAndroid Build Coastguard Worker if (!S.isSplittable())
1952*9880d681SAndroid Build Coastguard Worker return false; // Skip any unsplittable intrinsics.
1953*9880d681SAndroid Build Coastguard Worker } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1954*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1955*9880d681SAndroid Build Coastguard Worker II->getIntrinsicID() != Intrinsic::lifetime_end)
1956*9880d681SAndroid Build Coastguard Worker return false;
1957*9880d681SAndroid Build Coastguard Worker } else {
1958*9880d681SAndroid Build Coastguard Worker return false;
1959*9880d681SAndroid Build Coastguard Worker }
1960*9880d681SAndroid Build Coastguard Worker
1961*9880d681SAndroid Build Coastguard Worker return true;
1962*9880d681SAndroid Build Coastguard Worker }
1963*9880d681SAndroid Build Coastguard Worker
1964*9880d681SAndroid Build Coastguard Worker /// \brief Test whether the given alloca partition's integer operations can be
1965*9880d681SAndroid Build Coastguard Worker /// widened to promotable ones.
1966*9880d681SAndroid Build Coastguard Worker ///
1967*9880d681SAndroid Build Coastguard Worker /// This is a quick test to check whether we can rewrite the integer loads and
1968*9880d681SAndroid Build Coastguard Worker /// stores to a particular alloca into wider loads and stores and be able to
1969*9880d681SAndroid Build Coastguard Worker /// promote the resulting alloca.
isIntegerWideningViable(Partition & P,Type * AllocaTy,const DataLayout & DL)1970*9880d681SAndroid Build Coastguard Worker static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
1971*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
1972*9880d681SAndroid Build Coastguard Worker uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1973*9880d681SAndroid Build Coastguard Worker // Don't create integer types larger than the maximum bitwidth.
1974*9880d681SAndroid Build Coastguard Worker if (SizeInBits > IntegerType::MAX_INT_BITS)
1975*9880d681SAndroid Build Coastguard Worker return false;
1976*9880d681SAndroid Build Coastguard Worker
1977*9880d681SAndroid Build Coastguard Worker // Don't try to handle allocas with bit-padding.
1978*9880d681SAndroid Build Coastguard Worker if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1979*9880d681SAndroid Build Coastguard Worker return false;
1980*9880d681SAndroid Build Coastguard Worker
1981*9880d681SAndroid Build Coastguard Worker // We need to ensure that an integer type with the appropriate bitwidth can
1982*9880d681SAndroid Build Coastguard Worker // be converted to the alloca type, whatever that is. We don't want to force
1983*9880d681SAndroid Build Coastguard Worker // the alloca itself to have an integer type if there is a more suitable one.
1984*9880d681SAndroid Build Coastguard Worker Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1985*9880d681SAndroid Build Coastguard Worker if (!canConvertValue(DL, AllocaTy, IntTy) ||
1986*9880d681SAndroid Build Coastguard Worker !canConvertValue(DL, IntTy, AllocaTy))
1987*9880d681SAndroid Build Coastguard Worker return false;
1988*9880d681SAndroid Build Coastguard Worker
1989*9880d681SAndroid Build Coastguard Worker // While examining uses, we ensure that the alloca has a covering load or
1990*9880d681SAndroid Build Coastguard Worker // store. We don't want to widen the integer operations only to fail to
1991*9880d681SAndroid Build Coastguard Worker // promote due to some other unsplittable entry (which we may make splittable
1992*9880d681SAndroid Build Coastguard Worker // later). However, if there are only splittable uses, go ahead and assume
1993*9880d681SAndroid Build Coastguard Worker // that we cover the alloca.
1994*9880d681SAndroid Build Coastguard Worker // FIXME: We shouldn't consider split slices that happen to start in the
1995*9880d681SAndroid Build Coastguard Worker // partition here...
1996*9880d681SAndroid Build Coastguard Worker bool WholeAllocaOp =
1997*9880d681SAndroid Build Coastguard Worker P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
1998*9880d681SAndroid Build Coastguard Worker
1999*9880d681SAndroid Build Coastguard Worker for (const Slice &S : P)
2000*9880d681SAndroid Build Coastguard Worker if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2001*9880d681SAndroid Build Coastguard Worker WholeAllocaOp))
2002*9880d681SAndroid Build Coastguard Worker return false;
2003*9880d681SAndroid Build Coastguard Worker
2004*9880d681SAndroid Build Coastguard Worker for (const Slice *S : P.splitSliceTails())
2005*9880d681SAndroid Build Coastguard Worker if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2006*9880d681SAndroid Build Coastguard Worker WholeAllocaOp))
2007*9880d681SAndroid Build Coastguard Worker return false;
2008*9880d681SAndroid Build Coastguard Worker
2009*9880d681SAndroid Build Coastguard Worker return WholeAllocaOp;
2010*9880d681SAndroid Build Coastguard Worker }
2011*9880d681SAndroid Build Coastguard Worker
extractInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * V,IntegerType * Ty,uint64_t Offset,const Twine & Name)2012*9880d681SAndroid Build Coastguard Worker static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2013*9880d681SAndroid Build Coastguard Worker IntegerType *Ty, uint64_t Offset,
2014*9880d681SAndroid Build Coastguard Worker const Twine &Name) {
2015*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " start: " << *V << "\n");
2016*9880d681SAndroid Build Coastguard Worker IntegerType *IntTy = cast<IntegerType>(V->getType());
2017*9880d681SAndroid Build Coastguard Worker assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2018*9880d681SAndroid Build Coastguard Worker "Element extends past full value");
2019*9880d681SAndroid Build Coastguard Worker uint64_t ShAmt = 8 * Offset;
2020*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian())
2021*9880d681SAndroid Build Coastguard Worker ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2022*9880d681SAndroid Build Coastguard Worker if (ShAmt) {
2023*9880d681SAndroid Build Coastguard Worker V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2024*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " shifted: " << *V << "\n");
2025*9880d681SAndroid Build Coastguard Worker }
2026*9880d681SAndroid Build Coastguard Worker assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2027*9880d681SAndroid Build Coastguard Worker "Cannot extract to a larger integer!");
2028*9880d681SAndroid Build Coastguard Worker if (Ty != IntTy) {
2029*9880d681SAndroid Build Coastguard Worker V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2030*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " trunced: " << *V << "\n");
2031*9880d681SAndroid Build Coastguard Worker }
2032*9880d681SAndroid Build Coastguard Worker return V;
2033*9880d681SAndroid Build Coastguard Worker }
2034*9880d681SAndroid Build Coastguard Worker
insertInteger(const DataLayout & DL,IRBuilderTy & IRB,Value * Old,Value * V,uint64_t Offset,const Twine & Name)2035*9880d681SAndroid Build Coastguard Worker static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2036*9880d681SAndroid Build Coastguard Worker Value *V, uint64_t Offset, const Twine &Name) {
2037*9880d681SAndroid Build Coastguard Worker IntegerType *IntTy = cast<IntegerType>(Old->getType());
2038*9880d681SAndroid Build Coastguard Worker IntegerType *Ty = cast<IntegerType>(V->getType());
2039*9880d681SAndroid Build Coastguard Worker assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2040*9880d681SAndroid Build Coastguard Worker "Cannot insert a larger integer!");
2041*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " start: " << *V << "\n");
2042*9880d681SAndroid Build Coastguard Worker if (Ty != IntTy) {
2043*9880d681SAndroid Build Coastguard Worker V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2044*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " extended: " << *V << "\n");
2045*9880d681SAndroid Build Coastguard Worker }
2046*9880d681SAndroid Build Coastguard Worker assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2047*9880d681SAndroid Build Coastguard Worker "Element store outside of alloca store");
2048*9880d681SAndroid Build Coastguard Worker uint64_t ShAmt = 8 * Offset;
2049*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian())
2050*9880d681SAndroid Build Coastguard Worker ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2051*9880d681SAndroid Build Coastguard Worker if (ShAmt) {
2052*9880d681SAndroid Build Coastguard Worker V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2053*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " shifted: " << *V << "\n");
2054*9880d681SAndroid Build Coastguard Worker }
2055*9880d681SAndroid Build Coastguard Worker
2056*9880d681SAndroid Build Coastguard Worker if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2057*9880d681SAndroid Build Coastguard Worker APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2058*9880d681SAndroid Build Coastguard Worker Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2059*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " masked: " << *Old << "\n");
2060*9880d681SAndroid Build Coastguard Worker V = IRB.CreateOr(Old, V, Name + ".insert");
2061*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " inserted: " << *V << "\n");
2062*9880d681SAndroid Build Coastguard Worker }
2063*9880d681SAndroid Build Coastguard Worker return V;
2064*9880d681SAndroid Build Coastguard Worker }
2065*9880d681SAndroid Build Coastguard Worker
extractVector(IRBuilderTy & IRB,Value * V,unsigned BeginIndex,unsigned EndIndex,const Twine & Name)2066*9880d681SAndroid Build Coastguard Worker static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2067*9880d681SAndroid Build Coastguard Worker unsigned EndIndex, const Twine &Name) {
2068*9880d681SAndroid Build Coastguard Worker VectorType *VecTy = cast<VectorType>(V->getType());
2069*9880d681SAndroid Build Coastguard Worker unsigned NumElements = EndIndex - BeginIndex;
2070*9880d681SAndroid Build Coastguard Worker assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2071*9880d681SAndroid Build Coastguard Worker
2072*9880d681SAndroid Build Coastguard Worker if (NumElements == VecTy->getNumElements())
2073*9880d681SAndroid Build Coastguard Worker return V;
2074*9880d681SAndroid Build Coastguard Worker
2075*9880d681SAndroid Build Coastguard Worker if (NumElements == 1) {
2076*9880d681SAndroid Build Coastguard Worker V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2077*9880d681SAndroid Build Coastguard Worker Name + ".extract");
2078*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " extract: " << *V << "\n");
2079*9880d681SAndroid Build Coastguard Worker return V;
2080*9880d681SAndroid Build Coastguard Worker }
2081*9880d681SAndroid Build Coastguard Worker
2082*9880d681SAndroid Build Coastguard Worker SmallVector<Constant *, 8> Mask;
2083*9880d681SAndroid Build Coastguard Worker Mask.reserve(NumElements);
2084*9880d681SAndroid Build Coastguard Worker for (unsigned i = BeginIndex; i != EndIndex; ++i)
2085*9880d681SAndroid Build Coastguard Worker Mask.push_back(IRB.getInt32(i));
2086*9880d681SAndroid Build Coastguard Worker V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2087*9880d681SAndroid Build Coastguard Worker ConstantVector::get(Mask), Name + ".extract");
2088*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " shuffle: " << *V << "\n");
2089*9880d681SAndroid Build Coastguard Worker return V;
2090*9880d681SAndroid Build Coastguard Worker }
2091*9880d681SAndroid Build Coastguard Worker
insertVector(IRBuilderTy & IRB,Value * Old,Value * V,unsigned BeginIndex,const Twine & Name)2092*9880d681SAndroid Build Coastguard Worker static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2093*9880d681SAndroid Build Coastguard Worker unsigned BeginIndex, const Twine &Name) {
2094*9880d681SAndroid Build Coastguard Worker VectorType *VecTy = cast<VectorType>(Old->getType());
2095*9880d681SAndroid Build Coastguard Worker assert(VecTy && "Can only insert a vector into a vector");
2096*9880d681SAndroid Build Coastguard Worker
2097*9880d681SAndroid Build Coastguard Worker VectorType *Ty = dyn_cast<VectorType>(V->getType());
2098*9880d681SAndroid Build Coastguard Worker if (!Ty) {
2099*9880d681SAndroid Build Coastguard Worker // Single element to insert.
2100*9880d681SAndroid Build Coastguard Worker V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2101*9880d681SAndroid Build Coastguard Worker Name + ".insert");
2102*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " insert: " << *V << "\n");
2103*9880d681SAndroid Build Coastguard Worker return V;
2104*9880d681SAndroid Build Coastguard Worker }
2105*9880d681SAndroid Build Coastguard Worker
2106*9880d681SAndroid Build Coastguard Worker assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2107*9880d681SAndroid Build Coastguard Worker "Too many elements!");
2108*9880d681SAndroid Build Coastguard Worker if (Ty->getNumElements() == VecTy->getNumElements()) {
2109*9880d681SAndroid Build Coastguard Worker assert(V->getType() == VecTy && "Vector type mismatch");
2110*9880d681SAndroid Build Coastguard Worker return V;
2111*9880d681SAndroid Build Coastguard Worker }
2112*9880d681SAndroid Build Coastguard Worker unsigned EndIndex = BeginIndex + Ty->getNumElements();
2113*9880d681SAndroid Build Coastguard Worker
2114*9880d681SAndroid Build Coastguard Worker // When inserting a smaller vector into the larger to store, we first
2115*9880d681SAndroid Build Coastguard Worker // use a shuffle vector to widen it with undef elements, and then
2116*9880d681SAndroid Build Coastguard Worker // a second shuffle vector to select between the loaded vector and the
2117*9880d681SAndroid Build Coastguard Worker // incoming vector.
2118*9880d681SAndroid Build Coastguard Worker SmallVector<Constant *, 8> Mask;
2119*9880d681SAndroid Build Coastguard Worker Mask.reserve(VecTy->getNumElements());
2120*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2121*9880d681SAndroid Build Coastguard Worker if (i >= BeginIndex && i < EndIndex)
2122*9880d681SAndroid Build Coastguard Worker Mask.push_back(IRB.getInt32(i - BeginIndex));
2123*9880d681SAndroid Build Coastguard Worker else
2124*9880d681SAndroid Build Coastguard Worker Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2125*9880d681SAndroid Build Coastguard Worker V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2126*9880d681SAndroid Build Coastguard Worker ConstantVector::get(Mask), Name + ".expand");
2127*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " shuffle: " << *V << "\n");
2128*9880d681SAndroid Build Coastguard Worker
2129*9880d681SAndroid Build Coastguard Worker Mask.clear();
2130*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2131*9880d681SAndroid Build Coastguard Worker Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2132*9880d681SAndroid Build Coastguard Worker
2133*9880d681SAndroid Build Coastguard Worker V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2134*9880d681SAndroid Build Coastguard Worker
2135*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " blend: " << *V << "\n");
2136*9880d681SAndroid Build Coastguard Worker return V;
2137*9880d681SAndroid Build Coastguard Worker }
2138*9880d681SAndroid Build Coastguard Worker
2139*9880d681SAndroid Build Coastguard Worker /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2140*9880d681SAndroid Build Coastguard Worker /// to use a new alloca.
2141*9880d681SAndroid Build Coastguard Worker ///
2142*9880d681SAndroid Build Coastguard Worker /// Also implements the rewriting to vector-based accesses when the partition
2143*9880d681SAndroid Build Coastguard Worker /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2144*9880d681SAndroid Build Coastguard Worker /// lives here.
2145*9880d681SAndroid Build Coastguard Worker class llvm::sroa::AllocaSliceRewriter
2146*9880d681SAndroid Build Coastguard Worker : public InstVisitor<AllocaSliceRewriter, bool> {
2147*9880d681SAndroid Build Coastguard Worker // Befriend the base class so it can delegate to private visit methods.
2148*9880d681SAndroid Build Coastguard Worker friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2149*9880d681SAndroid Build Coastguard Worker typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2150*9880d681SAndroid Build Coastguard Worker
2151*9880d681SAndroid Build Coastguard Worker const DataLayout &DL;
2152*9880d681SAndroid Build Coastguard Worker AllocaSlices &AS;
2153*9880d681SAndroid Build Coastguard Worker SROA &Pass;
2154*9880d681SAndroid Build Coastguard Worker AllocaInst &OldAI, &NewAI;
2155*9880d681SAndroid Build Coastguard Worker const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2156*9880d681SAndroid Build Coastguard Worker Type *NewAllocaTy;
2157*9880d681SAndroid Build Coastguard Worker
2158*9880d681SAndroid Build Coastguard Worker // This is a convenience and flag variable that will be null unless the new
2159*9880d681SAndroid Build Coastguard Worker // alloca's integer operations should be widened to this integer type due to
2160*9880d681SAndroid Build Coastguard Worker // passing isIntegerWideningViable above. If it is non-null, the desired
2161*9880d681SAndroid Build Coastguard Worker // integer type will be stored here for easy access during rewriting.
2162*9880d681SAndroid Build Coastguard Worker IntegerType *IntTy;
2163*9880d681SAndroid Build Coastguard Worker
2164*9880d681SAndroid Build Coastguard Worker // If we are rewriting an alloca partition which can be written as pure
2165*9880d681SAndroid Build Coastguard Worker // vector operations, we stash extra information here. When VecTy is
2166*9880d681SAndroid Build Coastguard Worker // non-null, we have some strict guarantees about the rewritten alloca:
2167*9880d681SAndroid Build Coastguard Worker // - The new alloca is exactly the size of the vector type here.
2168*9880d681SAndroid Build Coastguard Worker // - The accesses all either map to the entire vector or to a single
2169*9880d681SAndroid Build Coastguard Worker // element.
2170*9880d681SAndroid Build Coastguard Worker // - The set of accessing instructions is only one of those handled above
2171*9880d681SAndroid Build Coastguard Worker // in isVectorPromotionViable. Generally these are the same access kinds
2172*9880d681SAndroid Build Coastguard Worker // which are promotable via mem2reg.
2173*9880d681SAndroid Build Coastguard Worker VectorType *VecTy;
2174*9880d681SAndroid Build Coastguard Worker Type *ElementTy;
2175*9880d681SAndroid Build Coastguard Worker uint64_t ElementSize;
2176*9880d681SAndroid Build Coastguard Worker
2177*9880d681SAndroid Build Coastguard Worker // The original offset of the slice currently being rewritten relative to
2178*9880d681SAndroid Build Coastguard Worker // the original alloca.
2179*9880d681SAndroid Build Coastguard Worker uint64_t BeginOffset, EndOffset;
2180*9880d681SAndroid Build Coastguard Worker // The new offsets of the slice currently being rewritten relative to the
2181*9880d681SAndroid Build Coastguard Worker // original alloca.
2182*9880d681SAndroid Build Coastguard Worker uint64_t NewBeginOffset, NewEndOffset;
2183*9880d681SAndroid Build Coastguard Worker
2184*9880d681SAndroid Build Coastguard Worker uint64_t SliceSize;
2185*9880d681SAndroid Build Coastguard Worker bool IsSplittable;
2186*9880d681SAndroid Build Coastguard Worker bool IsSplit;
2187*9880d681SAndroid Build Coastguard Worker Use *OldUse;
2188*9880d681SAndroid Build Coastguard Worker Instruction *OldPtr;
2189*9880d681SAndroid Build Coastguard Worker
2190*9880d681SAndroid Build Coastguard Worker // Track post-rewrite users which are PHI nodes and Selects.
2191*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<PHINode *> &PHIUsers;
2192*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<SelectInst *> &SelectUsers;
2193*9880d681SAndroid Build Coastguard Worker
2194*9880d681SAndroid Build Coastguard Worker // Utility IR builder, whose name prefix is setup for each visited use, and
2195*9880d681SAndroid Build Coastguard Worker // the insertion point is set to point to the user.
2196*9880d681SAndroid Build Coastguard Worker IRBuilderTy IRB;
2197*9880d681SAndroid Build Coastguard Worker
2198*9880d681SAndroid Build Coastguard Worker public:
AllocaSliceRewriter(const DataLayout & DL,AllocaSlices & AS,SROA & Pass,AllocaInst & OldAI,AllocaInst & NewAI,uint64_t NewAllocaBeginOffset,uint64_t NewAllocaEndOffset,bool IsIntegerPromotable,VectorType * PromotableVecTy,SmallPtrSetImpl<PHINode * > & PHIUsers,SmallPtrSetImpl<SelectInst * > & SelectUsers)2199*9880d681SAndroid Build Coastguard Worker AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2200*9880d681SAndroid Build Coastguard Worker AllocaInst &OldAI, AllocaInst &NewAI,
2201*9880d681SAndroid Build Coastguard Worker uint64_t NewAllocaBeginOffset,
2202*9880d681SAndroid Build Coastguard Worker uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2203*9880d681SAndroid Build Coastguard Worker VectorType *PromotableVecTy,
2204*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<PHINode *> &PHIUsers,
2205*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<SelectInst *> &SelectUsers)
2206*9880d681SAndroid Build Coastguard Worker : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2207*9880d681SAndroid Build Coastguard Worker NewAllocaBeginOffset(NewAllocaBeginOffset),
2208*9880d681SAndroid Build Coastguard Worker NewAllocaEndOffset(NewAllocaEndOffset),
2209*9880d681SAndroid Build Coastguard Worker NewAllocaTy(NewAI.getAllocatedType()),
2210*9880d681SAndroid Build Coastguard Worker IntTy(IsIntegerPromotable
2211*9880d681SAndroid Build Coastguard Worker ? Type::getIntNTy(
2212*9880d681SAndroid Build Coastguard Worker NewAI.getContext(),
2213*9880d681SAndroid Build Coastguard Worker DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2214*9880d681SAndroid Build Coastguard Worker : nullptr),
2215*9880d681SAndroid Build Coastguard Worker VecTy(PromotableVecTy),
2216*9880d681SAndroid Build Coastguard Worker ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2217*9880d681SAndroid Build Coastguard Worker ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2218*9880d681SAndroid Build Coastguard Worker BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2219*9880d681SAndroid Build Coastguard Worker OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2220*9880d681SAndroid Build Coastguard Worker IRB(NewAI.getContext(), ConstantFolder()) {
2221*9880d681SAndroid Build Coastguard Worker if (VecTy) {
2222*9880d681SAndroid Build Coastguard Worker assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2223*9880d681SAndroid Build Coastguard Worker "Only multiple-of-8 sized vector elements are viable");
2224*9880d681SAndroid Build Coastguard Worker ++NumVectorized;
2225*9880d681SAndroid Build Coastguard Worker }
2226*9880d681SAndroid Build Coastguard Worker assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2227*9880d681SAndroid Build Coastguard Worker }
2228*9880d681SAndroid Build Coastguard Worker
visit(AllocaSlices::const_iterator I)2229*9880d681SAndroid Build Coastguard Worker bool visit(AllocaSlices::const_iterator I) {
2230*9880d681SAndroid Build Coastguard Worker bool CanSROA = true;
2231*9880d681SAndroid Build Coastguard Worker BeginOffset = I->beginOffset();
2232*9880d681SAndroid Build Coastguard Worker EndOffset = I->endOffset();
2233*9880d681SAndroid Build Coastguard Worker IsSplittable = I->isSplittable();
2234*9880d681SAndroid Build Coastguard Worker IsSplit =
2235*9880d681SAndroid Build Coastguard Worker BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2236*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2237*9880d681SAndroid Build Coastguard Worker DEBUG(AS.printSlice(dbgs(), I, ""));
2238*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "\n");
2239*9880d681SAndroid Build Coastguard Worker
2240*9880d681SAndroid Build Coastguard Worker // Compute the intersecting offset range.
2241*9880d681SAndroid Build Coastguard Worker assert(BeginOffset < NewAllocaEndOffset);
2242*9880d681SAndroid Build Coastguard Worker assert(EndOffset > NewAllocaBeginOffset);
2243*9880d681SAndroid Build Coastguard Worker NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2244*9880d681SAndroid Build Coastguard Worker NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2245*9880d681SAndroid Build Coastguard Worker
2246*9880d681SAndroid Build Coastguard Worker SliceSize = NewEndOffset - NewBeginOffset;
2247*9880d681SAndroid Build Coastguard Worker
2248*9880d681SAndroid Build Coastguard Worker OldUse = I->getUse();
2249*9880d681SAndroid Build Coastguard Worker OldPtr = cast<Instruction>(OldUse->get());
2250*9880d681SAndroid Build Coastguard Worker
2251*9880d681SAndroid Build Coastguard Worker Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2252*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(OldUserI);
2253*9880d681SAndroid Build Coastguard Worker IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2254*9880d681SAndroid Build Coastguard Worker IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2255*9880d681SAndroid Build Coastguard Worker
2256*9880d681SAndroid Build Coastguard Worker CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2257*9880d681SAndroid Build Coastguard Worker if (VecTy || IntTy)
2258*9880d681SAndroid Build Coastguard Worker assert(CanSROA);
2259*9880d681SAndroid Build Coastguard Worker return CanSROA;
2260*9880d681SAndroid Build Coastguard Worker }
2261*9880d681SAndroid Build Coastguard Worker
2262*9880d681SAndroid Build Coastguard Worker private:
2263*9880d681SAndroid Build Coastguard Worker // Make sure the other visit overloads are visible.
2264*9880d681SAndroid Build Coastguard Worker using Base::visit;
2265*9880d681SAndroid Build Coastguard Worker
2266*9880d681SAndroid Build Coastguard Worker // Every instruction which can end up as a user must have a rewrite rule.
visitInstruction(Instruction & I)2267*9880d681SAndroid Build Coastguard Worker bool visitInstruction(Instruction &I) {
2268*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2269*9880d681SAndroid Build Coastguard Worker llvm_unreachable("No rewrite rule for this instruction!");
2270*9880d681SAndroid Build Coastguard Worker }
2271*9880d681SAndroid Build Coastguard Worker
getNewAllocaSlicePtr(IRBuilderTy & IRB,Type * PointerTy)2272*9880d681SAndroid Build Coastguard Worker Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2273*9880d681SAndroid Build Coastguard Worker // Note that the offset computation can use BeginOffset or NewBeginOffset
2274*9880d681SAndroid Build Coastguard Worker // interchangeably for unsplit slices.
2275*9880d681SAndroid Build Coastguard Worker assert(IsSplit || BeginOffset == NewBeginOffset);
2276*9880d681SAndroid Build Coastguard Worker uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2277*9880d681SAndroid Build Coastguard Worker
2278*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
2279*9880d681SAndroid Build Coastguard Worker StringRef OldName = OldPtr->getName();
2280*9880d681SAndroid Build Coastguard Worker // Skip through the last '.sroa.' component of the name.
2281*9880d681SAndroid Build Coastguard Worker size_t LastSROAPrefix = OldName.rfind(".sroa.");
2282*9880d681SAndroid Build Coastguard Worker if (LastSROAPrefix != StringRef::npos) {
2283*9880d681SAndroid Build Coastguard Worker OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2284*9880d681SAndroid Build Coastguard Worker // Look for an SROA slice index.
2285*9880d681SAndroid Build Coastguard Worker size_t IndexEnd = OldName.find_first_not_of("0123456789");
2286*9880d681SAndroid Build Coastguard Worker if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2287*9880d681SAndroid Build Coastguard Worker // Strip the index and look for the offset.
2288*9880d681SAndroid Build Coastguard Worker OldName = OldName.substr(IndexEnd + 1);
2289*9880d681SAndroid Build Coastguard Worker size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2290*9880d681SAndroid Build Coastguard Worker if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2291*9880d681SAndroid Build Coastguard Worker // Strip the offset.
2292*9880d681SAndroid Build Coastguard Worker OldName = OldName.substr(OffsetEnd + 1);
2293*9880d681SAndroid Build Coastguard Worker }
2294*9880d681SAndroid Build Coastguard Worker }
2295*9880d681SAndroid Build Coastguard Worker // Strip any SROA suffixes as well.
2296*9880d681SAndroid Build Coastguard Worker OldName = OldName.substr(0, OldName.find(".sroa_"));
2297*9880d681SAndroid Build Coastguard Worker #endif
2298*9880d681SAndroid Build Coastguard Worker
2299*9880d681SAndroid Build Coastguard Worker return getAdjustedPtr(IRB, DL, &NewAI,
2300*9880d681SAndroid Build Coastguard Worker APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2301*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
2302*9880d681SAndroid Build Coastguard Worker Twine(OldName) + "."
2303*9880d681SAndroid Build Coastguard Worker #else
2304*9880d681SAndroid Build Coastguard Worker Twine()
2305*9880d681SAndroid Build Coastguard Worker #endif
2306*9880d681SAndroid Build Coastguard Worker );
2307*9880d681SAndroid Build Coastguard Worker }
2308*9880d681SAndroid Build Coastguard Worker
2309*9880d681SAndroid Build Coastguard Worker /// \brief Compute suitable alignment to access this slice of the *new*
2310*9880d681SAndroid Build Coastguard Worker /// alloca.
2311*9880d681SAndroid Build Coastguard Worker ///
2312*9880d681SAndroid Build Coastguard Worker /// You can optionally pass a type to this routine and if that type's ABI
2313*9880d681SAndroid Build Coastguard Worker /// alignment is itself suitable, this will return zero.
getSliceAlign(Type * Ty=nullptr)2314*9880d681SAndroid Build Coastguard Worker unsigned getSliceAlign(Type *Ty = nullptr) {
2315*9880d681SAndroid Build Coastguard Worker unsigned NewAIAlign = NewAI.getAlignment();
2316*9880d681SAndroid Build Coastguard Worker if (!NewAIAlign)
2317*9880d681SAndroid Build Coastguard Worker NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2318*9880d681SAndroid Build Coastguard Worker unsigned Align =
2319*9880d681SAndroid Build Coastguard Worker MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2320*9880d681SAndroid Build Coastguard Worker return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2321*9880d681SAndroid Build Coastguard Worker }
2322*9880d681SAndroid Build Coastguard Worker
getIndex(uint64_t Offset)2323*9880d681SAndroid Build Coastguard Worker unsigned getIndex(uint64_t Offset) {
2324*9880d681SAndroid Build Coastguard Worker assert(VecTy && "Can only call getIndex when rewriting a vector");
2325*9880d681SAndroid Build Coastguard Worker uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2326*9880d681SAndroid Build Coastguard Worker assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2327*9880d681SAndroid Build Coastguard Worker uint32_t Index = RelOffset / ElementSize;
2328*9880d681SAndroid Build Coastguard Worker assert(Index * ElementSize == RelOffset);
2329*9880d681SAndroid Build Coastguard Worker return Index;
2330*9880d681SAndroid Build Coastguard Worker }
2331*9880d681SAndroid Build Coastguard Worker
deleteIfTriviallyDead(Value * V)2332*9880d681SAndroid Build Coastguard Worker void deleteIfTriviallyDead(Value *V) {
2333*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(V);
2334*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(I))
2335*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(I);
2336*9880d681SAndroid Build Coastguard Worker }
2337*9880d681SAndroid Build Coastguard Worker
rewriteVectorizedLoadInst()2338*9880d681SAndroid Build Coastguard Worker Value *rewriteVectorizedLoadInst() {
2339*9880d681SAndroid Build Coastguard Worker unsigned BeginIndex = getIndex(NewBeginOffset);
2340*9880d681SAndroid Build Coastguard Worker unsigned EndIndex = getIndex(NewEndOffset);
2341*9880d681SAndroid Build Coastguard Worker assert(EndIndex > BeginIndex && "Empty vector!");
2342*9880d681SAndroid Build Coastguard Worker
2343*9880d681SAndroid Build Coastguard Worker Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2344*9880d681SAndroid Build Coastguard Worker return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2345*9880d681SAndroid Build Coastguard Worker }
2346*9880d681SAndroid Build Coastguard Worker
rewriteIntegerLoad(LoadInst & LI)2347*9880d681SAndroid Build Coastguard Worker Value *rewriteIntegerLoad(LoadInst &LI) {
2348*9880d681SAndroid Build Coastguard Worker assert(IntTy && "We cannot insert an integer to the alloca");
2349*9880d681SAndroid Build Coastguard Worker assert(!LI.isVolatile());
2350*9880d681SAndroid Build Coastguard Worker Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2351*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, IntTy);
2352*9880d681SAndroid Build Coastguard Worker assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2353*9880d681SAndroid Build Coastguard Worker uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2354*9880d681SAndroid Build Coastguard Worker if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2355*9880d681SAndroid Build Coastguard Worker IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2356*9880d681SAndroid Build Coastguard Worker V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2357*9880d681SAndroid Build Coastguard Worker }
2358*9880d681SAndroid Build Coastguard Worker // It is possible that the extracted type is not the load type. This
2359*9880d681SAndroid Build Coastguard Worker // happens if there is a load past the end of the alloca, and as
2360*9880d681SAndroid Build Coastguard Worker // a consequence the slice is narrower but still a candidate for integer
2361*9880d681SAndroid Build Coastguard Worker // lowering. To handle this case, we just zero extend the extracted
2362*9880d681SAndroid Build Coastguard Worker // integer.
2363*9880d681SAndroid Build Coastguard Worker assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2364*9880d681SAndroid Build Coastguard Worker "Can only handle an extract for an overly wide load");
2365*9880d681SAndroid Build Coastguard Worker if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2366*9880d681SAndroid Build Coastguard Worker V = IRB.CreateZExt(V, LI.getType());
2367*9880d681SAndroid Build Coastguard Worker return V;
2368*9880d681SAndroid Build Coastguard Worker }
2369*9880d681SAndroid Build Coastguard Worker
visitLoadInst(LoadInst & LI)2370*9880d681SAndroid Build Coastguard Worker bool visitLoadInst(LoadInst &LI) {
2371*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << LI << "\n");
2372*9880d681SAndroid Build Coastguard Worker Value *OldOp = LI.getOperand(0);
2373*9880d681SAndroid Build Coastguard Worker assert(OldOp == OldPtr);
2374*9880d681SAndroid Build Coastguard Worker
2375*9880d681SAndroid Build Coastguard Worker Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2376*9880d681SAndroid Build Coastguard Worker : LI.getType();
2377*9880d681SAndroid Build Coastguard Worker const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
2378*9880d681SAndroid Build Coastguard Worker bool IsPtrAdjusted = false;
2379*9880d681SAndroid Build Coastguard Worker Value *V;
2380*9880d681SAndroid Build Coastguard Worker if (VecTy) {
2381*9880d681SAndroid Build Coastguard Worker V = rewriteVectorizedLoadInst();
2382*9880d681SAndroid Build Coastguard Worker } else if (IntTy && LI.getType()->isIntegerTy()) {
2383*9880d681SAndroid Build Coastguard Worker V = rewriteIntegerLoad(LI);
2384*9880d681SAndroid Build Coastguard Worker } else if (NewBeginOffset == NewAllocaBeginOffset &&
2385*9880d681SAndroid Build Coastguard Worker NewEndOffset == NewAllocaEndOffset &&
2386*9880d681SAndroid Build Coastguard Worker (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2387*9880d681SAndroid Build Coastguard Worker (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2388*9880d681SAndroid Build Coastguard Worker TargetTy->isIntegerTy()))) {
2389*9880d681SAndroid Build Coastguard Worker LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2390*9880d681SAndroid Build Coastguard Worker LI.isVolatile(), LI.getName());
2391*9880d681SAndroid Build Coastguard Worker if (LI.isVolatile())
2392*9880d681SAndroid Build Coastguard Worker NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2393*9880d681SAndroid Build Coastguard Worker V = NewLI;
2394*9880d681SAndroid Build Coastguard Worker
2395*9880d681SAndroid Build Coastguard Worker // If this is an integer load past the end of the slice (which means the
2396*9880d681SAndroid Build Coastguard Worker // bytes outside the slice are undef or this load is dead) just forcibly
2397*9880d681SAndroid Build Coastguard Worker // fix the integer size with correct handling of endianness.
2398*9880d681SAndroid Build Coastguard Worker if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2399*9880d681SAndroid Build Coastguard Worker if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2400*9880d681SAndroid Build Coastguard Worker if (AITy->getBitWidth() < TITy->getBitWidth()) {
2401*9880d681SAndroid Build Coastguard Worker V = IRB.CreateZExt(V, TITy, "load.ext");
2402*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian())
2403*9880d681SAndroid Build Coastguard Worker V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2404*9880d681SAndroid Build Coastguard Worker "endian_shift");
2405*9880d681SAndroid Build Coastguard Worker }
2406*9880d681SAndroid Build Coastguard Worker } else {
2407*9880d681SAndroid Build Coastguard Worker Type *LTy = TargetTy->getPointerTo();
2408*9880d681SAndroid Build Coastguard Worker LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2409*9880d681SAndroid Build Coastguard Worker getSliceAlign(TargetTy),
2410*9880d681SAndroid Build Coastguard Worker LI.isVolatile(), LI.getName());
2411*9880d681SAndroid Build Coastguard Worker if (LI.isVolatile())
2412*9880d681SAndroid Build Coastguard Worker NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2413*9880d681SAndroid Build Coastguard Worker
2414*9880d681SAndroid Build Coastguard Worker V = NewLI;
2415*9880d681SAndroid Build Coastguard Worker IsPtrAdjusted = true;
2416*9880d681SAndroid Build Coastguard Worker }
2417*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, TargetTy);
2418*9880d681SAndroid Build Coastguard Worker
2419*9880d681SAndroid Build Coastguard Worker if (IsSplit) {
2420*9880d681SAndroid Build Coastguard Worker assert(!LI.isVolatile());
2421*9880d681SAndroid Build Coastguard Worker assert(LI.getType()->isIntegerTy() &&
2422*9880d681SAndroid Build Coastguard Worker "Only integer type loads and stores are split");
2423*9880d681SAndroid Build Coastguard Worker assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2424*9880d681SAndroid Build Coastguard Worker "Split load isn't smaller than original load");
2425*9880d681SAndroid Build Coastguard Worker assert(LI.getType()->getIntegerBitWidth() ==
2426*9880d681SAndroid Build Coastguard Worker DL.getTypeStoreSizeInBits(LI.getType()) &&
2427*9880d681SAndroid Build Coastguard Worker "Non-byte-multiple bit width");
2428*9880d681SAndroid Build Coastguard Worker // Move the insertion point just past the load so that we can refer to it.
2429*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2430*9880d681SAndroid Build Coastguard Worker // Create a placeholder value with the same type as LI to use as the
2431*9880d681SAndroid Build Coastguard Worker // basis for the new value. This allows us to replace the uses of LI with
2432*9880d681SAndroid Build Coastguard Worker // the computed value, and then replace the placeholder with LI, leaving
2433*9880d681SAndroid Build Coastguard Worker // LI only used for this computation.
2434*9880d681SAndroid Build Coastguard Worker Value *Placeholder =
2435*9880d681SAndroid Build Coastguard Worker new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2436*9880d681SAndroid Build Coastguard Worker V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2437*9880d681SAndroid Build Coastguard Worker "insert");
2438*9880d681SAndroid Build Coastguard Worker LI.replaceAllUsesWith(V);
2439*9880d681SAndroid Build Coastguard Worker Placeholder->replaceAllUsesWith(&LI);
2440*9880d681SAndroid Build Coastguard Worker delete Placeholder;
2441*9880d681SAndroid Build Coastguard Worker } else {
2442*9880d681SAndroid Build Coastguard Worker LI.replaceAllUsesWith(V);
2443*9880d681SAndroid Build Coastguard Worker }
2444*9880d681SAndroid Build Coastguard Worker
2445*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&LI);
2446*9880d681SAndroid Build Coastguard Worker deleteIfTriviallyDead(OldOp);
2447*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *V << "\n");
2448*9880d681SAndroid Build Coastguard Worker return !LI.isVolatile() && !IsPtrAdjusted;
2449*9880d681SAndroid Build Coastguard Worker }
2450*9880d681SAndroid Build Coastguard Worker
rewriteVectorizedStoreInst(Value * V,StoreInst & SI,Value * OldOp)2451*9880d681SAndroid Build Coastguard Worker bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2452*9880d681SAndroid Build Coastguard Worker if (V->getType() != VecTy) {
2453*9880d681SAndroid Build Coastguard Worker unsigned BeginIndex = getIndex(NewBeginOffset);
2454*9880d681SAndroid Build Coastguard Worker unsigned EndIndex = getIndex(NewEndOffset);
2455*9880d681SAndroid Build Coastguard Worker assert(EndIndex > BeginIndex && "Empty vector!");
2456*9880d681SAndroid Build Coastguard Worker unsigned NumElements = EndIndex - BeginIndex;
2457*9880d681SAndroid Build Coastguard Worker assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2458*9880d681SAndroid Build Coastguard Worker Type *SliceTy = (NumElements == 1)
2459*9880d681SAndroid Build Coastguard Worker ? ElementTy
2460*9880d681SAndroid Build Coastguard Worker : VectorType::get(ElementTy, NumElements);
2461*9880d681SAndroid Build Coastguard Worker if (V->getType() != SliceTy)
2462*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, SliceTy);
2463*9880d681SAndroid Build Coastguard Worker
2464*9880d681SAndroid Build Coastguard Worker // Mix in the existing elements.
2465*9880d681SAndroid Build Coastguard Worker Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2466*9880d681SAndroid Build Coastguard Worker V = insertVector(IRB, Old, V, BeginIndex, "vec");
2467*9880d681SAndroid Build Coastguard Worker }
2468*9880d681SAndroid Build Coastguard Worker StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2469*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&SI);
2470*9880d681SAndroid Build Coastguard Worker
2471*9880d681SAndroid Build Coastguard Worker (void)Store;
2472*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *Store << "\n");
2473*9880d681SAndroid Build Coastguard Worker return true;
2474*9880d681SAndroid Build Coastguard Worker }
2475*9880d681SAndroid Build Coastguard Worker
rewriteIntegerStore(Value * V,StoreInst & SI)2476*9880d681SAndroid Build Coastguard Worker bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2477*9880d681SAndroid Build Coastguard Worker assert(IntTy && "We cannot extract an integer from the alloca");
2478*9880d681SAndroid Build Coastguard Worker assert(!SI.isVolatile());
2479*9880d681SAndroid Build Coastguard Worker if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2480*9880d681SAndroid Build Coastguard Worker Value *Old =
2481*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2482*9880d681SAndroid Build Coastguard Worker Old = convertValue(DL, IRB, Old, IntTy);
2483*9880d681SAndroid Build Coastguard Worker assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2484*9880d681SAndroid Build Coastguard Worker uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2485*9880d681SAndroid Build Coastguard Worker V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2486*9880d681SAndroid Build Coastguard Worker }
2487*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, NewAllocaTy);
2488*9880d681SAndroid Build Coastguard Worker StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2489*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&SI);
2490*9880d681SAndroid Build Coastguard Worker (void)Store;
2491*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *Store << "\n");
2492*9880d681SAndroid Build Coastguard Worker return true;
2493*9880d681SAndroid Build Coastguard Worker }
2494*9880d681SAndroid Build Coastguard Worker
visitStoreInst(StoreInst & SI)2495*9880d681SAndroid Build Coastguard Worker bool visitStoreInst(StoreInst &SI) {
2496*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << SI << "\n");
2497*9880d681SAndroid Build Coastguard Worker Value *OldOp = SI.getOperand(1);
2498*9880d681SAndroid Build Coastguard Worker assert(OldOp == OldPtr);
2499*9880d681SAndroid Build Coastguard Worker
2500*9880d681SAndroid Build Coastguard Worker Value *V = SI.getValueOperand();
2501*9880d681SAndroid Build Coastguard Worker
2502*9880d681SAndroid Build Coastguard Worker // Strip all inbounds GEPs and pointer casts to try to dig out any root
2503*9880d681SAndroid Build Coastguard Worker // alloca that should be re-examined after promoting this alloca.
2504*9880d681SAndroid Build Coastguard Worker if (V->getType()->isPointerTy())
2505*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2506*9880d681SAndroid Build Coastguard Worker Pass.PostPromotionWorklist.insert(AI);
2507*9880d681SAndroid Build Coastguard Worker
2508*9880d681SAndroid Build Coastguard Worker if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2509*9880d681SAndroid Build Coastguard Worker assert(!SI.isVolatile());
2510*9880d681SAndroid Build Coastguard Worker assert(V->getType()->isIntegerTy() &&
2511*9880d681SAndroid Build Coastguard Worker "Only integer type loads and stores are split");
2512*9880d681SAndroid Build Coastguard Worker assert(V->getType()->getIntegerBitWidth() ==
2513*9880d681SAndroid Build Coastguard Worker DL.getTypeStoreSizeInBits(V->getType()) &&
2514*9880d681SAndroid Build Coastguard Worker "Non-byte-multiple bit width");
2515*9880d681SAndroid Build Coastguard Worker IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2516*9880d681SAndroid Build Coastguard Worker V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2517*9880d681SAndroid Build Coastguard Worker "extract");
2518*9880d681SAndroid Build Coastguard Worker }
2519*9880d681SAndroid Build Coastguard Worker
2520*9880d681SAndroid Build Coastguard Worker if (VecTy)
2521*9880d681SAndroid Build Coastguard Worker return rewriteVectorizedStoreInst(V, SI, OldOp);
2522*9880d681SAndroid Build Coastguard Worker if (IntTy && V->getType()->isIntegerTy())
2523*9880d681SAndroid Build Coastguard Worker return rewriteIntegerStore(V, SI);
2524*9880d681SAndroid Build Coastguard Worker
2525*9880d681SAndroid Build Coastguard Worker const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
2526*9880d681SAndroid Build Coastguard Worker StoreInst *NewSI;
2527*9880d681SAndroid Build Coastguard Worker if (NewBeginOffset == NewAllocaBeginOffset &&
2528*9880d681SAndroid Build Coastguard Worker NewEndOffset == NewAllocaEndOffset &&
2529*9880d681SAndroid Build Coastguard Worker (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2530*9880d681SAndroid Build Coastguard Worker (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2531*9880d681SAndroid Build Coastguard Worker V->getType()->isIntegerTy()))) {
2532*9880d681SAndroid Build Coastguard Worker // If this is an integer store past the end of slice (and thus the bytes
2533*9880d681SAndroid Build Coastguard Worker // past that point are irrelevant or this is unreachable), truncate the
2534*9880d681SAndroid Build Coastguard Worker // value prior to storing.
2535*9880d681SAndroid Build Coastguard Worker if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2536*9880d681SAndroid Build Coastguard Worker if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2537*9880d681SAndroid Build Coastguard Worker if (VITy->getBitWidth() > AITy->getBitWidth()) {
2538*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian())
2539*9880d681SAndroid Build Coastguard Worker V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2540*9880d681SAndroid Build Coastguard Worker "endian_shift");
2541*9880d681SAndroid Build Coastguard Worker V = IRB.CreateTrunc(V, AITy, "load.trunc");
2542*9880d681SAndroid Build Coastguard Worker }
2543*9880d681SAndroid Build Coastguard Worker
2544*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, NewAllocaTy);
2545*9880d681SAndroid Build Coastguard Worker NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2546*9880d681SAndroid Build Coastguard Worker SI.isVolatile());
2547*9880d681SAndroid Build Coastguard Worker } else {
2548*9880d681SAndroid Build Coastguard Worker Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2549*9880d681SAndroid Build Coastguard Worker NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2550*9880d681SAndroid Build Coastguard Worker SI.isVolatile());
2551*9880d681SAndroid Build Coastguard Worker }
2552*9880d681SAndroid Build Coastguard Worker if (SI.isVolatile())
2553*9880d681SAndroid Build Coastguard Worker NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
2554*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&SI);
2555*9880d681SAndroid Build Coastguard Worker deleteIfTriviallyDead(OldOp);
2556*9880d681SAndroid Build Coastguard Worker
2557*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *NewSI << "\n");
2558*9880d681SAndroid Build Coastguard Worker return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2559*9880d681SAndroid Build Coastguard Worker }
2560*9880d681SAndroid Build Coastguard Worker
2561*9880d681SAndroid Build Coastguard Worker /// \brief Compute an integer value from splatting an i8 across the given
2562*9880d681SAndroid Build Coastguard Worker /// number of bytes.
2563*9880d681SAndroid Build Coastguard Worker ///
2564*9880d681SAndroid Build Coastguard Worker /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2565*9880d681SAndroid Build Coastguard Worker /// call this routine.
2566*9880d681SAndroid Build Coastguard Worker /// FIXME: Heed the advice above.
2567*9880d681SAndroid Build Coastguard Worker ///
2568*9880d681SAndroid Build Coastguard Worker /// \param V The i8 value to splat.
2569*9880d681SAndroid Build Coastguard Worker /// \param Size The number of bytes in the output (assuming i8 is one byte)
getIntegerSplat(Value * V,unsigned Size)2570*9880d681SAndroid Build Coastguard Worker Value *getIntegerSplat(Value *V, unsigned Size) {
2571*9880d681SAndroid Build Coastguard Worker assert(Size > 0 && "Expected a positive number of bytes.");
2572*9880d681SAndroid Build Coastguard Worker IntegerType *VTy = cast<IntegerType>(V->getType());
2573*9880d681SAndroid Build Coastguard Worker assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2574*9880d681SAndroid Build Coastguard Worker if (Size == 1)
2575*9880d681SAndroid Build Coastguard Worker return V;
2576*9880d681SAndroid Build Coastguard Worker
2577*9880d681SAndroid Build Coastguard Worker Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2578*9880d681SAndroid Build Coastguard Worker V = IRB.CreateMul(
2579*9880d681SAndroid Build Coastguard Worker IRB.CreateZExt(V, SplatIntTy, "zext"),
2580*9880d681SAndroid Build Coastguard Worker ConstantExpr::getUDiv(
2581*9880d681SAndroid Build Coastguard Worker Constant::getAllOnesValue(SplatIntTy),
2582*9880d681SAndroid Build Coastguard Worker ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2583*9880d681SAndroid Build Coastguard Worker SplatIntTy)),
2584*9880d681SAndroid Build Coastguard Worker "isplat");
2585*9880d681SAndroid Build Coastguard Worker return V;
2586*9880d681SAndroid Build Coastguard Worker }
2587*9880d681SAndroid Build Coastguard Worker
2588*9880d681SAndroid Build Coastguard Worker /// \brief Compute a vector splat for a given element value.
getVectorSplat(Value * V,unsigned NumElements)2589*9880d681SAndroid Build Coastguard Worker Value *getVectorSplat(Value *V, unsigned NumElements) {
2590*9880d681SAndroid Build Coastguard Worker V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2591*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " splat: " << *V << "\n");
2592*9880d681SAndroid Build Coastguard Worker return V;
2593*9880d681SAndroid Build Coastguard Worker }
2594*9880d681SAndroid Build Coastguard Worker
visitMemSetInst(MemSetInst & II)2595*9880d681SAndroid Build Coastguard Worker bool visitMemSetInst(MemSetInst &II) {
2596*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << II << "\n");
2597*9880d681SAndroid Build Coastguard Worker assert(II.getRawDest() == OldPtr);
2598*9880d681SAndroid Build Coastguard Worker
2599*9880d681SAndroid Build Coastguard Worker // If the memset has a variable size, it cannot be split, just adjust the
2600*9880d681SAndroid Build Coastguard Worker // pointer to the new alloca.
2601*9880d681SAndroid Build Coastguard Worker if (!isa<Constant>(II.getLength())) {
2602*9880d681SAndroid Build Coastguard Worker assert(!IsSplit);
2603*9880d681SAndroid Build Coastguard Worker assert(NewBeginOffset == BeginOffset);
2604*9880d681SAndroid Build Coastguard Worker II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2605*9880d681SAndroid Build Coastguard Worker Type *CstTy = II.getAlignmentCst()->getType();
2606*9880d681SAndroid Build Coastguard Worker II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2607*9880d681SAndroid Build Coastguard Worker
2608*9880d681SAndroid Build Coastguard Worker deleteIfTriviallyDead(OldPtr);
2609*9880d681SAndroid Build Coastguard Worker return false;
2610*9880d681SAndroid Build Coastguard Worker }
2611*9880d681SAndroid Build Coastguard Worker
2612*9880d681SAndroid Build Coastguard Worker // Record this instruction for deletion.
2613*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&II);
2614*9880d681SAndroid Build Coastguard Worker
2615*9880d681SAndroid Build Coastguard Worker Type *AllocaTy = NewAI.getAllocatedType();
2616*9880d681SAndroid Build Coastguard Worker Type *ScalarTy = AllocaTy->getScalarType();
2617*9880d681SAndroid Build Coastguard Worker
2618*9880d681SAndroid Build Coastguard Worker // If this doesn't map cleanly onto the alloca type, and that type isn't
2619*9880d681SAndroid Build Coastguard Worker // a single value type, just emit a memset.
2620*9880d681SAndroid Build Coastguard Worker if (!VecTy && !IntTy &&
2621*9880d681SAndroid Build Coastguard Worker (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2622*9880d681SAndroid Build Coastguard Worker SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2623*9880d681SAndroid Build Coastguard Worker !AllocaTy->isSingleValueType() ||
2624*9880d681SAndroid Build Coastguard Worker !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2625*9880d681SAndroid Build Coastguard Worker DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2626*9880d681SAndroid Build Coastguard Worker Type *SizeTy = II.getLength()->getType();
2627*9880d681SAndroid Build Coastguard Worker Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2628*9880d681SAndroid Build Coastguard Worker CallInst *New = IRB.CreateMemSet(
2629*9880d681SAndroid Build Coastguard Worker getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2630*9880d681SAndroid Build Coastguard Worker getSliceAlign(), II.isVolatile());
2631*9880d681SAndroid Build Coastguard Worker (void)New;
2632*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *New << "\n");
2633*9880d681SAndroid Build Coastguard Worker return false;
2634*9880d681SAndroid Build Coastguard Worker }
2635*9880d681SAndroid Build Coastguard Worker
2636*9880d681SAndroid Build Coastguard Worker // If we can represent this as a simple value, we have to build the actual
2637*9880d681SAndroid Build Coastguard Worker // value to store, which requires expanding the byte present in memset to
2638*9880d681SAndroid Build Coastguard Worker // a sensible representation for the alloca type. This is essentially
2639*9880d681SAndroid Build Coastguard Worker // splatting the byte to a sufficiently wide integer, splatting it across
2640*9880d681SAndroid Build Coastguard Worker // any desired vector width, and bitcasting to the final type.
2641*9880d681SAndroid Build Coastguard Worker Value *V;
2642*9880d681SAndroid Build Coastguard Worker
2643*9880d681SAndroid Build Coastguard Worker if (VecTy) {
2644*9880d681SAndroid Build Coastguard Worker // If this is a memset of a vectorized alloca, insert it.
2645*9880d681SAndroid Build Coastguard Worker assert(ElementTy == ScalarTy);
2646*9880d681SAndroid Build Coastguard Worker
2647*9880d681SAndroid Build Coastguard Worker unsigned BeginIndex = getIndex(NewBeginOffset);
2648*9880d681SAndroid Build Coastguard Worker unsigned EndIndex = getIndex(NewEndOffset);
2649*9880d681SAndroid Build Coastguard Worker assert(EndIndex > BeginIndex && "Empty vector!");
2650*9880d681SAndroid Build Coastguard Worker unsigned NumElements = EndIndex - BeginIndex;
2651*9880d681SAndroid Build Coastguard Worker assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2652*9880d681SAndroid Build Coastguard Worker
2653*9880d681SAndroid Build Coastguard Worker Value *Splat =
2654*9880d681SAndroid Build Coastguard Worker getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2655*9880d681SAndroid Build Coastguard Worker Splat = convertValue(DL, IRB, Splat, ElementTy);
2656*9880d681SAndroid Build Coastguard Worker if (NumElements > 1)
2657*9880d681SAndroid Build Coastguard Worker Splat = getVectorSplat(Splat, NumElements);
2658*9880d681SAndroid Build Coastguard Worker
2659*9880d681SAndroid Build Coastguard Worker Value *Old =
2660*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2661*9880d681SAndroid Build Coastguard Worker V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2662*9880d681SAndroid Build Coastguard Worker } else if (IntTy) {
2663*9880d681SAndroid Build Coastguard Worker // If this is a memset on an alloca where we can widen stores, insert the
2664*9880d681SAndroid Build Coastguard Worker // set integer.
2665*9880d681SAndroid Build Coastguard Worker assert(!II.isVolatile());
2666*9880d681SAndroid Build Coastguard Worker
2667*9880d681SAndroid Build Coastguard Worker uint64_t Size = NewEndOffset - NewBeginOffset;
2668*9880d681SAndroid Build Coastguard Worker V = getIntegerSplat(II.getValue(), Size);
2669*9880d681SAndroid Build Coastguard Worker
2670*9880d681SAndroid Build Coastguard Worker if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2671*9880d681SAndroid Build Coastguard Worker EndOffset != NewAllocaBeginOffset)) {
2672*9880d681SAndroid Build Coastguard Worker Value *Old =
2673*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2674*9880d681SAndroid Build Coastguard Worker Old = convertValue(DL, IRB, Old, IntTy);
2675*9880d681SAndroid Build Coastguard Worker uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2676*9880d681SAndroid Build Coastguard Worker V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2677*9880d681SAndroid Build Coastguard Worker } else {
2678*9880d681SAndroid Build Coastguard Worker assert(V->getType() == IntTy &&
2679*9880d681SAndroid Build Coastguard Worker "Wrong type for an alloca wide integer!");
2680*9880d681SAndroid Build Coastguard Worker }
2681*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, AllocaTy);
2682*9880d681SAndroid Build Coastguard Worker } else {
2683*9880d681SAndroid Build Coastguard Worker // Established these invariants above.
2684*9880d681SAndroid Build Coastguard Worker assert(NewBeginOffset == NewAllocaBeginOffset);
2685*9880d681SAndroid Build Coastguard Worker assert(NewEndOffset == NewAllocaEndOffset);
2686*9880d681SAndroid Build Coastguard Worker
2687*9880d681SAndroid Build Coastguard Worker V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2688*9880d681SAndroid Build Coastguard Worker if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2689*9880d681SAndroid Build Coastguard Worker V = getVectorSplat(V, AllocaVecTy->getNumElements());
2690*9880d681SAndroid Build Coastguard Worker
2691*9880d681SAndroid Build Coastguard Worker V = convertValue(DL, IRB, V, AllocaTy);
2692*9880d681SAndroid Build Coastguard Worker }
2693*9880d681SAndroid Build Coastguard Worker
2694*9880d681SAndroid Build Coastguard Worker Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2695*9880d681SAndroid Build Coastguard Worker II.isVolatile());
2696*9880d681SAndroid Build Coastguard Worker (void)New;
2697*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *New << "\n");
2698*9880d681SAndroid Build Coastguard Worker return !II.isVolatile();
2699*9880d681SAndroid Build Coastguard Worker }
2700*9880d681SAndroid Build Coastguard Worker
visitMemTransferInst(MemTransferInst & II)2701*9880d681SAndroid Build Coastguard Worker bool visitMemTransferInst(MemTransferInst &II) {
2702*9880d681SAndroid Build Coastguard Worker // Rewriting of memory transfer instructions can be a bit tricky. We break
2703*9880d681SAndroid Build Coastguard Worker // them into two categories: split intrinsics and unsplit intrinsics.
2704*9880d681SAndroid Build Coastguard Worker
2705*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << II << "\n");
2706*9880d681SAndroid Build Coastguard Worker
2707*9880d681SAndroid Build Coastguard Worker bool IsDest = &II.getRawDestUse() == OldUse;
2708*9880d681SAndroid Build Coastguard Worker assert((IsDest && II.getRawDest() == OldPtr) ||
2709*9880d681SAndroid Build Coastguard Worker (!IsDest && II.getRawSource() == OldPtr));
2710*9880d681SAndroid Build Coastguard Worker
2711*9880d681SAndroid Build Coastguard Worker unsigned SliceAlign = getSliceAlign();
2712*9880d681SAndroid Build Coastguard Worker
2713*9880d681SAndroid Build Coastguard Worker // For unsplit intrinsics, we simply modify the source and destination
2714*9880d681SAndroid Build Coastguard Worker // pointers in place. This isn't just an optimization, it is a matter of
2715*9880d681SAndroid Build Coastguard Worker // correctness. With unsplit intrinsics we may be dealing with transfers
2716*9880d681SAndroid Build Coastguard Worker // within a single alloca before SROA ran, or with transfers that have
2717*9880d681SAndroid Build Coastguard Worker // a variable length. We may also be dealing with memmove instead of
2718*9880d681SAndroid Build Coastguard Worker // memcpy, and so simply updating the pointers is the necessary for us to
2719*9880d681SAndroid Build Coastguard Worker // update both source and dest of a single call.
2720*9880d681SAndroid Build Coastguard Worker if (!IsSplittable) {
2721*9880d681SAndroid Build Coastguard Worker Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2722*9880d681SAndroid Build Coastguard Worker if (IsDest)
2723*9880d681SAndroid Build Coastguard Worker II.setDest(AdjustedPtr);
2724*9880d681SAndroid Build Coastguard Worker else
2725*9880d681SAndroid Build Coastguard Worker II.setSource(AdjustedPtr);
2726*9880d681SAndroid Build Coastguard Worker
2727*9880d681SAndroid Build Coastguard Worker if (II.getAlignment() > SliceAlign) {
2728*9880d681SAndroid Build Coastguard Worker Type *CstTy = II.getAlignmentCst()->getType();
2729*9880d681SAndroid Build Coastguard Worker II.setAlignment(
2730*9880d681SAndroid Build Coastguard Worker ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2731*9880d681SAndroid Build Coastguard Worker }
2732*9880d681SAndroid Build Coastguard Worker
2733*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << II << "\n");
2734*9880d681SAndroid Build Coastguard Worker deleteIfTriviallyDead(OldPtr);
2735*9880d681SAndroid Build Coastguard Worker return false;
2736*9880d681SAndroid Build Coastguard Worker }
2737*9880d681SAndroid Build Coastguard Worker // For split transfer intrinsics we have an incredibly useful assurance:
2738*9880d681SAndroid Build Coastguard Worker // the source and destination do not reside within the same alloca, and at
2739*9880d681SAndroid Build Coastguard Worker // least one of them does not escape. This means that we can replace
2740*9880d681SAndroid Build Coastguard Worker // memmove with memcpy, and we don't need to worry about all manner of
2741*9880d681SAndroid Build Coastguard Worker // downsides to splitting and transforming the operations.
2742*9880d681SAndroid Build Coastguard Worker
2743*9880d681SAndroid Build Coastguard Worker // If this doesn't map cleanly onto the alloca type, and that type isn't
2744*9880d681SAndroid Build Coastguard Worker // a single value type, just emit a memcpy.
2745*9880d681SAndroid Build Coastguard Worker bool EmitMemCpy =
2746*9880d681SAndroid Build Coastguard Worker !VecTy && !IntTy &&
2747*9880d681SAndroid Build Coastguard Worker (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2748*9880d681SAndroid Build Coastguard Worker SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2749*9880d681SAndroid Build Coastguard Worker !NewAI.getAllocatedType()->isSingleValueType());
2750*9880d681SAndroid Build Coastguard Worker
2751*9880d681SAndroid Build Coastguard Worker // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2752*9880d681SAndroid Build Coastguard Worker // size hasn't been shrunk based on analysis of the viable range, this is
2753*9880d681SAndroid Build Coastguard Worker // a no-op.
2754*9880d681SAndroid Build Coastguard Worker if (EmitMemCpy && &OldAI == &NewAI) {
2755*9880d681SAndroid Build Coastguard Worker // Ensure the start lines up.
2756*9880d681SAndroid Build Coastguard Worker assert(NewBeginOffset == BeginOffset);
2757*9880d681SAndroid Build Coastguard Worker
2758*9880d681SAndroid Build Coastguard Worker // Rewrite the size as needed.
2759*9880d681SAndroid Build Coastguard Worker if (NewEndOffset != EndOffset)
2760*9880d681SAndroid Build Coastguard Worker II.setLength(ConstantInt::get(II.getLength()->getType(),
2761*9880d681SAndroid Build Coastguard Worker NewEndOffset - NewBeginOffset));
2762*9880d681SAndroid Build Coastguard Worker return false;
2763*9880d681SAndroid Build Coastguard Worker }
2764*9880d681SAndroid Build Coastguard Worker // Record this instruction for deletion.
2765*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&II);
2766*9880d681SAndroid Build Coastguard Worker
2767*9880d681SAndroid Build Coastguard Worker // Strip all inbounds GEPs and pointer casts to try to dig out any root
2768*9880d681SAndroid Build Coastguard Worker // alloca that should be re-examined after rewriting this instruction.
2769*9880d681SAndroid Build Coastguard Worker Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2770*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI =
2771*9880d681SAndroid Build Coastguard Worker dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2772*9880d681SAndroid Build Coastguard Worker assert(AI != &OldAI && AI != &NewAI &&
2773*9880d681SAndroid Build Coastguard Worker "Splittable transfers cannot reach the same alloca on both ends.");
2774*9880d681SAndroid Build Coastguard Worker Pass.Worklist.insert(AI);
2775*9880d681SAndroid Build Coastguard Worker }
2776*9880d681SAndroid Build Coastguard Worker
2777*9880d681SAndroid Build Coastguard Worker Type *OtherPtrTy = OtherPtr->getType();
2778*9880d681SAndroid Build Coastguard Worker unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2779*9880d681SAndroid Build Coastguard Worker
2780*9880d681SAndroid Build Coastguard Worker // Compute the relative offset for the other pointer within the transfer.
2781*9880d681SAndroid Build Coastguard Worker unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2782*9880d681SAndroid Build Coastguard Worker APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2783*9880d681SAndroid Build Coastguard Worker unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2784*9880d681SAndroid Build Coastguard Worker OtherOffset.zextOrTrunc(64).getZExtValue());
2785*9880d681SAndroid Build Coastguard Worker
2786*9880d681SAndroid Build Coastguard Worker if (EmitMemCpy) {
2787*9880d681SAndroid Build Coastguard Worker // Compute the other pointer, folding as much as possible to produce
2788*9880d681SAndroid Build Coastguard Worker // a single, simple GEP in most cases.
2789*9880d681SAndroid Build Coastguard Worker OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2790*9880d681SAndroid Build Coastguard Worker OtherPtr->getName() + ".");
2791*9880d681SAndroid Build Coastguard Worker
2792*9880d681SAndroid Build Coastguard Worker Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2793*9880d681SAndroid Build Coastguard Worker Type *SizeTy = II.getLength()->getType();
2794*9880d681SAndroid Build Coastguard Worker Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2795*9880d681SAndroid Build Coastguard Worker
2796*9880d681SAndroid Build Coastguard Worker CallInst *New = IRB.CreateMemCpy(
2797*9880d681SAndroid Build Coastguard Worker IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2798*9880d681SAndroid Build Coastguard Worker MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2799*9880d681SAndroid Build Coastguard Worker (void)New;
2800*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *New << "\n");
2801*9880d681SAndroid Build Coastguard Worker return false;
2802*9880d681SAndroid Build Coastguard Worker }
2803*9880d681SAndroid Build Coastguard Worker
2804*9880d681SAndroid Build Coastguard Worker bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2805*9880d681SAndroid Build Coastguard Worker NewEndOffset == NewAllocaEndOffset;
2806*9880d681SAndroid Build Coastguard Worker uint64_t Size = NewEndOffset - NewBeginOffset;
2807*9880d681SAndroid Build Coastguard Worker unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2808*9880d681SAndroid Build Coastguard Worker unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2809*9880d681SAndroid Build Coastguard Worker unsigned NumElements = EndIndex - BeginIndex;
2810*9880d681SAndroid Build Coastguard Worker IntegerType *SubIntTy =
2811*9880d681SAndroid Build Coastguard Worker IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2812*9880d681SAndroid Build Coastguard Worker
2813*9880d681SAndroid Build Coastguard Worker // Reset the other pointer type to match the register type we're going to
2814*9880d681SAndroid Build Coastguard Worker // use, but using the address space of the original other pointer.
2815*9880d681SAndroid Build Coastguard Worker if (VecTy && !IsWholeAlloca) {
2816*9880d681SAndroid Build Coastguard Worker if (NumElements == 1)
2817*9880d681SAndroid Build Coastguard Worker OtherPtrTy = VecTy->getElementType();
2818*9880d681SAndroid Build Coastguard Worker else
2819*9880d681SAndroid Build Coastguard Worker OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2820*9880d681SAndroid Build Coastguard Worker
2821*9880d681SAndroid Build Coastguard Worker OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2822*9880d681SAndroid Build Coastguard Worker } else if (IntTy && !IsWholeAlloca) {
2823*9880d681SAndroid Build Coastguard Worker OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2824*9880d681SAndroid Build Coastguard Worker } else {
2825*9880d681SAndroid Build Coastguard Worker OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2826*9880d681SAndroid Build Coastguard Worker }
2827*9880d681SAndroid Build Coastguard Worker
2828*9880d681SAndroid Build Coastguard Worker Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2829*9880d681SAndroid Build Coastguard Worker OtherPtr->getName() + ".");
2830*9880d681SAndroid Build Coastguard Worker unsigned SrcAlign = OtherAlign;
2831*9880d681SAndroid Build Coastguard Worker Value *DstPtr = &NewAI;
2832*9880d681SAndroid Build Coastguard Worker unsigned DstAlign = SliceAlign;
2833*9880d681SAndroid Build Coastguard Worker if (!IsDest) {
2834*9880d681SAndroid Build Coastguard Worker std::swap(SrcPtr, DstPtr);
2835*9880d681SAndroid Build Coastguard Worker std::swap(SrcAlign, DstAlign);
2836*9880d681SAndroid Build Coastguard Worker }
2837*9880d681SAndroid Build Coastguard Worker
2838*9880d681SAndroid Build Coastguard Worker Value *Src;
2839*9880d681SAndroid Build Coastguard Worker if (VecTy && !IsWholeAlloca && !IsDest) {
2840*9880d681SAndroid Build Coastguard Worker Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2841*9880d681SAndroid Build Coastguard Worker Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2842*9880d681SAndroid Build Coastguard Worker } else if (IntTy && !IsWholeAlloca && !IsDest) {
2843*9880d681SAndroid Build Coastguard Worker Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2844*9880d681SAndroid Build Coastguard Worker Src = convertValue(DL, IRB, Src, IntTy);
2845*9880d681SAndroid Build Coastguard Worker uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2846*9880d681SAndroid Build Coastguard Worker Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2847*9880d681SAndroid Build Coastguard Worker } else {
2848*9880d681SAndroid Build Coastguard Worker Src =
2849*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
2850*9880d681SAndroid Build Coastguard Worker }
2851*9880d681SAndroid Build Coastguard Worker
2852*9880d681SAndroid Build Coastguard Worker if (VecTy && !IsWholeAlloca && IsDest) {
2853*9880d681SAndroid Build Coastguard Worker Value *Old =
2854*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2855*9880d681SAndroid Build Coastguard Worker Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2856*9880d681SAndroid Build Coastguard Worker } else if (IntTy && !IsWholeAlloca && IsDest) {
2857*9880d681SAndroid Build Coastguard Worker Value *Old =
2858*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2859*9880d681SAndroid Build Coastguard Worker Old = convertValue(DL, IRB, Old, IntTy);
2860*9880d681SAndroid Build Coastguard Worker uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2861*9880d681SAndroid Build Coastguard Worker Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2862*9880d681SAndroid Build Coastguard Worker Src = convertValue(DL, IRB, Src, NewAllocaTy);
2863*9880d681SAndroid Build Coastguard Worker }
2864*9880d681SAndroid Build Coastguard Worker
2865*9880d681SAndroid Build Coastguard Worker StoreInst *Store = cast<StoreInst>(
2866*9880d681SAndroid Build Coastguard Worker IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
2867*9880d681SAndroid Build Coastguard Worker (void)Store;
2868*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *Store << "\n");
2869*9880d681SAndroid Build Coastguard Worker return !II.isVolatile();
2870*9880d681SAndroid Build Coastguard Worker }
2871*9880d681SAndroid Build Coastguard Worker
visitIntrinsicInst(IntrinsicInst & II)2872*9880d681SAndroid Build Coastguard Worker bool visitIntrinsicInst(IntrinsicInst &II) {
2873*9880d681SAndroid Build Coastguard Worker assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2874*9880d681SAndroid Build Coastguard Worker II.getIntrinsicID() == Intrinsic::lifetime_end);
2875*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << II << "\n");
2876*9880d681SAndroid Build Coastguard Worker assert(II.getArgOperand(1) == OldPtr);
2877*9880d681SAndroid Build Coastguard Worker
2878*9880d681SAndroid Build Coastguard Worker // Record this instruction for deletion.
2879*9880d681SAndroid Build Coastguard Worker Pass.DeadInsts.insert(&II);
2880*9880d681SAndroid Build Coastguard Worker
2881*9880d681SAndroid Build Coastguard Worker ConstantInt *Size =
2882*9880d681SAndroid Build Coastguard Worker ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2883*9880d681SAndroid Build Coastguard Worker NewEndOffset - NewBeginOffset);
2884*9880d681SAndroid Build Coastguard Worker Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2885*9880d681SAndroid Build Coastguard Worker Value *New;
2886*9880d681SAndroid Build Coastguard Worker if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2887*9880d681SAndroid Build Coastguard Worker New = IRB.CreateLifetimeStart(Ptr, Size);
2888*9880d681SAndroid Build Coastguard Worker else
2889*9880d681SAndroid Build Coastguard Worker New = IRB.CreateLifetimeEnd(Ptr, Size);
2890*9880d681SAndroid Build Coastguard Worker
2891*9880d681SAndroid Build Coastguard Worker (void)New;
2892*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *New << "\n");
2893*9880d681SAndroid Build Coastguard Worker return true;
2894*9880d681SAndroid Build Coastguard Worker }
2895*9880d681SAndroid Build Coastguard Worker
visitPHINode(PHINode & PN)2896*9880d681SAndroid Build Coastguard Worker bool visitPHINode(PHINode &PN) {
2897*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << PN << "\n");
2898*9880d681SAndroid Build Coastguard Worker assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2899*9880d681SAndroid Build Coastguard Worker assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2900*9880d681SAndroid Build Coastguard Worker
2901*9880d681SAndroid Build Coastguard Worker // We would like to compute a new pointer in only one place, but have it be
2902*9880d681SAndroid Build Coastguard Worker // as local as possible to the PHI. To do that, we re-use the location of
2903*9880d681SAndroid Build Coastguard Worker // the old pointer, which necessarily must be in the right position to
2904*9880d681SAndroid Build Coastguard Worker // dominate the PHI.
2905*9880d681SAndroid Build Coastguard Worker IRBuilderTy PtrBuilder(IRB);
2906*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(OldPtr))
2907*9880d681SAndroid Build Coastguard Worker PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
2908*9880d681SAndroid Build Coastguard Worker else
2909*9880d681SAndroid Build Coastguard Worker PtrBuilder.SetInsertPoint(OldPtr);
2910*9880d681SAndroid Build Coastguard Worker PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
2911*9880d681SAndroid Build Coastguard Worker
2912*9880d681SAndroid Build Coastguard Worker Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
2913*9880d681SAndroid Build Coastguard Worker // Replace the operands which were using the old pointer.
2914*9880d681SAndroid Build Coastguard Worker std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2915*9880d681SAndroid Build Coastguard Worker
2916*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << PN << "\n");
2917*9880d681SAndroid Build Coastguard Worker deleteIfTriviallyDead(OldPtr);
2918*9880d681SAndroid Build Coastguard Worker
2919*9880d681SAndroid Build Coastguard Worker // PHIs can't be promoted on their own, but often can be speculated. We
2920*9880d681SAndroid Build Coastguard Worker // check the speculation outside of the rewriter so that we see the
2921*9880d681SAndroid Build Coastguard Worker // fully-rewritten alloca.
2922*9880d681SAndroid Build Coastguard Worker PHIUsers.insert(&PN);
2923*9880d681SAndroid Build Coastguard Worker return true;
2924*9880d681SAndroid Build Coastguard Worker }
2925*9880d681SAndroid Build Coastguard Worker
visitSelectInst(SelectInst & SI)2926*9880d681SAndroid Build Coastguard Worker bool visitSelectInst(SelectInst &SI) {
2927*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << SI << "\n");
2928*9880d681SAndroid Build Coastguard Worker assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2929*9880d681SAndroid Build Coastguard Worker "Pointer isn't an operand!");
2930*9880d681SAndroid Build Coastguard Worker assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2931*9880d681SAndroid Build Coastguard Worker assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2932*9880d681SAndroid Build Coastguard Worker
2933*9880d681SAndroid Build Coastguard Worker Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2934*9880d681SAndroid Build Coastguard Worker // Replace the operands which were using the old pointer.
2935*9880d681SAndroid Build Coastguard Worker if (SI.getOperand(1) == OldPtr)
2936*9880d681SAndroid Build Coastguard Worker SI.setOperand(1, NewPtr);
2937*9880d681SAndroid Build Coastguard Worker if (SI.getOperand(2) == OldPtr)
2938*9880d681SAndroid Build Coastguard Worker SI.setOperand(2, NewPtr);
2939*9880d681SAndroid Build Coastguard Worker
2940*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << SI << "\n");
2941*9880d681SAndroid Build Coastguard Worker deleteIfTriviallyDead(OldPtr);
2942*9880d681SAndroid Build Coastguard Worker
2943*9880d681SAndroid Build Coastguard Worker // Selects can't be promoted on their own, but often can be speculated. We
2944*9880d681SAndroid Build Coastguard Worker // check the speculation outside of the rewriter so that we see the
2945*9880d681SAndroid Build Coastguard Worker // fully-rewritten alloca.
2946*9880d681SAndroid Build Coastguard Worker SelectUsers.insert(&SI);
2947*9880d681SAndroid Build Coastguard Worker return true;
2948*9880d681SAndroid Build Coastguard Worker }
2949*9880d681SAndroid Build Coastguard Worker };
2950*9880d681SAndroid Build Coastguard Worker
2951*9880d681SAndroid Build Coastguard Worker namespace {
2952*9880d681SAndroid Build Coastguard Worker /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2953*9880d681SAndroid Build Coastguard Worker ///
2954*9880d681SAndroid Build Coastguard Worker /// This pass aggressively rewrites all aggregate loads and stores on
2955*9880d681SAndroid Build Coastguard Worker /// a particular pointer (or any pointer derived from it which we can identify)
2956*9880d681SAndroid Build Coastguard Worker /// with scalar loads and stores.
2957*9880d681SAndroid Build Coastguard Worker class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2958*9880d681SAndroid Build Coastguard Worker // Befriend the base class so it can delegate to private visit methods.
2959*9880d681SAndroid Build Coastguard Worker friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2960*9880d681SAndroid Build Coastguard Worker
2961*9880d681SAndroid Build Coastguard Worker /// Queue of pointer uses to analyze and potentially rewrite.
2962*9880d681SAndroid Build Coastguard Worker SmallVector<Use *, 8> Queue;
2963*9880d681SAndroid Build Coastguard Worker
2964*9880d681SAndroid Build Coastguard Worker /// Set to prevent us from cycling with phi nodes and loops.
2965*9880d681SAndroid Build Coastguard Worker SmallPtrSet<User *, 8> Visited;
2966*9880d681SAndroid Build Coastguard Worker
2967*9880d681SAndroid Build Coastguard Worker /// The current pointer use being rewritten. This is used to dig up the used
2968*9880d681SAndroid Build Coastguard Worker /// value (as opposed to the user).
2969*9880d681SAndroid Build Coastguard Worker Use *U;
2970*9880d681SAndroid Build Coastguard Worker
2971*9880d681SAndroid Build Coastguard Worker public:
2972*9880d681SAndroid Build Coastguard Worker /// Rewrite loads and stores through a pointer and all pointers derived from
2973*9880d681SAndroid Build Coastguard Worker /// it.
rewrite(Instruction & I)2974*9880d681SAndroid Build Coastguard Worker bool rewrite(Instruction &I) {
2975*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2976*9880d681SAndroid Build Coastguard Worker enqueueUsers(I);
2977*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2978*9880d681SAndroid Build Coastguard Worker while (!Queue.empty()) {
2979*9880d681SAndroid Build Coastguard Worker U = Queue.pop_back_val();
2980*9880d681SAndroid Build Coastguard Worker Changed |= visit(cast<Instruction>(U->getUser()));
2981*9880d681SAndroid Build Coastguard Worker }
2982*9880d681SAndroid Build Coastguard Worker return Changed;
2983*9880d681SAndroid Build Coastguard Worker }
2984*9880d681SAndroid Build Coastguard Worker
2985*9880d681SAndroid Build Coastguard Worker private:
2986*9880d681SAndroid Build Coastguard Worker /// Enqueue all the users of the given instruction for further processing.
2987*9880d681SAndroid Build Coastguard Worker /// This uses a set to de-duplicate users.
enqueueUsers(Instruction & I)2988*9880d681SAndroid Build Coastguard Worker void enqueueUsers(Instruction &I) {
2989*9880d681SAndroid Build Coastguard Worker for (Use &U : I.uses())
2990*9880d681SAndroid Build Coastguard Worker if (Visited.insert(U.getUser()).second)
2991*9880d681SAndroid Build Coastguard Worker Queue.push_back(&U);
2992*9880d681SAndroid Build Coastguard Worker }
2993*9880d681SAndroid Build Coastguard Worker
2994*9880d681SAndroid Build Coastguard Worker // Conservative default is to not rewrite anything.
visitInstruction(Instruction & I)2995*9880d681SAndroid Build Coastguard Worker bool visitInstruction(Instruction &I) { return false; }
2996*9880d681SAndroid Build Coastguard Worker
2997*9880d681SAndroid Build Coastguard Worker /// \brief Generic recursive split emission class.
2998*9880d681SAndroid Build Coastguard Worker template <typename Derived> class OpSplitter {
2999*9880d681SAndroid Build Coastguard Worker protected:
3000*9880d681SAndroid Build Coastguard Worker /// The builder used to form new instructions.
3001*9880d681SAndroid Build Coastguard Worker IRBuilderTy IRB;
3002*9880d681SAndroid Build Coastguard Worker /// The indices which to be used with insert- or extractvalue to select the
3003*9880d681SAndroid Build Coastguard Worker /// appropriate value within the aggregate.
3004*9880d681SAndroid Build Coastguard Worker SmallVector<unsigned, 4> Indices;
3005*9880d681SAndroid Build Coastguard Worker /// The indices to a GEP instruction which will move Ptr to the correct slot
3006*9880d681SAndroid Build Coastguard Worker /// within the aggregate.
3007*9880d681SAndroid Build Coastguard Worker SmallVector<Value *, 4> GEPIndices;
3008*9880d681SAndroid Build Coastguard Worker /// The base pointer of the original op, used as a base for GEPing the
3009*9880d681SAndroid Build Coastguard Worker /// split operations.
3010*9880d681SAndroid Build Coastguard Worker Value *Ptr;
3011*9880d681SAndroid Build Coastguard Worker
3012*9880d681SAndroid Build Coastguard Worker /// Initialize the splitter with an insertion point, Ptr and start with a
3013*9880d681SAndroid Build Coastguard Worker /// single zero GEP index.
OpSplitter(Instruction * InsertionPoint,Value * Ptr)3014*9880d681SAndroid Build Coastguard Worker OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3015*9880d681SAndroid Build Coastguard Worker : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3016*9880d681SAndroid Build Coastguard Worker
3017*9880d681SAndroid Build Coastguard Worker public:
3018*9880d681SAndroid Build Coastguard Worker /// \brief Generic recursive split emission routine.
3019*9880d681SAndroid Build Coastguard Worker ///
3020*9880d681SAndroid Build Coastguard Worker /// This method recursively splits an aggregate op (load or store) into
3021*9880d681SAndroid Build Coastguard Worker /// scalar or vector ops. It splits recursively until it hits a single value
3022*9880d681SAndroid Build Coastguard Worker /// and emits that single value operation via the template argument.
3023*9880d681SAndroid Build Coastguard Worker ///
3024*9880d681SAndroid Build Coastguard Worker /// The logic of this routine relies on GEPs and insertvalue and
3025*9880d681SAndroid Build Coastguard Worker /// extractvalue all operating with the same fundamental index list, merely
3026*9880d681SAndroid Build Coastguard Worker /// formatted differently (GEPs need actual values).
3027*9880d681SAndroid Build Coastguard Worker ///
3028*9880d681SAndroid Build Coastguard Worker /// \param Ty The type being split recursively into smaller ops.
3029*9880d681SAndroid Build Coastguard Worker /// \param Agg The aggregate value being built up or stored, depending on
3030*9880d681SAndroid Build Coastguard Worker /// whether this is splitting a load or a store respectively.
emitSplitOps(Type * Ty,Value * & Agg,const Twine & Name)3031*9880d681SAndroid Build Coastguard Worker void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3032*9880d681SAndroid Build Coastguard Worker if (Ty->isSingleValueType())
3033*9880d681SAndroid Build Coastguard Worker return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3034*9880d681SAndroid Build Coastguard Worker
3035*9880d681SAndroid Build Coastguard Worker if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3036*9880d681SAndroid Build Coastguard Worker unsigned OldSize = Indices.size();
3037*9880d681SAndroid Build Coastguard Worker (void)OldSize;
3038*9880d681SAndroid Build Coastguard Worker for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3039*9880d681SAndroid Build Coastguard Worker ++Idx) {
3040*9880d681SAndroid Build Coastguard Worker assert(Indices.size() == OldSize && "Did not return to the old size");
3041*9880d681SAndroid Build Coastguard Worker Indices.push_back(Idx);
3042*9880d681SAndroid Build Coastguard Worker GEPIndices.push_back(IRB.getInt32(Idx));
3043*9880d681SAndroid Build Coastguard Worker emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3044*9880d681SAndroid Build Coastguard Worker GEPIndices.pop_back();
3045*9880d681SAndroid Build Coastguard Worker Indices.pop_back();
3046*9880d681SAndroid Build Coastguard Worker }
3047*9880d681SAndroid Build Coastguard Worker return;
3048*9880d681SAndroid Build Coastguard Worker }
3049*9880d681SAndroid Build Coastguard Worker
3050*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(Ty)) {
3051*9880d681SAndroid Build Coastguard Worker unsigned OldSize = Indices.size();
3052*9880d681SAndroid Build Coastguard Worker (void)OldSize;
3053*9880d681SAndroid Build Coastguard Worker for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3054*9880d681SAndroid Build Coastguard Worker ++Idx) {
3055*9880d681SAndroid Build Coastguard Worker assert(Indices.size() == OldSize && "Did not return to the old size");
3056*9880d681SAndroid Build Coastguard Worker Indices.push_back(Idx);
3057*9880d681SAndroid Build Coastguard Worker GEPIndices.push_back(IRB.getInt32(Idx));
3058*9880d681SAndroid Build Coastguard Worker emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3059*9880d681SAndroid Build Coastguard Worker GEPIndices.pop_back();
3060*9880d681SAndroid Build Coastguard Worker Indices.pop_back();
3061*9880d681SAndroid Build Coastguard Worker }
3062*9880d681SAndroid Build Coastguard Worker return;
3063*9880d681SAndroid Build Coastguard Worker }
3064*9880d681SAndroid Build Coastguard Worker
3065*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Only arrays and structs are aggregate loadable types");
3066*9880d681SAndroid Build Coastguard Worker }
3067*9880d681SAndroid Build Coastguard Worker };
3068*9880d681SAndroid Build Coastguard Worker
3069*9880d681SAndroid Build Coastguard Worker struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
LoadOpSplitter__anonc542c7200b11::AggLoadStoreRewriter::LoadOpSplitter3070*9880d681SAndroid Build Coastguard Worker LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3071*9880d681SAndroid Build Coastguard Worker : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3072*9880d681SAndroid Build Coastguard Worker
3073*9880d681SAndroid Build Coastguard Worker /// Emit a leaf load of a single value. This is called at the leaves of the
3074*9880d681SAndroid Build Coastguard Worker /// recursive emission to actually load values.
emitFunc__anonc542c7200b11::AggLoadStoreRewriter::LoadOpSplitter3075*9880d681SAndroid Build Coastguard Worker void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3076*9880d681SAndroid Build Coastguard Worker assert(Ty->isSingleValueType());
3077*9880d681SAndroid Build Coastguard Worker // Load the single value and insert it using the indices.
3078*9880d681SAndroid Build Coastguard Worker Value *GEP =
3079*9880d681SAndroid Build Coastguard Worker IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
3080*9880d681SAndroid Build Coastguard Worker Value *Load = IRB.CreateLoad(GEP, Name + ".load");
3081*9880d681SAndroid Build Coastguard Worker Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3082*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *Load << "\n");
3083*9880d681SAndroid Build Coastguard Worker }
3084*9880d681SAndroid Build Coastguard Worker };
3085*9880d681SAndroid Build Coastguard Worker
visitLoadInst(LoadInst & LI)3086*9880d681SAndroid Build Coastguard Worker bool visitLoadInst(LoadInst &LI) {
3087*9880d681SAndroid Build Coastguard Worker assert(LI.getPointerOperand() == *U);
3088*9880d681SAndroid Build Coastguard Worker if (!LI.isSimple() || LI.getType()->isSingleValueType())
3089*9880d681SAndroid Build Coastguard Worker return false;
3090*9880d681SAndroid Build Coastguard Worker
3091*9880d681SAndroid Build Coastguard Worker // We have an aggregate being loaded, split it apart.
3092*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << LI << "\n");
3093*9880d681SAndroid Build Coastguard Worker LoadOpSplitter Splitter(&LI, *U);
3094*9880d681SAndroid Build Coastguard Worker Value *V = UndefValue::get(LI.getType());
3095*9880d681SAndroid Build Coastguard Worker Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3096*9880d681SAndroid Build Coastguard Worker LI.replaceAllUsesWith(V);
3097*9880d681SAndroid Build Coastguard Worker LI.eraseFromParent();
3098*9880d681SAndroid Build Coastguard Worker return true;
3099*9880d681SAndroid Build Coastguard Worker }
3100*9880d681SAndroid Build Coastguard Worker
3101*9880d681SAndroid Build Coastguard Worker struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
StoreOpSplitter__anonc542c7200b11::AggLoadStoreRewriter::StoreOpSplitter3102*9880d681SAndroid Build Coastguard Worker StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3103*9880d681SAndroid Build Coastguard Worker : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3104*9880d681SAndroid Build Coastguard Worker
3105*9880d681SAndroid Build Coastguard Worker /// Emit a leaf store of a single value. This is called at the leaves of the
3106*9880d681SAndroid Build Coastguard Worker /// recursive emission to actually produce stores.
emitFunc__anonc542c7200b11::AggLoadStoreRewriter::StoreOpSplitter3107*9880d681SAndroid Build Coastguard Worker void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3108*9880d681SAndroid Build Coastguard Worker assert(Ty->isSingleValueType());
3109*9880d681SAndroid Build Coastguard Worker // Extract the single value and store it using the indices.
3110*9880d681SAndroid Build Coastguard Worker //
3111*9880d681SAndroid Build Coastguard Worker // The gep and extractvalue values are factored out of the CreateStore
3112*9880d681SAndroid Build Coastguard Worker // call to make the output independent of the argument evaluation order.
3113*9880d681SAndroid Build Coastguard Worker Value *ExtractValue =
3114*9880d681SAndroid Build Coastguard Worker IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3115*9880d681SAndroid Build Coastguard Worker Value *InBoundsGEP =
3116*9880d681SAndroid Build Coastguard Worker IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
3117*9880d681SAndroid Build Coastguard Worker Value *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
3118*9880d681SAndroid Build Coastguard Worker (void)Store;
3119*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " to: " << *Store << "\n");
3120*9880d681SAndroid Build Coastguard Worker }
3121*9880d681SAndroid Build Coastguard Worker };
3122*9880d681SAndroid Build Coastguard Worker
visitStoreInst(StoreInst & SI)3123*9880d681SAndroid Build Coastguard Worker bool visitStoreInst(StoreInst &SI) {
3124*9880d681SAndroid Build Coastguard Worker if (!SI.isSimple() || SI.getPointerOperand() != *U)
3125*9880d681SAndroid Build Coastguard Worker return false;
3126*9880d681SAndroid Build Coastguard Worker Value *V = SI.getValueOperand();
3127*9880d681SAndroid Build Coastguard Worker if (V->getType()->isSingleValueType())
3128*9880d681SAndroid Build Coastguard Worker return false;
3129*9880d681SAndroid Build Coastguard Worker
3130*9880d681SAndroid Build Coastguard Worker // We have an aggregate being stored, split it apart.
3131*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " original: " << SI << "\n");
3132*9880d681SAndroid Build Coastguard Worker StoreOpSplitter Splitter(&SI, *U);
3133*9880d681SAndroid Build Coastguard Worker Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3134*9880d681SAndroid Build Coastguard Worker SI.eraseFromParent();
3135*9880d681SAndroid Build Coastguard Worker return true;
3136*9880d681SAndroid Build Coastguard Worker }
3137*9880d681SAndroid Build Coastguard Worker
visitBitCastInst(BitCastInst & BC)3138*9880d681SAndroid Build Coastguard Worker bool visitBitCastInst(BitCastInst &BC) {
3139*9880d681SAndroid Build Coastguard Worker enqueueUsers(BC);
3140*9880d681SAndroid Build Coastguard Worker return false;
3141*9880d681SAndroid Build Coastguard Worker }
3142*9880d681SAndroid Build Coastguard Worker
visitGetElementPtrInst(GetElementPtrInst & GEPI)3143*9880d681SAndroid Build Coastguard Worker bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3144*9880d681SAndroid Build Coastguard Worker enqueueUsers(GEPI);
3145*9880d681SAndroid Build Coastguard Worker return false;
3146*9880d681SAndroid Build Coastguard Worker }
3147*9880d681SAndroid Build Coastguard Worker
visitPHINode(PHINode & PN)3148*9880d681SAndroid Build Coastguard Worker bool visitPHINode(PHINode &PN) {
3149*9880d681SAndroid Build Coastguard Worker enqueueUsers(PN);
3150*9880d681SAndroid Build Coastguard Worker return false;
3151*9880d681SAndroid Build Coastguard Worker }
3152*9880d681SAndroid Build Coastguard Worker
visitSelectInst(SelectInst & SI)3153*9880d681SAndroid Build Coastguard Worker bool visitSelectInst(SelectInst &SI) {
3154*9880d681SAndroid Build Coastguard Worker enqueueUsers(SI);
3155*9880d681SAndroid Build Coastguard Worker return false;
3156*9880d681SAndroid Build Coastguard Worker }
3157*9880d681SAndroid Build Coastguard Worker };
3158*9880d681SAndroid Build Coastguard Worker }
3159*9880d681SAndroid Build Coastguard Worker
3160*9880d681SAndroid Build Coastguard Worker /// \brief Strip aggregate type wrapping.
3161*9880d681SAndroid Build Coastguard Worker ///
3162*9880d681SAndroid Build Coastguard Worker /// This removes no-op aggregate types wrapping an underlying type. It will
3163*9880d681SAndroid Build Coastguard Worker /// strip as many layers of types as it can without changing either the type
3164*9880d681SAndroid Build Coastguard Worker /// size or the allocated size.
stripAggregateTypeWrapping(const DataLayout & DL,Type * Ty)3165*9880d681SAndroid Build Coastguard Worker static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3166*9880d681SAndroid Build Coastguard Worker if (Ty->isSingleValueType())
3167*9880d681SAndroid Build Coastguard Worker return Ty;
3168*9880d681SAndroid Build Coastguard Worker
3169*9880d681SAndroid Build Coastguard Worker uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3170*9880d681SAndroid Build Coastguard Worker uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3171*9880d681SAndroid Build Coastguard Worker
3172*9880d681SAndroid Build Coastguard Worker Type *InnerTy;
3173*9880d681SAndroid Build Coastguard Worker if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3174*9880d681SAndroid Build Coastguard Worker InnerTy = ArrTy->getElementType();
3175*9880d681SAndroid Build Coastguard Worker } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3176*9880d681SAndroid Build Coastguard Worker const StructLayout *SL = DL.getStructLayout(STy);
3177*9880d681SAndroid Build Coastguard Worker unsigned Index = SL->getElementContainingOffset(0);
3178*9880d681SAndroid Build Coastguard Worker InnerTy = STy->getElementType(Index);
3179*9880d681SAndroid Build Coastguard Worker } else {
3180*9880d681SAndroid Build Coastguard Worker return Ty;
3181*9880d681SAndroid Build Coastguard Worker }
3182*9880d681SAndroid Build Coastguard Worker
3183*9880d681SAndroid Build Coastguard Worker if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3184*9880d681SAndroid Build Coastguard Worker TypeSize > DL.getTypeSizeInBits(InnerTy))
3185*9880d681SAndroid Build Coastguard Worker return Ty;
3186*9880d681SAndroid Build Coastguard Worker
3187*9880d681SAndroid Build Coastguard Worker return stripAggregateTypeWrapping(DL, InnerTy);
3188*9880d681SAndroid Build Coastguard Worker }
3189*9880d681SAndroid Build Coastguard Worker
3190*9880d681SAndroid Build Coastguard Worker /// \brief Try to find a partition of the aggregate type passed in for a given
3191*9880d681SAndroid Build Coastguard Worker /// offset and size.
3192*9880d681SAndroid Build Coastguard Worker ///
3193*9880d681SAndroid Build Coastguard Worker /// This recurses through the aggregate type and tries to compute a subtype
3194*9880d681SAndroid Build Coastguard Worker /// based on the offset and size. When the offset and size span a sub-section
3195*9880d681SAndroid Build Coastguard Worker /// of an array, it will even compute a new array type for that sub-section,
3196*9880d681SAndroid Build Coastguard Worker /// and the same for structs.
3197*9880d681SAndroid Build Coastguard Worker ///
3198*9880d681SAndroid Build Coastguard Worker /// Note that this routine is very strict and tries to find a partition of the
3199*9880d681SAndroid Build Coastguard Worker /// type which produces the *exact* right offset and size. It is not forgiving
3200*9880d681SAndroid Build Coastguard Worker /// when the size or offset cause either end of type-based partition to be off.
3201*9880d681SAndroid Build Coastguard Worker /// Also, this is a best-effort routine. It is reasonable to give up and not
3202*9880d681SAndroid Build Coastguard Worker /// return a type if necessary.
getTypePartition(const DataLayout & DL,Type * Ty,uint64_t Offset,uint64_t Size)3203*9880d681SAndroid Build Coastguard Worker static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3204*9880d681SAndroid Build Coastguard Worker uint64_t Size) {
3205*9880d681SAndroid Build Coastguard Worker if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3206*9880d681SAndroid Build Coastguard Worker return stripAggregateTypeWrapping(DL, Ty);
3207*9880d681SAndroid Build Coastguard Worker if (Offset > DL.getTypeAllocSize(Ty) ||
3208*9880d681SAndroid Build Coastguard Worker (DL.getTypeAllocSize(Ty) - Offset) < Size)
3209*9880d681SAndroid Build Coastguard Worker return nullptr;
3210*9880d681SAndroid Build Coastguard Worker
3211*9880d681SAndroid Build Coastguard Worker if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3212*9880d681SAndroid Build Coastguard Worker // We can't partition pointers...
3213*9880d681SAndroid Build Coastguard Worker if (SeqTy->isPointerTy())
3214*9880d681SAndroid Build Coastguard Worker return nullptr;
3215*9880d681SAndroid Build Coastguard Worker
3216*9880d681SAndroid Build Coastguard Worker Type *ElementTy = SeqTy->getElementType();
3217*9880d681SAndroid Build Coastguard Worker uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3218*9880d681SAndroid Build Coastguard Worker uint64_t NumSkippedElements = Offset / ElementSize;
3219*9880d681SAndroid Build Coastguard Worker if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3220*9880d681SAndroid Build Coastguard Worker if (NumSkippedElements >= ArrTy->getNumElements())
3221*9880d681SAndroid Build Coastguard Worker return nullptr;
3222*9880d681SAndroid Build Coastguard Worker } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3223*9880d681SAndroid Build Coastguard Worker if (NumSkippedElements >= VecTy->getNumElements())
3224*9880d681SAndroid Build Coastguard Worker return nullptr;
3225*9880d681SAndroid Build Coastguard Worker }
3226*9880d681SAndroid Build Coastguard Worker Offset -= NumSkippedElements * ElementSize;
3227*9880d681SAndroid Build Coastguard Worker
3228*9880d681SAndroid Build Coastguard Worker // First check if we need to recurse.
3229*9880d681SAndroid Build Coastguard Worker if (Offset > 0 || Size < ElementSize) {
3230*9880d681SAndroid Build Coastguard Worker // Bail if the partition ends in a different array element.
3231*9880d681SAndroid Build Coastguard Worker if ((Offset + Size) > ElementSize)
3232*9880d681SAndroid Build Coastguard Worker return nullptr;
3233*9880d681SAndroid Build Coastguard Worker // Recurse through the element type trying to peel off offset bytes.
3234*9880d681SAndroid Build Coastguard Worker return getTypePartition(DL, ElementTy, Offset, Size);
3235*9880d681SAndroid Build Coastguard Worker }
3236*9880d681SAndroid Build Coastguard Worker assert(Offset == 0);
3237*9880d681SAndroid Build Coastguard Worker
3238*9880d681SAndroid Build Coastguard Worker if (Size == ElementSize)
3239*9880d681SAndroid Build Coastguard Worker return stripAggregateTypeWrapping(DL, ElementTy);
3240*9880d681SAndroid Build Coastguard Worker assert(Size > ElementSize);
3241*9880d681SAndroid Build Coastguard Worker uint64_t NumElements = Size / ElementSize;
3242*9880d681SAndroid Build Coastguard Worker if (NumElements * ElementSize != Size)
3243*9880d681SAndroid Build Coastguard Worker return nullptr;
3244*9880d681SAndroid Build Coastguard Worker return ArrayType::get(ElementTy, NumElements);
3245*9880d681SAndroid Build Coastguard Worker }
3246*9880d681SAndroid Build Coastguard Worker
3247*9880d681SAndroid Build Coastguard Worker StructType *STy = dyn_cast<StructType>(Ty);
3248*9880d681SAndroid Build Coastguard Worker if (!STy)
3249*9880d681SAndroid Build Coastguard Worker return nullptr;
3250*9880d681SAndroid Build Coastguard Worker
3251*9880d681SAndroid Build Coastguard Worker const StructLayout *SL = DL.getStructLayout(STy);
3252*9880d681SAndroid Build Coastguard Worker if (Offset >= SL->getSizeInBytes())
3253*9880d681SAndroid Build Coastguard Worker return nullptr;
3254*9880d681SAndroid Build Coastguard Worker uint64_t EndOffset = Offset + Size;
3255*9880d681SAndroid Build Coastguard Worker if (EndOffset > SL->getSizeInBytes())
3256*9880d681SAndroid Build Coastguard Worker return nullptr;
3257*9880d681SAndroid Build Coastguard Worker
3258*9880d681SAndroid Build Coastguard Worker unsigned Index = SL->getElementContainingOffset(Offset);
3259*9880d681SAndroid Build Coastguard Worker Offset -= SL->getElementOffset(Index);
3260*9880d681SAndroid Build Coastguard Worker
3261*9880d681SAndroid Build Coastguard Worker Type *ElementTy = STy->getElementType(Index);
3262*9880d681SAndroid Build Coastguard Worker uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3263*9880d681SAndroid Build Coastguard Worker if (Offset >= ElementSize)
3264*9880d681SAndroid Build Coastguard Worker return nullptr; // The offset points into alignment padding.
3265*9880d681SAndroid Build Coastguard Worker
3266*9880d681SAndroid Build Coastguard Worker // See if any partition must be contained by the element.
3267*9880d681SAndroid Build Coastguard Worker if (Offset > 0 || Size < ElementSize) {
3268*9880d681SAndroid Build Coastguard Worker if ((Offset + Size) > ElementSize)
3269*9880d681SAndroid Build Coastguard Worker return nullptr;
3270*9880d681SAndroid Build Coastguard Worker return getTypePartition(DL, ElementTy, Offset, Size);
3271*9880d681SAndroid Build Coastguard Worker }
3272*9880d681SAndroid Build Coastguard Worker assert(Offset == 0);
3273*9880d681SAndroid Build Coastguard Worker
3274*9880d681SAndroid Build Coastguard Worker if (Size == ElementSize)
3275*9880d681SAndroid Build Coastguard Worker return stripAggregateTypeWrapping(DL, ElementTy);
3276*9880d681SAndroid Build Coastguard Worker
3277*9880d681SAndroid Build Coastguard Worker StructType::element_iterator EI = STy->element_begin() + Index,
3278*9880d681SAndroid Build Coastguard Worker EE = STy->element_end();
3279*9880d681SAndroid Build Coastguard Worker if (EndOffset < SL->getSizeInBytes()) {
3280*9880d681SAndroid Build Coastguard Worker unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3281*9880d681SAndroid Build Coastguard Worker if (Index == EndIndex)
3282*9880d681SAndroid Build Coastguard Worker return nullptr; // Within a single element and its padding.
3283*9880d681SAndroid Build Coastguard Worker
3284*9880d681SAndroid Build Coastguard Worker // Don't try to form "natural" types if the elements don't line up with the
3285*9880d681SAndroid Build Coastguard Worker // expected size.
3286*9880d681SAndroid Build Coastguard Worker // FIXME: We could potentially recurse down through the last element in the
3287*9880d681SAndroid Build Coastguard Worker // sub-struct to find a natural end point.
3288*9880d681SAndroid Build Coastguard Worker if (SL->getElementOffset(EndIndex) != EndOffset)
3289*9880d681SAndroid Build Coastguard Worker return nullptr;
3290*9880d681SAndroid Build Coastguard Worker
3291*9880d681SAndroid Build Coastguard Worker assert(Index < EndIndex);
3292*9880d681SAndroid Build Coastguard Worker EE = STy->element_begin() + EndIndex;
3293*9880d681SAndroid Build Coastguard Worker }
3294*9880d681SAndroid Build Coastguard Worker
3295*9880d681SAndroid Build Coastguard Worker // Try to build up a sub-structure.
3296*9880d681SAndroid Build Coastguard Worker StructType *SubTy =
3297*9880d681SAndroid Build Coastguard Worker StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3298*9880d681SAndroid Build Coastguard Worker const StructLayout *SubSL = DL.getStructLayout(SubTy);
3299*9880d681SAndroid Build Coastguard Worker if (Size != SubSL->getSizeInBytes())
3300*9880d681SAndroid Build Coastguard Worker return nullptr; // The sub-struct doesn't have quite the size needed.
3301*9880d681SAndroid Build Coastguard Worker
3302*9880d681SAndroid Build Coastguard Worker return SubTy;
3303*9880d681SAndroid Build Coastguard Worker }
3304*9880d681SAndroid Build Coastguard Worker
3305*9880d681SAndroid Build Coastguard Worker /// \brief Pre-split loads and stores to simplify rewriting.
3306*9880d681SAndroid Build Coastguard Worker ///
3307*9880d681SAndroid Build Coastguard Worker /// We want to break up the splittable load+store pairs as much as
3308*9880d681SAndroid Build Coastguard Worker /// possible. This is important to do as a preprocessing step, as once we
3309*9880d681SAndroid Build Coastguard Worker /// start rewriting the accesses to partitions of the alloca we lose the
3310*9880d681SAndroid Build Coastguard Worker /// necessary information to correctly split apart paired loads and stores
3311*9880d681SAndroid Build Coastguard Worker /// which both point into this alloca. The case to consider is something like
3312*9880d681SAndroid Build Coastguard Worker /// the following:
3313*9880d681SAndroid Build Coastguard Worker ///
3314*9880d681SAndroid Build Coastguard Worker /// %a = alloca [12 x i8]
3315*9880d681SAndroid Build Coastguard Worker /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3316*9880d681SAndroid Build Coastguard Worker /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3317*9880d681SAndroid Build Coastguard Worker /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3318*9880d681SAndroid Build Coastguard Worker /// %iptr1 = bitcast i8* %gep1 to i64*
3319*9880d681SAndroid Build Coastguard Worker /// %iptr2 = bitcast i8* %gep2 to i64*
3320*9880d681SAndroid Build Coastguard Worker /// %fptr1 = bitcast i8* %gep1 to float*
3321*9880d681SAndroid Build Coastguard Worker /// %fptr2 = bitcast i8* %gep2 to float*
3322*9880d681SAndroid Build Coastguard Worker /// %fptr3 = bitcast i8* %gep3 to float*
3323*9880d681SAndroid Build Coastguard Worker /// store float 0.0, float* %fptr1
3324*9880d681SAndroid Build Coastguard Worker /// store float 1.0, float* %fptr2
3325*9880d681SAndroid Build Coastguard Worker /// %v = load i64* %iptr1
3326*9880d681SAndroid Build Coastguard Worker /// store i64 %v, i64* %iptr2
3327*9880d681SAndroid Build Coastguard Worker /// %f1 = load float* %fptr2
3328*9880d681SAndroid Build Coastguard Worker /// %f2 = load float* %fptr3
3329*9880d681SAndroid Build Coastguard Worker ///
3330*9880d681SAndroid Build Coastguard Worker /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3331*9880d681SAndroid Build Coastguard Worker /// promote everything so we recover the 2 SSA values that should have been
3332*9880d681SAndroid Build Coastguard Worker /// there all along.
3333*9880d681SAndroid Build Coastguard Worker ///
3334*9880d681SAndroid Build Coastguard Worker /// \returns true if any changes are made.
presplitLoadsAndStores(AllocaInst & AI,AllocaSlices & AS)3335*9880d681SAndroid Build Coastguard Worker bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3336*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3337*9880d681SAndroid Build Coastguard Worker
3338*9880d681SAndroid Build Coastguard Worker // Track the loads and stores which are candidates for pre-splitting here, in
3339*9880d681SAndroid Build Coastguard Worker // the order they first appear during the partition scan. These give stable
3340*9880d681SAndroid Build Coastguard Worker // iteration order and a basis for tracking which loads and stores we
3341*9880d681SAndroid Build Coastguard Worker // actually split.
3342*9880d681SAndroid Build Coastguard Worker SmallVector<LoadInst *, 4> Loads;
3343*9880d681SAndroid Build Coastguard Worker SmallVector<StoreInst *, 4> Stores;
3344*9880d681SAndroid Build Coastguard Worker
3345*9880d681SAndroid Build Coastguard Worker // We need to accumulate the splits required of each load or store where we
3346*9880d681SAndroid Build Coastguard Worker // can find them via a direct lookup. This is important to cross-check loads
3347*9880d681SAndroid Build Coastguard Worker // and stores against each other. We also track the slice so that we can kill
3348*9880d681SAndroid Build Coastguard Worker // all the slices that end up split.
3349*9880d681SAndroid Build Coastguard Worker struct SplitOffsets {
3350*9880d681SAndroid Build Coastguard Worker Slice *S;
3351*9880d681SAndroid Build Coastguard Worker std::vector<uint64_t> Splits;
3352*9880d681SAndroid Build Coastguard Worker };
3353*9880d681SAndroid Build Coastguard Worker SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3354*9880d681SAndroid Build Coastguard Worker
3355*9880d681SAndroid Build Coastguard Worker // Track loads out of this alloca which cannot, for any reason, be pre-split.
3356*9880d681SAndroid Build Coastguard Worker // This is important as we also cannot pre-split stores of those loads!
3357*9880d681SAndroid Build Coastguard Worker // FIXME: This is all pretty gross. It means that we can be more aggressive
3358*9880d681SAndroid Build Coastguard Worker // in pre-splitting when the load feeding the store happens to come from
3359*9880d681SAndroid Build Coastguard Worker // a separate alloca. Put another way, the effectiveness of SROA would be
3360*9880d681SAndroid Build Coastguard Worker // decreased by a frontend which just concatenated all of its local allocas
3361*9880d681SAndroid Build Coastguard Worker // into one big flat alloca. But defeating such patterns is exactly the job
3362*9880d681SAndroid Build Coastguard Worker // SROA is tasked with! Sadly, to not have this discrepancy we would have
3363*9880d681SAndroid Build Coastguard Worker // change store pre-splitting to actually force pre-splitting of the load
3364*9880d681SAndroid Build Coastguard Worker // that feeds it *and all stores*. That makes pre-splitting much harder, but
3365*9880d681SAndroid Build Coastguard Worker // maybe it would make it more principled?
3366*9880d681SAndroid Build Coastguard Worker SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3367*9880d681SAndroid Build Coastguard Worker
3368*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3369*9880d681SAndroid Build Coastguard Worker for (auto &P : AS.partitions()) {
3370*9880d681SAndroid Build Coastguard Worker for (Slice &S : P) {
3371*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(S.getUse()->getUser());
3372*9880d681SAndroid Build Coastguard Worker if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3373*9880d681SAndroid Build Coastguard Worker // If this is a load we have to track that it can't participate in any
3374*9880d681SAndroid Build Coastguard Worker // pre-splitting. If this is a store of a load we have to track that
3375*9880d681SAndroid Build Coastguard Worker // that load also can't participate in any pre-splitting.
3376*9880d681SAndroid Build Coastguard Worker if (auto *LI = dyn_cast<LoadInst>(I))
3377*9880d681SAndroid Build Coastguard Worker UnsplittableLoads.insert(LI);
3378*9880d681SAndroid Build Coastguard Worker else if (auto *SI = dyn_cast<StoreInst>(I))
3379*9880d681SAndroid Build Coastguard Worker if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3380*9880d681SAndroid Build Coastguard Worker UnsplittableLoads.insert(LI);
3381*9880d681SAndroid Build Coastguard Worker continue;
3382*9880d681SAndroid Build Coastguard Worker }
3383*9880d681SAndroid Build Coastguard Worker assert(P.endOffset() > S.beginOffset() &&
3384*9880d681SAndroid Build Coastguard Worker "Empty or backwards partition!");
3385*9880d681SAndroid Build Coastguard Worker
3386*9880d681SAndroid Build Coastguard Worker // Determine if this is a pre-splittable slice.
3387*9880d681SAndroid Build Coastguard Worker if (auto *LI = dyn_cast<LoadInst>(I)) {
3388*9880d681SAndroid Build Coastguard Worker assert(!LI->isVolatile() && "Cannot split volatile loads!");
3389*9880d681SAndroid Build Coastguard Worker
3390*9880d681SAndroid Build Coastguard Worker // The load must be used exclusively to store into other pointers for
3391*9880d681SAndroid Build Coastguard Worker // us to be able to arbitrarily pre-split it. The stores must also be
3392*9880d681SAndroid Build Coastguard Worker // simple to avoid changing semantics.
3393*9880d681SAndroid Build Coastguard Worker auto IsLoadSimplyStored = [](LoadInst *LI) {
3394*9880d681SAndroid Build Coastguard Worker for (User *LU : LI->users()) {
3395*9880d681SAndroid Build Coastguard Worker auto *SI = dyn_cast<StoreInst>(LU);
3396*9880d681SAndroid Build Coastguard Worker if (!SI || !SI->isSimple())
3397*9880d681SAndroid Build Coastguard Worker return false;
3398*9880d681SAndroid Build Coastguard Worker }
3399*9880d681SAndroid Build Coastguard Worker return true;
3400*9880d681SAndroid Build Coastguard Worker };
3401*9880d681SAndroid Build Coastguard Worker if (!IsLoadSimplyStored(LI)) {
3402*9880d681SAndroid Build Coastguard Worker UnsplittableLoads.insert(LI);
3403*9880d681SAndroid Build Coastguard Worker continue;
3404*9880d681SAndroid Build Coastguard Worker }
3405*9880d681SAndroid Build Coastguard Worker
3406*9880d681SAndroid Build Coastguard Worker Loads.push_back(LI);
3407*9880d681SAndroid Build Coastguard Worker } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3408*9880d681SAndroid Build Coastguard Worker if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3409*9880d681SAndroid Build Coastguard Worker // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
3410*9880d681SAndroid Build Coastguard Worker continue;
3411*9880d681SAndroid Build Coastguard Worker auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3412*9880d681SAndroid Build Coastguard Worker if (!StoredLoad || !StoredLoad->isSimple())
3413*9880d681SAndroid Build Coastguard Worker continue;
3414*9880d681SAndroid Build Coastguard Worker assert(!SI->isVolatile() && "Cannot split volatile stores!");
3415*9880d681SAndroid Build Coastguard Worker
3416*9880d681SAndroid Build Coastguard Worker Stores.push_back(SI);
3417*9880d681SAndroid Build Coastguard Worker } else {
3418*9880d681SAndroid Build Coastguard Worker // Other uses cannot be pre-split.
3419*9880d681SAndroid Build Coastguard Worker continue;
3420*9880d681SAndroid Build Coastguard Worker }
3421*9880d681SAndroid Build Coastguard Worker
3422*9880d681SAndroid Build Coastguard Worker // Record the initial split.
3423*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Candidate: " << *I << "\n");
3424*9880d681SAndroid Build Coastguard Worker auto &Offsets = SplitOffsetsMap[I];
3425*9880d681SAndroid Build Coastguard Worker assert(Offsets.Splits.empty() &&
3426*9880d681SAndroid Build Coastguard Worker "Should not have splits the first time we see an instruction!");
3427*9880d681SAndroid Build Coastguard Worker Offsets.S = &S;
3428*9880d681SAndroid Build Coastguard Worker Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3429*9880d681SAndroid Build Coastguard Worker }
3430*9880d681SAndroid Build Coastguard Worker
3431*9880d681SAndroid Build Coastguard Worker // Now scan the already split slices, and add a split for any of them which
3432*9880d681SAndroid Build Coastguard Worker // we're going to pre-split.
3433*9880d681SAndroid Build Coastguard Worker for (Slice *S : P.splitSliceTails()) {
3434*9880d681SAndroid Build Coastguard Worker auto SplitOffsetsMapI =
3435*9880d681SAndroid Build Coastguard Worker SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3436*9880d681SAndroid Build Coastguard Worker if (SplitOffsetsMapI == SplitOffsetsMap.end())
3437*9880d681SAndroid Build Coastguard Worker continue;
3438*9880d681SAndroid Build Coastguard Worker auto &Offsets = SplitOffsetsMapI->second;
3439*9880d681SAndroid Build Coastguard Worker
3440*9880d681SAndroid Build Coastguard Worker assert(Offsets.S == S && "Found a mismatched slice!");
3441*9880d681SAndroid Build Coastguard Worker assert(!Offsets.Splits.empty() &&
3442*9880d681SAndroid Build Coastguard Worker "Cannot have an empty set of splits on the second partition!");
3443*9880d681SAndroid Build Coastguard Worker assert(Offsets.Splits.back() ==
3444*9880d681SAndroid Build Coastguard Worker P.beginOffset() - Offsets.S->beginOffset() &&
3445*9880d681SAndroid Build Coastguard Worker "Previous split does not end where this one begins!");
3446*9880d681SAndroid Build Coastguard Worker
3447*9880d681SAndroid Build Coastguard Worker // Record each split. The last partition's end isn't needed as the size
3448*9880d681SAndroid Build Coastguard Worker // of the slice dictates that.
3449*9880d681SAndroid Build Coastguard Worker if (S->endOffset() > P.endOffset())
3450*9880d681SAndroid Build Coastguard Worker Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3451*9880d681SAndroid Build Coastguard Worker }
3452*9880d681SAndroid Build Coastguard Worker }
3453*9880d681SAndroid Build Coastguard Worker
3454*9880d681SAndroid Build Coastguard Worker // We may have split loads where some of their stores are split stores. For
3455*9880d681SAndroid Build Coastguard Worker // such loads and stores, we can only pre-split them if their splits exactly
3456*9880d681SAndroid Build Coastguard Worker // match relative to their starting offset. We have to verify this prior to
3457*9880d681SAndroid Build Coastguard Worker // any rewriting.
3458*9880d681SAndroid Build Coastguard Worker Stores.erase(
3459*9880d681SAndroid Build Coastguard Worker std::remove_if(Stores.begin(), Stores.end(),
3460*9880d681SAndroid Build Coastguard Worker [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3461*9880d681SAndroid Build Coastguard Worker // Lookup the load we are storing in our map of split
3462*9880d681SAndroid Build Coastguard Worker // offsets.
3463*9880d681SAndroid Build Coastguard Worker auto *LI = cast<LoadInst>(SI->getValueOperand());
3464*9880d681SAndroid Build Coastguard Worker // If it was completely unsplittable, then we're done,
3465*9880d681SAndroid Build Coastguard Worker // and this store can't be pre-split.
3466*9880d681SAndroid Build Coastguard Worker if (UnsplittableLoads.count(LI))
3467*9880d681SAndroid Build Coastguard Worker return true;
3468*9880d681SAndroid Build Coastguard Worker
3469*9880d681SAndroid Build Coastguard Worker auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3470*9880d681SAndroid Build Coastguard Worker if (LoadOffsetsI == SplitOffsetsMap.end())
3471*9880d681SAndroid Build Coastguard Worker return false; // Unrelated loads are definitely safe.
3472*9880d681SAndroid Build Coastguard Worker auto &LoadOffsets = LoadOffsetsI->second;
3473*9880d681SAndroid Build Coastguard Worker
3474*9880d681SAndroid Build Coastguard Worker // Now lookup the store's offsets.
3475*9880d681SAndroid Build Coastguard Worker auto &StoreOffsets = SplitOffsetsMap[SI];
3476*9880d681SAndroid Build Coastguard Worker
3477*9880d681SAndroid Build Coastguard Worker // If the relative offsets of each split in the load and
3478*9880d681SAndroid Build Coastguard Worker // store match exactly, then we can split them and we
3479*9880d681SAndroid Build Coastguard Worker // don't need to remove them here.
3480*9880d681SAndroid Build Coastguard Worker if (LoadOffsets.Splits == StoreOffsets.Splits)
3481*9880d681SAndroid Build Coastguard Worker return false;
3482*9880d681SAndroid Build Coastguard Worker
3483*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs()
3484*9880d681SAndroid Build Coastguard Worker << " Mismatched splits for load and store:\n"
3485*9880d681SAndroid Build Coastguard Worker << " " << *LI << "\n"
3486*9880d681SAndroid Build Coastguard Worker << " " << *SI << "\n");
3487*9880d681SAndroid Build Coastguard Worker
3488*9880d681SAndroid Build Coastguard Worker // We've found a store and load that we need to split
3489*9880d681SAndroid Build Coastguard Worker // with mismatched relative splits. Just give up on them
3490*9880d681SAndroid Build Coastguard Worker // and remove both instructions from our list of
3491*9880d681SAndroid Build Coastguard Worker // candidates.
3492*9880d681SAndroid Build Coastguard Worker UnsplittableLoads.insert(LI);
3493*9880d681SAndroid Build Coastguard Worker return true;
3494*9880d681SAndroid Build Coastguard Worker }),
3495*9880d681SAndroid Build Coastguard Worker Stores.end());
3496*9880d681SAndroid Build Coastguard Worker // Now we have to go *back* through all the stores, because a later store may
3497*9880d681SAndroid Build Coastguard Worker // have caused an earlier store's load to become unsplittable and if it is
3498*9880d681SAndroid Build Coastguard Worker // unsplittable for the later store, then we can't rely on it being split in
3499*9880d681SAndroid Build Coastguard Worker // the earlier store either.
3500*9880d681SAndroid Build Coastguard Worker Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3501*9880d681SAndroid Build Coastguard Worker [&UnsplittableLoads](StoreInst *SI) {
3502*9880d681SAndroid Build Coastguard Worker auto *LI =
3503*9880d681SAndroid Build Coastguard Worker cast<LoadInst>(SI->getValueOperand());
3504*9880d681SAndroid Build Coastguard Worker return UnsplittableLoads.count(LI);
3505*9880d681SAndroid Build Coastguard Worker }),
3506*9880d681SAndroid Build Coastguard Worker Stores.end());
3507*9880d681SAndroid Build Coastguard Worker // Once we've established all the loads that can't be split for some reason,
3508*9880d681SAndroid Build Coastguard Worker // filter any that made it into our list out.
3509*9880d681SAndroid Build Coastguard Worker Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
3510*9880d681SAndroid Build Coastguard Worker [&UnsplittableLoads](LoadInst *LI) {
3511*9880d681SAndroid Build Coastguard Worker return UnsplittableLoads.count(LI);
3512*9880d681SAndroid Build Coastguard Worker }),
3513*9880d681SAndroid Build Coastguard Worker Loads.end());
3514*9880d681SAndroid Build Coastguard Worker
3515*9880d681SAndroid Build Coastguard Worker
3516*9880d681SAndroid Build Coastguard Worker // If no loads or stores are left, there is no pre-splitting to be done for
3517*9880d681SAndroid Build Coastguard Worker // this alloca.
3518*9880d681SAndroid Build Coastguard Worker if (Loads.empty() && Stores.empty())
3519*9880d681SAndroid Build Coastguard Worker return false;
3520*9880d681SAndroid Build Coastguard Worker
3521*9880d681SAndroid Build Coastguard Worker // From here on, we can't fail and will be building new accesses, so rig up
3522*9880d681SAndroid Build Coastguard Worker // an IR builder.
3523*9880d681SAndroid Build Coastguard Worker IRBuilderTy IRB(&AI);
3524*9880d681SAndroid Build Coastguard Worker
3525*9880d681SAndroid Build Coastguard Worker // Collect the new slices which we will merge into the alloca slices.
3526*9880d681SAndroid Build Coastguard Worker SmallVector<Slice, 4> NewSlices;
3527*9880d681SAndroid Build Coastguard Worker
3528*9880d681SAndroid Build Coastguard Worker // Track any allocas we end up splitting loads and stores for so we iterate
3529*9880d681SAndroid Build Coastguard Worker // on them.
3530*9880d681SAndroid Build Coastguard Worker SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3531*9880d681SAndroid Build Coastguard Worker
3532*9880d681SAndroid Build Coastguard Worker // At this point, we have collected all of the loads and stores we can
3533*9880d681SAndroid Build Coastguard Worker // pre-split, and the specific splits needed for them. We actually do the
3534*9880d681SAndroid Build Coastguard Worker // splitting in a specific order in order to handle when one of the loads in
3535*9880d681SAndroid Build Coastguard Worker // the value operand to one of the stores.
3536*9880d681SAndroid Build Coastguard Worker //
3537*9880d681SAndroid Build Coastguard Worker // First, we rewrite all of the split loads, and just accumulate each split
3538*9880d681SAndroid Build Coastguard Worker // load in a parallel structure. We also build the slices for them and append
3539*9880d681SAndroid Build Coastguard Worker // them to the alloca slices.
3540*9880d681SAndroid Build Coastguard Worker SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3541*9880d681SAndroid Build Coastguard Worker std::vector<LoadInst *> SplitLoads;
3542*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = AI.getModule()->getDataLayout();
3543*9880d681SAndroid Build Coastguard Worker for (LoadInst *LI : Loads) {
3544*9880d681SAndroid Build Coastguard Worker SplitLoads.clear();
3545*9880d681SAndroid Build Coastguard Worker
3546*9880d681SAndroid Build Coastguard Worker IntegerType *Ty = cast<IntegerType>(LI->getType());
3547*9880d681SAndroid Build Coastguard Worker uint64_t LoadSize = Ty->getBitWidth() / 8;
3548*9880d681SAndroid Build Coastguard Worker assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3549*9880d681SAndroid Build Coastguard Worker
3550*9880d681SAndroid Build Coastguard Worker auto &Offsets = SplitOffsetsMap[LI];
3551*9880d681SAndroid Build Coastguard Worker assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3552*9880d681SAndroid Build Coastguard Worker "Slice size should always match load size exactly!");
3553*9880d681SAndroid Build Coastguard Worker uint64_t BaseOffset = Offsets.S->beginOffset();
3554*9880d681SAndroid Build Coastguard Worker assert(BaseOffset + LoadSize > BaseOffset &&
3555*9880d681SAndroid Build Coastguard Worker "Cannot represent alloca access size using 64-bit integers!");
3556*9880d681SAndroid Build Coastguard Worker
3557*9880d681SAndroid Build Coastguard Worker Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3558*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(LI);
3559*9880d681SAndroid Build Coastguard Worker
3560*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3561*9880d681SAndroid Build Coastguard Worker
3562*9880d681SAndroid Build Coastguard Worker uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3563*9880d681SAndroid Build Coastguard Worker int Idx = 0, Size = Offsets.Splits.size();
3564*9880d681SAndroid Build Coastguard Worker for (;;) {
3565*9880d681SAndroid Build Coastguard Worker auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3566*9880d681SAndroid Build Coastguard Worker auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3567*9880d681SAndroid Build Coastguard Worker LoadInst *PLoad = IRB.CreateAlignedLoad(
3568*9880d681SAndroid Build Coastguard Worker getAdjustedPtr(IRB, DL, BasePtr,
3569*9880d681SAndroid Build Coastguard Worker APInt(DL.getPointerSizeInBits(), PartOffset),
3570*9880d681SAndroid Build Coastguard Worker PartPtrTy, BasePtr->getName() + "."),
3571*9880d681SAndroid Build Coastguard Worker getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3572*9880d681SAndroid Build Coastguard Worker LI->getName());
3573*9880d681SAndroid Build Coastguard Worker
3574*9880d681SAndroid Build Coastguard Worker // Append this load onto the list of split loads so we can find it later
3575*9880d681SAndroid Build Coastguard Worker // to rewrite the stores.
3576*9880d681SAndroid Build Coastguard Worker SplitLoads.push_back(PLoad);
3577*9880d681SAndroid Build Coastguard Worker
3578*9880d681SAndroid Build Coastguard Worker // Now build a new slice for the alloca.
3579*9880d681SAndroid Build Coastguard Worker NewSlices.push_back(
3580*9880d681SAndroid Build Coastguard Worker Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3581*9880d681SAndroid Build Coastguard Worker &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3582*9880d681SAndroid Build Coastguard Worker /*IsSplittable*/ false));
3583*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3584*9880d681SAndroid Build Coastguard Worker << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3585*9880d681SAndroid Build Coastguard Worker << "\n");
3586*9880d681SAndroid Build Coastguard Worker
3587*9880d681SAndroid Build Coastguard Worker // See if we've handled all the splits.
3588*9880d681SAndroid Build Coastguard Worker if (Idx >= Size)
3589*9880d681SAndroid Build Coastguard Worker break;
3590*9880d681SAndroid Build Coastguard Worker
3591*9880d681SAndroid Build Coastguard Worker // Setup the next partition.
3592*9880d681SAndroid Build Coastguard Worker PartOffset = Offsets.Splits[Idx];
3593*9880d681SAndroid Build Coastguard Worker ++Idx;
3594*9880d681SAndroid Build Coastguard Worker PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3595*9880d681SAndroid Build Coastguard Worker }
3596*9880d681SAndroid Build Coastguard Worker
3597*9880d681SAndroid Build Coastguard Worker // Now that we have the split loads, do the slow walk over all uses of the
3598*9880d681SAndroid Build Coastguard Worker // load and rewrite them as split stores, or save the split loads to use
3599*9880d681SAndroid Build Coastguard Worker // below if the store is going to be split there anyways.
3600*9880d681SAndroid Build Coastguard Worker bool DeferredStores = false;
3601*9880d681SAndroid Build Coastguard Worker for (User *LU : LI->users()) {
3602*9880d681SAndroid Build Coastguard Worker StoreInst *SI = cast<StoreInst>(LU);
3603*9880d681SAndroid Build Coastguard Worker if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3604*9880d681SAndroid Build Coastguard Worker DeferredStores = true;
3605*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3606*9880d681SAndroid Build Coastguard Worker continue;
3607*9880d681SAndroid Build Coastguard Worker }
3608*9880d681SAndroid Build Coastguard Worker
3609*9880d681SAndroid Build Coastguard Worker Value *StoreBasePtr = SI->getPointerOperand();
3610*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(SI);
3611*9880d681SAndroid Build Coastguard Worker
3612*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3613*9880d681SAndroid Build Coastguard Worker
3614*9880d681SAndroid Build Coastguard Worker for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3615*9880d681SAndroid Build Coastguard Worker LoadInst *PLoad = SplitLoads[Idx];
3616*9880d681SAndroid Build Coastguard Worker uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
3617*9880d681SAndroid Build Coastguard Worker auto *PartPtrTy =
3618*9880d681SAndroid Build Coastguard Worker PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3619*9880d681SAndroid Build Coastguard Worker
3620*9880d681SAndroid Build Coastguard Worker StoreInst *PStore = IRB.CreateAlignedStore(
3621*9880d681SAndroid Build Coastguard Worker PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3622*9880d681SAndroid Build Coastguard Worker APInt(DL.getPointerSizeInBits(), PartOffset),
3623*9880d681SAndroid Build Coastguard Worker PartPtrTy, StoreBasePtr->getName() + "."),
3624*9880d681SAndroid Build Coastguard Worker getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3625*9880d681SAndroid Build Coastguard Worker (void)PStore;
3626*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3627*9880d681SAndroid Build Coastguard Worker }
3628*9880d681SAndroid Build Coastguard Worker
3629*9880d681SAndroid Build Coastguard Worker // We want to immediately iterate on any allocas impacted by splitting
3630*9880d681SAndroid Build Coastguard Worker // this store, and we have to track any promotable alloca (indicated by
3631*9880d681SAndroid Build Coastguard Worker // a direct store) as needing to be resplit because it is no longer
3632*9880d681SAndroid Build Coastguard Worker // promotable.
3633*9880d681SAndroid Build Coastguard Worker if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3634*9880d681SAndroid Build Coastguard Worker ResplitPromotableAllocas.insert(OtherAI);
3635*9880d681SAndroid Build Coastguard Worker Worklist.insert(OtherAI);
3636*9880d681SAndroid Build Coastguard Worker } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3637*9880d681SAndroid Build Coastguard Worker StoreBasePtr->stripInBoundsOffsets())) {
3638*9880d681SAndroid Build Coastguard Worker Worklist.insert(OtherAI);
3639*9880d681SAndroid Build Coastguard Worker }
3640*9880d681SAndroid Build Coastguard Worker
3641*9880d681SAndroid Build Coastguard Worker // Mark the original store as dead.
3642*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(SI);
3643*9880d681SAndroid Build Coastguard Worker }
3644*9880d681SAndroid Build Coastguard Worker
3645*9880d681SAndroid Build Coastguard Worker // Save the split loads if there are deferred stores among the users.
3646*9880d681SAndroid Build Coastguard Worker if (DeferredStores)
3647*9880d681SAndroid Build Coastguard Worker SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3648*9880d681SAndroid Build Coastguard Worker
3649*9880d681SAndroid Build Coastguard Worker // Mark the original load as dead and kill the original slice.
3650*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(LI);
3651*9880d681SAndroid Build Coastguard Worker Offsets.S->kill();
3652*9880d681SAndroid Build Coastguard Worker }
3653*9880d681SAndroid Build Coastguard Worker
3654*9880d681SAndroid Build Coastguard Worker // Second, we rewrite all of the split stores. At this point, we know that
3655*9880d681SAndroid Build Coastguard Worker // all loads from this alloca have been split already. For stores of such
3656*9880d681SAndroid Build Coastguard Worker // loads, we can simply look up the pre-existing split loads. For stores of
3657*9880d681SAndroid Build Coastguard Worker // other loads, we split those loads first and then write split stores of
3658*9880d681SAndroid Build Coastguard Worker // them.
3659*9880d681SAndroid Build Coastguard Worker for (StoreInst *SI : Stores) {
3660*9880d681SAndroid Build Coastguard Worker auto *LI = cast<LoadInst>(SI->getValueOperand());
3661*9880d681SAndroid Build Coastguard Worker IntegerType *Ty = cast<IntegerType>(LI->getType());
3662*9880d681SAndroid Build Coastguard Worker uint64_t StoreSize = Ty->getBitWidth() / 8;
3663*9880d681SAndroid Build Coastguard Worker assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3664*9880d681SAndroid Build Coastguard Worker
3665*9880d681SAndroid Build Coastguard Worker auto &Offsets = SplitOffsetsMap[SI];
3666*9880d681SAndroid Build Coastguard Worker assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3667*9880d681SAndroid Build Coastguard Worker "Slice size should always match load size exactly!");
3668*9880d681SAndroid Build Coastguard Worker uint64_t BaseOffset = Offsets.S->beginOffset();
3669*9880d681SAndroid Build Coastguard Worker assert(BaseOffset + StoreSize > BaseOffset &&
3670*9880d681SAndroid Build Coastguard Worker "Cannot represent alloca access size using 64-bit integers!");
3671*9880d681SAndroid Build Coastguard Worker
3672*9880d681SAndroid Build Coastguard Worker Value *LoadBasePtr = LI->getPointerOperand();
3673*9880d681SAndroid Build Coastguard Worker Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3674*9880d681SAndroid Build Coastguard Worker
3675*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3676*9880d681SAndroid Build Coastguard Worker
3677*9880d681SAndroid Build Coastguard Worker // Check whether we have an already split load.
3678*9880d681SAndroid Build Coastguard Worker auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3679*9880d681SAndroid Build Coastguard Worker std::vector<LoadInst *> *SplitLoads = nullptr;
3680*9880d681SAndroid Build Coastguard Worker if (SplitLoadsMapI != SplitLoadsMap.end()) {
3681*9880d681SAndroid Build Coastguard Worker SplitLoads = &SplitLoadsMapI->second;
3682*9880d681SAndroid Build Coastguard Worker assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3683*9880d681SAndroid Build Coastguard Worker "Too few split loads for the number of splits in the store!");
3684*9880d681SAndroid Build Coastguard Worker } else {
3685*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " of load: " << *LI << "\n");
3686*9880d681SAndroid Build Coastguard Worker }
3687*9880d681SAndroid Build Coastguard Worker
3688*9880d681SAndroid Build Coastguard Worker uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3689*9880d681SAndroid Build Coastguard Worker int Idx = 0, Size = Offsets.Splits.size();
3690*9880d681SAndroid Build Coastguard Worker for (;;) {
3691*9880d681SAndroid Build Coastguard Worker auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3692*9880d681SAndroid Build Coastguard Worker auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3693*9880d681SAndroid Build Coastguard Worker
3694*9880d681SAndroid Build Coastguard Worker // Either lookup a split load or create one.
3695*9880d681SAndroid Build Coastguard Worker LoadInst *PLoad;
3696*9880d681SAndroid Build Coastguard Worker if (SplitLoads) {
3697*9880d681SAndroid Build Coastguard Worker PLoad = (*SplitLoads)[Idx];
3698*9880d681SAndroid Build Coastguard Worker } else {
3699*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(LI);
3700*9880d681SAndroid Build Coastguard Worker PLoad = IRB.CreateAlignedLoad(
3701*9880d681SAndroid Build Coastguard Worker getAdjustedPtr(IRB, DL, LoadBasePtr,
3702*9880d681SAndroid Build Coastguard Worker APInt(DL.getPointerSizeInBits(), PartOffset),
3703*9880d681SAndroid Build Coastguard Worker PartPtrTy, LoadBasePtr->getName() + "."),
3704*9880d681SAndroid Build Coastguard Worker getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3705*9880d681SAndroid Build Coastguard Worker LI->getName());
3706*9880d681SAndroid Build Coastguard Worker }
3707*9880d681SAndroid Build Coastguard Worker
3708*9880d681SAndroid Build Coastguard Worker // And store this partition.
3709*9880d681SAndroid Build Coastguard Worker IRB.SetInsertPoint(SI);
3710*9880d681SAndroid Build Coastguard Worker StoreInst *PStore = IRB.CreateAlignedStore(
3711*9880d681SAndroid Build Coastguard Worker PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3712*9880d681SAndroid Build Coastguard Worker APInt(DL.getPointerSizeInBits(), PartOffset),
3713*9880d681SAndroid Build Coastguard Worker PartPtrTy, StoreBasePtr->getName() + "."),
3714*9880d681SAndroid Build Coastguard Worker getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3715*9880d681SAndroid Build Coastguard Worker
3716*9880d681SAndroid Build Coastguard Worker // Now build a new slice for the alloca.
3717*9880d681SAndroid Build Coastguard Worker NewSlices.push_back(
3718*9880d681SAndroid Build Coastguard Worker Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3719*9880d681SAndroid Build Coastguard Worker &PStore->getOperandUse(PStore->getPointerOperandIndex()),
3720*9880d681SAndroid Build Coastguard Worker /*IsSplittable*/ false));
3721*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3722*9880d681SAndroid Build Coastguard Worker << ", " << NewSlices.back().endOffset() << "): " << *PStore
3723*9880d681SAndroid Build Coastguard Worker << "\n");
3724*9880d681SAndroid Build Coastguard Worker if (!SplitLoads) {
3725*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3726*9880d681SAndroid Build Coastguard Worker }
3727*9880d681SAndroid Build Coastguard Worker
3728*9880d681SAndroid Build Coastguard Worker // See if we've finished all the splits.
3729*9880d681SAndroid Build Coastguard Worker if (Idx >= Size)
3730*9880d681SAndroid Build Coastguard Worker break;
3731*9880d681SAndroid Build Coastguard Worker
3732*9880d681SAndroid Build Coastguard Worker // Setup the next partition.
3733*9880d681SAndroid Build Coastguard Worker PartOffset = Offsets.Splits[Idx];
3734*9880d681SAndroid Build Coastguard Worker ++Idx;
3735*9880d681SAndroid Build Coastguard Worker PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3736*9880d681SAndroid Build Coastguard Worker }
3737*9880d681SAndroid Build Coastguard Worker
3738*9880d681SAndroid Build Coastguard Worker // We want to immediately iterate on any allocas impacted by splitting
3739*9880d681SAndroid Build Coastguard Worker // this load, which is only relevant if it isn't a load of this alloca and
3740*9880d681SAndroid Build Coastguard Worker // thus we didn't already split the loads above. We also have to keep track
3741*9880d681SAndroid Build Coastguard Worker // of any promotable allocas we split loads on as they can no longer be
3742*9880d681SAndroid Build Coastguard Worker // promoted.
3743*9880d681SAndroid Build Coastguard Worker if (!SplitLoads) {
3744*9880d681SAndroid Build Coastguard Worker if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3745*9880d681SAndroid Build Coastguard Worker assert(OtherAI != &AI && "We can't re-split our own alloca!");
3746*9880d681SAndroid Build Coastguard Worker ResplitPromotableAllocas.insert(OtherAI);
3747*9880d681SAndroid Build Coastguard Worker Worklist.insert(OtherAI);
3748*9880d681SAndroid Build Coastguard Worker } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3749*9880d681SAndroid Build Coastguard Worker LoadBasePtr->stripInBoundsOffsets())) {
3750*9880d681SAndroid Build Coastguard Worker assert(OtherAI != &AI && "We can't re-split our own alloca!");
3751*9880d681SAndroid Build Coastguard Worker Worklist.insert(OtherAI);
3752*9880d681SAndroid Build Coastguard Worker }
3753*9880d681SAndroid Build Coastguard Worker }
3754*9880d681SAndroid Build Coastguard Worker
3755*9880d681SAndroid Build Coastguard Worker // Mark the original store as dead now that we've split it up and kill its
3756*9880d681SAndroid Build Coastguard Worker // slice. Note that we leave the original load in place unless this store
3757*9880d681SAndroid Build Coastguard Worker // was its only use. It may in turn be split up if it is an alloca load
3758*9880d681SAndroid Build Coastguard Worker // for some other alloca, but it may be a normal load. This may introduce
3759*9880d681SAndroid Build Coastguard Worker // redundant loads, but where those can be merged the rest of the optimizer
3760*9880d681SAndroid Build Coastguard Worker // should handle the merging, and this uncovers SSA splits which is more
3761*9880d681SAndroid Build Coastguard Worker // important. In practice, the original loads will almost always be fully
3762*9880d681SAndroid Build Coastguard Worker // split and removed eventually, and the splits will be merged by any
3763*9880d681SAndroid Build Coastguard Worker // trivial CSE, including instcombine.
3764*9880d681SAndroid Build Coastguard Worker if (LI->hasOneUse()) {
3765*9880d681SAndroid Build Coastguard Worker assert(*LI->user_begin() == SI && "Single use isn't this store!");
3766*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(LI);
3767*9880d681SAndroid Build Coastguard Worker }
3768*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(SI);
3769*9880d681SAndroid Build Coastguard Worker Offsets.S->kill();
3770*9880d681SAndroid Build Coastguard Worker }
3771*9880d681SAndroid Build Coastguard Worker
3772*9880d681SAndroid Build Coastguard Worker // Remove the killed slices that have ben pre-split.
3773*9880d681SAndroid Build Coastguard Worker AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3774*9880d681SAndroid Build Coastguard Worker return S.isDead();
3775*9880d681SAndroid Build Coastguard Worker }), AS.end());
3776*9880d681SAndroid Build Coastguard Worker
3777*9880d681SAndroid Build Coastguard Worker // Insert our new slices. This will sort and merge them into the sorted
3778*9880d681SAndroid Build Coastguard Worker // sequence.
3779*9880d681SAndroid Build Coastguard Worker AS.insert(NewSlices);
3780*9880d681SAndroid Build Coastguard Worker
3781*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Pre-split slices:\n");
3782*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
3783*9880d681SAndroid Build Coastguard Worker for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3784*9880d681SAndroid Build Coastguard Worker DEBUG(AS.print(dbgs(), I, " "));
3785*9880d681SAndroid Build Coastguard Worker #endif
3786*9880d681SAndroid Build Coastguard Worker
3787*9880d681SAndroid Build Coastguard Worker // Finally, don't try to promote any allocas that new require re-splitting.
3788*9880d681SAndroid Build Coastguard Worker // They have already been added to the worklist above.
3789*9880d681SAndroid Build Coastguard Worker PromotableAllocas.erase(
3790*9880d681SAndroid Build Coastguard Worker std::remove_if(
3791*9880d681SAndroid Build Coastguard Worker PromotableAllocas.begin(), PromotableAllocas.end(),
3792*9880d681SAndroid Build Coastguard Worker [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3793*9880d681SAndroid Build Coastguard Worker PromotableAllocas.end());
3794*9880d681SAndroid Build Coastguard Worker
3795*9880d681SAndroid Build Coastguard Worker return true;
3796*9880d681SAndroid Build Coastguard Worker }
3797*9880d681SAndroid Build Coastguard Worker
3798*9880d681SAndroid Build Coastguard Worker /// \brief Rewrite an alloca partition's users.
3799*9880d681SAndroid Build Coastguard Worker ///
3800*9880d681SAndroid Build Coastguard Worker /// This routine drives both of the rewriting goals of the SROA pass. It tries
3801*9880d681SAndroid Build Coastguard Worker /// to rewrite uses of an alloca partition to be conducive for SSA value
3802*9880d681SAndroid Build Coastguard Worker /// promotion. If the partition needs a new, more refined alloca, this will
3803*9880d681SAndroid Build Coastguard Worker /// build that new alloca, preserving as much type information as possible, and
3804*9880d681SAndroid Build Coastguard Worker /// rewrite the uses of the old alloca to point at the new one and have the
3805*9880d681SAndroid Build Coastguard Worker /// appropriate new offsets. It also evaluates how successful the rewrite was
3806*9880d681SAndroid Build Coastguard Worker /// at enabling promotion and if it was successful queues the alloca to be
3807*9880d681SAndroid Build Coastguard Worker /// promoted.
rewritePartition(AllocaInst & AI,AllocaSlices & AS,Partition & P)3808*9880d681SAndroid Build Coastguard Worker AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3809*9880d681SAndroid Build Coastguard Worker Partition &P) {
3810*9880d681SAndroid Build Coastguard Worker // Try to compute a friendly type for this partition of the alloca. This
3811*9880d681SAndroid Build Coastguard Worker // won't always succeed, in which case we fall back to a legal integer type
3812*9880d681SAndroid Build Coastguard Worker // or an i8 array of an appropriate size.
3813*9880d681SAndroid Build Coastguard Worker Type *SliceTy = nullptr;
3814*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = AI.getModule()->getDataLayout();
3815*9880d681SAndroid Build Coastguard Worker if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3816*9880d681SAndroid Build Coastguard Worker if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
3817*9880d681SAndroid Build Coastguard Worker SliceTy = CommonUseTy;
3818*9880d681SAndroid Build Coastguard Worker if (!SliceTy)
3819*9880d681SAndroid Build Coastguard Worker if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
3820*9880d681SAndroid Build Coastguard Worker P.beginOffset(), P.size()))
3821*9880d681SAndroid Build Coastguard Worker SliceTy = TypePartitionTy;
3822*9880d681SAndroid Build Coastguard Worker if ((!SliceTy || (SliceTy->isArrayTy() &&
3823*9880d681SAndroid Build Coastguard Worker SliceTy->getArrayElementType()->isIntegerTy())) &&
3824*9880d681SAndroid Build Coastguard Worker DL.isLegalInteger(P.size() * 8))
3825*9880d681SAndroid Build Coastguard Worker SliceTy = Type::getIntNTy(*C, P.size() * 8);
3826*9880d681SAndroid Build Coastguard Worker if (!SliceTy)
3827*9880d681SAndroid Build Coastguard Worker SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3828*9880d681SAndroid Build Coastguard Worker assert(DL.getTypeAllocSize(SliceTy) >= P.size());
3829*9880d681SAndroid Build Coastguard Worker
3830*9880d681SAndroid Build Coastguard Worker bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
3831*9880d681SAndroid Build Coastguard Worker
3832*9880d681SAndroid Build Coastguard Worker VectorType *VecTy =
3833*9880d681SAndroid Build Coastguard Worker IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
3834*9880d681SAndroid Build Coastguard Worker if (VecTy)
3835*9880d681SAndroid Build Coastguard Worker SliceTy = VecTy;
3836*9880d681SAndroid Build Coastguard Worker
3837*9880d681SAndroid Build Coastguard Worker // Check for the case where we're going to rewrite to a new alloca of the
3838*9880d681SAndroid Build Coastguard Worker // exact same type as the original, and with the same access offsets. In that
3839*9880d681SAndroid Build Coastguard Worker // case, re-use the existing alloca, but still run through the rewriter to
3840*9880d681SAndroid Build Coastguard Worker // perform phi and select speculation.
3841*9880d681SAndroid Build Coastguard Worker AllocaInst *NewAI;
3842*9880d681SAndroid Build Coastguard Worker if (SliceTy == AI.getAllocatedType()) {
3843*9880d681SAndroid Build Coastguard Worker assert(P.beginOffset() == 0 &&
3844*9880d681SAndroid Build Coastguard Worker "Non-zero begin offset but same alloca type");
3845*9880d681SAndroid Build Coastguard Worker NewAI = &AI;
3846*9880d681SAndroid Build Coastguard Worker // FIXME: We should be able to bail at this point with "nothing changed".
3847*9880d681SAndroid Build Coastguard Worker // FIXME: We might want to defer PHI speculation until after here.
3848*9880d681SAndroid Build Coastguard Worker // FIXME: return nullptr;
3849*9880d681SAndroid Build Coastguard Worker } else {
3850*9880d681SAndroid Build Coastguard Worker unsigned Alignment = AI.getAlignment();
3851*9880d681SAndroid Build Coastguard Worker if (!Alignment) {
3852*9880d681SAndroid Build Coastguard Worker // The minimum alignment which users can rely on when the explicit
3853*9880d681SAndroid Build Coastguard Worker // alignment is omitted or zero is that required by the ABI for this
3854*9880d681SAndroid Build Coastguard Worker // type.
3855*9880d681SAndroid Build Coastguard Worker Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
3856*9880d681SAndroid Build Coastguard Worker }
3857*9880d681SAndroid Build Coastguard Worker Alignment = MinAlign(Alignment, P.beginOffset());
3858*9880d681SAndroid Build Coastguard Worker // If we will get at least this much alignment from the type alone, leave
3859*9880d681SAndroid Build Coastguard Worker // the alloca's alignment unconstrained.
3860*9880d681SAndroid Build Coastguard Worker if (Alignment <= DL.getABITypeAlignment(SliceTy))
3861*9880d681SAndroid Build Coastguard Worker Alignment = 0;
3862*9880d681SAndroid Build Coastguard Worker NewAI = new AllocaInst(
3863*9880d681SAndroid Build Coastguard Worker SliceTy, nullptr, Alignment,
3864*9880d681SAndroid Build Coastguard Worker AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
3865*9880d681SAndroid Build Coastguard Worker ++NumNewAllocas;
3866*9880d681SAndroid Build Coastguard Worker }
3867*9880d681SAndroid Build Coastguard Worker
3868*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Rewriting alloca partition "
3869*9880d681SAndroid Build Coastguard Worker << "[" << P.beginOffset() << "," << P.endOffset()
3870*9880d681SAndroid Build Coastguard Worker << ") to: " << *NewAI << "\n");
3871*9880d681SAndroid Build Coastguard Worker
3872*9880d681SAndroid Build Coastguard Worker // Track the high watermark on the worklist as it is only relevant for
3873*9880d681SAndroid Build Coastguard Worker // promoted allocas. We will reset it to this point if the alloca is not in
3874*9880d681SAndroid Build Coastguard Worker // fact scheduled for promotion.
3875*9880d681SAndroid Build Coastguard Worker unsigned PPWOldSize = PostPromotionWorklist.size();
3876*9880d681SAndroid Build Coastguard Worker unsigned NumUses = 0;
3877*9880d681SAndroid Build Coastguard Worker SmallPtrSet<PHINode *, 8> PHIUsers;
3878*9880d681SAndroid Build Coastguard Worker SmallPtrSet<SelectInst *, 8> SelectUsers;
3879*9880d681SAndroid Build Coastguard Worker
3880*9880d681SAndroid Build Coastguard Worker AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
3881*9880d681SAndroid Build Coastguard Worker P.endOffset(), IsIntegerPromotable, VecTy,
3882*9880d681SAndroid Build Coastguard Worker PHIUsers, SelectUsers);
3883*9880d681SAndroid Build Coastguard Worker bool Promotable = true;
3884*9880d681SAndroid Build Coastguard Worker for (Slice *S : P.splitSliceTails()) {
3885*9880d681SAndroid Build Coastguard Worker Promotable &= Rewriter.visit(S);
3886*9880d681SAndroid Build Coastguard Worker ++NumUses;
3887*9880d681SAndroid Build Coastguard Worker }
3888*9880d681SAndroid Build Coastguard Worker for (Slice &S : P) {
3889*9880d681SAndroid Build Coastguard Worker Promotable &= Rewriter.visit(&S);
3890*9880d681SAndroid Build Coastguard Worker ++NumUses;
3891*9880d681SAndroid Build Coastguard Worker }
3892*9880d681SAndroid Build Coastguard Worker
3893*9880d681SAndroid Build Coastguard Worker NumAllocaPartitionUses += NumUses;
3894*9880d681SAndroid Build Coastguard Worker MaxUsesPerAllocaPartition =
3895*9880d681SAndroid Build Coastguard Worker std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3896*9880d681SAndroid Build Coastguard Worker
3897*9880d681SAndroid Build Coastguard Worker // Now that we've processed all the slices in the new partition, check if any
3898*9880d681SAndroid Build Coastguard Worker // PHIs or Selects would block promotion.
3899*9880d681SAndroid Build Coastguard Worker for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3900*9880d681SAndroid Build Coastguard Worker E = PHIUsers.end();
3901*9880d681SAndroid Build Coastguard Worker I != E; ++I)
3902*9880d681SAndroid Build Coastguard Worker if (!isSafePHIToSpeculate(**I)) {
3903*9880d681SAndroid Build Coastguard Worker Promotable = false;
3904*9880d681SAndroid Build Coastguard Worker PHIUsers.clear();
3905*9880d681SAndroid Build Coastguard Worker SelectUsers.clear();
3906*9880d681SAndroid Build Coastguard Worker break;
3907*9880d681SAndroid Build Coastguard Worker }
3908*9880d681SAndroid Build Coastguard Worker for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3909*9880d681SAndroid Build Coastguard Worker E = SelectUsers.end();
3910*9880d681SAndroid Build Coastguard Worker I != E; ++I)
3911*9880d681SAndroid Build Coastguard Worker if (!isSafeSelectToSpeculate(**I)) {
3912*9880d681SAndroid Build Coastguard Worker Promotable = false;
3913*9880d681SAndroid Build Coastguard Worker PHIUsers.clear();
3914*9880d681SAndroid Build Coastguard Worker SelectUsers.clear();
3915*9880d681SAndroid Build Coastguard Worker break;
3916*9880d681SAndroid Build Coastguard Worker }
3917*9880d681SAndroid Build Coastguard Worker
3918*9880d681SAndroid Build Coastguard Worker if (Promotable) {
3919*9880d681SAndroid Build Coastguard Worker if (PHIUsers.empty() && SelectUsers.empty()) {
3920*9880d681SAndroid Build Coastguard Worker // Promote the alloca.
3921*9880d681SAndroid Build Coastguard Worker PromotableAllocas.push_back(NewAI);
3922*9880d681SAndroid Build Coastguard Worker } else {
3923*9880d681SAndroid Build Coastguard Worker // If we have either PHIs or Selects to speculate, add them to those
3924*9880d681SAndroid Build Coastguard Worker // worklists and re-queue the new alloca so that we promote in on the
3925*9880d681SAndroid Build Coastguard Worker // next iteration.
3926*9880d681SAndroid Build Coastguard Worker for (PHINode *PHIUser : PHIUsers)
3927*9880d681SAndroid Build Coastguard Worker SpeculatablePHIs.insert(PHIUser);
3928*9880d681SAndroid Build Coastguard Worker for (SelectInst *SelectUser : SelectUsers)
3929*9880d681SAndroid Build Coastguard Worker SpeculatableSelects.insert(SelectUser);
3930*9880d681SAndroid Build Coastguard Worker Worklist.insert(NewAI);
3931*9880d681SAndroid Build Coastguard Worker }
3932*9880d681SAndroid Build Coastguard Worker } else {
3933*9880d681SAndroid Build Coastguard Worker // Drop any post-promotion work items if promotion didn't happen.
3934*9880d681SAndroid Build Coastguard Worker while (PostPromotionWorklist.size() > PPWOldSize)
3935*9880d681SAndroid Build Coastguard Worker PostPromotionWorklist.pop_back();
3936*9880d681SAndroid Build Coastguard Worker
3937*9880d681SAndroid Build Coastguard Worker // We couldn't promote and we didn't create a new partition, nothing
3938*9880d681SAndroid Build Coastguard Worker // happened.
3939*9880d681SAndroid Build Coastguard Worker if (NewAI == &AI)
3940*9880d681SAndroid Build Coastguard Worker return nullptr;
3941*9880d681SAndroid Build Coastguard Worker
3942*9880d681SAndroid Build Coastguard Worker // If we can't promote the alloca, iterate on it to check for new
3943*9880d681SAndroid Build Coastguard Worker // refinements exposed by splitting the current alloca. Don't iterate on an
3944*9880d681SAndroid Build Coastguard Worker // alloca which didn't actually change and didn't get promoted.
3945*9880d681SAndroid Build Coastguard Worker Worklist.insert(NewAI);
3946*9880d681SAndroid Build Coastguard Worker }
3947*9880d681SAndroid Build Coastguard Worker
3948*9880d681SAndroid Build Coastguard Worker return NewAI;
3949*9880d681SAndroid Build Coastguard Worker }
3950*9880d681SAndroid Build Coastguard Worker
3951*9880d681SAndroid Build Coastguard Worker /// \brief Walks the slices of an alloca and form partitions based on them,
3952*9880d681SAndroid Build Coastguard Worker /// rewriting each of their uses.
splitAlloca(AllocaInst & AI,AllocaSlices & AS)3953*9880d681SAndroid Build Coastguard Worker bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3954*9880d681SAndroid Build Coastguard Worker if (AS.begin() == AS.end())
3955*9880d681SAndroid Build Coastguard Worker return false;
3956*9880d681SAndroid Build Coastguard Worker
3957*9880d681SAndroid Build Coastguard Worker unsigned NumPartitions = 0;
3958*9880d681SAndroid Build Coastguard Worker bool Changed = false;
3959*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = AI.getModule()->getDataLayout();
3960*9880d681SAndroid Build Coastguard Worker
3961*9880d681SAndroid Build Coastguard Worker // First try to pre-split loads and stores.
3962*9880d681SAndroid Build Coastguard Worker Changed |= presplitLoadsAndStores(AI, AS);
3963*9880d681SAndroid Build Coastguard Worker
3964*9880d681SAndroid Build Coastguard Worker // Now that we have identified any pre-splitting opportunities, mark any
3965*9880d681SAndroid Build Coastguard Worker // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
3966*9880d681SAndroid Build Coastguard Worker // to split these during pre-splitting, we want to force them to be
3967*9880d681SAndroid Build Coastguard Worker // rewritten into a partition.
3968*9880d681SAndroid Build Coastguard Worker bool IsSorted = true;
3969*9880d681SAndroid Build Coastguard Worker for (Slice &S : AS) {
3970*9880d681SAndroid Build Coastguard Worker if (!S.isSplittable())
3971*9880d681SAndroid Build Coastguard Worker continue;
3972*9880d681SAndroid Build Coastguard Worker // FIXME: We currently leave whole-alloca splittable loads and stores. This
3973*9880d681SAndroid Build Coastguard Worker // used to be the only splittable loads and stores and we need to be
3974*9880d681SAndroid Build Coastguard Worker // confident that the above handling of splittable loads and stores is
3975*9880d681SAndroid Build Coastguard Worker // completely sufficient before we forcibly disable the remaining handling.
3976*9880d681SAndroid Build Coastguard Worker if (S.beginOffset() == 0 &&
3977*9880d681SAndroid Build Coastguard Worker S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
3978*9880d681SAndroid Build Coastguard Worker continue;
3979*9880d681SAndroid Build Coastguard Worker if (isa<LoadInst>(S.getUse()->getUser()) ||
3980*9880d681SAndroid Build Coastguard Worker isa<StoreInst>(S.getUse()->getUser())) {
3981*9880d681SAndroid Build Coastguard Worker S.makeUnsplittable();
3982*9880d681SAndroid Build Coastguard Worker IsSorted = false;
3983*9880d681SAndroid Build Coastguard Worker }
3984*9880d681SAndroid Build Coastguard Worker }
3985*9880d681SAndroid Build Coastguard Worker if (!IsSorted)
3986*9880d681SAndroid Build Coastguard Worker std::sort(AS.begin(), AS.end());
3987*9880d681SAndroid Build Coastguard Worker
3988*9880d681SAndroid Build Coastguard Worker /// \brief Describes the allocas introduced by rewritePartition
3989*9880d681SAndroid Build Coastguard Worker /// in order to migrate the debug info.
3990*9880d681SAndroid Build Coastguard Worker struct Piece {
3991*9880d681SAndroid Build Coastguard Worker AllocaInst *Alloca;
3992*9880d681SAndroid Build Coastguard Worker uint64_t Offset;
3993*9880d681SAndroid Build Coastguard Worker uint64_t Size;
3994*9880d681SAndroid Build Coastguard Worker Piece(AllocaInst *AI, uint64_t O, uint64_t S)
3995*9880d681SAndroid Build Coastguard Worker : Alloca(AI), Offset(O), Size(S) {}
3996*9880d681SAndroid Build Coastguard Worker };
3997*9880d681SAndroid Build Coastguard Worker SmallVector<Piece, 4> Pieces;
3998*9880d681SAndroid Build Coastguard Worker
3999*9880d681SAndroid Build Coastguard Worker // Rewrite each partition.
4000*9880d681SAndroid Build Coastguard Worker for (auto &P : AS.partitions()) {
4001*9880d681SAndroid Build Coastguard Worker if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4002*9880d681SAndroid Build Coastguard Worker Changed = true;
4003*9880d681SAndroid Build Coastguard Worker if (NewAI != &AI) {
4004*9880d681SAndroid Build Coastguard Worker uint64_t SizeOfByte = 8;
4005*9880d681SAndroid Build Coastguard Worker uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
4006*9880d681SAndroid Build Coastguard Worker // Don't include any padding.
4007*9880d681SAndroid Build Coastguard Worker uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4008*9880d681SAndroid Build Coastguard Worker Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
4009*9880d681SAndroid Build Coastguard Worker }
4010*9880d681SAndroid Build Coastguard Worker }
4011*9880d681SAndroid Build Coastguard Worker ++NumPartitions;
4012*9880d681SAndroid Build Coastguard Worker }
4013*9880d681SAndroid Build Coastguard Worker
4014*9880d681SAndroid Build Coastguard Worker NumAllocaPartitions += NumPartitions;
4015*9880d681SAndroid Build Coastguard Worker MaxPartitionsPerAlloca =
4016*9880d681SAndroid Build Coastguard Worker std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
4017*9880d681SAndroid Build Coastguard Worker
4018*9880d681SAndroid Build Coastguard Worker // Migrate debug information from the old alloca to the new alloca(s)
4019*9880d681SAndroid Build Coastguard Worker // and the individual partitions.
4020*9880d681SAndroid Build Coastguard Worker if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
4021*9880d681SAndroid Build Coastguard Worker auto *Var = DbgDecl->getVariable();
4022*9880d681SAndroid Build Coastguard Worker auto *Expr = DbgDecl->getExpression();
4023*9880d681SAndroid Build Coastguard Worker DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4024*9880d681SAndroid Build Coastguard Worker uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
4025*9880d681SAndroid Build Coastguard Worker for (auto Piece : Pieces) {
4026*9880d681SAndroid Build Coastguard Worker // Create a piece expression describing the new partition or reuse AI's
4027*9880d681SAndroid Build Coastguard Worker // expression if there is only one partition.
4028*9880d681SAndroid Build Coastguard Worker auto *PieceExpr = Expr;
4029*9880d681SAndroid Build Coastguard Worker if (Piece.Size < AllocaSize || Expr->isBitPiece()) {
4030*9880d681SAndroid Build Coastguard Worker // If this alloca is already a scalar replacement of a larger aggregate,
4031*9880d681SAndroid Build Coastguard Worker // Piece.Offset describes the offset inside the scalar.
4032*9880d681SAndroid Build Coastguard Worker uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
4033*9880d681SAndroid Build Coastguard Worker uint64_t Start = Offset + Piece.Offset;
4034*9880d681SAndroid Build Coastguard Worker uint64_t Size = Piece.Size;
4035*9880d681SAndroid Build Coastguard Worker if (Expr->isBitPiece()) {
4036*9880d681SAndroid Build Coastguard Worker uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
4037*9880d681SAndroid Build Coastguard Worker if (Start >= AbsEnd)
4038*9880d681SAndroid Build Coastguard Worker // No need to describe a SROAed padding.
4039*9880d681SAndroid Build Coastguard Worker continue;
4040*9880d681SAndroid Build Coastguard Worker Size = std::min(Size, AbsEnd - Start);
4041*9880d681SAndroid Build Coastguard Worker }
4042*9880d681SAndroid Build Coastguard Worker PieceExpr = DIB.createBitPieceExpression(Start, Size);
4043*9880d681SAndroid Build Coastguard Worker } else {
4044*9880d681SAndroid Build Coastguard Worker assert(Pieces.size() == 1 &&
4045*9880d681SAndroid Build Coastguard Worker "partition is as large as original alloca");
4046*9880d681SAndroid Build Coastguard Worker }
4047*9880d681SAndroid Build Coastguard Worker
4048*9880d681SAndroid Build Coastguard Worker // Remove any existing dbg.declare intrinsic describing the same alloca.
4049*9880d681SAndroid Build Coastguard Worker if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
4050*9880d681SAndroid Build Coastguard Worker OldDDI->eraseFromParent();
4051*9880d681SAndroid Build Coastguard Worker
4052*9880d681SAndroid Build Coastguard Worker DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
4053*9880d681SAndroid Build Coastguard Worker &AI);
4054*9880d681SAndroid Build Coastguard Worker }
4055*9880d681SAndroid Build Coastguard Worker }
4056*9880d681SAndroid Build Coastguard Worker return Changed;
4057*9880d681SAndroid Build Coastguard Worker }
4058*9880d681SAndroid Build Coastguard Worker
4059*9880d681SAndroid Build Coastguard Worker /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
clobberUse(Use & U)4060*9880d681SAndroid Build Coastguard Worker void SROA::clobberUse(Use &U) {
4061*9880d681SAndroid Build Coastguard Worker Value *OldV = U;
4062*9880d681SAndroid Build Coastguard Worker // Replace the use with an undef value.
4063*9880d681SAndroid Build Coastguard Worker U = UndefValue::get(OldV->getType());
4064*9880d681SAndroid Build Coastguard Worker
4065*9880d681SAndroid Build Coastguard Worker // Check for this making an instruction dead. We have to garbage collect
4066*9880d681SAndroid Build Coastguard Worker // all the dead instructions to ensure the uses of any alloca end up being
4067*9880d681SAndroid Build Coastguard Worker // minimal.
4068*9880d681SAndroid Build Coastguard Worker if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4069*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(OldI)) {
4070*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(OldI);
4071*9880d681SAndroid Build Coastguard Worker }
4072*9880d681SAndroid Build Coastguard Worker }
4073*9880d681SAndroid Build Coastguard Worker
4074*9880d681SAndroid Build Coastguard Worker /// \brief Analyze an alloca for SROA.
4075*9880d681SAndroid Build Coastguard Worker ///
4076*9880d681SAndroid Build Coastguard Worker /// This analyzes the alloca to ensure we can reason about it, builds
4077*9880d681SAndroid Build Coastguard Worker /// the slices of the alloca, and then hands it off to be split and
4078*9880d681SAndroid Build Coastguard Worker /// rewritten as needed.
runOnAlloca(AllocaInst & AI)4079*9880d681SAndroid Build Coastguard Worker bool SROA::runOnAlloca(AllocaInst &AI) {
4080*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4081*9880d681SAndroid Build Coastguard Worker ++NumAllocasAnalyzed;
4082*9880d681SAndroid Build Coastguard Worker
4083*9880d681SAndroid Build Coastguard Worker // Special case dead allocas, as they're trivial.
4084*9880d681SAndroid Build Coastguard Worker if (AI.use_empty()) {
4085*9880d681SAndroid Build Coastguard Worker AI.eraseFromParent();
4086*9880d681SAndroid Build Coastguard Worker return true;
4087*9880d681SAndroid Build Coastguard Worker }
4088*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = AI.getModule()->getDataLayout();
4089*9880d681SAndroid Build Coastguard Worker
4090*9880d681SAndroid Build Coastguard Worker // Skip alloca forms that this analysis can't handle.
4091*9880d681SAndroid Build Coastguard Worker if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
4092*9880d681SAndroid Build Coastguard Worker DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
4093*9880d681SAndroid Build Coastguard Worker return false;
4094*9880d681SAndroid Build Coastguard Worker
4095*9880d681SAndroid Build Coastguard Worker bool Changed = false;
4096*9880d681SAndroid Build Coastguard Worker
4097*9880d681SAndroid Build Coastguard Worker // First, split any FCA loads and stores touching this alloca to promote
4098*9880d681SAndroid Build Coastguard Worker // better splitting and promotion opportunities.
4099*9880d681SAndroid Build Coastguard Worker AggLoadStoreRewriter AggRewriter;
4100*9880d681SAndroid Build Coastguard Worker Changed |= AggRewriter.rewrite(AI);
4101*9880d681SAndroid Build Coastguard Worker
4102*9880d681SAndroid Build Coastguard Worker // Build the slices using a recursive instruction-visiting builder.
4103*9880d681SAndroid Build Coastguard Worker AllocaSlices AS(DL, AI);
4104*9880d681SAndroid Build Coastguard Worker DEBUG(AS.print(dbgs()));
4105*9880d681SAndroid Build Coastguard Worker if (AS.isEscaped())
4106*9880d681SAndroid Build Coastguard Worker return Changed;
4107*9880d681SAndroid Build Coastguard Worker
4108*9880d681SAndroid Build Coastguard Worker // Delete all the dead users of this alloca before splitting and rewriting it.
4109*9880d681SAndroid Build Coastguard Worker for (Instruction *DeadUser : AS.getDeadUsers()) {
4110*9880d681SAndroid Build Coastguard Worker // Free up everything used by this instruction.
4111*9880d681SAndroid Build Coastguard Worker for (Use &DeadOp : DeadUser->operands())
4112*9880d681SAndroid Build Coastguard Worker clobberUse(DeadOp);
4113*9880d681SAndroid Build Coastguard Worker
4114*9880d681SAndroid Build Coastguard Worker // Now replace the uses of this instruction.
4115*9880d681SAndroid Build Coastguard Worker DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4116*9880d681SAndroid Build Coastguard Worker
4117*9880d681SAndroid Build Coastguard Worker // And mark it for deletion.
4118*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(DeadUser);
4119*9880d681SAndroid Build Coastguard Worker Changed = true;
4120*9880d681SAndroid Build Coastguard Worker }
4121*9880d681SAndroid Build Coastguard Worker for (Use *DeadOp : AS.getDeadOperands()) {
4122*9880d681SAndroid Build Coastguard Worker clobberUse(*DeadOp);
4123*9880d681SAndroid Build Coastguard Worker Changed = true;
4124*9880d681SAndroid Build Coastguard Worker }
4125*9880d681SAndroid Build Coastguard Worker
4126*9880d681SAndroid Build Coastguard Worker // No slices to split. Leave the dead alloca for a later pass to clean up.
4127*9880d681SAndroid Build Coastguard Worker if (AS.begin() == AS.end())
4128*9880d681SAndroid Build Coastguard Worker return Changed;
4129*9880d681SAndroid Build Coastguard Worker
4130*9880d681SAndroid Build Coastguard Worker Changed |= splitAlloca(AI, AS);
4131*9880d681SAndroid Build Coastguard Worker
4132*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Speculating PHIs\n");
4133*9880d681SAndroid Build Coastguard Worker while (!SpeculatablePHIs.empty())
4134*9880d681SAndroid Build Coastguard Worker speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4135*9880d681SAndroid Build Coastguard Worker
4136*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Speculating Selects\n");
4137*9880d681SAndroid Build Coastguard Worker while (!SpeculatableSelects.empty())
4138*9880d681SAndroid Build Coastguard Worker speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4139*9880d681SAndroid Build Coastguard Worker
4140*9880d681SAndroid Build Coastguard Worker return Changed;
4141*9880d681SAndroid Build Coastguard Worker }
4142*9880d681SAndroid Build Coastguard Worker
4143*9880d681SAndroid Build Coastguard Worker /// \brief Delete the dead instructions accumulated in this run.
4144*9880d681SAndroid Build Coastguard Worker ///
4145*9880d681SAndroid Build Coastguard Worker /// Recursively deletes the dead instructions we've accumulated. This is done
4146*9880d681SAndroid Build Coastguard Worker /// at the very end to maximize locality of the recursive delete and to
4147*9880d681SAndroid Build Coastguard Worker /// minimize the problems of invalidated instruction pointers as such pointers
4148*9880d681SAndroid Build Coastguard Worker /// are used heavily in the intermediate stages of the algorithm.
4149*9880d681SAndroid Build Coastguard Worker ///
4150*9880d681SAndroid Build Coastguard Worker /// We also record the alloca instructions deleted here so that they aren't
4151*9880d681SAndroid Build Coastguard Worker /// subsequently handed to mem2reg to promote.
deleteDeadInstructions(SmallPtrSetImpl<AllocaInst * > & DeletedAllocas)4152*9880d681SAndroid Build Coastguard Worker void SROA::deleteDeadInstructions(
4153*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4154*9880d681SAndroid Build Coastguard Worker while (!DeadInsts.empty()) {
4155*9880d681SAndroid Build Coastguard Worker Instruction *I = DeadInsts.pop_back_val();
4156*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4157*9880d681SAndroid Build Coastguard Worker
4158*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(UndefValue::get(I->getType()));
4159*9880d681SAndroid Build Coastguard Worker
4160*9880d681SAndroid Build Coastguard Worker for (Use &Operand : I->operands())
4161*9880d681SAndroid Build Coastguard Worker if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4162*9880d681SAndroid Build Coastguard Worker // Zero out the operand and see if it becomes trivially dead.
4163*9880d681SAndroid Build Coastguard Worker Operand = nullptr;
4164*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(U))
4165*9880d681SAndroid Build Coastguard Worker DeadInsts.insert(U);
4166*9880d681SAndroid Build Coastguard Worker }
4167*9880d681SAndroid Build Coastguard Worker
4168*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4169*9880d681SAndroid Build Coastguard Worker DeletedAllocas.insert(AI);
4170*9880d681SAndroid Build Coastguard Worker if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4171*9880d681SAndroid Build Coastguard Worker DbgDecl->eraseFromParent();
4172*9880d681SAndroid Build Coastguard Worker }
4173*9880d681SAndroid Build Coastguard Worker
4174*9880d681SAndroid Build Coastguard Worker ++NumDeleted;
4175*9880d681SAndroid Build Coastguard Worker I->eraseFromParent();
4176*9880d681SAndroid Build Coastguard Worker }
4177*9880d681SAndroid Build Coastguard Worker }
4178*9880d681SAndroid Build Coastguard Worker
4179*9880d681SAndroid Build Coastguard Worker /// \brief Promote the allocas, using the best available technique.
4180*9880d681SAndroid Build Coastguard Worker ///
4181*9880d681SAndroid Build Coastguard Worker /// This attempts to promote whatever allocas have been identified as viable in
4182*9880d681SAndroid Build Coastguard Worker /// the PromotableAllocas list. If that list is empty, there is nothing to do.
4183*9880d681SAndroid Build Coastguard Worker /// This function returns whether any promotion occurred.
promoteAllocas(Function & F)4184*9880d681SAndroid Build Coastguard Worker bool SROA::promoteAllocas(Function &F) {
4185*9880d681SAndroid Build Coastguard Worker if (PromotableAllocas.empty())
4186*9880d681SAndroid Build Coastguard Worker return false;
4187*9880d681SAndroid Build Coastguard Worker
4188*9880d681SAndroid Build Coastguard Worker NumPromoted += PromotableAllocas.size();
4189*9880d681SAndroid Build Coastguard Worker
4190*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4191*9880d681SAndroid Build Coastguard Worker PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
4192*9880d681SAndroid Build Coastguard Worker PromotableAllocas.clear();
4193*9880d681SAndroid Build Coastguard Worker return true;
4194*9880d681SAndroid Build Coastguard Worker }
4195*9880d681SAndroid Build Coastguard Worker
runImpl(Function & F,DominatorTree & RunDT,AssumptionCache & RunAC)4196*9880d681SAndroid Build Coastguard Worker PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4197*9880d681SAndroid Build Coastguard Worker AssumptionCache &RunAC) {
4198*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4199*9880d681SAndroid Build Coastguard Worker C = &F.getContext();
4200*9880d681SAndroid Build Coastguard Worker DT = &RunDT;
4201*9880d681SAndroid Build Coastguard Worker AC = &RunAC;
4202*9880d681SAndroid Build Coastguard Worker
4203*9880d681SAndroid Build Coastguard Worker BasicBlock &EntryBB = F.getEntryBlock();
4204*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4205*9880d681SAndroid Build Coastguard Worker I != E; ++I) {
4206*9880d681SAndroid Build Coastguard Worker if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4207*9880d681SAndroid Build Coastguard Worker Worklist.insert(AI);
4208*9880d681SAndroid Build Coastguard Worker }
4209*9880d681SAndroid Build Coastguard Worker
4210*9880d681SAndroid Build Coastguard Worker bool Changed = false;
4211*9880d681SAndroid Build Coastguard Worker // A set of deleted alloca instruction pointers which should be removed from
4212*9880d681SAndroid Build Coastguard Worker // the list of promotable allocas.
4213*9880d681SAndroid Build Coastguard Worker SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4214*9880d681SAndroid Build Coastguard Worker
4215*9880d681SAndroid Build Coastguard Worker do {
4216*9880d681SAndroid Build Coastguard Worker while (!Worklist.empty()) {
4217*9880d681SAndroid Build Coastguard Worker Changed |= runOnAlloca(*Worklist.pop_back_val());
4218*9880d681SAndroid Build Coastguard Worker deleteDeadInstructions(DeletedAllocas);
4219*9880d681SAndroid Build Coastguard Worker
4220*9880d681SAndroid Build Coastguard Worker // Remove the deleted allocas from various lists so that we don't try to
4221*9880d681SAndroid Build Coastguard Worker // continue processing them.
4222*9880d681SAndroid Build Coastguard Worker if (!DeletedAllocas.empty()) {
4223*9880d681SAndroid Build Coastguard Worker auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4224*9880d681SAndroid Build Coastguard Worker Worklist.remove_if(IsInSet);
4225*9880d681SAndroid Build Coastguard Worker PostPromotionWorklist.remove_if(IsInSet);
4226*9880d681SAndroid Build Coastguard Worker PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4227*9880d681SAndroid Build Coastguard Worker PromotableAllocas.end(),
4228*9880d681SAndroid Build Coastguard Worker IsInSet),
4229*9880d681SAndroid Build Coastguard Worker PromotableAllocas.end());
4230*9880d681SAndroid Build Coastguard Worker DeletedAllocas.clear();
4231*9880d681SAndroid Build Coastguard Worker }
4232*9880d681SAndroid Build Coastguard Worker }
4233*9880d681SAndroid Build Coastguard Worker
4234*9880d681SAndroid Build Coastguard Worker Changed |= promoteAllocas(F);
4235*9880d681SAndroid Build Coastguard Worker
4236*9880d681SAndroid Build Coastguard Worker Worklist = PostPromotionWorklist;
4237*9880d681SAndroid Build Coastguard Worker PostPromotionWorklist.clear();
4238*9880d681SAndroid Build Coastguard Worker } while (!Worklist.empty());
4239*9880d681SAndroid Build Coastguard Worker
4240*9880d681SAndroid Build Coastguard Worker if (!Changed)
4241*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
4242*9880d681SAndroid Build Coastguard Worker
4243*9880d681SAndroid Build Coastguard Worker // FIXME: Even when promoting allocas we should preserve some abstract set of
4244*9880d681SAndroid Build Coastguard Worker // CFG-specific analyses.
4245*9880d681SAndroid Build Coastguard Worker PreservedAnalyses PA;
4246*9880d681SAndroid Build Coastguard Worker PA.preserve<GlobalsAA>();
4247*9880d681SAndroid Build Coastguard Worker return PA;
4248*9880d681SAndroid Build Coastguard Worker }
4249*9880d681SAndroid Build Coastguard Worker
run(Function & F,AnalysisManager<Function> & AM)4250*9880d681SAndroid Build Coastguard Worker PreservedAnalyses SROA::run(Function &F, AnalysisManager<Function> &AM) {
4251*9880d681SAndroid Build Coastguard Worker return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4252*9880d681SAndroid Build Coastguard Worker AM.getResult<AssumptionAnalysis>(F));
4253*9880d681SAndroid Build Coastguard Worker }
4254*9880d681SAndroid Build Coastguard Worker
4255*9880d681SAndroid Build Coastguard Worker /// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4256*9880d681SAndroid Build Coastguard Worker ///
4257*9880d681SAndroid Build Coastguard Worker /// This is in the llvm namespace purely to allow it to be a friend of the \c
4258*9880d681SAndroid Build Coastguard Worker /// SROA pass.
4259*9880d681SAndroid Build Coastguard Worker class llvm::sroa::SROALegacyPass : public FunctionPass {
4260*9880d681SAndroid Build Coastguard Worker /// The SROA implementation.
4261*9880d681SAndroid Build Coastguard Worker SROA Impl;
4262*9880d681SAndroid Build Coastguard Worker
4263*9880d681SAndroid Build Coastguard Worker public:
SROALegacyPass()4264*9880d681SAndroid Build Coastguard Worker SROALegacyPass() : FunctionPass(ID) {
4265*9880d681SAndroid Build Coastguard Worker initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4266*9880d681SAndroid Build Coastguard Worker }
runOnFunction(Function & F)4267*9880d681SAndroid Build Coastguard Worker bool runOnFunction(Function &F) override {
4268*9880d681SAndroid Build Coastguard Worker if (skipFunction(F))
4269*9880d681SAndroid Build Coastguard Worker return false;
4270*9880d681SAndroid Build Coastguard Worker
4271*9880d681SAndroid Build Coastguard Worker auto PA = Impl.runImpl(
4272*9880d681SAndroid Build Coastguard Worker F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4273*9880d681SAndroid Build Coastguard Worker getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4274*9880d681SAndroid Build Coastguard Worker return !PA.areAllPreserved();
4275*9880d681SAndroid Build Coastguard Worker }
getAnalysisUsage(AnalysisUsage & AU) const4276*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
4277*9880d681SAndroid Build Coastguard Worker AU.addRequired<AssumptionCacheTracker>();
4278*9880d681SAndroid Build Coastguard Worker AU.addRequired<DominatorTreeWrapperPass>();
4279*9880d681SAndroid Build Coastguard Worker AU.addPreserved<GlobalsAAWrapperPass>();
4280*9880d681SAndroid Build Coastguard Worker AU.setPreservesCFG();
4281*9880d681SAndroid Build Coastguard Worker }
4282*9880d681SAndroid Build Coastguard Worker
getPassName() const4283*9880d681SAndroid Build Coastguard Worker const char *getPassName() const override { return "SROA"; }
4284*9880d681SAndroid Build Coastguard Worker static char ID;
4285*9880d681SAndroid Build Coastguard Worker };
4286*9880d681SAndroid Build Coastguard Worker
4287*9880d681SAndroid Build Coastguard Worker char SROALegacyPass::ID = 0;
4288*9880d681SAndroid Build Coastguard Worker
createSROAPass()4289*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4290*9880d681SAndroid Build Coastguard Worker
4291*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4292*9880d681SAndroid Build Coastguard Worker "Scalar Replacement Of Aggregates", false, false)
4293*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4294*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4295*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4296*9880d681SAndroid Build Coastguard Worker false, false)
4297