blob: dbbc1758b9fe057375d29efe2430e8f7bdec56d6 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth29a18a42015-09-12 09:09:14 +000026#include "llvm/Transforms/Scalar/SROA.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000030#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000031#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000036#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000041#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000046#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000047#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000048#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/MathExtras.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000052#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000054#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000057
58#if __cplusplus >= 201103L && !defined(NDEBUG)
59// We only use this for a debug check in C++11
60#include <random>
61#endif
62
Chandler Carruth1b398ae2012-09-14 09:22:59 +000063using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +000064using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "sroa"
67
Chandler Carruth1b398ae2012-09-14 09:22:59 +000068STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000069STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000070STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
71STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
72STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000073STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
74STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000076STATISTIC(NumDeleted, "Number of instructions deleted");
77STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078
Chandler Carruth83cee772014-02-25 03:59:29 +000079/// Hidden option to enable randomly shuffling the slices to help uncover
80/// instability in their order.
81static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
82 cl::init(false), cl::Hidden);
83
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000084/// Hidden option to experiment with completely strict handling of inbounds
85/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +000086static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
87 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000088
Chandler Carruth1b398ae2012-09-14 09:22:59 +000089namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000090/// \brief A custom IRBuilder inserter which prefixes all names if they are
91/// preserved.
92template <bool preserveNames = true>
Chandler Carruth113dc642014-12-20 02:39:18 +000093class IRBuilderPrefixedInserter
94 : public IRBuilderDefaultInserter<preserveNames> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000095 std::string Prefix;
96
97public:
98 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
99
100protected:
101 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
102 BasicBlock::iterator InsertPt) const {
103 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
104 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
105 }
106};
107
108// Specialization for not preserving the name is trivial.
109template <>
Chandler Carruth113dc642014-12-20 02:39:18 +0000110class IRBuilderPrefixedInserter<false>
111 : public IRBuilderDefaultInserter<false> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000112public:
113 void SetNamePrefix(const Twine &P) {}
114};
115
Chandler Carruthd177f862013-03-20 07:30:36 +0000116/// \brief Provide a typedef for IRBuilder that drops names in release builds.
117#ifndef NDEBUG
Chandler Carruth113dc642014-12-20 02:39:18 +0000118typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
119 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000120#else
Chandler Carruth113dc642014-12-20 02:39:18 +0000121typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
122 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000123#endif
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000124}
Chandler Carruthd177f862013-03-20 07:30:36 +0000125
126namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000128///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129/// This structure represents a slice of an alloca used by some instruction. It
130/// stores both the begin and end offsets of this use, a pointer to the use
131/// itself, and a flag indicating whether we can classify the use as splittable
132/// or not when forming partitions of the alloca.
133class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000134 /// \brief The beginning offset of the range.
135 uint64_t BeginOffset;
136
137 /// \brief The ending offset, not included in the range.
138 uint64_t EndOffset;
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000141 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000142 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000143
144public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000145 Slice() : BeginOffset(), EndOffset() {}
146 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000147 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000148 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000149
150 uint64_t beginOffset() const { return BeginOffset; }
151 uint64_t endOffset() const { return EndOffset; }
152
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000153 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
154 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000155
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000156 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000157
Craig Topperf40110f2014-04-25 05:29:35 +0000158 bool isDead() const { return getUse() == nullptr; }
159 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000160
161 /// \brief Support for ordering ranges.
162 ///
163 /// This provides an ordering over ranges such that start offsets are
164 /// always increasing, and within equal start offsets, the end offsets are
165 /// decreasing. Thus the spanning range comes first in a cluster with the
166 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000167 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000168 if (beginOffset() < RHS.beginOffset())
169 return true;
170 if (beginOffset() > RHS.beginOffset())
171 return false;
172 if (isSplittable() != RHS.isSplittable())
173 return !isSplittable();
174 if (endOffset() > RHS.endOffset())
175 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000176 return false;
177 }
178
179 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000181 uint64_t RHSOffset) {
182 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000183 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000184 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000185 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000186 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000187 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000188
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000189 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000190 return isSplittable() == RHS.isSplittable() &&
191 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000192 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000193 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000194};
Chandler Carruthf0546402013-07-18 07:15:00 +0000195} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000196
197namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000198template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000199template <> struct isPodLike<Slice> { static const bool value = true; };
Chandler Carruthf74654d2013-03-18 08:36:46 +0000200}
201
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000202/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000203///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000204/// This class represents the slices of an alloca which are formed by its
205/// various uses. If a pointer escapes, we can't fully build a representation
206/// for the slices used and we reflect that in this structure. The uses are
207/// stored, sorted by increasing beginning offset and with unsplittable slices
208/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000209class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000210public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211 /// \brief Construct the slices of a particular alloca.
212 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000213
214 /// \brief Test whether a pointer to the allocation escapes our analysis.
215 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000216 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217 /// ignored.
218 bool isEscaped() const { return PointerEscapingInstr; }
219
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000220 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000221 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000222 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000223 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000224 iterator begin() { return Slices.begin(); }
225 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000226
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000227 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000228 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000229 const_iterator begin() const { return Slices.begin(); }
230 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000231 /// @}
232
Chandler Carruth0715cba2015-01-01 11:54:38 +0000233 /// \brief Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000234 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000235
236 /// \brief Insert new slices for this alloca.
237 ///
238 /// This moves the slices into the alloca's slices collection, and re-sorts
239 /// everything so that the usual ordering properties of the alloca's slices
240 /// hold.
241 void insert(ArrayRef<Slice> NewSlices) {
242 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000243 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000244 auto SliceI = Slices.begin() + OldSize;
245 std::sort(SliceI, Slices.end());
246 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
247 }
248
Chandler Carruth29a18a42015-09-12 09:09:14 +0000249 // Forward declare the iterator and range accessor for walking the
250 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000251 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000252 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000253
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000254 /// \brief Access the dead users for this alloca.
255 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000256
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000257 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000258 ///
259 /// These are operands which have cannot actually be used to refer to the
260 /// alloca as they are outside its range and the user doesn't correct for
261 /// that. These mostly consist of PHI node inputs and the like which we just
262 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000263 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000264
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000265#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000266 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000267 void printSlice(raw_ostream &OS, const_iterator I,
268 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000269 void printUse(raw_ostream &OS, const_iterator I,
270 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000271 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000272 void dump(const_iterator I) const;
273 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000274#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000275
276private:
277 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000278 class SliceBuilder;
279 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000280
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000281#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000282 /// \brief Handle to alloca instruction to simplify method interfaces.
283 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000284#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000285
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000286 /// \brief The instruction responsible for this alloca not having a known set
287 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288 ///
289 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000290 /// store a pointer to that here and abort trying to form slices of the
291 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000292 Instruction *PointerEscapingInstr;
293
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000294 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000296 /// We store a vector of the slices formed by uses of the alloca here. This
297 /// vector is sorted by increasing begin offset, and then the unsplittable
298 /// slices before the splittable ones. See the Slice inner class for more
299 /// details.
300 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000301
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000302 /// \brief Instructions which will become dead if we rewrite the alloca.
303 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000304 /// Note that these are not separated by slice. This is because we expect an
305 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
306 /// all these instructions can simply be removed and replaced with undef as
307 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308 SmallVector<Instruction *, 8> DeadUsers;
309
310 /// \brief Operands which will become dead if we rewrite the alloca.
311 ///
312 /// These are operands that in their particular use can be replaced with
313 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
314 /// to PHI nodes and the like. They aren't entirely dead (there might be
315 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
316 /// want to swap this particular input for undef to simplify the use lists of
317 /// the alloca.
318 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000319};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000320
321/// \brief A partition of the slices.
322///
323/// An ephemeral representation for a range of slices which can be viewed as
324/// a partition of the alloca. This range represents a span of the alloca's
325/// memory which cannot be split, and provides access to all of the slices
326/// overlapping some part of the partition.
327///
328/// Objects of this type are produced by traversing the alloca's slices, but
329/// are only ephemeral and not persistent.
330class llvm::sroa::Partition {
331private:
332 friend class AllocaSlices;
333 friend class AllocaSlices::partition_iterator;
334
335 typedef AllocaSlices::iterator iterator;
336
337 /// \brief The beginning and ending offsets of the alloca for this
338 /// partition.
339 uint64_t BeginOffset, EndOffset;
340
341 /// \brief The start end end iterators of this partition.
342 iterator SI, SJ;
343
344 /// \brief A collection of split slice tails overlapping the partition.
345 SmallVector<Slice *, 4> SplitTails;
346
347 /// \brief Raw constructor builds an empty partition starting and ending at
348 /// the given iterator.
349 Partition(iterator SI) : SI(SI), SJ(SI) {}
350
351public:
352 /// \brief The start offset of this partition.
353 ///
354 /// All of the contained slices start at or after this offset.
355 uint64_t beginOffset() const { return BeginOffset; }
356
357 /// \brief The end offset of this partition.
358 ///
359 /// All of the contained slices end at or before this offset.
360 uint64_t endOffset() const { return EndOffset; }
361
362 /// \brief The size of the partition.
363 ///
364 /// Note that this can never be zero.
365 uint64_t size() const {
366 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
367 return EndOffset - BeginOffset;
368 }
369
370 /// \brief Test whether this partition contains no slices, and merely spans
371 /// a region occupied by split slices.
372 bool empty() const { return SI == SJ; }
373
374 /// \name Iterate slices that start within the partition.
375 /// These may be splittable or unsplittable. They have a begin offset >= the
376 /// partition begin offset.
377 /// @{
378 // FIXME: We should probably define a "concat_iterator" helper and use that
379 // to stitch together pointee_iterators over the split tails and the
380 // contiguous iterators of the partition. That would give a much nicer
381 // interface here. We could then additionally expose filtered iterators for
382 // split, unsplit, and unsplittable splices based on the usage patterns.
383 iterator begin() const { return SI; }
384 iterator end() const { return SJ; }
385 /// @}
386
387 /// \brief Get the sequence of split slice tails.
388 ///
389 /// These tails are of slices which start before this partition but are
390 /// split and overlap into the partition. We accumulate these while forming
391 /// partitions.
392 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
393};
394
395/// \brief An iterator over partitions of the alloca's slices.
396///
397/// This iterator implements the core algorithm for partitioning the alloca's
398/// slices. It is a forward iterator as we don't support backtracking for
399/// efficiency reasons, and re-use a single storage area to maintain the
400/// current set of split slices.
401///
402/// It is templated on the slice iterator type to use so that it can operate
403/// with either const or non-const slice iterators.
404class AllocaSlices::partition_iterator
405 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
406 Partition> {
407 friend class AllocaSlices;
408
409 /// \brief Most of the state for walking the partitions is held in a class
410 /// with a nice interface for examining them.
411 Partition P;
412
413 /// \brief We need to keep the end of the slices to know when to stop.
414 AllocaSlices::iterator SE;
415
416 /// \brief We also need to keep track of the maximum split end offset seen.
417 /// FIXME: Do we really?
418 uint64_t MaxSplitSliceEndOffset;
419
420 /// \brief Sets the partition to be empty at given iterator, and sets the
421 /// end iterator.
422 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
423 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
424 // If not already at the end, advance our state to form the initial
425 // partition.
426 if (SI != SE)
427 advance();
428 }
429
430 /// \brief Advance the iterator to the next partition.
431 ///
432 /// Requires that the iterator not be at the end of the slices.
433 void advance() {
434 assert((P.SI != SE || !P.SplitTails.empty()) &&
435 "Cannot advance past the end of the slices!");
436
437 // Clear out any split uses which have ended.
438 if (!P.SplitTails.empty()) {
439 if (P.EndOffset >= MaxSplitSliceEndOffset) {
440 // If we've finished all splits, this is easy.
441 P.SplitTails.clear();
442 MaxSplitSliceEndOffset = 0;
443 } else {
444 // Remove the uses which have ended in the prior partition. This
445 // cannot change the max split slice end because we just checked that
446 // the prior partition ended prior to that max.
447 P.SplitTails.erase(
448 std::remove_if(
449 P.SplitTails.begin(), P.SplitTails.end(),
450 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
451 P.SplitTails.end());
452 assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
453 [&](Slice *S) {
454 return S->endOffset() == MaxSplitSliceEndOffset;
455 }) &&
456 "Could not find the current max split slice offset!");
457 assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
458 [&](Slice *S) {
459 return S->endOffset() <= MaxSplitSliceEndOffset;
460 }) &&
461 "Max split slice end offset is not actually the max!");
462 }
463 }
464
465 // If P.SI is already at the end, then we've cleared the split tail and
466 // now have an end iterator.
467 if (P.SI == SE) {
468 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
469 return;
470 }
471
472 // If we had a non-empty partition previously, set up the state for
473 // subsequent partitions.
474 if (P.SI != P.SJ) {
475 // Accumulate all the splittable slices which started in the old
476 // partition into the split list.
477 for (Slice &S : P)
478 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
479 P.SplitTails.push_back(&S);
480 MaxSplitSliceEndOffset =
481 std::max(S.endOffset(), MaxSplitSliceEndOffset);
482 }
483
484 // Start from the end of the previous partition.
485 P.SI = P.SJ;
486
487 // If P.SI is now at the end, we at most have a tail of split slices.
488 if (P.SI == SE) {
489 P.BeginOffset = P.EndOffset;
490 P.EndOffset = MaxSplitSliceEndOffset;
491 return;
492 }
493
494 // If the we have split slices and the next slice is after a gap and is
495 // not splittable immediately form an empty partition for the split
496 // slices up until the next slice begins.
497 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
498 !P.SI->isSplittable()) {
499 P.BeginOffset = P.EndOffset;
500 P.EndOffset = P.SI->beginOffset();
501 return;
502 }
503 }
504
505 // OK, we need to consume new slices. Set the end offset based on the
506 // current slice, and step SJ past it. The beginning offset of the
507 // partition is the beginning offset of the next slice unless we have
508 // pre-existing split slices that are continuing, in which case we begin
509 // at the prior end offset.
510 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
511 P.EndOffset = P.SI->endOffset();
512 ++P.SJ;
513
514 // There are two strategies to form a partition based on whether the
515 // partition starts with an unsplittable slice or a splittable slice.
516 if (!P.SI->isSplittable()) {
517 // When we're forming an unsplittable region, it must always start at
518 // the first slice and will extend through its end.
519 assert(P.BeginOffset == P.SI->beginOffset());
520
521 // Form a partition including all of the overlapping slices with this
522 // unsplittable slice.
523 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
524 if (!P.SJ->isSplittable())
525 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
526 ++P.SJ;
527 }
528
529 // We have a partition across a set of overlapping unsplittable
530 // partitions.
531 return;
532 }
533
534 // If we're starting with a splittable slice, then we need to form
535 // a synthetic partition spanning it and any other overlapping splittable
536 // splices.
537 assert(P.SI->isSplittable() && "Forming a splittable partition!");
538
539 // Collect all of the overlapping splittable slices.
540 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
541 P.SJ->isSplittable()) {
542 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
543 ++P.SJ;
544 }
545
546 // Back upiP.EndOffset if we ended the span early when encountering an
547 // unsplittable slice. This synthesizes the early end offset of
548 // a partition spanning only splittable slices.
549 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
550 assert(!P.SJ->isSplittable());
551 P.EndOffset = P.SJ->beginOffset();
552 }
553 }
554
555public:
556 bool operator==(const partition_iterator &RHS) const {
557 assert(SE == RHS.SE &&
558 "End iterators don't match between compared partition iterators!");
559
560 // The observed positions of partitions is marked by the P.SI iterator and
561 // the emptiness of the split slices. The latter is only relevant when
562 // P.SI == SE, as the end iterator will additionally have an empty split
563 // slices list, but the prior may have the same P.SI and a tail of split
564 // slices.
565 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
566 assert(P.SJ == RHS.P.SJ &&
567 "Same set of slices formed two different sized partitions!");
568 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
569 "Same slice position with differently sized non-empty split "
570 "slice tails!");
571 return true;
572 }
573 return false;
574 }
575
576 partition_iterator &operator++() {
577 advance();
578 return *this;
579 }
580
581 Partition &operator*() { return P; }
582};
583
584/// \brief A forward range over the partitions of the alloca's slices.
585///
586/// This accesses an iterator range over the partitions of the alloca's
587/// slices. It computes these partitions on the fly based on the overlapping
588/// offsets of the slices and the ability to split them. It will visit "empty"
589/// partitions to cover regions of the alloca only accessed via split
590/// slices.
591iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
592 return make_range(partition_iterator(begin(), end()),
593 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000594}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000595
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000596static Value *foldSelectInst(SelectInst &SI) {
597 // If the condition being selected on is a constant or the same value is
598 // being selected between, fold the select. Yes this does (rarely) happen
599 // early on.
600 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000601 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000602 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000603 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000604
Craig Topperf40110f2014-04-25 05:29:35 +0000605 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000606}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607
Jingyue Wuec33fa92014-08-22 22:45:57 +0000608/// \brief A helper that folds a PHI node or a select.
609static Value *foldPHINodeOrSelectInst(Instruction &I) {
610 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
611 // If PN merges together the same value, return that value.
612 return PN->hasConstantValue();
613 }
614 return foldSelectInst(cast<SelectInst>(I));
615}
616
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000617/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000618///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000619/// This class builds a set of alloca slices by recursively visiting the uses
620/// of an alloca and making a slice for each load and store at each offset.
621class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
622 friend class PtrUseVisitor<SliceBuilder>;
623 friend class InstVisitor<SliceBuilder>;
624 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000625
626 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000627 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000628
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000629 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000630 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
631
632 /// \brief Set to de-duplicate dead instructions found in the use walk.
633 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000634
635public:
Chandler Carruth83934062014-10-16 21:11:55 +0000636 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000637 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000638 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000639
640private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000641 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000642 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000643 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000644 }
645
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000646 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000647 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000648 // Completely skip uses which have a zero size or start either before or
649 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000650 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000651 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000652 << " which has zero size or starts outside of the "
653 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000654 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000655 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000656 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000657 }
658
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000659 uint64_t BeginOffset = Offset.getZExtValue();
660 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000661
662 // Clamp the end offset to the end of the allocation. Note that this is
663 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000664 // This may appear superficially to be something we could ignore entirely,
665 // but that is not so! There may be widened loads or PHI-node uses where
666 // some instructions are dead but not others. We can't completely ignore
667 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000668 assert(AllocSize >= BeginOffset); // Established above.
669 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000670 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
671 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000672 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000673 << " use: " << I << "\n");
674 EndOffset = AllocSize;
675 }
676
Chandler Carruth83934062014-10-16 21:11:55 +0000677 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000678 }
679
680 void visitBitCastInst(BitCastInst &BC) {
681 if (BC.use_empty())
682 return markAsDead(BC);
683
684 return Base::visitBitCastInst(BC);
685 }
686
687 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
688 if (GEPI.use_empty())
689 return markAsDead(GEPI);
690
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000691 if (SROAStrictInbounds && GEPI.isInBounds()) {
692 // FIXME: This is a manually un-factored variant of the basic code inside
693 // of GEPs with checking of the inbounds invariant specified in the
694 // langref in a very strict sense. If we ever want to enable
695 // SROAStrictInbounds, this code should be factored cleanly into
696 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
697 // by writing out the code here where we have tho underlying allocation
698 // size readily available.
699 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000700 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000701 for (gep_type_iterator GTI = gep_type_begin(GEPI),
702 GTE = gep_type_end(GEPI);
703 GTI != GTE; ++GTI) {
704 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
705 if (!OpC)
706 break;
707
708 // Handle a struct index, which adds its field offset to the pointer.
709 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
710 unsigned ElementIdx = OpC->getZExtValue();
711 const StructLayout *SL = DL.getStructLayout(STy);
712 GEPOffset +=
713 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
714 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000715 // For array or vector indices, scale the index by the size of the
716 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000717 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
718 GEPOffset += Index * APInt(Offset.getBitWidth(),
719 DL.getTypeAllocSize(GTI.getIndexedType()));
720 }
721
722 // If this index has computed an intermediate pointer which is not
723 // inbounds, then the result of the GEP is a poison value and we can
724 // delete it and all uses.
725 if (GEPOffset.ugt(AllocSize))
726 return markAsDead(GEPI);
727 }
728 }
729
Chandler Carruthf0546402013-07-18 07:15:00 +0000730 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000731 }
732
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000733 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000734 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000735 // We allow splitting of non-volatile loads and stores where the type is an
736 // integer type. These may be used to implement 'memcpy' or other "transfer
737 // of bits" patterns.
738 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000739
740 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000741 }
742
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000743 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000744 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
745 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000746
747 if (!IsOffsetKnown)
748 return PI.setAborted(&LI);
749
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000750 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000751 uint64_t Size = DL.getTypeStoreSize(LI.getType());
752 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000753 }
754
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000755 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000756 Value *ValOp = SI.getValueOperand();
757 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000758 return PI.setEscapedAndAborted(&SI);
759 if (!IsOffsetKnown)
760 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000761
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000762 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000763 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
764
765 // If this memory access can be shown to *statically* extend outside the
766 // bounds of of the allocation, it's behavior is undefined, so simply
767 // ignore it. Note that this is more strict than the generic clamping
768 // behavior of insertUse. We also try to handle cases which might run the
769 // risk of overflow.
770 // FIXME: We should instead consider the pointer to have escaped if this
771 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000772 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000773 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
774 << " which extends past the end of the " << AllocSize
775 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000776 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000777 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000778 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000779 }
780
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000781 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
782 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000783 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000784 }
785
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000786 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000787 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000788 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000789 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000790 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000791 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000792 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000793
794 if (!IsOffsetKnown)
795 return PI.setAborted(&II);
796
Chandler Carruth113dc642014-12-20 02:39:18 +0000797 insertUse(II, Offset, Length ? Length->getLimitedValue()
798 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000799 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000800 }
801
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000802 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000803 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000804 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000805 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000806 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000807
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000808 // Because we can visit these intrinsics twice, also check to see if the
809 // first time marked this instruction as dead. If so, skip it.
810 if (VisitedDeadInsts.count(&II))
811 return;
812
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000813 if (!IsOffsetKnown)
814 return PI.setAborted(&II);
815
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000816 // This side of the transfer is completely out-of-bounds, and so we can
817 // nuke the entire transfer. However, we also need to nuke the other side
818 // if already added to our partitions.
819 // FIXME: Yet another place we really should bypass this when
820 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000821 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000822 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
823 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000824 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000825 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000826 return markAsDead(II);
827 }
828
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000829 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000830 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000831
Chandler Carruthf0546402013-07-18 07:15:00 +0000832 // Check for the special case where the same exact value is used for both
833 // source and dest.
834 if (*U == II.getRawDest() && *U == II.getRawSource()) {
835 // For non-volatile transfers this is a no-op.
836 if (!II.isVolatile())
837 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000838
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000839 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000840 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000841
Chandler Carruthf0546402013-07-18 07:15:00 +0000842 // If we have seen both source and destination for a mem transfer, then
843 // they both point to the same alloca.
844 bool Inserted;
845 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000846 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000847 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000848 unsigned PrevIdx = MTPI->second;
849 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000850 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000851
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000852 // Check if the begin offsets match and this is a non-volatile transfer.
853 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000854 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
855 PrevP.kill();
856 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000857 }
858
859 // Otherwise we have an offset transfer within the same alloca. We can't
860 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000861 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000862 }
863
Chandler Carruthe3899f22013-07-15 17:36:21 +0000864 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000865 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000866
Chandler Carruthf0546402013-07-18 07:15:00 +0000867 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000868 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000869 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000870 }
871
872 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000873 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000874 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000875 void visitIntrinsicInst(IntrinsicInst &II) {
876 if (!IsOffsetKnown)
877 return PI.setAborted(&II);
878
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000879 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
880 II.getIntrinsicID() == Intrinsic::lifetime_end) {
881 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000882 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
883 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000884 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000885 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000886 }
887
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000888 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000889 }
890
891 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
892 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000893 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000894 // are considered unsplittable and the size is the maximum loaded or stored
895 // size.
896 SmallPtrSet<Instruction *, 4> Visited;
897 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
898 Visited.insert(Root);
899 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000900 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000901 // If there are no loads or stores, the access is dead. We mark that as
902 // a size zero access.
903 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000904 do {
905 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000906 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000907
908 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000909 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000910 continue;
911 }
912 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
913 Value *Op = SI->getOperand(0);
914 if (Op == UsedI)
915 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000916 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000917 continue;
918 }
919
920 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
921 if (!GEP->hasAllZeroIndices())
922 return GEP;
923 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
924 !isa<SelectInst>(I)) {
925 return I;
926 }
927
Chandler Carruthcdf47882014-03-09 03:16:01 +0000928 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000929 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000930 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000931 } while (!Uses.empty());
932
Craig Topperf40110f2014-04-25 05:29:35 +0000933 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000934 }
935
Jingyue Wuec33fa92014-08-22 22:45:57 +0000936 void visitPHINodeOrSelectInst(Instruction &I) {
937 assert(isa<PHINode>(I) || isa<SelectInst>(I));
938 if (I.use_empty())
939 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000940
Jingyue Wuec33fa92014-08-22 22:45:57 +0000941 // TODO: We could use SimplifyInstruction here to fold PHINodes and
942 // SelectInsts. However, doing so requires to change the current
943 // dead-operand-tracking mechanism. For instance, suppose neither loading
944 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
945 // trap either. However, if we simply replace %U with undef using the
946 // current dead-operand-tracking mechanism, "load (select undef, undef,
947 // %other)" may trap because the select may return the first operand
948 // "undef".
949 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000950 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000951 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000952 // through the PHI/select as if we had RAUW'ed it.
953 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000954 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000955 // Otherwise the operand to the PHI/select is dead, and we can replace
956 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000957 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000958
959 return;
960 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000961
Chandler Carruthf0546402013-07-18 07:15:00 +0000962 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000963 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000964
Chandler Carruthf0546402013-07-18 07:15:00 +0000965 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000966 uint64_t &Size = PHIOrSelectSizes[&I];
967 if (!Size) {
968 // This is a new PHI/Select, check for an unsafe use of it.
969 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000970 return PI.setAborted(UnsafeI);
971 }
972
973 // For PHI and select operands outside the alloca, we can't nuke the entire
974 // phi or select -- the other side might still be relevant, so we special
975 // case them here and use a separate structure to track the operands
976 // themselves which should be replaced with undef.
977 // FIXME: This should instead be escaped in the event we're instrumenting
978 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000979 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000980 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000981 return;
982 }
983
Jingyue Wuec33fa92014-08-22 22:45:57 +0000984 insertUse(I, Offset, Size);
985 }
986
Chandler Carruth113dc642014-12-20 02:39:18 +0000987 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000988
Chandler Carruth113dc642014-12-20 02:39:18 +0000989 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000990
Chandler Carruthf0546402013-07-18 07:15:00 +0000991 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000992 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000993};
994
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000995AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000996 :
997#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
998 AI(AI),
999#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001000 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001001 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001002 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001003 if (PtrI.isEscaped() || PtrI.isAborted()) {
1004 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001005 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001006 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1007 : PtrI.getAbortingInst();
1008 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001009 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001010 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001011
Benjamin Kramer08e50702013-07-20 08:38:34 +00001012 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
Chandler Carruth68ea4152014-12-18 05:19:47 +00001013 [](const Slice &S) {
1014 return S.isDead();
1015 }),
Benjamin Kramer08e50702013-07-20 08:38:34 +00001016 Slices.end());
1017
Chandler Carruth83cee772014-02-25 03:59:29 +00001018#if __cplusplus >= 201103L && !defined(NDEBUG)
1019 if (SROARandomShuffleSlices) {
1020 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1021 std::shuffle(Slices.begin(), Slices.end(), MT);
1022 }
1023#endif
1024
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001025 // Sort the uses. This arranges for the offsets to be in ascending order,
1026 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001027 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001028}
1029
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001030#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1031
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001032void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1033 StringRef Indent) const {
1034 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001035 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001036 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001037}
1038
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001039void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1040 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001041 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001042 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001043 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001044}
1045
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001046void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1047 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001048 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001049}
1050
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001051void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001052 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001053 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001054 << " A pointer to this alloca escaped by:\n"
1055 << " " << *PointerEscapingInstr << "\n";
1056 return;
1057 }
1058
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001059 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001060 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001061 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001062}
1063
Alp Tokerf929e092014-01-04 22:47:48 +00001064LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1065 print(dbgs(), I);
1066}
1067LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001068
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001069#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1070
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001071/// Walk the range of a partitioning looking for a common type to cover this
1072/// sequence of slices.
1073static Type *findCommonType(AllocaSlices::const_iterator B,
1074 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001075 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001076 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001077 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001078 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001079
1080 // Note that we need to look at *every* alloca slice's Use to ensure we
1081 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001082 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001083 Use *U = I->getUse();
1084 if (isa<IntrinsicInst>(*U->getUser()))
1085 continue;
1086 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1087 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001088
Craig Topperf40110f2014-04-25 05:29:35 +00001089 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001090 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001091 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001092 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001093 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001094 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001095
Chandler Carruth4de31542014-01-21 23:16:05 +00001096 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001097 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001098 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001099 // entity causing the split. Also skip if the type is not a byte width
1100 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001101 if (UserITy->getBitWidth() % 8 != 0 ||
1102 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001103 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001104
Chandler Carruth4de31542014-01-21 23:16:05 +00001105 // Track the largest bitwidth integer type used in this way in case there
1106 // is no common type.
1107 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1108 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001109 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001110
1111 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1112 // depend on types skipped above.
1113 if (!UserTy || (Ty && Ty != UserTy))
1114 TyIsCommon = false; // Give up on anything but an iN type.
1115 else
1116 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001117 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001118
1119 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001120}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001121
Chandler Carruthf0546402013-07-18 07:15:00 +00001122/// PHI instructions that use an alloca and are subsequently loaded can be
1123/// rewritten to load both input pointers in the pred blocks and then PHI the
1124/// results, allowing the load of the alloca to be promoted.
1125/// From this:
1126/// %P2 = phi [i32* %Alloca, i32* %Other]
1127/// %V = load i32* %P2
1128/// to:
1129/// %V1 = load i32* %Alloca -> will be mem2reg'd
1130/// ...
1131/// %V2 = load i32* %Other
1132/// ...
1133/// %V = phi [i32 %V1, i32 %V2]
1134///
1135/// We can do this to a select if its only uses are loads and if the operands
1136/// to the select can be loaded unconditionally.
1137///
1138/// FIXME: This should be hoisted into a generic utility, likely in
1139/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001140static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001141 // For now, we can only do this promotion if the load is in the same block
1142 // as the PHI, and if there are no stores between the phi and load.
1143 // TODO: Allow recursive phi users.
1144 // TODO: Allow stores.
1145 BasicBlock *BB = PN.getParent();
1146 unsigned MaxAlign = 0;
1147 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001148 for (User *U : PN.users()) {
1149 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001150 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001151 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001152
Chandler Carruthf0546402013-07-18 07:15:00 +00001153 // For now we only allow loads in the same block as the PHI. This is
1154 // a common case that happens when instcombine merges two loads through
1155 // a PHI.
1156 if (LI->getParent() != BB)
1157 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001158
Chandler Carruthf0546402013-07-18 07:15:00 +00001159 // Ensure that there are no instructions between the PHI and the load that
1160 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001161 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001162 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001163 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001164
Chandler Carruthf0546402013-07-18 07:15:00 +00001165 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1166 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001167 }
1168
Chandler Carruthf0546402013-07-18 07:15:00 +00001169 if (!HaveLoad)
1170 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001171
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001172 const DataLayout &DL = PN.getModule()->getDataLayout();
1173
Chandler Carruthf0546402013-07-18 07:15:00 +00001174 // We can only transform this if it is safe to push the loads into the
1175 // predecessor blocks. The only thing to watch out for is that we can't put
1176 // a possibly trapping load in the predecessor if it is a critical edge.
1177 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1178 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1179 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001180
Chandler Carruthf0546402013-07-18 07:15:00 +00001181 // If the value is produced by the terminator of the predecessor (an
1182 // invoke) or it has side-effects, there is no valid place to put a load
1183 // in the predecessor.
1184 if (TI == InVal || TI->mayHaveSideEffects())
1185 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001186
Chandler Carruthf0546402013-07-18 07:15:00 +00001187 // If the predecessor has a single successor, then the edge isn't
1188 // critical.
1189 if (TI->getNumSuccessors() == 1)
1190 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001191
Chandler Carruthf0546402013-07-18 07:15:00 +00001192 // If this pointer is always safe to load, or if we can prove that there
1193 // is already a load in the block, then we can move the load to the pred
1194 // block.
Artur Pilipenkof84dc062016-01-17 12:35:29 +00001195 if (isSafeToLoadUnconditionally(InVal, MaxAlign, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001196 continue;
1197
1198 return false;
1199 }
1200
1201 return true;
1202}
1203
1204static void speculatePHINodeLoads(PHINode &PN) {
1205 DEBUG(dbgs() << " original: " << PN << "\n");
1206
1207 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1208 IRBuilderTy PHIBuilder(&PN);
1209 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1210 PN.getName() + ".sroa.speculated");
1211
Hal Finkelcc39b672014-07-24 12:16:19 +00001212 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001213 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001214 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001215
1216 AAMDNodes AATags;
1217 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001218 unsigned Align = SomeLoad->getAlignment();
1219
1220 // Rewrite all loads of the PN to use the new PHI.
1221 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001222 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001223 LI->replaceAllUsesWith(NewPN);
1224 LI->eraseFromParent();
1225 }
1226
1227 // Inject loads into all of the pred blocks.
1228 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1229 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1230 TerminatorInst *TI = Pred->getTerminator();
1231 Value *InVal = PN.getIncomingValue(Idx);
1232 IRBuilderTy PredBuilder(TI);
1233
1234 LoadInst *Load = PredBuilder.CreateLoad(
1235 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1236 ++NumLoadsSpeculated;
1237 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001238 if (AATags)
1239 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001240 NewPN->addIncoming(Load, Pred);
1241 }
1242
1243 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1244 PN.eraseFromParent();
1245}
1246
1247/// Select instructions that use an alloca and are subsequently loaded can be
1248/// rewritten to load both input pointers and then select between the result,
1249/// allowing the load of the alloca to be promoted.
1250/// From this:
1251/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1252/// %V = load i32* %P2
1253/// to:
1254/// %V1 = load i32* %Alloca -> will be mem2reg'd
1255/// %V2 = load i32* %Other
1256/// %V = select i1 %cond, i32 %V1, i32 %V2
1257///
1258/// We can do this to a select if its only uses are loads and if the operand
1259/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001260static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001261 Value *TValue = SI.getTrueValue();
1262 Value *FValue = SI.getFalseValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001263 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001264
Chandler Carruthcdf47882014-03-09 03:16:01 +00001265 for (User *U : SI.users()) {
1266 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001267 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001268 return false;
1269
1270 // Both operands to the select need to be dereferencable, either
1271 // absolutely (e.g. allocas) or at this point because we can see other
1272 // accesses to it.
Artur Pilipenkof84dc062016-01-17 12:35:29 +00001273 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001274 return false;
Artur Pilipenkof84dc062016-01-17 12:35:29 +00001275 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001276 return false;
1277 }
1278
1279 return true;
1280}
1281
1282static void speculateSelectInstLoads(SelectInst &SI) {
1283 DEBUG(dbgs() << " original: " << SI << "\n");
1284
1285 IRBuilderTy IRB(&SI);
1286 Value *TV = SI.getTrueValue();
1287 Value *FV = SI.getFalseValue();
1288 // Replace the loads of the select with a select of two loads.
1289 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001290 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001291 assert(LI->isSimple() && "We only speculate simple loads");
1292
1293 IRB.SetInsertPoint(LI);
1294 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001295 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001296 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001297 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001298 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001299
Hal Finkelcc39b672014-07-24 12:16:19 +00001300 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001301 TL->setAlignment(LI->getAlignment());
1302 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001303
1304 AAMDNodes Tags;
1305 LI->getAAMetadata(Tags);
1306 if (Tags) {
1307 TL->setAAMetadata(Tags);
1308 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001309 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001310
1311 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1312 LI->getName() + ".sroa.speculated");
1313
1314 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1315 LI->replaceAllUsesWith(V);
1316 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001317 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001318 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001319}
1320
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001321/// \brief Build a GEP out of a base pointer and indices.
1322///
1323/// This will return the BasePtr if that is valid, or build a new GEP
1324/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001325static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001326 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001327 if (Indices.empty())
1328 return BasePtr;
1329
1330 // A single zero index is a no-op, so check for this and avoid building a GEP
1331 // in that case.
1332 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1333 return BasePtr;
1334
David Blaikieaa41cd52015-04-03 21:33:42 +00001335 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1336 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001337}
1338
1339/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1340/// TargetTy without changing the offset of the pointer.
1341///
1342/// This routine assumes we've already established a properly offset GEP with
1343/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1344/// zero-indices down through type layers until we find one the same as
1345/// TargetTy. If we can't find one with the same type, we at least try to use
1346/// one with the same size. If none of that works, we just produce the GEP as
1347/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001348static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001349 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001350 SmallVectorImpl<Value *> &Indices,
1351 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001352 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001353 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001354
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001355 // Pointer size to use for the indices.
1356 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1357
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001358 // See if we can descend into a struct and locate a field with the correct
1359 // type.
1360 unsigned NumLayers = 0;
1361 Type *ElementTy = Ty;
1362 do {
1363 if (ElementTy->isPointerTy())
1364 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001365
1366 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1367 ElementTy = ArrayTy->getElementType();
1368 Indices.push_back(IRB.getIntN(PtrSize, 0));
1369 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1370 ElementTy = VectorTy->getElementType();
1371 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001372 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001373 if (STy->element_begin() == STy->element_end())
1374 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001375 ElementTy = *STy->element_begin();
1376 Indices.push_back(IRB.getInt32(0));
1377 } else {
1378 break;
1379 }
1380 ++NumLayers;
1381 } while (ElementTy != TargetTy);
1382 if (ElementTy != TargetTy)
1383 Indices.erase(Indices.end() - NumLayers, Indices.end());
1384
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001385 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001386}
1387
1388/// \brief Recursively compute indices for a natural GEP.
1389///
1390/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1391/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001392static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001393 Value *Ptr, Type *Ty, APInt &Offset,
1394 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001395 SmallVectorImpl<Value *> &Indices,
1396 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001398 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1399 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400
1401 // We can't recurse through pointer types.
1402 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001403 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001404
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001405 // We try to analyze GEPs over vectors here, but note that these GEPs are
1406 // extremely poorly defined currently. The long-term goal is to remove GEPing
1407 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001408 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001409 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001410 if (ElementSizeInBits % 8 != 0) {
1411 // GEPs over non-multiple of 8 size vector elements are invalid.
1412 return nullptr;
1413 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001415 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001416 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001417 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001418 Offset -= NumSkippedElements * ElementSize;
1419 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001420 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001421 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001422 }
1423
1424 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1425 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001426 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001427 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001428 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001429 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001430
1431 Offset -= NumSkippedElements * ElementSize;
1432 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001433 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001434 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001435 }
1436
1437 StructType *STy = dyn_cast<StructType>(Ty);
1438 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001439 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001440
Chandler Carruth90a735d2013-07-19 07:21:28 +00001441 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001442 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001443 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001444 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001445 unsigned Index = SL->getElementContainingOffset(StructOffset);
1446 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1447 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001448 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001449 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001450
1451 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001452 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001453 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001454}
1455
1456/// \brief Get a natural GEP from a base pointer to a particular offset and
1457/// resulting in a particular type.
1458///
1459/// The goal is to produce a "natural" looking GEP that works with the existing
1460/// composite types to arrive at the appropriate offset and element type for
1461/// a pointer. TargetTy is the element type the returned GEP should point-to if
1462/// possible. We recurse by decreasing Offset, adding the appropriate index to
1463/// Indices, and setting Ty to the result subtype.
1464///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001465/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001466static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001467 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001468 SmallVectorImpl<Value *> &Indices,
1469 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001470 PointerType *Ty = cast<PointerType>(Ptr->getType());
1471
1472 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1473 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001474 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001475 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001476
1477 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001478 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001479 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001480 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001481 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001482 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001483 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001484
1485 Offset -= NumSkippedElements * ElementSize;
1486 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001487 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001488 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001489}
1490
1491/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1492/// resulting pointer has PointerTy.
1493///
1494/// This tries very hard to compute a "natural" GEP which arrives at the offset
1495/// and produces the pointer type desired. Where it cannot, it will try to use
1496/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1497/// fails, it will try to use an existing i8* and GEP to the byte offset and
1498/// bitcast to the type.
1499///
1500/// The strategy for finding the more natural GEPs is to peel off layers of the
1501/// pointer, walking back through bit casts and GEPs, searching for a base
1502/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001503/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001504/// a single GEP as possible, thus making each GEP more independent of the
1505/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001506static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001507 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508 // Even though we don't look through PHI nodes, we could be called on an
1509 // instruction in an unreachable block, which may be on a cycle.
1510 SmallPtrSet<Value *, 4> Visited;
1511 Visited.insert(Ptr);
1512 SmallVector<Value *, 4> Indices;
1513
1514 // We may end up computing an offset pointer that has the wrong type. If we
1515 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001516 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001517 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001518 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001519
1520 // Remember any i8 pointer we come across to re-use if we need to do a raw
1521 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001522 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001523 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1524
1525 Type *TargetTy = PointerTy->getPointerElementType();
1526
1527 do {
1528 // First fold any existing GEPs into the offset.
1529 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1530 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001531 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001532 break;
1533 Offset += GEPOffset;
1534 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001535 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001536 break;
1537 }
1538
1539 // See if we can perform a natural GEP here.
1540 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001541 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001542 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001543 // If we have a new natural pointer at the offset, clear out any old
1544 // offset pointer we computed. Unless it is the base pointer or
1545 // a non-instruction, we built a GEP we don't need. Zap it.
1546 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1547 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1548 assert(I->use_empty() && "Built a GEP with uses some how!");
1549 I->eraseFromParent();
1550 }
1551 OffsetPtr = P;
1552 OffsetBasePtr = Ptr;
1553 // If we also found a pointer of the right type, we're done.
1554 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001555 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001556 }
1557
1558 // Stash this pointer if we've found an i8*.
1559 if (Ptr->getType()->isIntegerTy(8)) {
1560 Int8Ptr = Ptr;
1561 Int8PtrOffset = Offset;
1562 }
1563
1564 // Peel off a layer of the pointer and update the offset appropriately.
1565 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1566 Ptr = cast<Operator>(Ptr)->getOperand(0);
1567 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1568 if (GA->mayBeOverridden())
1569 break;
1570 Ptr = GA->getAliasee();
1571 } else {
1572 break;
1573 }
1574 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001575 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001576
1577 if (!OffsetPtr) {
1578 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001579 Int8Ptr = IRB.CreateBitCast(
1580 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1581 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001582 Int8PtrOffset = Offset;
1583 }
1584
Chandler Carruth113dc642014-12-20 02:39:18 +00001585 OffsetPtr = Int8PtrOffset == 0
1586 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001587 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1588 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001589 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001590 }
1591 Ptr = OffsetPtr;
1592
1593 // On the off chance we were targeting i8*, guard the bitcast here.
1594 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001595 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001596
1597 return Ptr;
1598}
1599
Chandler Carruth0715cba2015-01-01 11:54:38 +00001600/// \brief Compute the adjusted alignment for a load or store from an offset.
1601static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1602 const DataLayout &DL) {
1603 unsigned Alignment;
1604 Type *Ty;
1605 if (auto *LI = dyn_cast<LoadInst>(I)) {
1606 Alignment = LI->getAlignment();
1607 Ty = LI->getType();
1608 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1609 Alignment = SI->getAlignment();
1610 Ty = SI->getValueOperand()->getType();
1611 } else {
1612 llvm_unreachable("Only loads and stores are allowed!");
1613 }
1614
1615 if (!Alignment)
1616 Alignment = DL.getABITypeAlignment(Ty);
1617
1618 return MinAlign(Alignment, Offset);
1619}
1620
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001621/// \brief Test whether we can convert a value from the old to the new type.
1622///
1623/// This predicate should be used to guard calls to convertValue in order to
1624/// ensure that we only try to convert viable values. The strategy is that we
1625/// will peel off single element struct and array wrappings to get to an
1626/// underlying value, and convert that value.
1627static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1628 if (OldTy == NewTy)
1629 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001630
1631 // For integer types, we can't handle any bit-width differences. This would
1632 // break both vector conversions with extension and introduce endianness
1633 // issues when in conjunction with loads and stores.
1634 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1635 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1636 cast<IntegerType>(NewTy)->getBitWidth() &&
1637 "We can't have the same bitwidth for different int types");
1638 return false;
1639 }
1640
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001641 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1642 return false;
1643 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1644 return false;
1645
Benjamin Kramer56262592013-09-22 11:24:58 +00001646 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001647 // of pointers and integers.
1648 OldTy = OldTy->getScalarType();
1649 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001650 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1651 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1652 return true;
1653 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1654 return true;
1655 return false;
1656 }
1657
1658 return true;
1659}
1660
1661/// \brief Generic routine to convert an SSA value to a value of a different
1662/// type.
1663///
1664/// This will try various different casting techniques, such as bitcasts,
1665/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1666/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001667static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001668 Type *NewTy) {
1669 Type *OldTy = V->getType();
1670 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1671
1672 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001673 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001674
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001675 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1676 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001677
Benjamin Kramer90901a32013-09-21 20:36:04 +00001678 // See if we need inttoptr for this type pair. A cast involving both scalars
1679 // and vectors requires and additional bitcast.
1680 if (OldTy->getScalarType()->isIntegerTy() &&
1681 NewTy->getScalarType()->isPointerTy()) {
1682 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1683 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1684 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1685 NewTy);
1686
1687 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1688 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1689 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1690 NewTy);
1691
1692 return IRB.CreateIntToPtr(V, NewTy);
1693 }
1694
1695 // See if we need ptrtoint for this type pair. A cast involving both scalars
1696 // and vectors requires and additional bitcast.
1697 if (OldTy->getScalarType()->isPointerTy() &&
1698 NewTy->getScalarType()->isIntegerTy()) {
1699 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1700 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1701 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1702 NewTy);
1703
1704 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1705 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1706 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1707 NewTy);
1708
1709 return IRB.CreatePtrToInt(V, NewTy);
1710 }
1711
1712 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001713}
1714
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001715/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001716///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001717/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001718/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001719static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1720 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001721 uint64_t ElementSize,
1722 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001723 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001724 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001725 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001726 uint64_t BeginIndex = BeginOffset / ElementSize;
1727 if (BeginIndex * ElementSize != BeginOffset ||
1728 BeginIndex >= Ty->getNumElements())
1729 return false;
1730 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001731 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001732 uint64_t EndIndex = EndOffset / ElementSize;
1733 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1734 return false;
1735
1736 assert(EndIndex > BeginIndex && "Empty vector!");
1737 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001738 Type *SliceTy = (NumElements == 1)
1739 ? Ty->getElementType()
1740 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001741
1742 Type *SplitIntTy =
1743 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1744
Chandler Carruthc659df92014-10-16 20:24:07 +00001745 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001746
1747 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1748 if (MI->isVolatile())
1749 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001750 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001751 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001752 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1753 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1754 II->getIntrinsicID() != Intrinsic::lifetime_end)
1755 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001756 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1757 // Disable vector promotion when there are loads or stores of an FCA.
1758 return false;
1759 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1760 if (LI->isVolatile())
1761 return false;
1762 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001763 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001764 assert(LTy->isIntegerTy());
1765 LTy = SplitIntTy;
1766 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001767 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001768 return false;
1769 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1770 if (SI->isVolatile())
1771 return false;
1772 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001773 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001774 assert(STy->isIntegerTy());
1775 STy = SplitIntTy;
1776 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001777 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001778 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001779 } else {
1780 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001781 }
1782
1783 return true;
1784}
1785
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001786/// \brief Test whether the given alloca partitioning and range of slices can be
1787/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001788///
1789/// This is a quick test to check whether we can rewrite a particular alloca
1790/// partition (and its newly formed alloca) into a vector alloca with only
1791/// whole-vector loads and stores such that it could be promoted to a vector
1792/// SSA value. We only can ensure this for a limited set of operations, and we
1793/// don't want to do the rewrites unless we are confident that the result will
1794/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001795static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001796 // Collect the candidate types for vector-based promotion. Also track whether
1797 // we have different element types.
1798 SmallVector<VectorType *, 4> CandidateTys;
1799 Type *CommonEltTy = nullptr;
1800 bool HaveCommonEltTy = true;
1801 auto CheckCandidateType = [&](Type *Ty) {
1802 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1803 CandidateTys.push_back(VTy);
1804 if (!CommonEltTy)
1805 CommonEltTy = VTy->getElementType();
1806 else if (CommonEltTy != VTy->getElementType())
1807 HaveCommonEltTy = false;
1808 }
1809 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001810 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001811 for (const Slice &S : P)
1812 if (S.beginOffset() == P.beginOffset() &&
1813 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001814 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1815 CheckCandidateType(LI->getType());
1816 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1817 CheckCandidateType(SI->getValueOperand()->getType());
1818 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001819
Chandler Carruth2dc96822014-10-18 00:44:02 +00001820 // If we didn't find a vector type, nothing to do here.
1821 if (CandidateTys.empty())
1822 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001823
Chandler Carruth2dc96822014-10-18 00:44:02 +00001824 // Remove non-integer vector types if we had multiple common element types.
1825 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1826 // do that until all the backends are known to produce good code for all
1827 // integer vector types.
1828 if (!HaveCommonEltTy) {
1829 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1830 [](VectorType *VTy) {
1831 return !VTy->getElementType()->isIntegerTy();
1832 }),
1833 CandidateTys.end());
1834
1835 // If there were no integer vector types, give up.
1836 if (CandidateTys.empty())
1837 return nullptr;
1838
1839 // Rank the remaining candidate vector types. This is easy because we know
1840 // they're all integer vectors. We sort by ascending number of elements.
1841 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1842 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1843 "Cannot have vector types of different sizes!");
1844 assert(RHSTy->getElementType()->isIntegerTy() &&
1845 "All non-integer types eliminated!");
1846 assert(LHSTy->getElementType()->isIntegerTy() &&
1847 "All non-integer types eliminated!");
1848 return RHSTy->getNumElements() < LHSTy->getNumElements();
1849 };
1850 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1851 CandidateTys.erase(
1852 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1853 CandidateTys.end());
1854 } else {
1855// The only way to have the same element type in every vector type is to
1856// have the same vector type. Check that and remove all but one.
1857#ifndef NDEBUG
1858 for (VectorType *VTy : CandidateTys) {
1859 assert(VTy->getElementType() == CommonEltTy &&
1860 "Unaccounted for element type!");
1861 assert(VTy == CandidateTys[0] &&
1862 "Different vector types with the same element type!");
1863 }
1864#endif
1865 CandidateTys.resize(1);
1866 }
1867
1868 // Try each vector type, and return the one which works.
1869 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1870 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1871
1872 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1873 // that aren't byte sized.
1874 if (ElementSize % 8)
1875 return false;
1876 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1877 "vector size not a multiple of element size?");
1878 ElementSize /= 8;
1879
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001880 for (const Slice &S : P)
1881 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001882 return false;
1883
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001884 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001885 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001886 return false;
1887
1888 return true;
1889 };
1890 for (VectorType *VTy : CandidateTys)
1891 if (CheckVectorTypeForPromotion(VTy))
1892 return VTy;
1893
1894 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001895}
1896
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001897/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001898///
1899/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001900/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001901static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001902 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001903 Type *AllocaTy,
1904 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001905 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001906 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1907
Chandler Carruthc659df92014-10-16 20:24:07 +00001908 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1909 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001910
1911 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001912 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001913 if (RelEnd > Size)
1914 return false;
1915
Chandler Carruthc659df92014-10-16 20:24:07 +00001916 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001917
1918 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1919 if (LI->isVolatile())
1920 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001921 // We can't handle loads that extend past the allocated memory.
1922 if (DL.getTypeStoreSize(LI->getType()) > Size)
1923 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001924 // Note that we don't count vector loads or stores as whole-alloca
1925 // operations which enable integer widening because we would prefer to use
1926 // vector widening instead.
1927 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001928 WholeAllocaOp = true;
1929 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001930 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001931 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001932 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001933 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001934 // Non-integer loads need to be convertible from the alloca type so that
1935 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001936 return false;
1937 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001938 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1939 Type *ValueTy = SI->getValueOperand()->getType();
1940 if (SI->isVolatile())
1941 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001942 // We can't handle stores that extend past the allocated memory.
1943 if (DL.getTypeStoreSize(ValueTy) > Size)
1944 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001945 // Note that we don't count vector loads or stores as whole-alloca
1946 // operations which enable integer widening because we would prefer to use
1947 // vector widening instead.
1948 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001949 WholeAllocaOp = true;
1950 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001951 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001952 return false;
1953 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001954 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001955 // Non-integer stores need to be convertible to the alloca type so that
1956 // they are promotable.
1957 return false;
1958 }
1959 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1960 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1961 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001962 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001963 return false; // Skip any unsplittable intrinsics.
1964 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1965 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1966 II->getIntrinsicID() != Intrinsic::lifetime_end)
1967 return false;
1968 } else {
1969 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001970 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001971
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001972 return true;
1973}
1974
Chandler Carruth435c4e02012-10-15 08:40:30 +00001975/// \brief Test whether the given alloca partition's integer operations can be
1976/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001977///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001978/// This is a quick test to check whether we can rewrite the integer loads and
1979/// stores to a particular alloca into wider loads and stores and be able to
1980/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001981static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001982 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001983 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001984 // Don't create integer types larger than the maximum bitwidth.
1985 if (SizeInBits > IntegerType::MAX_INT_BITS)
1986 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001987
1988 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001989 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001990 return false;
1991
Chandler Carruth58d05562012-10-25 04:37:07 +00001992 // We need to ensure that an integer type with the appropriate bitwidth can
1993 // be converted to the alloca type, whatever that is. We don't want to force
1994 // the alloca itself to have an integer type if there is a more suitable one.
1995 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001996 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1997 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001998 return false;
1999
Chandler Carruthf0546402013-07-18 07:15:00 +00002000 // While examining uses, we ensure that the alloca has a covering load or
2001 // store. We don't want to widen the integer operations only to fail to
2002 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002003 // later). However, if there are only splittable uses, go ahead and assume
2004 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002005 // FIXME: We shouldn't consider split slices that happen to start in the
2006 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002007 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002008 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002009
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002010 for (const Slice &S : P)
2011 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2012 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002013 return false;
2014
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002015 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002016 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2017 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002018 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002019
Chandler Carruth92924fd2012-09-24 00:34:20 +00002020 return WholeAllocaOp;
2021}
2022
Chandler Carruthd177f862013-03-20 07:30:36 +00002023static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002024 IntegerType *Ty, uint64_t Offset,
2025 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002026 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002027 IntegerType *IntTy = cast<IntegerType>(V->getType());
2028 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2029 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002030 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002031 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002032 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002033 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002034 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002035 DEBUG(dbgs() << " shifted: " << *V << "\n");
2036 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002037 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2038 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002039 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002040 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002041 DEBUG(dbgs() << " trunced: " << *V << "\n");
2042 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002043 return V;
2044}
2045
Chandler Carruthd177f862013-03-20 07:30:36 +00002046static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002047 Value *V, uint64_t Offset, const Twine &Name) {
2048 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2049 IntegerType *Ty = cast<IntegerType>(V->getType());
2050 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2051 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002052 DEBUG(dbgs() << " start: " << *V << "\n");
2053 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002054 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002055 DEBUG(dbgs() << " extended: " << *V << "\n");
2056 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002057 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2058 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002059 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002060 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002061 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002062 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002063 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002064 DEBUG(dbgs() << " shifted: " << *V << "\n");
2065 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002066
2067 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2068 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2069 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002070 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002071 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002072 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002073 }
2074 return V;
2075}
2076
Chandler Carruth113dc642014-12-20 02:39:18 +00002077static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2078 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002079 VectorType *VecTy = cast<VectorType>(V->getType());
2080 unsigned NumElements = EndIndex - BeginIndex;
2081 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2082
2083 if (NumElements == VecTy->getNumElements())
2084 return V;
2085
2086 if (NumElements == 1) {
2087 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2088 Name + ".extract");
2089 DEBUG(dbgs() << " extract: " << *V << "\n");
2090 return V;
2091 }
2092
Chandler Carruth113dc642014-12-20 02:39:18 +00002093 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002094 Mask.reserve(NumElements);
2095 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2096 Mask.push_back(IRB.getInt32(i));
2097 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002098 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002099 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2100 return V;
2101}
2102
Chandler Carruthd177f862013-03-20 07:30:36 +00002103static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002104 unsigned BeginIndex, const Twine &Name) {
2105 VectorType *VecTy = cast<VectorType>(Old->getType());
2106 assert(VecTy && "Can only insert a vector into a vector");
2107
2108 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2109 if (!Ty) {
2110 // Single element to insert.
2111 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2112 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002113 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002114 return V;
2115 }
2116
2117 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2118 "Too many elements!");
2119 if (Ty->getNumElements() == VecTy->getNumElements()) {
2120 assert(V->getType() == VecTy && "Vector type mismatch");
2121 return V;
2122 }
2123 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2124
2125 // When inserting a smaller vector into the larger to store, we first
2126 // use a shuffle vector to widen it with undef elements, and then
2127 // a second shuffle vector to select between the loaded vector and the
2128 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002129 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002130 Mask.reserve(VecTy->getNumElements());
2131 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2132 if (i >= BeginIndex && i < EndIndex)
2133 Mask.push_back(IRB.getInt32(i - BeginIndex));
2134 else
2135 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2136 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002137 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002138 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002139
2140 Mask.clear();
2141 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002142 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2143
2144 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2145
2146 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002147 return V;
2148}
2149
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002150/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2151/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002152///
2153/// Also implements the rewriting to vector-based accesses when the partition
2154/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2155/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002156class llvm::sroa::AllocaSliceRewriter
2157 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002158 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002159 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2160 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002161
Chandler Carruth90a735d2013-07-19 07:21:28 +00002162 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002163 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002164 SROA &Pass;
2165 AllocaInst &OldAI, &NewAI;
2166 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002167 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002168
Chandler Carruth2dc96822014-10-18 00:44:02 +00002169 // This is a convenience and flag variable that will be null unless the new
2170 // alloca's integer operations should be widened to this integer type due to
2171 // passing isIntegerWideningViable above. If it is non-null, the desired
2172 // integer type will be stored here for easy access during rewriting.
2173 IntegerType *IntTy;
2174
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002175 // If we are rewriting an alloca partition which can be written as pure
2176 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002177 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002178 // - The new alloca is exactly the size of the vector type here.
2179 // - The accesses all either map to the entire vector or to a single
2180 // element.
2181 // - The set of accessing instructions is only one of those handled above
2182 // in isVectorPromotionViable. Generally these are the same access kinds
2183 // which are promotable via mem2reg.
2184 VectorType *VecTy;
2185 Type *ElementTy;
2186 uint64_t ElementSize;
2187
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002188 // The original offset of the slice currently being rewritten relative to
2189 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002190 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002191 // The new offsets of the slice currently being rewritten relative to the
2192 // original alloca.
2193 uint64_t NewBeginOffset, NewEndOffset;
2194
2195 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002196 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002197 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002198 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002199 Instruction *OldPtr;
2200
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002201 // Track post-rewrite users which are PHI nodes and Selects.
2202 SmallPtrSetImpl<PHINode *> &PHIUsers;
2203 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002204
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002205 // Utility IR builder, whose name prefix is setup for each visited use, and
2206 // the insertion point is set to point to the user.
2207 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002208
2209public:
Chandler Carruth83934062014-10-16 21:11:55 +00002210 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002211 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002212 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002213 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2214 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002215 SmallPtrSetImpl<PHINode *> &PHIUsers,
2216 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002217 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002218 NewAllocaBeginOffset(NewAllocaBeginOffset),
2219 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002220 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002221 IntTy(IsIntegerPromotable
2222 ? Type::getIntNTy(
2223 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002224 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002225 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002226 VecTy(PromotableVecTy),
2227 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2228 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002229 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002230 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002231 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002232 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002233 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002234 "Only multiple-of-8 sized vector elements are viable");
2235 ++NumVectorized;
2236 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002237 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002238 }
2239
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002240 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002241 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002242 BeginOffset = I->beginOffset();
2243 EndOffset = I->endOffset();
2244 IsSplittable = I->isSplittable();
2245 IsSplit =
2246 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002247 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2248 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth0715cba2015-01-01 11:54:38 +00002249 DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002250
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002251 // Compute the intersecting offset range.
2252 assert(BeginOffset < NewAllocaEndOffset);
2253 assert(EndOffset > NewAllocaBeginOffset);
2254 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2255 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2256
2257 SliceSize = NewEndOffset - NewBeginOffset;
2258
Chandler Carruthf0546402013-07-18 07:15:00 +00002259 OldUse = I->getUse();
2260 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002261
Chandler Carruthf0546402013-07-18 07:15:00 +00002262 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2263 IRB.SetInsertPoint(OldUserI);
2264 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2265 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2266
2267 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2268 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002269 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270 return CanSROA;
2271 }
2272
2273private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002274 // Make sure the other visit overloads are visible.
2275 using Base::visit;
2276
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002277 // Every instruction which can end up as a user must have a rewrite rule.
2278 bool visitInstruction(Instruction &I) {
2279 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2280 llvm_unreachable("No rewrite rule for this instruction!");
2281 }
2282
Chandler Carruth47954c82014-02-26 05:12:43 +00002283 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2284 // Note that the offset computation can use BeginOffset or NewBeginOffset
2285 // interchangeably for unsplit slices.
2286 assert(IsSplit || BeginOffset == NewBeginOffset);
2287 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2288
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002289#ifndef NDEBUG
2290 StringRef OldName = OldPtr->getName();
2291 // Skip through the last '.sroa.' component of the name.
2292 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2293 if (LastSROAPrefix != StringRef::npos) {
2294 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2295 // Look for an SROA slice index.
2296 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2297 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2298 // Strip the index and look for the offset.
2299 OldName = OldName.substr(IndexEnd + 1);
2300 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2301 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2302 // Strip the offset.
2303 OldName = OldName.substr(OffsetEnd + 1);
2304 }
2305 }
2306 // Strip any SROA suffixes as well.
2307 OldName = OldName.substr(0, OldName.find(".sroa_"));
2308#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002309
2310 return getAdjustedPtr(IRB, DL, &NewAI,
2311 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002312#ifndef NDEBUG
2313 Twine(OldName) + "."
2314#else
2315 Twine()
2316#endif
2317 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002318 }
2319
Chandler Carruth113dc642014-12-20 02:39:18 +00002320 /// \brief Compute suitable alignment to access this slice of the *new*
2321 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002322 ///
2323 /// You can optionally pass a type to this routine and if that type's ABI
2324 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002325 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002326 unsigned NewAIAlign = NewAI.getAlignment();
2327 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002328 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002329 unsigned Align =
2330 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002331 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002332 }
2333
Chandler Carruth845b73c2012-11-21 08:16:30 +00002334 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002335 assert(VecTy && "Can only call getIndex when rewriting a vector");
2336 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2337 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2338 uint32_t Index = RelOffset / ElementSize;
2339 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002340 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002341 }
2342
2343 void deleteIfTriviallyDead(Value *V) {
2344 Instruction *I = cast<Instruction>(V);
2345 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002346 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002347 }
2348
Chandler Carruthea27cf02014-02-26 04:25:04 +00002349 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002350 unsigned BeginIndex = getIndex(NewBeginOffset);
2351 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002352 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002353
Chandler Carruth113dc642014-12-20 02:39:18 +00002354 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002355 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002356 }
2357
Chandler Carruthea27cf02014-02-26 04:25:04 +00002358 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002359 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002360 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002361 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002362 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002363 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2364 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002365 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2366 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2367 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2368 }
2369 // It is possible that the extracted type is not the load type. This
2370 // happens if there is a load past the end of the alloca, and as
2371 // a consequence the slice is narrower but still a candidate for integer
2372 // lowering. To handle this case, we just zero extend the extracted
2373 // integer.
2374 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2375 "Can only handle an extract for an overly wide load");
2376 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2377 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002378 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002379 }
2380
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002381 bool visitLoadInst(LoadInst &LI) {
2382 DEBUG(dbgs() << " original: " << LI << "\n");
2383 Value *OldOp = LI.getOperand(0);
2384 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002385
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002386 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002387 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002388 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002389 bool IsPtrAdjusted = false;
2390 Value *V;
2391 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002392 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002393 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002394 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002395 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002396 NewEndOffset == NewAllocaEndOffset &&
2397 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2398 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2399 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002400 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2401 LI.isVolatile(), LI.getName());
2402 if (LI.isVolatile())
2403 NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
David Majnemer62690b12015-07-14 06:19:58 +00002404 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002405
2406 // If this is an integer load past the end of the slice (which means the
2407 // bytes outside the slice are undef or this load is dead) just forcibly
2408 // fix the integer size with correct handling of endianness.
2409 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2410 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2411 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2412 V = IRB.CreateZExt(V, TITy, "load.ext");
2413 if (DL.isBigEndian())
2414 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2415 "endian_shift");
2416 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002417 } else {
2418 Type *LTy = TargetTy->getPointerTo();
David Majnemer62690b12015-07-14 06:19:58 +00002419 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2420 getSliceAlign(TargetTy),
2421 LI.isVolatile(), LI.getName());
2422 if (LI.isVolatile())
2423 NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2424
2425 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002426 IsPtrAdjusted = true;
2427 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002428 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002429
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002430 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002431 assert(!LI.isVolatile());
2432 assert(LI.getType()->isIntegerTy() &&
2433 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002434 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002435 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002436 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002437 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002438 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002439 // Move the insertion point just past the load so that we can refer to it.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002440 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002441 // Create a placeholder value with the same type as LI to use as the
2442 // basis for the new value. This allows us to replace the uses of LI with
2443 // the computed value, and then replace the placeholder with LI, leaving
2444 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002445 Value *Placeholder =
2446 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002447 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2448 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002449 LI.replaceAllUsesWith(V);
2450 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002451 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002452 } else {
2453 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002454 }
2455
Chandler Carruth18db7952012-11-20 01:12:50 +00002456 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002457 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002458 DEBUG(dbgs() << " to: " << *V << "\n");
2459 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002460 }
2461
Chandler Carruthea27cf02014-02-26 04:25:04 +00002462 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002463 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002464 unsigned BeginIndex = getIndex(NewBeginOffset);
2465 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002466 assert(EndIndex > BeginIndex && "Empty vector!");
2467 unsigned NumElements = EndIndex - BeginIndex;
2468 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002469 Type *SliceTy = (NumElements == 1)
2470 ? ElementTy
2471 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002472 if (V->getType() != SliceTy)
2473 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002474
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002475 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002476 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002477 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2478 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002479 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002480 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002481
2482 (void)Store;
2483 DEBUG(dbgs() << " to: " << *Store << "\n");
2484 return true;
2485 }
2486
Chandler Carruthea27cf02014-02-26 04:25:04 +00002487 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002488 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002489 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002490 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002491 Value *Old =
2492 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002493 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002494 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2495 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002496 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002497 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002498 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002499 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002500 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002501 (void)Store;
2502 DEBUG(dbgs() << " to: " << *Store << "\n");
2503 return true;
2504 }
2505
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002506 bool visitStoreInst(StoreInst &SI) {
2507 DEBUG(dbgs() << " original: " << SI << "\n");
2508 Value *OldOp = SI.getOperand(1);
2509 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002510
Chandler Carruth18db7952012-11-20 01:12:50 +00002511 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002512
Chandler Carruthac8317f2012-10-04 12:33:50 +00002513 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2514 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002515 if (V->getType()->isPointerTy())
2516 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002517 Pass.PostPromotionWorklist.insert(AI);
2518
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002519 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002520 assert(!SI.isVolatile());
2521 assert(V->getType()->isIntegerTy() &&
2522 "Only integer type loads and stores are split");
2523 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002524 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002525 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002526 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002527 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2528 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002529 }
2530
Chandler Carruth18db7952012-11-20 01:12:50 +00002531 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002532 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002533 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002534 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002535
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002536 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002537 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002538 if (NewBeginOffset == NewAllocaBeginOffset &&
2539 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002540 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2541 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2542 V->getType()->isIntegerTy()))) {
2543 // If this is an integer store past the end of slice (and thus the bytes
2544 // past that point are irrelevant or this is unreachable), truncate the
2545 // value prior to storing.
2546 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2547 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2548 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2549 if (DL.isBigEndian())
2550 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2551 "endian_shift");
2552 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2553 }
2554
Chandler Carruth90a735d2013-07-19 07:21:28 +00002555 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002556 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2557 SI.isVolatile());
2558 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002559 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002560 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2561 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002562 }
David Majnemer62690b12015-07-14 06:19:58 +00002563 if (SI.isVolatile())
2564 NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
Chandler Carruth18db7952012-11-20 01:12:50 +00002565 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002566 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002567
2568 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2569 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002570 }
2571
Chandler Carruth514f34f2012-12-17 04:07:30 +00002572 /// \brief Compute an integer value from splatting an i8 across the given
2573 /// number of bytes.
2574 ///
2575 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2576 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002577 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002578 ///
2579 /// \param V The i8 value to splat.
2580 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002581 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002582 assert(Size > 0 && "Expected a positive number of bytes.");
2583 IntegerType *VTy = cast<IntegerType>(V->getType());
2584 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2585 if (Size == 1)
2586 return V;
2587
Chandler Carruth113dc642014-12-20 02:39:18 +00002588 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2589 V = IRB.CreateMul(
2590 IRB.CreateZExt(V, SplatIntTy, "zext"),
2591 ConstantExpr::getUDiv(
2592 Constant::getAllOnesValue(SplatIntTy),
2593 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2594 SplatIntTy)),
2595 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002596 return V;
2597 }
2598
Chandler Carruthccca5042012-12-17 04:07:37 +00002599 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002600 Value *getVectorSplat(Value *V, unsigned NumElements) {
2601 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002602 DEBUG(dbgs() << " splat: " << *V << "\n");
2603 return V;
2604 }
2605
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002606 bool visitMemSetInst(MemSetInst &II) {
2607 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002608 assert(II.getRawDest() == OldPtr);
2609
2610 // If the memset has a variable size, it cannot be split, just adjust the
2611 // pointer to the new alloca.
2612 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002613 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002614 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002615 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002616 Type *CstTy = II.getAlignmentCst()->getType();
2617 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002618
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002619 deleteIfTriviallyDead(OldPtr);
2620 return false;
2621 }
2622
2623 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002624 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002625
2626 Type *AllocaTy = NewAI.getAllocatedType();
2627 Type *ScalarTy = AllocaTy->getScalarType();
2628
2629 // If this doesn't map cleanly onto the alloca type, and that type isn't
2630 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002631 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002632 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002633 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002634 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002635 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002636 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002637 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002638 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2639 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002640 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2641 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002642 (void)New;
2643 DEBUG(dbgs() << " to: " << *New << "\n");
2644 return false;
2645 }
2646
2647 // If we can represent this as a simple value, we have to build the actual
2648 // value to store, which requires expanding the byte present in memset to
2649 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002650 // splatting the byte to a sufficiently wide integer, splatting it across
2651 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002652 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002653
Chandler Carruthccca5042012-12-17 04:07:37 +00002654 if (VecTy) {
2655 // If this is a memset of a vectorized alloca, insert it.
2656 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002657
Chandler Carruthf0546402013-07-18 07:15:00 +00002658 unsigned BeginIndex = getIndex(NewBeginOffset);
2659 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002660 assert(EndIndex > BeginIndex && "Empty vector!");
2661 unsigned NumElements = EndIndex - BeginIndex;
2662 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2663
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002664 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002665 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2666 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002667 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002668 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002669
Chandler Carruth113dc642014-12-20 02:39:18 +00002670 Value *Old =
2671 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002672 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002673 } else if (IntTy) {
2674 // If this is a memset on an alloca where we can widen stores, insert the
2675 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002676 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002677
Chandler Carruthf0546402013-07-18 07:15:00 +00002678 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002679 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002680
2681 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2682 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002683 Value *Old =
2684 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002685 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002686 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002687 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002688 } else {
2689 assert(V->getType() == IntTy &&
2690 "Wrong type for an alloca wide integer!");
2691 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002692 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002693 } else {
2694 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002695 assert(NewBeginOffset == NewAllocaBeginOffset);
2696 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002697
Chandler Carruth90a735d2013-07-19 07:21:28 +00002698 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002699 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002700 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002701
Chandler Carruth90a735d2013-07-19 07:21:28 +00002702 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002703 }
2704
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002705 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002706 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002707 (void)New;
2708 DEBUG(dbgs() << " to: " << *New << "\n");
2709 return !II.isVolatile();
2710 }
2711
2712 bool visitMemTransferInst(MemTransferInst &II) {
2713 // Rewriting of memory transfer instructions can be a bit tricky. We break
2714 // them into two categories: split intrinsics and unsplit intrinsics.
2715
2716 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002718 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002719 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002720 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002721
Chandler Carruthaa72b932014-02-26 07:29:54 +00002722 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002723
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002724 // For unsplit intrinsics, we simply modify the source and destination
2725 // pointers in place. This isn't just an optimization, it is a matter of
2726 // correctness. With unsplit intrinsics we may be dealing with transfers
2727 // within a single alloca before SROA ran, or with transfers that have
2728 // a variable length. We may also be dealing with memmove instead of
2729 // memcpy, and so simply updating the pointers is the necessary for us to
2730 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002731 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002732 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Pete Cooper67cf9a72015-11-19 05:56:52 +00002733 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002734 II.setDest(AdjustedPtr);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002735 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002736 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002737
Pete Cooper67cf9a72015-11-19 05:56:52 +00002738 if (II.getAlignment() > SliceAlign) {
2739 Type *CstTy = II.getAlignmentCst()->getType();
2740 II.setAlignment(
2741 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002742 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002743
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002744 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002745 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002746 return false;
2747 }
2748 // For split transfer intrinsics we have an incredibly useful assurance:
2749 // the source and destination do not reside within the same alloca, and at
2750 // least one of them does not escape. This means that we can replace
2751 // memmove with memcpy, and we don't need to worry about all manner of
2752 // downsides to splitting and transforming the operations.
2753
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002754 // If this doesn't map cleanly onto the alloca type, and that type isn't
2755 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002756 bool EmitMemCpy =
2757 !VecTy && !IntTy &&
2758 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2759 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2760 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002761
2762 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2763 // size hasn't been shrunk based on analysis of the viable range, this is
2764 // a no-op.
2765 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002766 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002767 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002768
2769 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002770 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002771 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002772 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002773 return false;
2774 }
2775 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002776 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002777
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002778 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2779 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002780 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002781 if (AllocaInst *AI =
2782 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002783 assert(AI != &OldAI && AI != &NewAI &&
2784 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002785 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002786 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002787
Chandler Carruth286d87e2014-02-26 08:25:02 +00002788 Type *OtherPtrTy = OtherPtr->getType();
2789 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2790
Chandler Carruth181ed052014-02-26 05:33:36 +00002791 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002792 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002793 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002794 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2795 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002796
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002797 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002798 // Compute the other pointer, folding as much as possible to produce
2799 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002800 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002801 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002802
Chandler Carruth47954c82014-02-26 05:12:43 +00002803 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002804 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002805 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002806
Pete Cooper67cf9a72015-11-19 05:56:52 +00002807 CallInst *New = IRB.CreateMemCpy(
2808 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2809 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002810 (void)New;
2811 DEBUG(dbgs() << " to: " << *New << "\n");
2812 return false;
2813 }
2814
Chandler Carruthf0546402013-07-18 07:15:00 +00002815 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2816 NewEndOffset == NewAllocaEndOffset;
2817 uint64_t Size = NewEndOffset - NewBeginOffset;
2818 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2819 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002820 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002821 IntegerType *SubIntTy =
2822 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002823
Chandler Carruth286d87e2014-02-26 08:25:02 +00002824 // Reset the other pointer type to match the register type we're going to
2825 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002826 if (VecTy && !IsWholeAlloca) {
2827 if (NumElements == 1)
2828 OtherPtrTy = VecTy->getElementType();
2829 else
2830 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2831
Chandler Carruth286d87e2014-02-26 08:25:02 +00002832 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002833 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002834 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2835 } else {
2836 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002837 }
2838
Chandler Carruth181ed052014-02-26 05:33:36 +00002839 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002840 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002841 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002842 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002843 unsigned DstAlign = SliceAlign;
2844 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002845 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002846 std::swap(SrcAlign, DstAlign);
2847 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002848
2849 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002850 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002851 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002852 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002853 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002854 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002855 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002856 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002857 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002858 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002859 Src =
2860 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002861 }
2862
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002863 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002864 Value *Old =
2865 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002866 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002867 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002868 Value *Old =
2869 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002870 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002871 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002872 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2873 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002874 }
2875
Chandler Carruth871ba722012-09-26 10:27:46 +00002876 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002877 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002878 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002879 DEBUG(dbgs() << " to: " << *Store << "\n");
2880 return !II.isVolatile();
2881 }
2882
2883 bool visitIntrinsicInst(IntrinsicInst &II) {
2884 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2885 II.getIntrinsicID() == Intrinsic::lifetime_end);
2886 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887 assert(II.getArgOperand(1) == OldPtr);
2888
2889 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002890 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002891
Chandler Carruth113dc642014-12-20 02:39:18 +00002892 ConstantInt *Size =
2893 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002894 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002895 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002896 Value *New;
2897 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2898 New = IRB.CreateLifetimeStart(Ptr, Size);
2899 else
2900 New = IRB.CreateLifetimeEnd(Ptr, Size);
2901
Edwin Vane82f80d42013-01-29 17:42:24 +00002902 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002903 DEBUG(dbgs() << " to: " << *New << "\n");
2904 return true;
2905 }
2906
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002907 bool visitPHINode(PHINode &PN) {
2908 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002909 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2910 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002911
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002912 // We would like to compute a new pointer in only one place, but have it be
2913 // as local as possible to the PHI. To do that, we re-use the location of
2914 // the old pointer, which necessarily must be in the right position to
2915 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002916 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002917 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002918 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00002919 else
2920 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002921 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002922
Chandler Carruth47954c82014-02-26 05:12:43 +00002923 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002924 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002925 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002926
Chandler Carruth82a57542012-10-01 10:54:05 +00002927 DEBUG(dbgs() << " to: " << PN << "\n");
2928 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002929
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002930 // PHIs can't be promoted on their own, but often can be speculated. We
2931 // check the speculation outside of the rewriter so that we see the
2932 // fully-rewritten alloca.
2933 PHIUsers.insert(&PN);
2934 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002935 }
2936
2937 bool visitSelectInst(SelectInst &SI) {
2938 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002939 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2940 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002941 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2942 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002943
Chandler Carruth47954c82014-02-26 05:12:43 +00002944 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002945 // Replace the operands which were using the old pointer.
2946 if (SI.getOperand(1) == OldPtr)
2947 SI.setOperand(1, NewPtr);
2948 if (SI.getOperand(2) == OldPtr)
2949 SI.setOperand(2, NewPtr);
2950
Chandler Carruth82a57542012-10-01 10:54:05 +00002951 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002952 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002953
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002954 // Selects can't be promoted on their own, but often can be speculated. We
2955 // check the speculation outside of the rewriter so that we see the
2956 // fully-rewritten alloca.
2957 SelectUsers.insert(&SI);
2958 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002959 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002960};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002961
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002962namespace {
2963/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2964///
2965/// This pass aggressively rewrites all aggregate loads and stores on
2966/// a particular pointer (or any pointer derived from it which we can identify)
2967/// with scalar loads and stores.
2968class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2969 // Befriend the base class so it can delegate to private visit methods.
2970 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2971
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002972 /// Queue of pointer uses to analyze and potentially rewrite.
2973 SmallVector<Use *, 8> Queue;
2974
2975 /// Set to prevent us from cycling with phi nodes and loops.
2976 SmallPtrSet<User *, 8> Visited;
2977
2978 /// The current pointer use being rewritten. This is used to dig up the used
2979 /// value (as opposed to the user).
2980 Use *U;
2981
2982public:
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002983 /// Rewrite loads and stores through a pointer and all pointers derived from
2984 /// it.
2985 bool rewrite(Instruction &I) {
2986 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2987 enqueueUsers(I);
2988 bool Changed = false;
2989 while (!Queue.empty()) {
2990 U = Queue.pop_back_val();
2991 Changed |= visit(cast<Instruction>(U->getUser()));
2992 }
2993 return Changed;
2994 }
2995
2996private:
2997 /// Enqueue all the users of the given instruction for further processing.
2998 /// This uses a set to de-duplicate users.
2999 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003000 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003001 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003002 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003003 }
3004
3005 // Conservative default is to not rewrite anything.
3006 bool visitInstruction(Instruction &I) { return false; }
3007
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003008 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003009 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003010 protected:
3011 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003012 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003013 /// The indices which to be used with insert- or extractvalue to select the
3014 /// appropriate value within the aggregate.
3015 SmallVector<unsigned, 4> Indices;
3016 /// The indices to a GEP instruction which will move Ptr to the correct slot
3017 /// within the aggregate.
3018 SmallVector<Value *, 4> GEPIndices;
3019 /// The base pointer of the original op, used as a base for GEPing the
3020 /// split operations.
3021 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003022
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003023 /// Initialize the splitter with an insertion point, Ptr and start with a
3024 /// single zero GEP index.
3025 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003026 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003027
3028 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003029 /// \brief Generic recursive split emission routine.
3030 ///
3031 /// This method recursively splits an aggregate op (load or store) into
3032 /// scalar or vector ops. It splits recursively until it hits a single value
3033 /// and emits that single value operation via the template argument.
3034 ///
3035 /// The logic of this routine relies on GEPs and insertvalue and
3036 /// extractvalue all operating with the same fundamental index list, merely
3037 /// formatted differently (GEPs need actual values).
3038 ///
3039 /// \param Ty The type being split recursively into smaller ops.
3040 /// \param Agg The aggregate value being built up or stored, depending on
3041 /// whether this is splitting a load or a store respectively.
3042 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3043 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003044 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003045
3046 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3047 unsigned OldSize = Indices.size();
3048 (void)OldSize;
3049 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3050 ++Idx) {
3051 assert(Indices.size() == OldSize && "Did not return to the old size");
3052 Indices.push_back(Idx);
3053 GEPIndices.push_back(IRB.getInt32(Idx));
3054 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3055 GEPIndices.pop_back();
3056 Indices.pop_back();
3057 }
3058 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003059 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003060
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003061 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3062 unsigned OldSize = Indices.size();
3063 (void)OldSize;
3064 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3065 ++Idx) {
3066 assert(Indices.size() == OldSize && "Did not return to the old size");
3067 Indices.push_back(Idx);
3068 GEPIndices.push_back(IRB.getInt32(Idx));
3069 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3070 GEPIndices.pop_back();
3071 Indices.pop_back();
3072 }
3073 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003074 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003075
3076 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003077 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003078 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003079
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003080 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003081 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003082 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003083
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003084 /// Emit a leaf load of a single value. This is called at the leaves of the
3085 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003086 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003087 assert(Ty->isSingleValueType());
3088 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003089 Value *GEP =
3090 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003091 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003092 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3093 DEBUG(dbgs() << " to: " << *Load << "\n");
3094 }
3095 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003096
3097 bool visitLoadInst(LoadInst &LI) {
3098 assert(LI.getPointerOperand() == *U);
3099 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3100 return false;
3101
3102 // We have an aggregate being loaded, split it apart.
3103 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003104 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003105 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003106 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003107 LI.replaceAllUsesWith(V);
3108 LI.eraseFromParent();
3109 return true;
3110 }
3111
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003112 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003113 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003114 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003115
3116 /// Emit a leaf store of a single value. This is called at the leaves of the
3117 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003118 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003119 assert(Ty->isSingleValueType());
3120 // Extract the single value and store it using the indices.
3121 Value *Store = IRB.CreateStore(
Chandler Carruth113dc642014-12-20 02:39:18 +00003122 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
David Blaikieaa41cd52015-04-03 21:33:42 +00003123 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003124 (void)Store;
3125 DEBUG(dbgs() << " to: " << *Store << "\n");
3126 }
3127 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003128
3129 bool visitStoreInst(StoreInst &SI) {
3130 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3131 return false;
3132 Value *V = SI.getValueOperand();
3133 if (V->getType()->isSingleValueType())
3134 return false;
3135
3136 // We have an aggregate being stored, split it apart.
3137 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003138 StoreOpSplitter Splitter(&SI, *U);
3139 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003140 SI.eraseFromParent();
3141 return true;
3142 }
3143
3144 bool visitBitCastInst(BitCastInst &BC) {
3145 enqueueUsers(BC);
3146 return false;
3147 }
3148
3149 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3150 enqueueUsers(GEPI);
3151 return false;
3152 }
3153
3154 bool visitPHINode(PHINode &PN) {
3155 enqueueUsers(PN);
3156 return false;
3157 }
3158
3159 bool visitSelectInst(SelectInst &SI) {
3160 enqueueUsers(SI);
3161 return false;
3162 }
3163};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003164}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003165
Chandler Carruthba931992012-10-13 10:49:33 +00003166/// \brief Strip aggregate type wrapping.
3167///
3168/// This removes no-op aggregate types wrapping an underlying type. It will
3169/// strip as many layers of types as it can without changing either the type
3170/// size or the allocated size.
3171static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3172 if (Ty->isSingleValueType())
3173 return Ty;
3174
3175 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3176 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3177
3178 Type *InnerTy;
3179 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3180 InnerTy = ArrTy->getElementType();
3181 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3182 const StructLayout *SL = DL.getStructLayout(STy);
3183 unsigned Index = SL->getElementContainingOffset(0);
3184 InnerTy = STy->getElementType(Index);
3185 } else {
3186 return Ty;
3187 }
3188
3189 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3190 TypeSize > DL.getTypeSizeInBits(InnerTy))
3191 return Ty;
3192
3193 return stripAggregateTypeWrapping(DL, InnerTy);
3194}
3195
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003196/// \brief Try to find a partition of the aggregate type passed in for a given
3197/// offset and size.
3198///
3199/// This recurses through the aggregate type and tries to compute a subtype
3200/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003201/// of an array, it will even compute a new array type for that sub-section,
3202/// and the same for structs.
3203///
3204/// Note that this routine is very strict and tries to find a partition of the
3205/// type which produces the *exact* right offset and size. It is not forgiving
3206/// when the size or offset cause either end of type-based partition to be off.
3207/// Also, this is a best-effort routine. It is reasonable to give up and not
3208/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003209static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3210 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003211 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3212 return stripAggregateTypeWrapping(DL, Ty);
3213 if (Offset > DL.getTypeAllocSize(Ty) ||
3214 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003215 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003216
3217 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3218 // We can't partition pointers...
3219 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003220 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003221
3222 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003223 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003224 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003225 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003226 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003227 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003228 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003229 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003230 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003231 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003232 Offset -= NumSkippedElements * ElementSize;
3233
3234 // First check if we need to recurse.
3235 if (Offset > 0 || Size < ElementSize) {
3236 // Bail if the partition ends in a different array element.
3237 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003238 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003239 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003240 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003241 }
3242 assert(Offset == 0);
3243
3244 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003245 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003246 assert(Size > ElementSize);
3247 uint64_t NumElements = Size / ElementSize;
3248 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003249 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003250 return ArrayType::get(ElementTy, NumElements);
3251 }
3252
3253 StructType *STy = dyn_cast<StructType>(Ty);
3254 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003255 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003256
Chandler Carruth90a735d2013-07-19 07:21:28 +00003257 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003258 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003259 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003260 uint64_t EndOffset = Offset + Size;
3261 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003262 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003263
3264 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003265 Offset -= SL->getElementOffset(Index);
3266
3267 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003268 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003269 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003270 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003271
3272 // See if any partition must be contained by the element.
3273 if (Offset > 0 || Size < ElementSize) {
3274 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003275 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003276 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003277 }
3278 assert(Offset == 0);
3279
3280 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003281 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003282
3283 StructType::element_iterator EI = STy->element_begin() + Index,
3284 EE = STy->element_end();
3285 if (EndOffset < SL->getSizeInBytes()) {
3286 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3287 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003288 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003289
3290 // Don't try to form "natural" types if the elements don't line up with the
3291 // expected size.
3292 // FIXME: We could potentially recurse down through the last element in the
3293 // sub-struct to find a natural end point.
3294 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003295 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003296
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003297 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003298 EE = STy->element_begin() + EndIndex;
3299 }
3300
3301 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003302 StructType *SubTy =
3303 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003304 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003305 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003306 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003307
Chandler Carruth054a40a2012-09-14 11:08:31 +00003308 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003309}
3310
Chandler Carruth0715cba2015-01-01 11:54:38 +00003311/// \brief Pre-split loads and stores to simplify rewriting.
3312///
3313/// We want to break up the splittable load+store pairs as much as
3314/// possible. This is important to do as a preprocessing step, as once we
3315/// start rewriting the accesses to partitions of the alloca we lose the
3316/// necessary information to correctly split apart paired loads and stores
3317/// which both point into this alloca. The case to consider is something like
3318/// the following:
3319///
3320/// %a = alloca [12 x i8]
3321/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3322/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3323/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3324/// %iptr1 = bitcast i8* %gep1 to i64*
3325/// %iptr2 = bitcast i8* %gep2 to i64*
3326/// %fptr1 = bitcast i8* %gep1 to float*
3327/// %fptr2 = bitcast i8* %gep2 to float*
3328/// %fptr3 = bitcast i8* %gep3 to float*
3329/// store float 0.0, float* %fptr1
3330/// store float 1.0, float* %fptr2
3331/// %v = load i64* %iptr1
3332/// store i64 %v, i64* %iptr2
3333/// %f1 = load float* %fptr2
3334/// %f2 = load float* %fptr3
3335///
3336/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3337/// promote everything so we recover the 2 SSA values that should have been
3338/// there all along.
3339///
3340/// \returns true if any changes are made.
3341bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3342 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3343
3344 // Track the loads and stores which are candidates for pre-splitting here, in
3345 // the order they first appear during the partition scan. These give stable
3346 // iteration order and a basis for tracking which loads and stores we
3347 // actually split.
3348 SmallVector<LoadInst *, 4> Loads;
3349 SmallVector<StoreInst *, 4> Stores;
3350
3351 // We need to accumulate the splits required of each load or store where we
3352 // can find them via a direct lookup. This is important to cross-check loads
3353 // and stores against each other. We also track the slice so that we can kill
3354 // all the slices that end up split.
3355 struct SplitOffsets {
3356 Slice *S;
3357 std::vector<uint64_t> Splits;
3358 };
3359 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3360
Chandler Carruth73b01642015-01-05 04:17:53 +00003361 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3362 // This is important as we also cannot pre-split stores of those loads!
3363 // FIXME: This is all pretty gross. It means that we can be more aggressive
3364 // in pre-splitting when the load feeding the store happens to come from
3365 // a separate alloca. Put another way, the effectiveness of SROA would be
3366 // decreased by a frontend which just concatenated all of its local allocas
3367 // into one big flat alloca. But defeating such patterns is exactly the job
3368 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3369 // change store pre-splitting to actually force pre-splitting of the load
3370 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3371 // maybe it would make it more principled?
3372 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3373
Chandler Carruth0715cba2015-01-01 11:54:38 +00003374 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3375 for (auto &P : AS.partitions()) {
3376 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003377 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3378 if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
3379 // If this was a load we have to track that it can't participate in any
3380 // pre-splitting!
3381 if (auto *LI = dyn_cast<LoadInst>(I))
3382 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003383 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003384 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003385 assert(P.endOffset() > S.beginOffset() &&
3386 "Empty or backwards partition!");
3387
3388 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003389 if (auto *LI = dyn_cast<LoadInst>(I)) {
3390 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3391
3392 // The load must be used exclusively to store into other pointers for
3393 // us to be able to arbitrarily pre-split it. The stores must also be
3394 // simple to avoid changing semantics.
3395 auto IsLoadSimplyStored = [](LoadInst *LI) {
3396 for (User *LU : LI->users()) {
3397 auto *SI = dyn_cast<StoreInst>(LU);
3398 if (!SI || !SI->isSimple())
3399 return false;
3400 }
3401 return true;
3402 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003403 if (!IsLoadSimplyStored(LI)) {
3404 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003405 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003406 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003407
3408 Loads.push_back(LI);
3409 } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
Chandler Carruth994cde82015-01-01 12:01:03 +00003410 if (!SI ||
3411 S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3412 continue;
3413 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3414 if (!StoredLoad || !StoredLoad->isSimple())
3415 continue;
3416 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003417
Chandler Carruth994cde82015-01-01 12:01:03 +00003418 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003419 } else {
3420 // Other uses cannot be pre-split.
3421 continue;
3422 }
3423
3424 // Record the initial split.
3425 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3426 auto &Offsets = SplitOffsetsMap[I];
3427 assert(Offsets.Splits.empty() &&
3428 "Should not have splits the first time we see an instruction!");
3429 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003430 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003431 }
3432
3433 // Now scan the already split slices, and add a split for any of them which
3434 // we're going to pre-split.
3435 for (Slice *S : P.splitSliceTails()) {
3436 auto SplitOffsetsMapI =
3437 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3438 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3439 continue;
3440 auto &Offsets = SplitOffsetsMapI->second;
3441
3442 assert(Offsets.S == S && "Found a mismatched slice!");
3443 assert(!Offsets.Splits.empty() &&
3444 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003445 assert(Offsets.Splits.back() ==
3446 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003447 "Previous split does not end where this one begins!");
3448
3449 // Record each split. The last partition's end isn't needed as the size
3450 // of the slice dictates that.
3451 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003452 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003453 }
3454 }
3455
3456 // We may have split loads where some of their stores are split stores. For
3457 // such loads and stores, we can only pre-split them if their splits exactly
3458 // match relative to their starting offset. We have to verify this prior to
3459 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003460 Stores.erase(
Chandler Carruth994cde82015-01-01 12:01:03 +00003461 std::remove_if(Stores.begin(), Stores.end(),
Chandler Carruth73b01642015-01-05 04:17:53 +00003462 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
Chandler Carruth994cde82015-01-01 12:01:03 +00003463 // Lookup the load we are storing in our map of split
3464 // offsets.
3465 auto *LI = cast<LoadInst>(SI->getValueOperand());
Chandler Carruth73b01642015-01-05 04:17:53 +00003466 // If it was completely unsplittable, then we're done,
3467 // and this store can't be pre-split.
3468 if (UnsplittableLoads.count(LI))
3469 return true;
3470
Chandler Carruth994cde82015-01-01 12:01:03 +00003471 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3472 if (LoadOffsetsI == SplitOffsetsMap.end())
Chandler Carruth73b01642015-01-05 04:17:53 +00003473 return false; // Unrelated loads are definitely safe.
Chandler Carruth994cde82015-01-01 12:01:03 +00003474 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003475
Chandler Carruth994cde82015-01-01 12:01:03 +00003476 // Now lookup the store's offsets.
3477 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003478
Chandler Carruth994cde82015-01-01 12:01:03 +00003479 // If the relative offsets of each split in the load and
3480 // store match exactly, then we can split them and we
3481 // don't need to remove them here.
3482 if (LoadOffsets.Splits == StoreOffsets.Splits)
3483 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003484
Chandler Carruth994cde82015-01-01 12:01:03 +00003485 DEBUG(dbgs()
3486 << " Mismatched splits for load and store:\n"
3487 << " " << *LI << "\n"
3488 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003489
Chandler Carruth994cde82015-01-01 12:01:03 +00003490 // We've found a store and load that we need to split
3491 // with mismatched relative splits. Just give up on them
3492 // and remove both instructions from our list of
3493 // candidates.
Chandler Carruth73b01642015-01-05 04:17:53 +00003494 UnsplittableLoads.insert(LI);
Chandler Carruth994cde82015-01-01 12:01:03 +00003495 return true;
3496 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003497 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003498 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003499 // have caused an earlier store's load to become unsplittable and if it is
3500 // unsplittable for the later store, then we can't rely on it being split in
3501 // the earlier store either.
3502 Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3503 [&UnsplittableLoads](StoreInst *SI) {
3504 auto *LI =
3505 cast<LoadInst>(SI->getValueOperand());
3506 return UnsplittableLoads.count(LI);
3507 }),
3508 Stores.end());
3509 // Once we've established all the loads that can't be split for some reason,
3510 // filter any that made it into our list out.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003511 Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
Chandler Carruth73b01642015-01-05 04:17:53 +00003512 [&UnsplittableLoads](LoadInst *LI) {
3513 return UnsplittableLoads.count(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003514 }),
3515 Loads.end());
3516
Chandler Carruth73b01642015-01-05 04:17:53 +00003517
Chandler Carruth0715cba2015-01-01 11:54:38 +00003518 // If no loads or stores are left, there is no pre-splitting to be done for
3519 // this alloca.
3520 if (Loads.empty() && Stores.empty())
3521 return false;
3522
3523 // From here on, we can't fail and will be building new accesses, so rig up
3524 // an IR builder.
3525 IRBuilderTy IRB(&AI);
3526
3527 // Collect the new slices which we will merge into the alloca slices.
3528 SmallVector<Slice, 4> NewSlices;
3529
3530 // Track any allocas we end up splitting loads and stores for so we iterate
3531 // on them.
3532 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3533
3534 // At this point, we have collected all of the loads and stores we can
3535 // pre-split, and the specific splits needed for them. We actually do the
3536 // splitting in a specific order in order to handle when one of the loads in
3537 // the value operand to one of the stores.
3538 //
3539 // First, we rewrite all of the split loads, and just accumulate each split
3540 // load in a parallel structure. We also build the slices for them and append
3541 // them to the alloca slices.
3542 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3543 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003544 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003545 for (LoadInst *LI : Loads) {
3546 SplitLoads.clear();
3547
3548 IntegerType *Ty = cast<IntegerType>(LI->getType());
3549 uint64_t LoadSize = Ty->getBitWidth() / 8;
3550 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3551
3552 auto &Offsets = SplitOffsetsMap[LI];
3553 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3554 "Slice size should always match load size exactly!");
3555 uint64_t BaseOffset = Offsets.S->beginOffset();
3556 assert(BaseOffset + LoadSize > BaseOffset &&
3557 "Cannot represent alloca access size using 64-bit integers!");
3558
3559 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003560 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003561
3562 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3563
3564 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3565 int Idx = 0, Size = Offsets.Splits.size();
3566 for (;;) {
3567 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3568 auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3569 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003570 getAdjustedPtr(IRB, DL, BasePtr,
3571 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003572 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003573 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003574 LI->getName());
3575
3576 // Append this load onto the list of split loads so we can find it later
3577 // to rewrite the stores.
3578 SplitLoads.push_back(PLoad);
3579
3580 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003581 NewSlices.push_back(
3582 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3583 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003584 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003585 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3586 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3587 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003588
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003589 // See if we've handled all the splits.
3590 if (Idx >= Size)
3591 break;
3592
Chandler Carruth0715cba2015-01-01 11:54:38 +00003593 // Setup the next partition.
3594 PartOffset = Offsets.Splits[Idx];
3595 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003596 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3597 }
3598
3599 // Now that we have the split loads, do the slow walk over all uses of the
3600 // load and rewrite them as split stores, or save the split loads to use
3601 // below if the store is going to be split there anyways.
3602 bool DeferredStores = false;
3603 for (User *LU : LI->users()) {
3604 StoreInst *SI = cast<StoreInst>(LU);
3605 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3606 DeferredStores = true;
3607 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3608 continue;
3609 }
3610
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003611 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003612 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003613
3614 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3615
3616 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3617 LoadInst *PLoad = SplitLoads[Idx];
3618 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003619 auto *PartPtrTy =
3620 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003621
3622 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003623 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3624 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003625 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003626 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003627 (void)PStore;
3628 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3629 }
3630
3631 // We want to immediately iterate on any allocas impacted by splitting
3632 // this store, and we have to track any promotable alloca (indicated by
3633 // a direct store) as needing to be resplit because it is no longer
3634 // promotable.
3635 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3636 ResplitPromotableAllocas.insert(OtherAI);
3637 Worklist.insert(OtherAI);
3638 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3639 StoreBasePtr->stripInBoundsOffsets())) {
3640 Worklist.insert(OtherAI);
3641 }
3642
3643 // Mark the original store as dead.
3644 DeadInsts.insert(SI);
3645 }
3646
3647 // Save the split loads if there are deferred stores among the users.
3648 if (DeferredStores)
3649 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3650
3651 // Mark the original load as dead and kill the original slice.
3652 DeadInsts.insert(LI);
3653 Offsets.S->kill();
3654 }
3655
3656 // Second, we rewrite all of the split stores. At this point, we know that
3657 // all loads from this alloca have been split already. For stores of such
3658 // loads, we can simply look up the pre-existing split loads. For stores of
3659 // other loads, we split those loads first and then write split stores of
3660 // them.
3661 for (StoreInst *SI : Stores) {
3662 auto *LI = cast<LoadInst>(SI->getValueOperand());
3663 IntegerType *Ty = cast<IntegerType>(LI->getType());
3664 uint64_t StoreSize = Ty->getBitWidth() / 8;
3665 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3666
3667 auto &Offsets = SplitOffsetsMap[SI];
3668 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3669 "Slice size should always match load size exactly!");
3670 uint64_t BaseOffset = Offsets.S->beginOffset();
3671 assert(BaseOffset + StoreSize > BaseOffset &&
3672 "Cannot represent alloca access size using 64-bit integers!");
3673
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003674 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003675 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3676
3677 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3678
3679 // Check whether we have an already split load.
3680 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3681 std::vector<LoadInst *> *SplitLoads = nullptr;
3682 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3683 SplitLoads = &SplitLoadsMapI->second;
3684 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3685 "Too few split loads for the number of splits in the store!");
3686 } else {
3687 DEBUG(dbgs() << " of load: " << *LI << "\n");
3688 }
3689
Chandler Carruth0715cba2015-01-01 11:54:38 +00003690 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3691 int Idx = 0, Size = Offsets.Splits.size();
3692 for (;;) {
3693 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3694 auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3695
3696 // Either lookup a split load or create one.
3697 LoadInst *PLoad;
3698 if (SplitLoads) {
3699 PLoad = (*SplitLoads)[Idx];
3700 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003701 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003702 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003703 getAdjustedPtr(IRB, DL, LoadBasePtr,
3704 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003705 PartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003706 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003707 LI->getName());
3708 }
3709
3710 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003711 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003712 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003713 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3714 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003715 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003716 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003717
3718 // Now build a new slice for the alloca.
3719 NewSlices.push_back(
3720 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3721 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003722 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003723 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3724 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3725 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003726 if (!SplitLoads) {
3727 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3728 }
3729
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003730 // See if we've finished all the splits.
3731 if (Idx >= Size)
3732 break;
3733
Chandler Carruth0715cba2015-01-01 11:54:38 +00003734 // Setup the next partition.
3735 PartOffset = Offsets.Splits[Idx];
3736 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003737 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3738 }
3739
3740 // We want to immediately iterate on any allocas impacted by splitting
3741 // this load, which is only relevant if it isn't a load of this alloca and
3742 // thus we didn't already split the loads above. We also have to keep track
3743 // of any promotable allocas we split loads on as they can no longer be
3744 // promoted.
3745 if (!SplitLoads) {
3746 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3747 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3748 ResplitPromotableAllocas.insert(OtherAI);
3749 Worklist.insert(OtherAI);
3750 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3751 LoadBasePtr->stripInBoundsOffsets())) {
3752 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3753 Worklist.insert(OtherAI);
3754 }
3755 }
3756
3757 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003758 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003759 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003760 // for some other alloca, but it may be a normal load. This may introduce
3761 // redundant loads, but where those can be merged the rest of the optimizer
3762 // should handle the merging, and this uncovers SSA splits which is more
3763 // important. In practice, the original loads will almost always be fully
3764 // split and removed eventually, and the splits will be merged by any
3765 // trivial CSE, including instcombine.
3766 if (LI->hasOneUse()) {
3767 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3768 DeadInsts.insert(LI);
3769 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003770 DeadInsts.insert(SI);
3771 Offsets.S->kill();
3772 }
3773
Chandler Carruth24ac8302015-01-02 03:55:54 +00003774 // Remove the killed slices that have ben pre-split.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003775 AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3776 return S.isDead();
3777 }), AS.end());
3778
Chandler Carruth24ac8302015-01-02 03:55:54 +00003779 // Insert our new slices. This will sort and merge them into the sorted
3780 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003781 AS.insert(NewSlices);
3782
3783 DEBUG(dbgs() << " Pre-split slices:\n");
3784#ifndef NDEBUG
3785 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3786 DEBUG(AS.print(dbgs(), I, " "));
3787#endif
3788
3789 // Finally, don't try to promote any allocas that new require re-splitting.
3790 // They have already been added to the worklist above.
3791 PromotableAllocas.erase(
3792 std::remove_if(
3793 PromotableAllocas.begin(), PromotableAllocas.end(),
3794 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3795 PromotableAllocas.end());
3796
3797 return true;
3798}
3799
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003800/// \brief Rewrite an alloca partition's users.
3801///
3802/// This routine drives both of the rewriting goals of the SROA pass. It tries
3803/// to rewrite uses of an alloca partition to be conducive for SSA value
3804/// promotion. If the partition needs a new, more refined alloca, this will
3805/// build that new alloca, preserving as much type information as possible, and
3806/// rewrite the uses of the old alloca to point at the new one and have the
3807/// appropriate new offsets. It also evaluates how successful the rewrite was
3808/// at enabling promotion and if it was successful queues the alloca to be
3809/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003810AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00003811 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003812 // Try to compute a friendly type for this partition of the alloca. This
3813 // won't always succeed, in which case we fall back to a legal integer type
3814 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003815 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003816 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003817 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003818 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003819 SliceTy = CommonUseTy;
3820 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003821 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003822 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003823 SliceTy = TypePartitionTy;
3824 if ((!SliceTy || (SliceTy->isArrayTy() &&
3825 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003826 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003827 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003828 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003829 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003830 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003831
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003832 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003833
Chandler Carruth2dc96822014-10-18 00:44:02 +00003834 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003835 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003836 if (VecTy)
3837 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003838
3839 // Check for the case where we're going to rewrite to a new alloca of the
3840 // exact same type as the original, and with the same access offsets. In that
3841 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003842 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003843 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003844 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003845 assert(P.beginOffset() == 0 &&
3846 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003847 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003848 // FIXME: We should be able to bail at this point with "nothing changed".
3849 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00003850 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003851 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003852 unsigned Alignment = AI.getAlignment();
3853 if (!Alignment) {
3854 // The minimum alignment which users can rely on when the explicit
3855 // alignment is omitted or zero is that required by the ABI for this
3856 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003857 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003858 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003859 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003860 // If we will get at least this much alignment from the type alone, leave
3861 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003862 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003863 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003864 NewAI = new AllocaInst(
3865 SliceTy, nullptr, Alignment,
3866 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003867 ++NumNewAllocas;
3868 }
3869
3870 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003871 << "[" << P.beginOffset() << "," << P.endOffset()
3872 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003873
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003874 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003875 // promoted allocas. We will reset it to this point if the alloca is not in
3876 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003877 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003878 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003879 SmallPtrSet<PHINode *, 8> PHIUsers;
3880 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003881
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003882 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003883 P.endOffset(), IsIntegerPromotable, VecTy,
3884 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003885 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003886 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003887 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003888 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003889 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003890 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003891 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003892 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003893 }
3894
Chandler Carruth6c321c12013-07-19 10:57:36 +00003895 NumAllocaPartitionUses += NumUses;
3896 MaxUsesPerAllocaPartition =
3897 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003898
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003899 // Now that we've processed all the slices in the new partition, check if any
3900 // PHIs or Selects would block promotion.
3901 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3902 E = PHIUsers.end();
3903 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003904 if (!isSafePHIToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003905 Promotable = false;
3906 PHIUsers.clear();
3907 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003908 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003909 }
3910 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3911 E = SelectUsers.end();
3912 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003913 if (!isSafeSelectToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003914 Promotable = false;
3915 PHIUsers.clear();
3916 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003917 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003918 }
3919
3920 if (Promotable) {
3921 if (PHIUsers.empty() && SelectUsers.empty()) {
3922 // Promote the alloca.
3923 PromotableAllocas.push_back(NewAI);
3924 } else {
3925 // If we have either PHIs or Selects to speculate, add them to those
3926 // worklists and re-queue the new alloca so that we promote in on the
3927 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003928 for (PHINode *PHIUser : PHIUsers)
3929 SpeculatablePHIs.insert(PHIUser);
3930 for (SelectInst *SelectUser : SelectUsers)
3931 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003932 Worklist.insert(NewAI);
3933 }
3934 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003935 // If we can't promote the alloca, iterate on it to check for new
3936 // refinements exposed by splitting the current alloca. Don't iterate on an
3937 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003938 if (NewAI != &AI)
3939 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003940
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003941 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003942 while (PostPromotionWorklist.size() > PPWOldSize)
3943 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003944 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003945
Adrian Prantl565cc182015-01-20 19:42:22 +00003946 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003947}
3948
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003949/// \brief Walks the slices of an alloca and form partitions based on them,
3950/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003951bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3952 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003953 return false;
3954
Chandler Carruth6c321c12013-07-19 10:57:36 +00003955 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003956 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003957 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00003958
Chandler Carruth24ac8302015-01-02 03:55:54 +00003959 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003960 Changed |= presplitLoadsAndStores(AI, AS);
3961
Chandler Carruth24ac8302015-01-02 03:55:54 +00003962 // Now that we have identified any pre-splitting opportunities, mark any
3963 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
3964 // to split these during pre-splitting, we want to force them to be
3965 // rewritten into a partition.
3966 bool IsSorted = true;
3967 for (Slice &S : AS) {
3968 if (!S.isSplittable())
3969 continue;
3970 // FIXME: We currently leave whole-alloca splittable loads and stores. This
3971 // used to be the only splittable loads and stores and we need to be
3972 // confident that the above handling of splittable loads and stores is
3973 // completely sufficient before we forcibly disable the remaining handling.
3974 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003975 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00003976 continue;
3977 if (isa<LoadInst>(S.getUse()->getUser()) ||
3978 isa<StoreInst>(S.getUse()->getUser())) {
3979 S.makeUnsplittable();
3980 IsSorted = false;
3981 }
3982 }
3983 if (!IsSorted)
3984 std::sort(AS.begin(), AS.end());
3985
Adrian Prantl565cc182015-01-20 19:42:22 +00003986 /// \brief Describes the allocas introduced by rewritePartition
3987 /// in order to migrate the debug info.
3988 struct Piece {
3989 AllocaInst *Alloca;
3990 uint64_t Offset;
3991 uint64_t Size;
3992 Piece(AllocaInst *AI, uint64_t O, uint64_t S)
3993 : Alloca(AI), Offset(O), Size(S) {}
3994 };
3995 SmallVector<Piece, 4> Pieces;
3996
Chandler Carruth0715cba2015-01-01 11:54:38 +00003997 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003998 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00003999 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4000 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004001 if (NewAI != &AI) {
4002 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004003 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004004 // Don't include any padding.
4005 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4006 Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
4007 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004008 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004009 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004010 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004011
Chandler Carruth6c321c12013-07-19 10:57:36 +00004012 NumAllocaPartitions += NumPartitions;
4013 MaxPartitionsPerAlloca =
4014 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004015
Adrian Prantl565cc182015-01-20 19:42:22 +00004016 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004017 // and the individual partitions.
Adrian Prantl565cc182015-01-20 19:42:22 +00004018 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00004019 auto *Var = DbgDecl->getVariable();
4020 auto *Expr = DbgDecl->getExpression();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004021 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004022 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl565cc182015-01-20 19:42:22 +00004023 for (auto Piece : Pieces) {
4024 // Create a piece expression describing the new partition or reuse AI's
4025 // expression if there is only one partition.
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00004026 auto *PieceExpr = Expr;
Keno Fischerd5354fd2016-01-14 20:06:34 +00004027 if (Piece.Size < AllocaSize || Expr->isBitPiece()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004028 // If this alloca is already a scalar replacement of a larger aggregate,
4029 // Piece.Offset describes the offset inside the scalar.
Duncan P. N. Exon Smith6a0320a2015-04-14 01:12:42 +00004030 uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
Adrian Prantl34e75902015-02-09 23:57:22 +00004031 uint64_t Start = Offset + Piece.Offset;
4032 uint64_t Size = Piece.Size;
Duncan P. N. Exon Smith6a0320a2015-04-14 01:12:42 +00004033 if (Expr->isBitPiece()) {
4034 uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
Adrian Prantl34e75902015-02-09 23:57:22 +00004035 if (Start >= AbsEnd)
4036 // No need to describe a SROAed padding.
4037 continue;
4038 Size = std::min(Size, AbsEnd - Start);
4039 }
4040 PieceExpr = DIB.createBitPieceExpression(Start, Size);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004041 } else {
4042 assert(Pieces.size() == 1 &&
4043 "partition is as large as original alloca");
Adrian Prantl152ac392015-02-01 00:58:04 +00004044 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004045
4046 // Remove any existing dbg.declare intrinsic describing the same alloca.
4047 if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
4048 OldDDI->eraseFromParent();
4049
Duncan P. N. Exon Smithcd1aecf2015-04-15 21:18:07 +00004050 DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
4051 &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004052 }
4053 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004054 return Changed;
4055}
4056
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004057/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4058void SROA::clobberUse(Use &U) {
4059 Value *OldV = U;
4060 // Replace the use with an undef value.
4061 U = UndefValue::get(OldV->getType());
4062
4063 // Check for this making an instruction dead. We have to garbage collect
4064 // all the dead instructions to ensure the uses of any alloca end up being
4065 // minimal.
4066 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4067 if (isInstructionTriviallyDead(OldI)) {
4068 DeadInsts.insert(OldI);
4069 }
4070}
4071
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004072/// \brief Analyze an alloca for SROA.
4073///
4074/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004075/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004076/// rewritten as needed.
4077bool SROA::runOnAlloca(AllocaInst &AI) {
4078 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4079 ++NumAllocasAnalyzed;
4080
4081 // Special case dead allocas, as they're trivial.
4082 if (AI.use_empty()) {
4083 AI.eraseFromParent();
4084 return true;
4085 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004086 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004087
4088 // Skip alloca forms that this analysis can't handle.
4089 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004090 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004091 return false;
4092
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004093 bool Changed = false;
4094
4095 // First, split any FCA loads and stores touching this alloca to promote
4096 // better splitting and promotion opportunities.
Benjamin Kramer6db33382015-10-15 15:08:58 +00004097 AggLoadStoreRewriter AggRewriter;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004098 Changed |= AggRewriter.rewrite(AI);
4099
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004100 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004101 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004102 DEBUG(AS.print(dbgs()));
4103 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004104 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004105
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004106 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004107 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004108 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004109 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004110 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004111
4112 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004113 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004114
4115 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004116 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004117 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004118 }
Chandler Carruth83934062014-10-16 21:11:55 +00004119 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004120 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004121 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004122 }
4123
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004124 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004125 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004126 return Changed;
4127
Chandler Carruth83934062014-10-16 21:11:55 +00004128 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004129
4130 DEBUG(dbgs() << " Speculating PHIs\n");
4131 while (!SpeculatablePHIs.empty())
4132 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4133
4134 DEBUG(dbgs() << " Speculating Selects\n");
4135 while (!SpeculatableSelects.empty())
4136 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4137
4138 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004139}
4140
Chandler Carruth19450da2012-09-14 10:26:38 +00004141/// \brief Delete the dead instructions accumulated in this run.
4142///
4143/// Recursively deletes the dead instructions we've accumulated. This is done
4144/// at the very end to maximize locality of the recursive delete and to
4145/// minimize the problems of invalidated instruction pointers as such pointers
4146/// are used heavily in the intermediate stages of the algorithm.
4147///
4148/// We also record the alloca instructions deleted here so that they aren't
4149/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00004150void SROA::deleteDeadInstructions(
4151 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004152 while (!DeadInsts.empty()) {
4153 Instruction *I = DeadInsts.pop_back_val();
4154 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4155
Chandler Carruth58d05562012-10-25 04:37:07 +00004156 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4157
Chandler Carruth1583e992014-03-03 10:42:58 +00004158 for (Use &Operand : I->operands())
4159 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004160 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004161 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004162 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004163 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004164 }
4165
Adrian Prantl565cc182015-01-20 19:42:22 +00004166 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004167 DeletedAllocas.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004168 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4169 DbgDecl->eraseFromParent();
4170 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004171
4172 ++NumDeleted;
4173 I->eraseFromParent();
4174 }
4175}
4176
Chandler Carruth70b44c52012-09-15 11:43:14 +00004177/// \brief Promote the allocas, using the best available technique.
4178///
4179/// This attempts to promote whatever allocas have been identified as viable in
4180/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004181/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004182bool SROA::promoteAllocas(Function &F) {
4183 if (PromotableAllocas.empty())
4184 return false;
4185
4186 NumPromoted += PromotableAllocas.size();
4187
Chandler Carruth748d0952015-08-26 09:09:29 +00004188 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4189 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004190 PromotableAllocas.clear();
4191 return true;
4192}
4193
Chandler Carruth29a18a42015-09-12 09:09:14 +00004194PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4195 AssumptionCache &RunAC) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004196 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4197 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004198 DT = &RunDT;
4199 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004200
4201 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004202 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004203 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004204 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4205 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004206 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004207
4208 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004209 // A set of deleted alloca instruction pointers which should be removed from
4210 // the list of promotable allocas.
4211 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4212
Chandler Carruthac8317f2012-10-04 12:33:50 +00004213 do {
4214 while (!Worklist.empty()) {
4215 Changed |= runOnAlloca(*Worklist.pop_back_val());
4216 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004217
Chandler Carruthac8317f2012-10-04 12:33:50 +00004218 // Remove the deleted allocas from various lists so that we don't try to
4219 // continue processing them.
4220 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004221 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004222 Worklist.remove_if(IsInSet);
4223 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00004224 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4225 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004226 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004227 PromotableAllocas.end());
4228 DeletedAllocas.clear();
4229 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004230 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004231
Chandler Carruthac8317f2012-10-04 12:33:50 +00004232 Changed |= promoteAllocas(F);
4233
4234 Worklist = PostPromotionWorklist;
4235 PostPromotionWorklist.clear();
4236 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004237
Chandler Carruth29a18a42015-09-12 09:09:14 +00004238 // FIXME: Even when promoting allocas we should preserve some abstract set of
4239 // CFG-specific analyses.
4240 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004241}
4242
Chandler Carruth29a18a42015-09-12 09:09:14 +00004243PreservedAnalyses SROA::run(Function &F, AnalysisManager<Function> *AM) {
4244 return runImpl(F, AM->getResult<DominatorTreeAnalysis>(F),
4245 AM->getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004246}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004247
4248/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4249///
4250/// This is in the llvm namespace purely to allow it to be a friend of the \c
4251/// SROA pass.
4252class llvm::sroa::SROALegacyPass : public FunctionPass {
4253 /// The SROA implementation.
4254 SROA Impl;
4255
4256public:
4257 SROALegacyPass() : FunctionPass(ID) {
4258 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4259 }
4260 bool runOnFunction(Function &F) override {
4261 if (skipOptnoneFunction(F))
4262 return false;
4263
4264 auto PA = Impl.runImpl(
4265 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4266 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4267 return !PA.areAllPreserved();
4268 }
4269 void getAnalysisUsage(AnalysisUsage &AU) const override {
4270 AU.addRequired<AssumptionCacheTracker>();
4271 AU.addRequired<DominatorTreeWrapperPass>();
4272 AU.addPreserved<GlobalsAAWrapperPass>();
4273 AU.setPreservesCFG();
4274 }
4275
4276 const char *getPassName() const override { return "SROA"; }
4277 static char ID;
4278};
4279
4280char SROALegacyPass::ID = 0;
4281
4282FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4283
4284INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4285 "Scalar Replacement Of Aggregates", false, false)
4286INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4287INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4288INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4289 false, false)