blob: 9ec39d2528147aaf6c31d3f55f329a6c1378ad25 [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
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruthdbd69582012-11-30 03:08:41 +000047#include "llvm/InstVisitor.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
58using namespace llvm;
59
60STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000061STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000062STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
63STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
64STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000065STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000067STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000068STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000070
Chandler Carruth70b44c52012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000077/// \brief A custom IRBuilder inserter which prefixes all names if they are
78/// preserved.
79template <bool preserveNames = true>
80class IRBuilderPrefixedInserter :
81 public IRBuilderDefaultInserter<preserveNames> {
82 std::string Prefix;
83
84public:
85 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
86
87protected:
88 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
89 BasicBlock::iterator InsertPt) const {
90 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
91 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
92 }
93};
94
95// Specialization for not preserving the name is trivial.
96template <>
97class IRBuilderPrefixedInserter<false> :
98 public IRBuilderDefaultInserter<false> {
99public:
100 void SetNamePrefix(const Twine &P) {}
101};
102
Chandler Carruthd177f862013-03-20 07:30:36 +0000103/// \brief Provide a typedef for IRBuilder that drops names in release builds.
104#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000105typedef llvm::IRBuilder<true, ConstantFolder,
106 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000107#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000108typedef llvm::IRBuilder<false, ConstantFolder,
109 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000110#endif
111}
112
113namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000114/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000115///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000116/// This structure represents a slice of an alloca used by some instruction. It
117/// stores both the begin and end offsets of this use, a pointer to the use
118/// itself, and a flag indicating whether we can classify the use as splittable
119/// or not when forming partitions of the alloca.
120class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
123
124 /// \brief The ending offset, not included in the range.
125 uint64_t EndOffset;
126
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000127 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000128 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000130
131public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000136
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
139
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000142
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000144
145 bool isDead() const { return getUse() == 0; }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 void kill() { UseAndIsSplittable.setPointer(0); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000147
148 /// \brief Support for ordering ranges.
149 ///
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000155 if (beginOffset() < RHS.beginOffset()) return true;
156 if (beginOffset() > RHS.beginOffset()) return false;
157 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
158 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000159 return false;
160 }
161
162 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000163 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000164 uint64_t RHSOffset) {
165 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000169 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000170 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 return isSplittable() == RHS.isSplittable() &&
174 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000175 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000176 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000177};
Chandler Carruthf0546402013-07-18 07:15:00 +0000178} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000179
180namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000181template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000183 static const bool value = true;
184};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185}
186
187namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000188/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000189///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000190/// This class represents the slices of an alloca which are formed by its
191/// various uses. If a pointer escapes, we can't fully build a representation
192/// for the slices used and we reflect that in this structure. The uses are
193/// stored, sorted by increasing beginning offset and with unsplittable slices
194/// starting at a particular offset before splittable slices.
195class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000196public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000197 /// \brief Construct the slices of a particular alloca.
198 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000199
200 /// \brief Test whether a pointer to the allocation escapes our analysis.
201 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000202 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000203 /// ignored.
204 bool isEscaped() const { return PointerEscapingInstr; }
205
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000207 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000208 typedef SmallVectorImpl<Slice>::iterator iterator;
209 iterator begin() { return Slices.begin(); }
210 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000211
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
213 const_iterator begin() const { return Slices.begin(); }
214 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215 /// @}
216
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217 /// \brief Allow iterating the dead users for this alloca.
218 ///
219 /// These are instructions which will never actually use the alloca as they
220 /// are outside the allocated range. They are safe to replace with undef and
221 /// delete.
222 /// @{
223 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
224 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
225 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
226 /// @}
227
Chandler Carruth93a21e72012-09-14 10:18:49 +0000228 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000229 ///
230 /// These are operands which have cannot actually be used to refer to the
231 /// alloca as they are outside its range and the user doesn't correct for
232 /// that. These mostly consist of PHI node inputs and the like which we just
233 /// need to replace with undef.
234 /// @{
235 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
236 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
237 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
238 /// @}
239
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000240#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000241 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000242 void printSlice(raw_ostream &OS, const_iterator I,
243 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000244 void printUse(raw_ostream &OS, const_iterator I,
245 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000247 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
248 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000249#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250
251private:
252 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 class SliceBuilder;
254 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255
Chandler Carruthb7915f72012-11-20 10:23:07 +0000256#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000257 /// \brief Handle to alloca instruction to simplify method interfaces.
258 AllocaInst &AI;
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000259#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000260
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000261 /// \brief The instruction responsible for this alloca not having a known set
262 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263 ///
264 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000265 /// store a pointer to that here and abort trying to form slices of the
266 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267 Instruction *PointerEscapingInstr;
268
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000269 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000270 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000271 /// We store a vector of the slices formed by uses of the alloca here. This
272 /// vector is sorted by increasing begin offset, and then the unsplittable
273 /// slices before the splittable ones. See the Slice inner class for more
274 /// details.
275 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000277 /// \brief Instructions which will become dead if we rewrite the alloca.
278 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000279 /// Note that these are not separated by slice. This is because we expect an
280 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
281 /// all these instructions can simply be removed and replaced with undef as
282 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000283 SmallVector<Instruction *, 8> DeadUsers;
284
285 /// \brief Operands which will become dead if we rewrite the alloca.
286 ///
287 /// These are operands that in their particular use can be replaced with
288 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
289 /// to PHI nodes and the like. They aren't entirely dead (there might be
290 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
291 /// want to swap this particular input for undef to simplify the use lists of
292 /// the alloca.
293 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294};
295}
296
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000297static Value *foldSelectInst(SelectInst &SI) {
298 // If the condition being selected on is a constant or the same value is
299 // being selected between, fold the select. Yes this does (rarely) happen
300 // early on.
301 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
302 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000303 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000304 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000305
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000306 return 0;
307}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000309/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000310///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000311/// This class builds a set of alloca slices by recursively visiting the uses
312/// of an alloca and making a slice for each load and store at each offset.
313class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
314 friend class PtrUseVisitor<SliceBuilder>;
315 friend class InstVisitor<SliceBuilder>;
316 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000317
318 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000319 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000322 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
323
324 /// \brief Set to de-duplicate dead instructions found in the use walk.
325 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
327public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000328 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
329 : PtrUseVisitor<SliceBuilder>(DL),
330 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000331
332private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000333 void markAsDead(Instruction &I) {
334 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000335 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000336 }
337
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000338 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000339 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000340 // Completely skip uses which have a zero size or start either before or
341 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000342 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000344 << " which has zero size or starts outside of the "
345 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000346 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000347 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000348 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000349 }
350
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000351 uint64_t BeginOffset = Offset.getZExtValue();
352 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000353
354 // Clamp the end offset to the end of the allocation. Note that this is
355 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000356 // This may appear superficially to be something we could ignore entirely,
357 // but that is not so! There may be widened loads or PHI-node uses where
358 // some instructions are dead but not others. We can't completely ignore
359 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000360 assert(AllocSize >= BeginOffset); // Established above.
361 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000362 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
363 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000364 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000365 << " use: " << I << "\n");
366 EndOffset = AllocSize;
367 }
368
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000369 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000370 }
371
372 void visitBitCastInst(BitCastInst &BC) {
373 if (BC.use_empty())
374 return markAsDead(BC);
375
376 return Base::visitBitCastInst(BC);
377 }
378
379 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
380 if (GEPI.use_empty())
381 return markAsDead(GEPI);
382
383 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000384 }
385
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000386 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000387 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000388 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000389 // and cover the entire alloca. This prevents us from splitting over
390 // eagerly.
391 // FIXME: In the great blue eventually, we should eagerly split all integer
392 // loads and stores, and then have a separate step that merges adjacent
393 // alloca partitions into a single partition suitable for integer widening.
394 // Or we should skip the merge step and rely on GVN and other passes to
395 // merge adjacent loads and stores that survive mem2reg.
396 bool IsSplittable =
397 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000398
399 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000400 }
401
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000402 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000403 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
404 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000405
406 if (!IsOffsetKnown)
407 return PI.setAborted(&LI);
408
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000409 uint64_t Size = DL.getTypeStoreSize(LI.getType());
410 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000411 }
412
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000413 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000414 Value *ValOp = SI.getValueOperand();
415 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000416 return PI.setEscapedAndAborted(&SI);
417 if (!IsOffsetKnown)
418 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000419
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000420 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
421
422 // If this memory access can be shown to *statically* extend outside the
423 // bounds of of the allocation, it's behavior is undefined, so simply
424 // ignore it. Note that this is more strict than the generic clamping
425 // behavior of insertUse. We also try to handle cases which might run the
426 // risk of overflow.
427 // FIXME: We should instead consider the pointer to have escaped if this
428 // function is being instrumented for addressing bugs or race conditions.
429 if (Offset.isNegative() || Size > AllocSize ||
430 Offset.ugt(AllocSize - Size)) {
431 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
432 << " which extends past the end of the " << AllocSize
433 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000434 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000435 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000436 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000437 }
438
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000439 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
440 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000441 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000442 }
443
444
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000445 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000446 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000447 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000448 if ((Length && Length->getValue() == 0) ||
449 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
450 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000451 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000452
453 if (!IsOffsetKnown)
454 return PI.setAborted(&II);
455
456 insertUse(II, Offset,
457 Length ? Length->getLimitedValue()
458 : AllocSize - Offset.getLimitedValue(),
459 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000460 }
461
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000462 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000463 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000464 if ((Length && Length->getValue() == 0) ||
465 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000466 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000467 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000468
469 if (!IsOffsetKnown)
470 return PI.setAborted(&II);
471
472 uint64_t RawOffset = Offset.getLimitedValue();
473 uint64_t Size = Length ? Length->getLimitedValue()
474 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000475
Chandler Carruthf0546402013-07-18 07:15:00 +0000476 // Check for the special case where the same exact value is used for both
477 // source and dest.
478 if (*U == II.getRawDest() && *U == II.getRawSource()) {
479 // For non-volatile transfers this is a no-op.
480 if (!II.isVolatile())
481 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000482
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000483 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000484 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000485
Chandler Carruthf0546402013-07-18 07:15:00 +0000486 // If we have seen both source and destination for a mem transfer, then
487 // they both point to the same alloca.
488 bool Inserted;
489 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
490 llvm::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000491 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000492 unsigned PrevIdx = MTPI->second;
493 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000494 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000495
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000496 // Check if the begin offsets match and this is a non-volatile transfer.
497 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000498 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
499 PrevP.kill();
500 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000501 }
502
503 // Otherwise we have an offset transfer within the same alloca. We can't
504 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000505 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000506 }
507
Chandler Carruthe3899f22013-07-15 17:36:21 +0000508 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000509 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000510
Chandler Carruthf0546402013-07-18 07:15:00 +0000511 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000512 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
513 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000514 }
515
516 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000517 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000518 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000519 void visitIntrinsicInst(IntrinsicInst &II) {
520 if (!IsOffsetKnown)
521 return PI.setAborted(&II);
522
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000523 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
524 II.getIntrinsicID() == Intrinsic::lifetime_end) {
525 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000526 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
527 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000528 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000529 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000530 }
531
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000532 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000533 }
534
535 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
536 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000537 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000538 // are considered unsplittable and the size is the maximum loaded or stored
539 // size.
540 SmallPtrSet<Instruction *, 4> Visited;
541 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
542 Visited.insert(Root);
543 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000544 // If there are no loads or stores, the access is dead. We mark that as
545 // a size zero access.
546 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000547 do {
548 Instruction *I, *UsedI;
549 llvm::tie(UsedI, I) = Uses.pop_back_val();
550
551 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000552 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000553 continue;
554 }
555 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
556 Value *Op = SI->getOperand(0);
557 if (Op == UsedI)
558 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000559 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000560 continue;
561 }
562
563 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
564 if (!GEP->hasAllZeroIndices())
565 return GEP;
566 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
567 !isa<SelectInst>(I)) {
568 return I;
569 }
570
571 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
572 ++UI)
573 if (Visited.insert(cast<Instruction>(*UI)))
574 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
575 } while (!Uses.empty());
576
577 return 0;
578 }
579
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000580 void visitPHINode(PHINode &PN) {
581 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000582 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000583 if (!IsOffsetKnown)
584 return PI.setAborted(&PN);
585
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000586 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000587 uint64_t &PHISize = PHIOrSelectSizes[&PN];
588 if (!PHISize) {
589 // This is a new PHI node, check for an unsafe use of the PHI node.
590 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
591 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000592 }
593
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000594 // For PHI and select operands outside the alloca, we can't nuke the entire
595 // phi or select -- the other side might still be relevant, so we special
596 // case them here and use a separate structure to track the operands
597 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000598 // FIXME: This should instead be escaped in the event we're instrumenting
599 // for address sanitization.
600 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000601 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000602 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603 return;
604 }
605
Chandler Carruthf0546402013-07-18 07:15:00 +0000606 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000608
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000609 void visitSelectInst(SelectInst &SI) {
610 if (SI.use_empty())
611 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000612 if (Value *Result = foldSelectInst(SI)) {
613 if (Result == *U)
614 // If the result of the constant fold will be the pointer, recurse
615 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000616 enqueueUsers(SI);
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000617 else
618 // Otherwise the operand to the select is dead, and we can replace it
619 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000620 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000621
622 return;
623 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000624 if (!IsOffsetKnown)
625 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000626
Chandler Carruthf0546402013-07-18 07:15:00 +0000627 // See if we already have computed info on this node.
628 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
629 if (!SelectSize) {
630 // This is a new Select, check for an unsafe use of it.
631 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
632 return PI.setAborted(UnsafeI);
633 }
634
635 // For PHI and select operands outside the alloca, we can't nuke the entire
636 // phi or select -- the other side might still be relevant, so we special
637 // case them here and use a separate structure to track the operands
638 // themselves which should be replaced with undef.
639 // FIXME: This should instead be escaped in the event we're instrumenting
640 // for address sanitization.
641 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
642 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000643 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000644 return;
645 }
646
647 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000648 }
649
Chandler Carruthf0546402013-07-18 07:15:00 +0000650 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000651 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000652 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000653 }
654};
655
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000656AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000657 :
Chandler Carruthb7915f72012-11-20 10:23:07 +0000658#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000659 AI(AI),
660#endif
661 PointerEscapingInstr(0) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000662 SliceBuilder PB(DL, AI, *this);
663 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000664 if (PtrI.isEscaped() || PtrI.isAborted()) {
665 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000666 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000667 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
668 : PtrI.getAbortingInst();
669 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000670 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000671 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000672
Benjamin Kramer08e50702013-07-20 08:38:34 +0000673 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
674 std::mem_fun_ref(&Slice::isDead)),
675 Slices.end());
676
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000677 // Sort the uses. This arranges for the offsets to be in ascending order,
678 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000679 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000680}
681
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000682#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
683
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000684void AllocaSlices::print(raw_ostream &OS, const_iterator I,
685 StringRef Indent) const {
686 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000687 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000688}
689
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000690void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
691 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000693 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000694 << (I->isSplittable() ? " (splittable)" : "") << "\n";
695}
696
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000697void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
698 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000699 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000700}
701
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000702void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000703 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000704 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000705 << " A pointer to this alloca escaped by:\n"
706 << " " << *PointerEscapingInstr << "\n";
707 return;
708 }
709
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000710 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000711 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000712 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000713}
714
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000715void AllocaSlices::dump(const_iterator I) const { print(dbgs(), I); }
716void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000718#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
719
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000720namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000721/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
722///
723/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
724/// the loads and stores of an alloca instruction, as well as updating its
725/// debug information. This is used when a domtree is unavailable and thus
726/// mem2reg in its full form can't be used to handle promotion of allocas to
727/// scalar values.
728class AllocaPromoter : public LoadAndStorePromoter {
729 AllocaInst &AI;
730 DIBuilder &DIB;
731
732 SmallVector<DbgDeclareInst *, 4> DDIs;
733 SmallVector<DbgValueInst *, 4> DVIs;
734
735public:
736 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
737 AllocaInst &AI, DIBuilder &DIB)
738 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
739
740 void run(const SmallVectorImpl<Instruction*> &Insts) {
741 // Remember which alloca we're promoting (for isInstInList).
742 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
743 for (Value::use_iterator UI = DebugNode->use_begin(),
744 UE = DebugNode->use_end();
745 UI != UE; ++UI)
746 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
747 DDIs.push_back(DDI);
748 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
749 DVIs.push_back(DVI);
750 }
751
752 LoadAndStorePromoter::run(Insts);
753 AI.eraseFromParent();
754 while (!DDIs.empty())
755 DDIs.pop_back_val()->eraseFromParent();
756 while (!DVIs.empty())
757 DVIs.pop_back_val()->eraseFromParent();
758 }
759
760 virtual bool isInstInList(Instruction *I,
761 const SmallVectorImpl<Instruction*> &Insts) const {
762 if (LoadInst *LI = dyn_cast<LoadInst>(I))
763 return LI->getOperand(0) == &AI;
764 return cast<StoreInst>(I)->getPointerOperand() == &AI;
765 }
766
767 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000768 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000769 E = DDIs.end(); I != E; ++I) {
770 DbgDeclareInst *DDI = *I;
771 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
772 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
773 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
774 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
775 }
Craig Topper31ee5862013-07-03 15:07:05 +0000776 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000777 E = DVIs.end(); I != E; ++I) {
778 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000779 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000780 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
781 // If an argument is zero extended then use argument directly. The ZExt
782 // may be zapped by an optimization pass in future.
783 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
784 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000785 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000786 Arg = dyn_cast<Argument>(SExt->getOperand(0));
787 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000788 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000789 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000790 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000791 } else {
792 continue;
793 }
794 Instruction *DbgVal =
795 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
796 Inst);
797 DbgVal->setDebugLoc(DVI->getDebugLoc());
798 }
799 }
800};
801} // end anon namespace
802
803
804namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000805/// \brief An optimization pass providing Scalar Replacement of Aggregates.
806///
807/// This pass takes allocations which can be completely analyzed (that is, they
808/// don't escape) and tries to turn them into scalar SSA values. There are
809/// a few steps to this process.
810///
811/// 1) It takes allocations of aggregates and analyzes the ways in which they
812/// are used to try to split them into smaller allocations, ideally of
813/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000814/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000815/// 2) It will transform accesses into forms which are suitable for SSA value
816/// promotion. This can be replacing a memset with a scalar store of an
817/// integer value, or it can involve speculating operations on a PHI or
818/// select to be a PHI or select of the results.
819/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
820/// onto insert and extract operations on a vector value, and convert them to
821/// this form. By doing so, it will enable promotion of vector aggregates to
822/// SSA vector values.
823class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000824 const bool RequiresDomTree;
825
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000826 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000827 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000828 DominatorTree *DT;
829
830 /// \brief Worklist of alloca instructions to simplify.
831 ///
832 /// Each alloca in the function is added to this. Each new alloca formed gets
833 /// added to it as well to recursively simplify unless that alloca can be
834 /// directly promoted. Finally, each time we rewrite a use of an alloca other
835 /// the one being actively rewritten, we add it back onto the list if not
836 /// already present to ensure it is re-visited.
837 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
838
839 /// \brief A collection of instructions to delete.
840 /// We try to batch deletions to simplify code and make things a bit more
841 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000842 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000843
Chandler Carruthac8317f2012-10-04 12:33:50 +0000844 /// \brief Post-promotion worklist.
845 ///
846 /// Sometimes we discover an alloca which has a high probability of becoming
847 /// viable for SROA after a round of promotion takes place. In those cases,
848 /// the alloca is enqueued here for re-processing.
849 ///
850 /// Note that we have to be very careful to clear allocas out of this list in
851 /// the event they are deleted.
852 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
853
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000854 /// \brief A collection of alloca instructions we can directly promote.
855 std::vector<AllocaInst *> PromotableAllocas;
856
Chandler Carruthf0546402013-07-18 07:15:00 +0000857 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
858 ///
859 /// All of these PHIs have been checked for the safety of speculation and by
860 /// being speculated will allow promoting allocas currently in the promotable
861 /// queue.
862 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
863
864 /// \brief A worklist of select instructions to speculate prior to promoting
865 /// allocas.
866 ///
867 /// All of these select instructions have been checked for the safety of
868 /// speculation and by being speculated will allow promoting allocas
869 /// currently in the promotable queue.
870 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
871
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000872public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000873 SROA(bool RequiresDomTree = true)
874 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000875 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000876 initializeSROAPass(*PassRegistry::getPassRegistry());
877 }
878 bool runOnFunction(Function &F);
879 void getAnalysisUsage(AnalysisUsage &AU) const;
880
881 const char *getPassName() const { return "SROA"; }
882 static char ID;
883
884private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000885 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000886 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000887
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000888 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
889 AllocaSlices::iterator B, AllocaSlices::iterator E,
890 int64_t BeginOffset, int64_t EndOffset,
891 ArrayRef<AllocaSlices::iterator> SplitUses);
892 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000893 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +0000894 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000895 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000896};
897}
898
899char SROA::ID = 0;
900
Chandler Carruth70b44c52012-09-15 11:43:14 +0000901FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
902 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000903}
904
905INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
906 false, false)
907INITIALIZE_PASS_DEPENDENCY(DominatorTree)
908INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
909 false, false)
910
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000911/// Walk the range of a partitioning looking for a common type to cover this
912/// sequence of slices.
913static Type *findCommonType(AllocaSlices::const_iterator B,
914 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000915 uint64_t EndOffset) {
916 Type *Ty = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000917 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000918 Use *U = I->getUse();
919 if (isa<IntrinsicInst>(*U->getUser()))
920 continue;
921 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
922 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000923
Chandler Carruthf0546402013-07-18 07:15:00 +0000924 Type *UserTy = 0;
925 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
926 UserTy = LI->getType();
927 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
928 UserTy = SI->getValueOperand()->getType();
929 else
930 return 0; // Bail if we have weird uses.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000931
Chandler Carruthf0546402013-07-18 07:15:00 +0000932 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
933 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000934 // this for split integer operations where we want to use the type of the
Chandler Carruthf0546402013-07-18 07:15:00 +0000935 // entity causing the split.
936 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
937 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000938
Chandler Carruthf0546402013-07-18 07:15:00 +0000939 // If we have found an integer type use covering the alloca, use that
940 // regardless of the other types, as integers are often used for a
941 // "bucket
942 // of bits" type.
943 return ITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000944 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000945
946 if (Ty && Ty != UserTy)
947 return 0;
948
949 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000950 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000951 return Ty;
952}
Chandler Carruthe3899f22013-07-15 17:36:21 +0000953
Chandler Carruthf0546402013-07-18 07:15:00 +0000954/// PHI instructions that use an alloca and are subsequently loaded can be
955/// rewritten to load both input pointers in the pred blocks and then PHI the
956/// results, allowing the load of the alloca to be promoted.
957/// From this:
958/// %P2 = phi [i32* %Alloca, i32* %Other]
959/// %V = load i32* %P2
960/// to:
961/// %V1 = load i32* %Alloca -> will be mem2reg'd
962/// ...
963/// %V2 = load i32* %Other
964/// ...
965/// %V = phi [i32 %V1, i32 %V2]
966///
967/// We can do this to a select if its only uses are loads and if the operands
968/// to the select can be loaded unconditionally.
969///
970/// FIXME: This should be hoisted into a generic utility, likely in
971/// Transforms/Util/Local.h
972static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +0000973 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000974 // For now, we can only do this promotion if the load is in the same block
975 // as the PHI, and if there are no stores between the phi and load.
976 // TODO: Allow recursive phi users.
977 // TODO: Allow stores.
978 BasicBlock *BB = PN.getParent();
979 unsigned MaxAlign = 0;
980 bool HaveLoad = false;
981 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
982 ++UI) {
983 LoadInst *LI = dyn_cast<LoadInst>(*UI);
984 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000985 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000986
Chandler Carruthf0546402013-07-18 07:15:00 +0000987 // For now we only allow loads in the same block as the PHI. This is
988 // a common case that happens when instcombine merges two loads through
989 // a PHI.
990 if (LI->getParent() != BB)
991 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000992
Chandler Carruthf0546402013-07-18 07:15:00 +0000993 // Ensure that there are no instructions between the PHI and the load that
994 // could store.
995 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
996 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +0000997 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000998
Chandler Carruthf0546402013-07-18 07:15:00 +0000999 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1000 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001001 }
1002
Chandler Carruthf0546402013-07-18 07:15:00 +00001003 if (!HaveLoad)
1004 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001005
Chandler Carruthf0546402013-07-18 07:15:00 +00001006 // We can only transform this if it is safe to push the loads into the
1007 // predecessor blocks. The only thing to watch out for is that we can't put
1008 // a possibly trapping load in the predecessor if it is a critical edge.
1009 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1010 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1011 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001012
Chandler Carruthf0546402013-07-18 07:15:00 +00001013 // If the value is produced by the terminator of the predecessor (an
1014 // invoke) or it has side-effects, there is no valid place to put a load
1015 // in the predecessor.
1016 if (TI == InVal || TI->mayHaveSideEffects())
1017 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001018
Chandler Carruthf0546402013-07-18 07:15:00 +00001019 // If the predecessor has a single successor, then the edge isn't
1020 // critical.
1021 if (TI->getNumSuccessors() == 1)
1022 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001023
Chandler Carruthf0546402013-07-18 07:15:00 +00001024 // If this pointer is always safe to load, or if we can prove that there
1025 // is already a load in the block, then we can move the load to the pred
1026 // block.
1027 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001028 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001029 continue;
1030
1031 return false;
1032 }
1033
1034 return true;
1035}
1036
1037static void speculatePHINodeLoads(PHINode &PN) {
1038 DEBUG(dbgs() << " original: " << PN << "\n");
1039
1040 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1041 IRBuilderTy PHIBuilder(&PN);
1042 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1043 PN.getName() + ".sroa.speculated");
1044
1045 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1046 // matter which one we get and if any differ.
1047 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1048 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1049 unsigned Align = SomeLoad->getAlignment();
1050
1051 // Rewrite all loads of the PN to use the new PHI.
1052 while (!PN.use_empty()) {
1053 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1054 LI->replaceAllUsesWith(NewPN);
1055 LI->eraseFromParent();
1056 }
1057
1058 // Inject loads into all of the pred blocks.
1059 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1060 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1061 TerminatorInst *TI = Pred->getTerminator();
1062 Value *InVal = PN.getIncomingValue(Idx);
1063 IRBuilderTy PredBuilder(TI);
1064
1065 LoadInst *Load = PredBuilder.CreateLoad(
1066 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1067 ++NumLoadsSpeculated;
1068 Load->setAlignment(Align);
1069 if (TBAATag)
1070 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1071 NewPN->addIncoming(Load, Pred);
1072 }
1073
1074 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1075 PN.eraseFromParent();
1076}
1077
1078/// Select instructions that use an alloca and are subsequently loaded can be
1079/// rewritten to load both input pointers and then select between the result,
1080/// allowing the load of the alloca to be promoted.
1081/// From this:
1082/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1083/// %V = load i32* %P2
1084/// to:
1085/// %V1 = load i32* %Alloca -> will be mem2reg'd
1086/// %V2 = load i32* %Other
1087/// %V = select i1 %cond, i32 %V1, i32 %V2
1088///
1089/// We can do this to a select if its only uses are loads and if the operand
1090/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001091static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001092 Value *TValue = SI.getTrueValue();
1093 Value *FValue = SI.getFalseValue();
1094 bool TDerefable = TValue->isDereferenceablePointer();
1095 bool FDerefable = FValue->isDereferenceablePointer();
1096
1097 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1098 ++UI) {
1099 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1100 if (LI == 0 || !LI->isSimple())
1101 return false;
1102
1103 // Both operands to the select need to be dereferencable, either
1104 // absolutely (e.g. allocas) or at this point because we can see other
1105 // accesses to it.
1106 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001107 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001108 return false;
1109 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001110 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001111 return false;
1112 }
1113
1114 return true;
1115}
1116
1117static void speculateSelectInstLoads(SelectInst &SI) {
1118 DEBUG(dbgs() << " original: " << SI << "\n");
1119
1120 IRBuilderTy IRB(&SI);
1121 Value *TV = SI.getTrueValue();
1122 Value *FV = SI.getFalseValue();
1123 // Replace the loads of the select with a select of two loads.
1124 while (!SI.use_empty()) {
1125 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1126 assert(LI->isSimple() && "We only speculate simple loads");
1127
1128 IRB.SetInsertPoint(LI);
1129 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001130 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001131 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001132 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001133 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001134
Chandler Carruthf0546402013-07-18 07:15:00 +00001135 // Transfer alignment and TBAA info if present.
1136 TL->setAlignment(LI->getAlignment());
1137 FL->setAlignment(LI->getAlignment());
1138 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1139 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1140 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001141 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001142
1143 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1144 LI->getName() + ".sroa.speculated");
1145
1146 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1147 LI->replaceAllUsesWith(V);
1148 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001149 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001150 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001151}
1152
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001153/// \brief Build a GEP out of a base pointer and indices.
1154///
1155/// This will return the BasePtr if that is valid, or build a new GEP
1156/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001157static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001158 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001159 if (Indices.empty())
1160 return BasePtr;
1161
1162 // A single zero index is a no-op, so check for this and avoid building a GEP
1163 // in that case.
1164 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1165 return BasePtr;
1166
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001167 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001168}
1169
1170/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1171/// TargetTy without changing the offset of the pointer.
1172///
1173/// This routine assumes we've already established a properly offset GEP with
1174/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1175/// zero-indices down through type layers until we find one the same as
1176/// TargetTy. If we can't find one with the same type, we at least try to use
1177/// one with the same size. If none of that works, we just produce the GEP as
1178/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001179static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001180 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001181 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001182 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001183 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001184
1185 // See if we can descend into a struct and locate a field with the correct
1186 // type.
1187 unsigned NumLayers = 0;
1188 Type *ElementTy = Ty;
1189 do {
1190 if (ElementTy->isPointerTy())
1191 break;
1192 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1193 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001194 // Note that we use the default address space as this index is over an
1195 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001196 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001197 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001198 if (STy->element_begin() == STy->element_end())
1199 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001200 ElementTy = *STy->element_begin();
1201 Indices.push_back(IRB.getInt32(0));
1202 } else {
1203 break;
1204 }
1205 ++NumLayers;
1206 } while (ElementTy != TargetTy);
1207 if (ElementTy != TargetTy)
1208 Indices.erase(Indices.end() - NumLayers, Indices.end());
1209
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001210 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001211}
1212
1213/// \brief Recursively compute indices for a natural GEP.
1214///
1215/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1216/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001217static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001218 Value *Ptr, Type *Ty, APInt &Offset,
1219 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001220 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001221 if (Offset == 0)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001222 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001223
1224 // We can't recurse through pointer types.
1225 if (Ty->isPointerTy())
1226 return 0;
1227
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001228 // We try to analyze GEPs over vectors here, but note that these GEPs are
1229 // extremely poorly defined currently. The long-term goal is to remove GEPing
1230 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001231 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001232 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001233 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001234 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001235 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001236 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001237 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1238 return 0;
1239 Offset -= NumSkippedElements * ElementSize;
1240 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001241 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001242 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001243 }
1244
1245 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1246 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001247 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001248 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001249 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1250 return 0;
1251
1252 Offset -= NumSkippedElements * ElementSize;
1253 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001254 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001255 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001256 }
1257
1258 StructType *STy = dyn_cast<StructType>(Ty);
1259 if (!STy)
1260 return 0;
1261
Chandler Carruth90a735d2013-07-19 07:21:28 +00001262 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001263 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001264 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001265 return 0;
1266 unsigned Index = SL->getElementContainingOffset(StructOffset);
1267 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1268 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001269 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001270 return 0; // The offset points into alignment padding.
1271
1272 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001273 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001274 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001275}
1276
1277/// \brief Get a natural GEP from a base pointer to a particular offset and
1278/// resulting in a particular type.
1279///
1280/// The goal is to produce a "natural" looking GEP that works with the existing
1281/// composite types to arrive at the appropriate offset and element type for
1282/// a pointer. TargetTy is the element type the returned GEP should point-to if
1283/// possible. We recurse by decreasing Offset, adding the appropriate index to
1284/// Indices, and setting Ty to the result subtype.
1285///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001286/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001287static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001288 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001289 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001290 PointerType *Ty = cast<PointerType>(Ptr->getType());
1291
1292 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1293 // an i8.
1294 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1295 return 0;
1296
1297 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001298 if (!ElementTy->isSized())
1299 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001300 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001301 if (ElementSize == 0)
1302 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001303 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001304
1305 Offset -= NumSkippedElements * ElementSize;
1306 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001307 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001308 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001309}
1310
1311/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1312/// resulting pointer has PointerTy.
1313///
1314/// This tries very hard to compute a "natural" GEP which arrives at the offset
1315/// and produces the pointer type desired. Where it cannot, it will try to use
1316/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1317/// fails, it will try to use an existing i8* and GEP to the byte offset and
1318/// bitcast to the type.
1319///
1320/// The strategy for finding the more natural GEPs is to peel off layers of the
1321/// pointer, walking back through bit casts and GEPs, searching for a base
1322/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001323/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001324/// a single GEP as possible, thus making each GEP more independent of the
1325/// surrounding code.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001326static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001327 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001328 // Even though we don't look through PHI nodes, we could be called on an
1329 // instruction in an unreachable block, which may be on a cycle.
1330 SmallPtrSet<Value *, 4> Visited;
1331 Visited.insert(Ptr);
1332 SmallVector<Value *, 4> Indices;
1333
1334 // We may end up computing an offset pointer that has the wrong type. If we
1335 // never are able to compute one directly that has the correct type, we'll
1336 // fall back to it, so keep it around here.
1337 Value *OffsetPtr = 0;
1338
1339 // Remember any i8 pointer we come across to re-use if we need to do a raw
1340 // byte offset.
1341 Value *Int8Ptr = 0;
1342 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1343
1344 Type *TargetTy = PointerTy->getPointerElementType();
1345
1346 do {
1347 // First fold any existing GEPs into the offset.
1348 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1349 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001350 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001351 break;
1352 Offset += GEPOffset;
1353 Ptr = GEP->getPointerOperand();
1354 if (!Visited.insert(Ptr))
1355 break;
1356 }
1357
1358 // See if we can perform a natural GEP here.
1359 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001360 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001361 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001362 if (P->getType() == PointerTy) {
1363 // Zap any offset pointer that we ended up computing in previous rounds.
1364 if (OffsetPtr && OffsetPtr->use_empty())
1365 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1366 I->eraseFromParent();
1367 return P;
1368 }
1369 if (!OffsetPtr) {
1370 OffsetPtr = P;
1371 }
1372 }
1373
1374 // Stash this pointer if we've found an i8*.
1375 if (Ptr->getType()->isIntegerTy(8)) {
1376 Int8Ptr = Ptr;
1377 Int8PtrOffset = Offset;
1378 }
1379
1380 // Peel off a layer of the pointer and update the offset appropriately.
1381 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1382 Ptr = cast<Operator>(Ptr)->getOperand(0);
1383 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1384 if (GA->mayBeOverridden())
1385 break;
1386 Ptr = GA->getAliasee();
1387 } else {
1388 break;
1389 }
1390 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1391 } while (Visited.insert(Ptr));
1392
1393 if (!OffsetPtr) {
1394 if (!Int8Ptr) {
1395 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001396 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 Int8PtrOffset = Offset;
1398 }
1399
1400 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1401 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001402 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001403 }
1404 Ptr = OffsetPtr;
1405
1406 // On the off chance we were targeting i8*, guard the bitcast here.
1407 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001408 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001409
1410 return Ptr;
1411}
1412
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001413/// \brief Test whether we can convert a value from the old to the new type.
1414///
1415/// This predicate should be used to guard calls to convertValue in order to
1416/// ensure that we only try to convert viable values. The strategy is that we
1417/// will peel off single element struct and array wrappings to get to an
1418/// underlying value, and convert that value.
1419static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1420 if (OldTy == NewTy)
1421 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001422 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1423 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1424 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1425 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001426 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1427 return false;
1428 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1429 return false;
1430
1431 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1432 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1433 return true;
1434 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1435 return true;
1436 return false;
1437 }
1438
1439 return true;
1440}
1441
1442/// \brief Generic routine to convert an SSA value to a value of a different
1443/// type.
1444///
1445/// This will try various different casting techniques, such as bitcasts,
1446/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1447/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001448static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001449 Type *Ty) {
1450 assert(canConvertValue(DL, V->getType(), Ty) &&
1451 "Value not convertable to type");
1452 if (V->getType() == Ty)
1453 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001454 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1455 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1456 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1457 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001458 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1459 return IRB.CreateIntToPtr(V, Ty);
1460 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1461 return IRB.CreatePtrToInt(V, Ty);
1462
1463 return IRB.CreateBitCast(V, Ty);
1464}
1465
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001466/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001467///
1468/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001469/// for a single slice.
1470static bool isVectorPromotionViableForSlice(
1471 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1472 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1473 AllocaSlices::const_iterator I) {
1474 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001475 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001476 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001477 uint64_t BeginIndex = BeginOffset / ElementSize;
1478 if (BeginIndex * ElementSize != BeginOffset ||
1479 BeginIndex >= Ty->getNumElements())
1480 return false;
1481 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001482 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001483 uint64_t EndIndex = EndOffset / ElementSize;
1484 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1485 return false;
1486
1487 assert(EndIndex > BeginIndex && "Empty vector!");
1488 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001489 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001490 (NumElements == 1) ? Ty->getElementType()
1491 : VectorType::get(Ty->getElementType(), NumElements);
1492
1493 Type *SplitIntTy =
1494 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1495
1496 Use *U = I->getUse();
1497
1498 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1499 if (MI->isVolatile())
1500 return false;
1501 if (!I->isSplittable())
1502 return false; // Skip any unsplittable intrinsics.
1503 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1504 // Disable vector promotion when there are loads or stores of an FCA.
1505 return false;
1506 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1507 if (LI->isVolatile())
1508 return false;
1509 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001510 if (SliceBeginOffset > I->beginOffset() ||
1511 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001512 assert(LTy->isIntegerTy());
1513 LTy = SplitIntTy;
1514 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001515 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001516 return false;
1517 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1518 if (SI->isVolatile())
1519 return false;
1520 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001521 if (SliceBeginOffset > I->beginOffset() ||
1522 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001523 assert(STy->isIntegerTy());
1524 STy = SplitIntTy;
1525 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001526 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001527 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001528 } else {
1529 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001530 }
1531
1532 return true;
1533}
1534
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001535/// \brief Test whether the given alloca partitioning and range of slices can be
1536/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001537///
1538/// This is a quick test to check whether we can rewrite a particular alloca
1539/// partition (and its newly formed alloca) into a vector alloca with only
1540/// whole-vector loads and stores such that it could be promoted to a vector
1541/// SSA value. We only can ensure this for a limited set of operations, and we
1542/// don't want to do the rewrites unless we are confident that the result will
1543/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001544static bool
1545isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1546 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1547 AllocaSlices::const_iterator I,
1548 AllocaSlices::const_iterator E,
1549 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001550 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1551 if (!Ty)
1552 return false;
1553
Chandler Carruth90a735d2013-07-19 07:21:28 +00001554 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001555
1556 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1557 // that aren't byte sized.
1558 if (ElementSize % 8)
1559 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001560 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001561 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001562 ElementSize /= 8;
1563
Chandler Carruthf0546402013-07-18 07:15:00 +00001564 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001565 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1566 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001567 return false;
1568
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001569 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1570 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001571 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001572 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1573 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001574 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001575
1576 return true;
1577}
1578
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001579/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001580///
1581/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001582/// test below on a single slice of the alloca.
1583static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1584 Type *AllocaTy,
1585 uint64_t AllocBeginOffset,
1586 uint64_t Size, AllocaSlices &S,
1587 AllocaSlices::const_iterator I,
1588 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001589 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1590 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1591
1592 // We can't reasonably handle cases where the load or store extends past
1593 // the end of the aloca's type and into its padding.
1594 if (RelEnd > Size)
1595 return false;
1596
1597 Use *U = I->getUse();
1598
1599 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1600 if (LI->isVolatile())
1601 return false;
1602 if (RelBegin == 0 && RelEnd == Size)
1603 WholeAllocaOp = true;
1604 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001605 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001606 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001607 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001608 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001609 // Non-integer loads need to be convertible from the alloca type so that
1610 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001611 return false;
1612 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001613 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1614 Type *ValueTy = SI->getValueOperand()->getType();
1615 if (SI->isVolatile())
1616 return false;
1617 if (RelBegin == 0 && RelEnd == Size)
1618 WholeAllocaOp = true;
1619 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001620 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001621 return false;
1622 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001623 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001624 // Non-integer stores need to be convertible to the alloca type so that
1625 // they are promotable.
1626 return false;
1627 }
1628 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1629 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1630 return false;
1631 if (!I->isSplittable())
1632 return false; // Skip any unsplittable intrinsics.
1633 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1634 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1635 II->getIntrinsicID() != Intrinsic::lifetime_end)
1636 return false;
1637 } else {
1638 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001639 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001640
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001641 return true;
1642}
1643
Chandler Carruth435c4e02012-10-15 08:40:30 +00001644/// \brief Test whether the given alloca partition's integer operations can be
1645/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001646///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001647/// This is a quick test to check whether we can rewrite the integer loads and
1648/// stores to a particular alloca into wider loads and stores and be able to
1649/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001650static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001651isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001652 uint64_t AllocBeginOffset, AllocaSlices &S,
1653 AllocaSlices::const_iterator I,
1654 AllocaSlices::const_iterator E,
1655 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001656 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001657 // Don't create integer types larger than the maximum bitwidth.
1658 if (SizeInBits > IntegerType::MAX_INT_BITS)
1659 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001660
1661 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001662 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001663 return false;
1664
Chandler Carruth58d05562012-10-25 04:37:07 +00001665 // We need to ensure that an integer type with the appropriate bitwidth can
1666 // be converted to the alloca type, whatever that is. We don't want to force
1667 // the alloca itself to have an integer type if there is a more suitable one.
1668 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001669 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1670 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001671 return false;
1672
Chandler Carruth90a735d2013-07-19 07:21:28 +00001673 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001674
Chandler Carruthf0546402013-07-18 07:15:00 +00001675 // While examining uses, we ensure that the alloca has a covering load or
1676 // store. We don't want to widen the integer operations only to fail to
1677 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001678 // later). However, if there are only splittable uses, go ahead and assume
1679 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001680 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001681
Chandler Carruthf0546402013-07-18 07:15:00 +00001682 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001683 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1684 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001685 return false;
1686
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001687 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1688 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001689 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001690 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1691 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001692 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001693
Chandler Carruth92924fd2012-09-24 00:34:20 +00001694 return WholeAllocaOp;
1695}
1696
Chandler Carruthd177f862013-03-20 07:30:36 +00001697static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001698 IntegerType *Ty, uint64_t Offset,
1699 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001700 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001701 IntegerType *IntTy = cast<IntegerType>(V->getType());
1702 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1703 "Element extends past full value");
1704 uint64_t ShAmt = 8*Offset;
1705 if (DL.isBigEndian())
1706 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001707 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001708 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001709 DEBUG(dbgs() << " shifted: " << *V << "\n");
1710 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001711 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1712 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001713 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001714 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001715 DEBUG(dbgs() << " trunced: " << *V << "\n");
1716 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001717 return V;
1718}
1719
Chandler Carruthd177f862013-03-20 07:30:36 +00001720static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001721 Value *V, uint64_t Offset, const Twine &Name) {
1722 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1723 IntegerType *Ty = cast<IntegerType>(V->getType());
1724 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1725 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001726 DEBUG(dbgs() << " start: " << *V << "\n");
1727 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001728 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001729 DEBUG(dbgs() << " extended: " << *V << "\n");
1730 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001731 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1732 "Element store outside of alloca store");
1733 uint64_t ShAmt = 8*Offset;
1734 if (DL.isBigEndian())
1735 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001736 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001737 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001738 DEBUG(dbgs() << " shifted: " << *V << "\n");
1739 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001740
1741 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1742 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1743 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001744 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001745 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001746 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001747 }
1748 return V;
1749}
1750
Chandler Carruthd177f862013-03-20 07:30:36 +00001751static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001752 unsigned BeginIndex, unsigned EndIndex,
1753 const Twine &Name) {
1754 VectorType *VecTy = cast<VectorType>(V->getType());
1755 unsigned NumElements = EndIndex - BeginIndex;
1756 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1757
1758 if (NumElements == VecTy->getNumElements())
1759 return V;
1760
1761 if (NumElements == 1) {
1762 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1763 Name + ".extract");
1764 DEBUG(dbgs() << " extract: " << *V << "\n");
1765 return V;
1766 }
1767
1768 SmallVector<Constant*, 8> Mask;
1769 Mask.reserve(NumElements);
1770 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1771 Mask.push_back(IRB.getInt32(i));
1772 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1773 ConstantVector::get(Mask),
1774 Name + ".extract");
1775 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1776 return V;
1777}
1778
Chandler Carruthd177f862013-03-20 07:30:36 +00001779static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001780 unsigned BeginIndex, const Twine &Name) {
1781 VectorType *VecTy = cast<VectorType>(Old->getType());
1782 assert(VecTy && "Can only insert a vector into a vector");
1783
1784 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1785 if (!Ty) {
1786 // Single element to insert.
1787 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1788 Name + ".insert");
1789 DEBUG(dbgs() << " insert: " << *V << "\n");
1790 return V;
1791 }
1792
1793 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1794 "Too many elements!");
1795 if (Ty->getNumElements() == VecTy->getNumElements()) {
1796 assert(V->getType() == VecTy && "Vector type mismatch");
1797 return V;
1798 }
1799 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1800
1801 // When inserting a smaller vector into the larger to store, we first
1802 // use a shuffle vector to widen it with undef elements, and then
1803 // a second shuffle vector to select between the loaded vector and the
1804 // incoming vector.
1805 SmallVector<Constant*, 8> Mask;
1806 Mask.reserve(VecTy->getNumElements());
1807 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1808 if (i >= BeginIndex && i < EndIndex)
1809 Mask.push_back(IRB.getInt32(i - BeginIndex));
1810 else
1811 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1812 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1813 ConstantVector::get(Mask),
1814 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001815 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001816
1817 Mask.clear();
1818 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001819 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1820
1821 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1822
1823 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001824 return V;
1825}
1826
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001827namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001828/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1829/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001830///
1831/// Also implements the rewriting to vector-based accesses when the partition
1832/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1833/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001834class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001835 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001836 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1837 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001838
Chandler Carruth90a735d2013-07-19 07:21:28 +00001839 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001840 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001841 SROA &Pass;
1842 AllocaInst &OldAI, &NewAI;
1843 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001844 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001845
1846 // If we are rewriting an alloca partition which can be written as pure
1847 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001848 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001849 // - The new alloca is exactly the size of the vector type here.
1850 // - The accesses all either map to the entire vector or to a single
1851 // element.
1852 // - The set of accessing instructions is only one of those handled above
1853 // in isVectorPromotionViable. Generally these are the same access kinds
1854 // which are promotable via mem2reg.
1855 VectorType *VecTy;
1856 Type *ElementTy;
1857 uint64_t ElementSize;
1858
Chandler Carruth92924fd2012-09-24 00:34:20 +00001859 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001860 // alloca's integer operations should be widened to this integer type due to
1861 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001862 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001863 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001864
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001865 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001866 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001867 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001868 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001869 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001870 Instruction *OldPtr;
1871
Chandler Carruth83ea1952013-07-24 09:47:28 +00001872 // Output members carrying state about the result of visiting and rewriting
1873 // the slice of the alloca.
1874 bool IsUsedByRewrittenSpeculatableInstructions;
1875
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001876 // Utility IR builder, whose name prefix is setup for each visited use, and
1877 // the insertion point is set to point to the user.
1878 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001879
1880public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001881 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1882 AllocaInst &OldAI, AllocaInst &NewAI,
1883 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1884 bool IsVectorPromotable = false,
1885 bool IsIntegerPromotable = false)
1886 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001887 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1888 NewAllocaTy(NewAI.getAllocatedType()),
1889 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1890 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001891 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00001892 IntTy(IsIntegerPromotable
1893 ? Type::getIntNTy(
1894 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001895 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001896 : 0),
1897 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth83ea1952013-07-24 09:47:28 +00001898 OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1899 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001900 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001901 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00001902 "Only multiple-of-8 sized vector elements are viable");
1903 ++NumVectorized;
1904 }
1905 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1906 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001907 }
1908
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001909 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001910 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00001911 BeginOffset = I->beginOffset();
1912 EndOffset = I->endOffset();
1913 IsSplittable = I->isSplittable();
1914 IsSplit =
1915 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001916
Chandler Carruthf0546402013-07-18 07:15:00 +00001917 OldUse = I->getUse();
1918 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001919
Chandler Carruthf0546402013-07-18 07:15:00 +00001920 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1921 IRB.SetInsertPoint(OldUserI);
1922 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1923 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1924
1925 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1926 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001927 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001928 return CanSROA;
1929 }
1930
Chandler Carruth83ea1952013-07-24 09:47:28 +00001931 /// \brief Query whether this slice is used by speculatable instructions after
1932 /// rewriting.
1933 ///
1934 /// These instructions (PHIs and Selects currently) require the alloca slice
1935 /// to run back through the rewriter. Thus, they are promotable, but not on
1936 /// this iteration. This is distinct from a slice which is unpromotable for
1937 /// some other reason, in which case we don't even want to perform the
1938 /// speculation. This can be querried at any time and reflects whether (at
1939 /// that point) a visit call has rewritten a speculatable instruction on the
1940 /// current slice.
1941 bool isUsedByRewrittenSpeculatableInstructions() const {
1942 return IsUsedByRewrittenSpeculatableInstructions;
1943 }
1944
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001945private:
Chandler Carruthf0546402013-07-18 07:15:00 +00001946 // Make sure the other visit overloads are visible.
1947 using Base::visit;
1948
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001949 // Every instruction which can end up as a user must have a rewrite rule.
1950 bool visitInstruction(Instruction &I) {
1951 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1952 llvm_unreachable("No rewrite rule for this instruction!");
1953 }
1954
Chandler Carruthf0546402013-07-18 07:15:00 +00001955 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
1956 Type *PointerTy) {
1957 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001958 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00001959 Offset - NewAllocaBeginOffset),
1960 PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001961 }
1962
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001963 /// \brief Compute suitable alignment to access an offset into the new alloca.
1964 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00001965 unsigned NewAIAlign = NewAI.getAlignment();
1966 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001967 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00001968 return MinAlign(NewAIAlign, Offset);
1969 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001970
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001971 /// \brief Compute suitable alignment to access a type at an offset of the
1972 /// new alloca.
1973 ///
1974 /// \returns zero if the type's ABI alignment is a suitable alignment,
1975 /// otherwise returns the maximal suitable alignment.
1976 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
1977 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001978 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001979 }
1980
Chandler Carruth845b73c2012-11-21 08:16:30 +00001981 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001982 assert(VecTy && "Can only call getIndex when rewriting a vector");
1983 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1984 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1985 uint32_t Index = RelOffset / ElementSize;
1986 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00001987 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001988 }
1989
1990 void deleteIfTriviallyDead(Value *V) {
1991 Instruction *I = cast<Instruction>(V);
1992 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00001993 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001994 }
1995
Chandler Carruthf0546402013-07-18 07:15:00 +00001996 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
1997 uint64_t NewEndOffset) {
1998 unsigned BeginIndex = getIndex(NewBeginOffset);
1999 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002000 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002001
2002 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002003 "load");
2004 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002005 }
2006
Chandler Carruthf0546402013-07-18 07:15:00 +00002007 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2008 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002009 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002010 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002011 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002012 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002013 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002014 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2015 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2016 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002017 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002018 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002019 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002020 }
2021
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002022 bool visitLoadInst(LoadInst &LI) {
2023 DEBUG(dbgs() << " original: " << LI << "\n");
2024 Value *OldOp = LI.getOperand(0);
2025 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002026
Chandler Carruthf0546402013-07-18 07:15:00 +00002027 // Compute the intersecting offset range.
2028 assert(BeginOffset < NewAllocaEndOffset);
2029 assert(EndOffset > NewAllocaBeginOffset);
2030 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2031 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2032
2033 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002034
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002035 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2036 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002037 bool IsPtrAdjusted = false;
2038 Value *V;
2039 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002040 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002041 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002042 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2043 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002044 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002045 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002046 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002047 } else {
2048 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002049 V = IRB.CreateAlignedLoad(
2050 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2051 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2052 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002053 IsPtrAdjusted = true;
2054 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002055 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002056
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002057 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002058 assert(!LI.isVolatile());
2059 assert(LI.getType()->isIntegerTy() &&
2060 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002061 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002062 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002063 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002064 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002065 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002066 // Move the insertion point just past the load so that we can refer to it.
2067 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002068 // Create a placeholder value with the same type as LI to use as the
2069 // basis for the new value. This allows us to replace the uses of LI with
2070 // the computed value, and then replace the placeholder with LI, leaving
2071 // LI only used for this computation.
2072 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002073 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002074 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002075 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002076 LI.replaceAllUsesWith(V);
2077 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002078 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002079 } else {
2080 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002081 }
2082
Chandler Carruth18db7952012-11-20 01:12:50 +00002083 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002084 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002085 DEBUG(dbgs() << " to: " << *V << "\n");
2086 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002087 }
2088
Chandler Carruthf0546402013-07-18 07:15:00 +00002089 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2090 uint64_t NewBeginOffset,
2091 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002092 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002093 unsigned BeginIndex = getIndex(NewBeginOffset);
2094 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002095 assert(EndIndex > BeginIndex && "Empty vector!");
2096 unsigned NumElements = EndIndex - BeginIndex;
2097 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002098 Type *SliceTy =
2099 (NumElements == 1) ? ElementTy
2100 : VectorType::get(ElementTy, NumElements);
2101 if (V->getType() != SliceTy)
2102 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002103
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002104 // Mix in the existing elements.
2105 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2106 "load");
2107 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2108 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002109 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002110 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002111
2112 (void)Store;
2113 DEBUG(dbgs() << " to: " << *Store << "\n");
2114 return true;
2115 }
2116
Chandler Carruthf0546402013-07-18 07:15:00 +00002117 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2118 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002119 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002120 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002121 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002122 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002123 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002124 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002125 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2126 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002127 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002128 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002129 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002130 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002131 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002132 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002133 (void)Store;
2134 DEBUG(dbgs() << " to: " << *Store << "\n");
2135 return true;
2136 }
2137
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002138 bool visitStoreInst(StoreInst &SI) {
2139 DEBUG(dbgs() << " original: " << SI << "\n");
2140 Value *OldOp = SI.getOperand(1);
2141 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002142
Chandler Carruth18db7952012-11-20 01:12:50 +00002143 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002144
Chandler Carruthac8317f2012-10-04 12:33:50 +00002145 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2146 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002147 if (V->getType()->isPointerTy())
2148 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002149 Pass.PostPromotionWorklist.insert(AI);
2150
Chandler Carruthf0546402013-07-18 07:15:00 +00002151 // Compute the intersecting offset range.
2152 assert(BeginOffset < NewAllocaEndOffset);
2153 assert(EndOffset > NewAllocaBeginOffset);
2154 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2155 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2156
2157 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002158 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002159 assert(!SI.isVolatile());
2160 assert(V->getType()->isIntegerTy() &&
2161 "Only integer type loads and stores are split");
2162 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002163 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002164 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002165 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002166 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002167 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002168 }
2169
Chandler Carruth18db7952012-11-20 01:12:50 +00002170 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002171 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2172 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002173 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002174 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002175
Chandler Carruth18db7952012-11-20 01:12:50 +00002176 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002177 if (NewBeginOffset == NewAllocaBeginOffset &&
2178 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002179 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2180 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002181 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2182 SI.isVolatile());
2183 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002184 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2185 V->getType()->getPointerTo());
2186 NewSI = IRB.CreateAlignedStore(
2187 V, NewPtr, getOffsetTypeAlign(
2188 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2189 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002190 }
2191 (void)NewSI;
2192 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002193 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002194
2195 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2196 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002197 }
2198
Chandler Carruth514f34f2012-12-17 04:07:30 +00002199 /// \brief Compute an integer value from splatting an i8 across the given
2200 /// number of bytes.
2201 ///
2202 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2203 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002204 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002205 ///
2206 /// \param V The i8 value to splat.
2207 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002208 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002209 assert(Size > 0 && "Expected a positive number of bytes.");
2210 IntegerType *VTy = cast<IntegerType>(V->getType());
2211 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2212 if (Size == 1)
2213 return V;
2214
2215 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002216 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002217 ConstantExpr::getUDiv(
2218 Constant::getAllOnesValue(SplatIntTy),
2219 ConstantExpr::getZExt(
2220 Constant::getAllOnesValue(V->getType()),
2221 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002222 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002223 return V;
2224 }
2225
Chandler Carruthccca5042012-12-17 04:07:37 +00002226 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002227 Value *getVectorSplat(Value *V, unsigned NumElements) {
2228 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002229 DEBUG(dbgs() << " splat: " << *V << "\n");
2230 return V;
2231 }
2232
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002233 bool visitMemSetInst(MemSetInst &II) {
2234 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002235 assert(II.getRawDest() == OldPtr);
2236
2237 // If the memset has a variable size, it cannot be split, just adjust the
2238 // pointer to the new alloca.
2239 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002240 assert(!IsSplit);
2241 assert(BeginOffset >= NewAllocaBeginOffset);
2242 II.setDest(
2243 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002244 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002245 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002246
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002247 deleteIfTriviallyDead(OldPtr);
2248 return false;
2249 }
2250
2251 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002252 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002253
2254 Type *AllocaTy = NewAI.getAllocatedType();
2255 Type *ScalarTy = AllocaTy->getScalarType();
2256
Chandler Carruthf0546402013-07-18 07:15:00 +00002257 // Compute the intersecting offset range.
2258 assert(BeginOffset < NewAllocaEndOffset);
2259 assert(EndOffset > NewAllocaBeginOffset);
2260 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2261 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002262 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002263
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002264 // If this doesn't map cleanly onto the alloca type, and that type isn't
2265 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002266 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002267 (BeginOffset > NewAllocaBeginOffset ||
2268 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002269 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002270 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2271 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002272 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002273 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2274 CallInst *New = IRB.CreateMemSet(
2275 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002276 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002277 (void)New;
2278 DEBUG(dbgs() << " to: " << *New << "\n");
2279 return false;
2280 }
2281
2282 // If we can represent this as a simple value, we have to build the actual
2283 // value to store, which requires expanding the byte present in memset to
2284 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002285 // splatting the byte to a sufficiently wide integer, splatting it across
2286 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002287 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002288
Chandler Carruthccca5042012-12-17 04:07:37 +00002289 if (VecTy) {
2290 // If this is a memset of a vectorized alloca, insert it.
2291 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002292
Chandler Carruthf0546402013-07-18 07:15:00 +00002293 unsigned BeginIndex = getIndex(NewBeginOffset);
2294 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002295 assert(EndIndex > BeginIndex && "Empty vector!");
2296 unsigned NumElements = EndIndex - BeginIndex;
2297 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2298
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002299 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002300 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2301 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002302 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002303 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002304
Chandler Carruthce4562b2012-12-17 13:41:21 +00002305 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002306 "oldload");
2307 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002308 } else if (IntTy) {
2309 // If this is a memset on an alloca where we can widen stores, insert the
2310 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002311 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002312
Chandler Carruthf0546402013-07-18 07:15:00 +00002313 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002314 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002315
2316 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2317 EndOffset != NewAllocaBeginOffset)) {
2318 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002319 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002320 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002321 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002322 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002323 } else {
2324 assert(V->getType() == IntTy &&
2325 "Wrong type for an alloca wide integer!");
2326 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002327 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002328 } else {
2329 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002330 assert(NewBeginOffset == NewAllocaBeginOffset);
2331 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002332
Chandler Carruth90a735d2013-07-19 07:21:28 +00002333 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002334 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002335 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002336
Chandler Carruth90a735d2013-07-19 07:21:28 +00002337 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002338 }
2339
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002340 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002341 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002342 (void)New;
2343 DEBUG(dbgs() << " to: " << *New << "\n");
2344 return !II.isVolatile();
2345 }
2346
2347 bool visitMemTransferInst(MemTransferInst &II) {
2348 // Rewriting of memory transfer instructions can be a bit tricky. We break
2349 // them into two categories: split intrinsics and unsplit intrinsics.
2350
2351 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002352
Chandler Carruthf0546402013-07-18 07:15:00 +00002353 // Compute the intersecting offset range.
2354 assert(BeginOffset < NewAllocaEndOffset);
2355 assert(EndOffset > NewAllocaBeginOffset);
2356 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2357 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2358
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002359 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2360 bool IsDest = II.getRawDest() == OldPtr;
2361
Chandler Carruth176ca712012-10-01 12:16:54 +00002362 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002363 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002364 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002365
2366 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002367 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002368 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002369 Align =
2370 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2371 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002372
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002373 // For unsplit intrinsics, we simply modify the source and destination
2374 // pointers in place. This isn't just an optimization, it is a matter of
2375 // correctness. With unsplit intrinsics we may be dealing with transfers
2376 // within a single alloca before SROA ran, or with transfers that have
2377 // a variable length. We may also be dealing with memmove instead of
2378 // memcpy, and so simply updating the pointers is the necessary for us to
2379 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002380 if (!IsSplittable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002381 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2382 if (IsDest)
Chandler Carruthf0546402013-07-18 07:15:00 +00002383 II.setDest(
2384 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002385 else
Chandler Carruthf0546402013-07-18 07:15:00 +00002386 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2387 II.getRawSource()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388
Chandler Carruth208124f2012-09-26 10:59:22 +00002389 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002390 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002391
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002392 DEBUG(dbgs() << " to: " << II << "\n");
2393 deleteIfTriviallyDead(OldOp);
2394 return false;
2395 }
2396 // For split transfer intrinsics we have an incredibly useful assurance:
2397 // the source and destination do not reside within the same alloca, and at
2398 // least one of them does not escape. This means that we can replace
2399 // memmove with memcpy, and we don't need to worry about all manner of
2400 // downsides to splitting and transforming the operations.
2401
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002402 // If this doesn't map cleanly onto the alloca type, and that type isn't
2403 // a single value type, just emit a memcpy.
2404 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002405 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2406 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002407 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002408
2409 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2410 // size hasn't been shrunk based on analysis of the viable range, this is
2411 // a no-op.
2412 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002413 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002414 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002415
2416 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002417 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002418 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002419 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002420 return false;
2421 }
2422 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002423 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002424
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002425 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2426 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002427 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002428 if (AllocaInst *AI
2429 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002430 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002431
2432 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002433 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2434 : II.getRawDest()->getType();
2435
2436 // Compute the other pointer, folding as much as possible to produce
2437 // a single, simple GEP in most cases.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002438 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002439
Chandler Carruthf0546402013-07-18 07:15:00 +00002440 Value *OurPtr = getAdjustedAllocaPtr(
2441 IRB, NewBeginOffset,
2442 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002443 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002444 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002445
2446 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2447 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002448 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002449 (void)New;
2450 DEBUG(dbgs() << " to: " << *New << "\n");
2451 return false;
2452 }
2453
Chandler Carruth08e5f492012-10-03 08:26:28 +00002454 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2455 // is equivalent to 1, but that isn't true if we end up rewriting this as
2456 // a load or store.
2457 if (!Align)
2458 Align = 1;
2459
Chandler Carruthf0546402013-07-18 07:15:00 +00002460 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2461 NewEndOffset == NewAllocaEndOffset;
2462 uint64_t Size = NewEndOffset - NewBeginOffset;
2463 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2464 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002465 unsigned NumElements = EndIndex - BeginIndex;
2466 IntegerType *SubIntTy
2467 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2468
2469 Type *OtherPtrTy = NewAI.getType();
2470 if (VecTy && !IsWholeAlloca) {
2471 if (NumElements == 1)
2472 OtherPtrTy = VecTy->getElementType();
2473 else
2474 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2475
2476 OtherPtrTy = OtherPtrTy->getPointerTo();
2477 } else if (IntTy && !IsWholeAlloca) {
2478 OtherPtrTy = SubIntTy->getPointerTo();
2479 }
2480
Chandler Carruth90a735d2013-07-19 07:21:28 +00002481 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002482 Value *DstPtr = &NewAI;
2483 if (!IsDest)
2484 std::swap(SrcPtr, DstPtr);
2485
2486 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002487 if (VecTy && !IsWholeAlloca && !IsDest) {
2488 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002489 "load");
2490 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002491 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002492 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002493 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002494 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002495 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002496 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002497 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002498 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002499 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500 }
2501
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002502 if (VecTy && !IsWholeAlloca && IsDest) {
2503 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002504 "oldload");
2505 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002506 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002507 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002508 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002509 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002510 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002511 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2512 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002513 }
2514
Chandler Carruth871ba722012-09-26 10:27:46 +00002515 StoreInst *Store = cast<StoreInst>(
2516 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2517 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002518 DEBUG(dbgs() << " to: " << *Store << "\n");
2519 return !II.isVolatile();
2520 }
2521
2522 bool visitIntrinsicInst(IntrinsicInst &II) {
2523 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2524 II.getIntrinsicID() == Intrinsic::lifetime_end);
2525 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002526 assert(II.getArgOperand(1) == OldPtr);
2527
Chandler Carruthf0546402013-07-18 07:15:00 +00002528 // Compute the intersecting offset range.
2529 assert(BeginOffset < NewAllocaEndOffset);
2530 assert(EndOffset > NewAllocaBeginOffset);
2531 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2532 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2533
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002534 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002535 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002536
2537 ConstantInt *Size
2538 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002539 NewEndOffset - NewBeginOffset);
2540 Value *Ptr =
2541 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002542 Value *New;
2543 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2544 New = IRB.CreateLifetimeStart(Ptr, Size);
2545 else
2546 New = IRB.CreateLifetimeEnd(Ptr, Size);
2547
Edwin Vane82f80d42013-01-29 17:42:24 +00002548 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002549 DEBUG(dbgs() << " to: " << *New << "\n");
2550 return true;
2551 }
2552
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002553 bool visitPHINode(PHINode &PN) {
2554 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002555 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2556 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002557
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002558 // We would like to compute a new pointer in only one place, but have it be
2559 // as local as possible to the PHI. To do that, we re-use the location of
2560 // the old pointer, which necessarily must be in the right position to
2561 // dominate the PHI.
Jakub Staszakcb132fa2013-07-22 22:10:43 +00002562 IRBuilderTy PtrBuilder(OldPtr);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002563 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2564 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002565
Chandler Carruthf0546402013-07-18 07:15:00 +00002566 Value *NewPtr =
2567 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002568 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002569 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002570
Chandler Carruth82a57542012-10-01 10:54:05 +00002571 DEBUG(dbgs() << " to: " << PN << "\n");
2572 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002573
2574 // Check whether we can speculate this PHI node, and if so remember that
Chandler Carruth83ea1952013-07-24 09:47:28 +00002575 // fact and queue it up for another iteration after the speculation
2576 // occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002577 if (isSafePHIToSpeculate(PN, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002578 Pass.SpeculatablePHIs.insert(&PN);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002579 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002580 return true;
2581 }
2582
2583 return false; // PHIs can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002584 }
2585
2586 bool visitSelectInst(SelectInst &SI) {
2587 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002588 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2589 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002590 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2591 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002592
Chandler Carruthf0546402013-07-18 07:15:00 +00002593 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002594 // Replace the operands which were using the old pointer.
2595 if (SI.getOperand(1) == OldPtr)
2596 SI.setOperand(1, NewPtr);
2597 if (SI.getOperand(2) == OldPtr)
2598 SI.setOperand(2, NewPtr);
2599
Chandler Carruth82a57542012-10-01 10:54:05 +00002600 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002601 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002602
2603 // Check whether we can speculate this select instruction, and if so
Chandler Carruth83ea1952013-07-24 09:47:28 +00002604 // remember that fact and queue it up for another iteration after the
2605 // speculation occurs.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002606 if (isSafeSelectToSpeculate(SI, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002607 Pass.SpeculatableSelects.insert(&SI);
Chandler Carruth83ea1952013-07-24 09:47:28 +00002608 IsUsedByRewrittenSpeculatableInstructions = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002609 return true;
2610 }
2611
2612 return false; // Selects can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002613 }
2614
2615};
2616}
2617
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002618namespace {
2619/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2620///
2621/// This pass aggressively rewrites all aggregate loads and stores on
2622/// a particular pointer (or any pointer derived from it which we can identify)
2623/// with scalar loads and stores.
2624class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2625 // Befriend the base class so it can delegate to private visit methods.
2626 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2627
Chandler Carruth90a735d2013-07-19 07:21:28 +00002628 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002629
2630 /// Queue of pointer uses to analyze and potentially rewrite.
2631 SmallVector<Use *, 8> Queue;
2632
2633 /// Set to prevent us from cycling with phi nodes and loops.
2634 SmallPtrSet<User *, 8> Visited;
2635
2636 /// The current pointer use being rewritten. This is used to dig up the used
2637 /// value (as opposed to the user).
2638 Use *U;
2639
2640public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002641 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002642
2643 /// Rewrite loads and stores through a pointer and all pointers derived from
2644 /// it.
2645 bool rewrite(Instruction &I) {
2646 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2647 enqueueUsers(I);
2648 bool Changed = false;
2649 while (!Queue.empty()) {
2650 U = Queue.pop_back_val();
2651 Changed |= visit(cast<Instruction>(U->getUser()));
2652 }
2653 return Changed;
2654 }
2655
2656private:
2657 /// Enqueue all the users of the given instruction for further processing.
2658 /// This uses a set to de-duplicate users.
2659 void enqueueUsers(Instruction &I) {
2660 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2661 ++UI)
2662 if (Visited.insert(*UI))
2663 Queue.push_back(&UI.getUse());
2664 }
2665
2666 // Conservative default is to not rewrite anything.
2667 bool visitInstruction(Instruction &I) { return false; }
2668
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002669 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002670 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002671 class OpSplitter {
2672 protected:
2673 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002674 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002675 /// The indices which to be used with insert- or extractvalue to select the
2676 /// appropriate value within the aggregate.
2677 SmallVector<unsigned, 4> Indices;
2678 /// The indices to a GEP instruction which will move Ptr to the correct slot
2679 /// within the aggregate.
2680 SmallVector<Value *, 4> GEPIndices;
2681 /// The base pointer of the original op, used as a base for GEPing the
2682 /// split operations.
2683 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002684
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002685 /// Initialize the splitter with an insertion point, Ptr and start with a
2686 /// single zero GEP index.
2687 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002688 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002689
2690 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002691 /// \brief Generic recursive split emission routine.
2692 ///
2693 /// This method recursively splits an aggregate op (load or store) into
2694 /// scalar or vector ops. It splits recursively until it hits a single value
2695 /// and emits that single value operation via the template argument.
2696 ///
2697 /// The logic of this routine relies on GEPs and insertvalue and
2698 /// extractvalue all operating with the same fundamental index list, merely
2699 /// formatted differently (GEPs need actual values).
2700 ///
2701 /// \param Ty The type being split recursively into smaller ops.
2702 /// \param Agg The aggregate value being built up or stored, depending on
2703 /// whether this is splitting a load or a store respectively.
2704 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2705 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002706 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002707
2708 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2709 unsigned OldSize = Indices.size();
2710 (void)OldSize;
2711 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2712 ++Idx) {
2713 assert(Indices.size() == OldSize && "Did not return to the old size");
2714 Indices.push_back(Idx);
2715 GEPIndices.push_back(IRB.getInt32(Idx));
2716 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2717 GEPIndices.pop_back();
2718 Indices.pop_back();
2719 }
2720 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002721 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002722
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002723 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2724 unsigned OldSize = Indices.size();
2725 (void)OldSize;
2726 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2727 ++Idx) {
2728 assert(Indices.size() == OldSize && "Did not return to the old size");
2729 Indices.push_back(Idx);
2730 GEPIndices.push_back(IRB.getInt32(Idx));
2731 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2732 GEPIndices.pop_back();
2733 Indices.pop_back();
2734 }
2735 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002736 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002737
2738 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002739 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002740 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002741
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002742 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002743 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002744 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002745
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002746 /// Emit a leaf load of a single value. This is called at the leaves of the
2747 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002748 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002749 assert(Ty->isSingleValueType());
2750 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002751 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2752 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002753 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2754 DEBUG(dbgs() << " to: " << *Load << "\n");
2755 }
2756 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002757
2758 bool visitLoadInst(LoadInst &LI) {
2759 assert(LI.getPointerOperand() == *U);
2760 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2761 return false;
2762
2763 // We have an aggregate being loaded, split it apart.
2764 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002765 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002766 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002767 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002768 LI.replaceAllUsesWith(V);
2769 LI.eraseFromParent();
2770 return true;
2771 }
2772
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002773 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002774 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002775 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002776
2777 /// Emit a leaf store of a single value. This is called at the leaves of the
2778 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002779 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002780 assert(Ty->isSingleValueType());
2781 // Extract the single value and store it using the indices.
2782 Value *Store = IRB.CreateStore(
2783 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2784 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2785 (void)Store;
2786 DEBUG(dbgs() << " to: " << *Store << "\n");
2787 }
2788 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002789
2790 bool visitStoreInst(StoreInst &SI) {
2791 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2792 return false;
2793 Value *V = SI.getValueOperand();
2794 if (V->getType()->isSingleValueType())
2795 return false;
2796
2797 // We have an aggregate being stored, split it apart.
2798 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002799 StoreOpSplitter Splitter(&SI, *U);
2800 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002801 SI.eraseFromParent();
2802 return true;
2803 }
2804
2805 bool visitBitCastInst(BitCastInst &BC) {
2806 enqueueUsers(BC);
2807 return false;
2808 }
2809
2810 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2811 enqueueUsers(GEPI);
2812 return false;
2813 }
2814
2815 bool visitPHINode(PHINode &PN) {
2816 enqueueUsers(PN);
2817 return false;
2818 }
2819
2820 bool visitSelectInst(SelectInst &SI) {
2821 enqueueUsers(SI);
2822 return false;
2823 }
2824};
2825}
2826
Chandler Carruthba931992012-10-13 10:49:33 +00002827/// \brief Strip aggregate type wrapping.
2828///
2829/// This removes no-op aggregate types wrapping an underlying type. It will
2830/// strip as many layers of types as it can without changing either the type
2831/// size or the allocated size.
2832static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2833 if (Ty->isSingleValueType())
2834 return Ty;
2835
2836 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2837 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2838
2839 Type *InnerTy;
2840 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2841 InnerTy = ArrTy->getElementType();
2842 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2843 const StructLayout *SL = DL.getStructLayout(STy);
2844 unsigned Index = SL->getElementContainingOffset(0);
2845 InnerTy = STy->getElementType(Index);
2846 } else {
2847 return Ty;
2848 }
2849
2850 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2851 TypeSize > DL.getTypeSizeInBits(InnerTy))
2852 return Ty;
2853
2854 return stripAggregateTypeWrapping(DL, InnerTy);
2855}
2856
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002857/// \brief Try to find a partition of the aggregate type passed in for a given
2858/// offset and size.
2859///
2860/// This recurses through the aggregate type and tries to compute a subtype
2861/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002862/// of an array, it will even compute a new array type for that sub-section,
2863/// and the same for structs.
2864///
2865/// Note that this routine is very strict and tries to find a partition of the
2866/// type which produces the *exact* right offset and size. It is not forgiving
2867/// when the size or offset cause either end of type-based partition to be off.
2868/// Also, this is a best-effort routine. It is reasonable to give up and not
2869/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002870static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002871 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002872 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2873 return stripAggregateTypeWrapping(DL, Ty);
2874 if (Offset > DL.getTypeAllocSize(Ty) ||
2875 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002876 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002877
2878 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2879 // We can't partition pointers...
2880 if (SeqTy->isPointerTy())
2881 return 0;
2882
2883 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002884 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002885 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002886 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887 if (NumSkippedElements >= ArrTy->getNumElements())
2888 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002889 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002890 if (NumSkippedElements >= VecTy->getNumElements())
2891 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002892 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002893 Offset -= NumSkippedElements * ElementSize;
2894
2895 // First check if we need to recurse.
2896 if (Offset > 0 || Size < ElementSize) {
2897 // Bail if the partition ends in a different array element.
2898 if ((Offset + Size) > ElementSize)
2899 return 0;
2900 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002901 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002902 }
2903 assert(Offset == 0);
2904
2905 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002906 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002907 assert(Size > ElementSize);
2908 uint64_t NumElements = Size / ElementSize;
2909 if (NumElements * ElementSize != Size)
2910 return 0;
2911 return ArrayType::get(ElementTy, NumElements);
2912 }
2913
2914 StructType *STy = dyn_cast<StructType>(Ty);
2915 if (!STy)
2916 return 0;
2917
Chandler Carruth90a735d2013-07-19 07:21:28 +00002918 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002919 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920 return 0;
2921 uint64_t EndOffset = Offset + Size;
2922 if (EndOffset > SL->getSizeInBytes())
2923 return 0;
2924
2925 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002926 Offset -= SL->getElementOffset(Index);
2927
2928 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002929 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002930 if (Offset >= ElementSize)
2931 return 0; // The offset points into alignment padding.
2932
2933 // See if any partition must be contained by the element.
2934 if (Offset > 0 || Size < ElementSize) {
2935 if ((Offset + Size) > ElementSize)
2936 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002937 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002938 }
2939 assert(Offset == 0);
2940
2941 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002942 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002943
2944 StructType::element_iterator EI = STy->element_begin() + Index,
2945 EE = STy->element_end();
2946 if (EndOffset < SL->getSizeInBytes()) {
2947 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2948 if (Index == EndIndex)
2949 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00002950
2951 // Don't try to form "natural" types if the elements don't line up with the
2952 // expected size.
2953 // FIXME: We could potentially recurse down through the last element in the
2954 // sub-struct to find a natural end point.
2955 if (SL->getElementOffset(EndIndex) != EndOffset)
2956 return 0;
2957
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002958 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002959 EE = STy->element_begin() + EndIndex;
2960 }
2961
2962 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002963 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002964 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002965 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002966 if (Size != SubSL->getSizeInBytes())
2967 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002968
Chandler Carruth054a40a2012-09-14 11:08:31 +00002969 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002970}
2971
2972/// \brief Rewrite an alloca partition's users.
2973///
2974/// This routine drives both of the rewriting goals of the SROA pass. It tries
2975/// to rewrite uses of an alloca partition to be conducive for SSA value
2976/// promotion. If the partition needs a new, more refined alloca, this will
2977/// build that new alloca, preserving as much type information as possible, and
2978/// rewrite the uses of the old alloca to point at the new one and have the
2979/// appropriate new offsets. It also evaluates how successful the rewrite was
2980/// at enabling promotion and if it was successful queues the alloca to be
2981/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002982bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
2983 AllocaSlices::iterator B, AllocaSlices::iterator E,
2984 int64_t BeginOffset, int64_t EndOffset,
2985 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002986 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002987 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00002988
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002989 // Try to compute a friendly type for this partition of the alloca. This
2990 // won't always succeed, in which case we fall back to a legal integer type
2991 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002992 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00002993 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002994 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
2995 SliceTy = CommonUseTy;
2996 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002997 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002998 BeginOffset, SliceSize))
2999 SliceTy = TypePartitionTy;
3000 if ((!SliceTy || (SliceTy->isArrayTy() &&
3001 SliceTy->getArrayElementType()->isIntegerTy())) &&
3002 DL->isLegalInteger(SliceSize * 8))
3003 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3004 if (!SliceTy)
3005 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3006 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003007
3008 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003009 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003010
3011 bool IsIntegerPromotable =
3012 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003013 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003014
3015 // Check for the case where we're going to rewrite to a new alloca of the
3016 // exact same type as the original, and with the same access offsets. In that
3017 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003018 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003020 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003021 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003022 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003023 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003024 // FIXME: We should be able to bail at this point with "nothing changed".
3025 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003026 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003027 unsigned Alignment = AI.getAlignment();
3028 if (!Alignment) {
3029 // The minimum alignment which users can rely on when the explicit
3030 // alignment is omitted or zero is that required by the ABI for this
3031 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003032 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003033 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003034 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003035 // If we will get at least this much alignment from the type alone, leave
3036 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003037 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003038 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003039 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3040 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003041 ++NumNewAllocas;
3042 }
3043
3044 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003045 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3046 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003047
Chandler Carruthf0546402013-07-18 07:15:00 +00003048 // Track the high watermark on several worklists that are only relevant for
3049 // promoted allocas. We will reset it to this point if the alloca is not in
3050 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003051 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruthf0546402013-07-18 07:15:00 +00003052 unsigned SPOldSize = SpeculatablePHIs.size();
3053 unsigned SSOldSize = SpeculatableSelects.size();
Chandler Carruthac8317f2012-10-04 12:33:50 +00003054
Chandler Carruth6c321c12013-07-19 10:57:36 +00003055#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3056 unsigned NumUses = 0;
3057#endif
3058
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003059 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3060 EndOffset, IsVectorPromotable,
3061 IsIntegerPromotable);
Chandler Carruthf0546402013-07-18 07:15:00 +00003062 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003063 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3064 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003065 SUI != SUE; ++SUI) {
3066 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003067 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003068 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003069#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3070 ++NumUses;
3071#endif
Chandler Carruthf0546402013-07-18 07:15:00 +00003072 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003073 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003074 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003075 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003076 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003077#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3078 ++NumUses;
3079#endif
Chandler Carruthf0546402013-07-18 07:15:00 +00003080 }
3081
Chandler Carruth6c321c12013-07-19 10:57:36 +00003082#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3083 NumAllocaPartitionUses += NumUses;
3084 MaxUsesPerAllocaPartition =
3085 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3086#endif
3087
Chandler Carruth83ea1952013-07-24 09:47:28 +00003088 if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003089 DEBUG(dbgs() << " and queuing for promotion\n");
3090 PromotableAllocas.push_back(NewAI);
Chandler Carruth58e25d32013-07-24 12:12:17 +00003091 } else if (NewAI != &AI ||
3092 (Promotable &&
3093 Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003094 // If we can't promote the alloca, iterate on it to check for new
3095 // refinements exposed by splitting the current alloca. Don't iterate on an
3096 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth58e25d32013-07-24 12:12:17 +00003097 //
3098 // Alternatively, if we could promote the alloca but have speculatable
3099 // instructions then we will speculate them after finishing our processing
3100 // of the original alloca. Mark the new one for re-visiting in the next
3101 // iteration so the speculated operations can be rewritten.
3102 //
Chandler Carruthf0546402013-07-18 07:15:00 +00003103 // FIXME: We should actually track whether the rewriter changed anything.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003104 Worklist.insert(NewAI);
3105 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003106
3107 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthf0546402013-07-18 07:15:00 +00003108 if (!Promotable) {
Chandler Carruthac8317f2012-10-04 12:33:50 +00003109 while (PostPromotionWorklist.size() > PPWOldSize)
3110 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003111 while (SpeculatablePHIs.size() > SPOldSize)
3112 SpeculatablePHIs.pop_back();
3113 while (SpeculatableSelects.size() > SSOldSize)
3114 SpeculatableSelects.pop_back();
3115 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003116
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003117 return true;
3118}
3119
Chandler Carruthf0546402013-07-18 07:15:00 +00003120namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003121struct IsSliceEndLessOrEqualTo {
3122 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003123
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003124 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003125
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003126 bool operator()(const AllocaSlices::iterator &I) {
3127 return I->endOffset() <= UpperBound;
3128 }
3129};
Chandler Carruthf0546402013-07-18 07:15:00 +00003130}
3131
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003132static void
3133removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3134 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003135 if (Offset >= MaxSplitUseEndOffset) {
3136 SplitUses.clear();
3137 MaxSplitUseEndOffset = 0;
3138 return;
3139 }
3140
3141 size_t SplitUsesOldSize = SplitUses.size();
3142 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003143 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003144 SplitUses.end());
3145 if (SplitUsesOldSize == SplitUses.size())
3146 return;
3147
3148 // Recompute the max. While this is linear, so is remove_if.
3149 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003150 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003151 SUI = SplitUses.begin(),
3152 SUE = SplitUses.end();
3153 SUI != SUE; ++SUI)
3154 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3155}
3156
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003157/// \brief Walks the slices of an alloca and form partitions based on them,
3158/// rewriting each of their uses.
3159bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3160 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003161 return false;
3162
Chandler Carruth6c321c12013-07-19 10:57:36 +00003163#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3164 unsigned NumPartitions = 0;
3165#endif
3166
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003167 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003168 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003169 uint64_t MaxSplitUseEndOffset = 0;
3170
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003171 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003172
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003173 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3174 SI != SE; SI = SJ) {
3175 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003176
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003177 if (!SI->isSplittable()) {
3178 // When we're forming an unsplittable region, it must always start at the
3179 // first slice and will extend through its end.
3180 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003181
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003182 // Form a partition including all of the overlapping slices with this
3183 // unsplittable slice.
3184 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3185 if (!SJ->isSplittable())
3186 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3187 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003188 }
3189 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003190 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003191
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003192 // Collect all of the overlapping splittable slices.
3193 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3194 SJ->isSplittable()) {
3195 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3196 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003197 }
3198
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003199 // Back up MaxEndOffset and SJ if we ended the span early when
3200 // encountering an unsplittable slice.
3201 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3202 assert(!SJ->isSplittable());
3203 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003204 }
3205 }
3206
3207 // Check if we have managed to move the end offset forward yet. If so,
3208 // we'll have to rewrite uses and erase old split uses.
3209 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003210 // Rewrite a sequence of overlapping slices.
3211 Changed |=
3212 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003213#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3214 ++NumPartitions;
3215#endif
Chandler Carruthf0546402013-07-18 07:15:00 +00003216
3217 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3218 }
3219
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003220 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003221 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003222 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3223 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3224 SplitUses.push_back(SK);
3225 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003226 }
3227
3228 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003229 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003230 break;
3231
3232 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003233 // the next slice.
3234 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3235 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003236 continue;
3237 }
3238
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003239 // Even if we have split slices, if the next slice is splittable and the
3240 // split slices reach it, we can simply set up the beginning offset of the
3241 // next iteration to bridge between them.
3242 if (SJ != SE && SJ->isSplittable() &&
3243 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003244 BeginOffset = MaxEndOffset;
3245 continue;
3246 }
3247
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003248 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3249 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003250 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003251 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003252
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003253 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3254 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003255#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3256 ++NumPartitions;
3257#endif
3258
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003259 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003260 break; // Skip the rest, we don't need to do any cleanup.
3261
3262 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3263 PostSplitEndOffset);
3264
3265 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003266 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003267 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003268
Chandler Carruth6c321c12013-07-19 10:57:36 +00003269#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3270 NumAllocaPartitions += NumPartitions;
3271 MaxPartitionsPerAlloca =
3272 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3273#endif
3274
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003275 return Changed;
3276}
3277
3278/// \brief Analyze an alloca for SROA.
3279///
3280/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003281/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003282/// rewritten as needed.
3283bool SROA::runOnAlloca(AllocaInst &AI) {
3284 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3285 ++NumAllocasAnalyzed;
3286
3287 // Special case dead allocas, as they're trivial.
3288 if (AI.use_empty()) {
3289 AI.eraseFromParent();
3290 return true;
3291 }
3292
3293 // Skip alloca forms that this analysis can't handle.
3294 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003295 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003296 return false;
3297
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003298 bool Changed = false;
3299
3300 // First, split any FCA loads and stores touching this alloca to promote
3301 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003302 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003303 Changed |= AggRewriter.rewrite(AI);
3304
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003305 // Build the slices using a recursive instruction-visiting builder.
3306 AllocaSlices S(*DL, AI);
3307 DEBUG(S.print(dbgs()));
3308 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003309 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003310
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003311 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003312 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3313 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003314 DI != DE; ++DI) {
3315 Changed = true;
3316 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003317 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003318 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003319 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3320 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003321 DO != DE; ++DO) {
3322 Value *OldV = **DO;
3323 // Clobber the use with an undef value.
3324 **DO = UndefValue::get(OldV->getType());
3325 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3326 if (isInstructionTriviallyDead(OldI)) {
3327 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003328 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003329 }
3330 }
3331
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003332 // No slices to split. Leave the dead alloca for a later pass to clean up.
3333 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003334 return Changed;
3335
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003336 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003337
3338 DEBUG(dbgs() << " Speculating PHIs\n");
3339 while (!SpeculatablePHIs.empty())
3340 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3341
3342 DEBUG(dbgs() << " Speculating Selects\n");
3343 while (!SpeculatableSelects.empty())
3344 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3345
3346 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003347}
3348
Chandler Carruth19450da2012-09-14 10:26:38 +00003349/// \brief Delete the dead instructions accumulated in this run.
3350///
3351/// Recursively deletes the dead instructions we've accumulated. This is done
3352/// at the very end to maximize locality of the recursive delete and to
3353/// minimize the problems of invalidated instruction pointers as such pointers
3354/// are used heavily in the intermediate stages of the algorithm.
3355///
3356/// We also record the alloca instructions deleted here so that they aren't
3357/// subsequently handed to mem2reg to promote.
3358void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003359 while (!DeadInsts.empty()) {
3360 Instruction *I = DeadInsts.pop_back_val();
3361 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3362
Chandler Carruth58d05562012-10-25 04:37:07 +00003363 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3364
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003365 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3366 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3367 // Zero out the operand and see if it becomes trivially dead.
3368 *OI = 0;
3369 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003370 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003371 }
3372
3373 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3374 DeletedAllocas.insert(AI);
3375
3376 ++NumDeleted;
3377 I->eraseFromParent();
3378 }
3379}
3380
Chandler Carruth70b44c52012-09-15 11:43:14 +00003381/// \brief Promote the allocas, using the best available technique.
3382///
3383/// This attempts to promote whatever allocas have been identified as viable in
3384/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3385/// If there is a domtree available, we attempt to promote using the full power
3386/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3387/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003388/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003389bool SROA::promoteAllocas(Function &F) {
3390 if (PromotableAllocas.empty())
3391 return false;
3392
3393 NumPromoted += PromotableAllocas.size();
3394
3395 if (DT && !ForceSSAUpdater) {
3396 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3397 PromoteMemToReg(PromotableAllocas, *DT);
3398 PromotableAllocas.clear();
3399 return true;
3400 }
3401
3402 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3403 SSAUpdater SSA;
3404 DIBuilder DIB(*F.getParent());
3405 SmallVector<Instruction*, 64> Insts;
3406
3407 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3408 AllocaInst *AI = PromotableAllocas[Idx];
3409 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3410 UI != UE;) {
3411 Instruction *I = cast<Instruction>(*UI++);
3412 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3413 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3414 // leading to them) here. Eventually it should use them to optimize the
3415 // scalar values produced.
3416 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3417 assert(onlyUsedByLifetimeMarkers(I) &&
3418 "Found a bitcast used outside of a lifetime marker.");
3419 while (!I->use_empty())
3420 cast<Instruction>(*I->use_begin())->eraseFromParent();
3421 I->eraseFromParent();
3422 continue;
3423 }
3424 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3425 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3426 II->getIntrinsicID() == Intrinsic::lifetime_end);
3427 II->eraseFromParent();
3428 continue;
3429 }
3430
3431 Insts.push_back(I);
3432 }
3433 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3434 Insts.clear();
3435 }
3436
3437 PromotableAllocas.clear();
3438 return true;
3439}
3440
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003441namespace {
3442 /// \brief A predicate to test whether an alloca belongs to a set.
3443 class IsAllocaInSet {
3444 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3445 const SetType &Set;
3446
3447 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003448 typedef AllocaInst *argument_type;
3449
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003450 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003451 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003452 };
3453}
3454
3455bool SROA::runOnFunction(Function &F) {
3456 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3457 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003458 DL = getAnalysisIfAvailable<DataLayout>();
3459 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003460 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3461 return false;
3462 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003463 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003464
3465 BasicBlock &EntryBB = F.getEntryBlock();
3466 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3467 I != E; ++I)
3468 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3469 Worklist.insert(AI);
3470
3471 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003472 // A set of deleted alloca instruction pointers which should be removed from
3473 // the list of promotable allocas.
3474 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3475
Chandler Carruthac8317f2012-10-04 12:33:50 +00003476 do {
3477 while (!Worklist.empty()) {
3478 Changed |= runOnAlloca(*Worklist.pop_back_val());
3479 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003480
Chandler Carruthac8317f2012-10-04 12:33:50 +00003481 // Remove the deleted allocas from various lists so that we don't try to
3482 // continue processing them.
3483 if (!DeletedAllocas.empty()) {
3484 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3485 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3486 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3487 PromotableAllocas.end(),
3488 IsAllocaInSet(DeletedAllocas)),
3489 PromotableAllocas.end());
3490 DeletedAllocas.clear();
3491 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003492 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003493
Chandler Carruthac8317f2012-10-04 12:33:50 +00003494 Changed |= promoteAllocas(F);
3495
3496 Worklist = PostPromotionWorklist;
3497 PostPromotionWorklist.clear();
3498 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003499
3500 return Changed;
3501}
3502
3503void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003504 if (RequiresDomTree)
3505 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003506 AU.setPreservesCFG();
3507}