blob: 2c1aef68fbb0a6952063b9d3c6f7c566335ad3bf [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
Chandler Carruthf0546402013-07-18 07:15:00 +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 Carruthf0546402013-07-18 07:15:00 +0000656namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000657struct IsSliceDead {
658 bool operator()(const Slice &S) { return S.isDead(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000659};
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000660}
661
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000662AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000663 :
Chandler Carruthb7915f72012-11-20 10:23:07 +0000664#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000665 AI(AI),
666#endif
667 PointerEscapingInstr(0) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000668 SliceBuilder PB(DL, AI, *this);
669 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000670 if (PtrI.isEscaped() || PtrI.isAborted()) {
671 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000672 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000673 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
674 : PtrI.getAbortingInst();
675 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000676 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000677 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000678
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000679 // Sort the uses. This arranges for the offsets to be in ascending order,
680 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000681 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000682
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000683 Slices.erase(std::remove_if(Slices.begin(), Slices.end(), IsSliceDead()),
684 Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000685}
686
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000687#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
688
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000689void AllocaSlices::print(raw_ostream &OS, const_iterator I,
690 StringRef Indent) const {
691 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000693}
694
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000695void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
696 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000697 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000698 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000699 << (I->isSplittable() ? " (splittable)" : "") << "\n";
700}
701
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000702void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
703 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000704 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000705}
706
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000707void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000708 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000709 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000710 << " A pointer to this alloca escaped by:\n"
711 << " " << *PointerEscapingInstr << "\n";
712 return;
713 }
714
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000715 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000716 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000717 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000718}
719
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000720void AllocaSlices::dump(const_iterator I) const { print(dbgs(), I); }
721void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000722
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000723#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
724
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000725namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000726/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
727///
728/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
729/// the loads and stores of an alloca instruction, as well as updating its
730/// debug information. This is used when a domtree is unavailable and thus
731/// mem2reg in its full form can't be used to handle promotion of allocas to
732/// scalar values.
733class AllocaPromoter : public LoadAndStorePromoter {
734 AllocaInst &AI;
735 DIBuilder &DIB;
736
737 SmallVector<DbgDeclareInst *, 4> DDIs;
738 SmallVector<DbgValueInst *, 4> DVIs;
739
740public:
741 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
742 AllocaInst &AI, DIBuilder &DIB)
743 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
744
745 void run(const SmallVectorImpl<Instruction*> &Insts) {
746 // Remember which alloca we're promoting (for isInstInList).
747 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
748 for (Value::use_iterator UI = DebugNode->use_begin(),
749 UE = DebugNode->use_end();
750 UI != UE; ++UI)
751 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
752 DDIs.push_back(DDI);
753 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
754 DVIs.push_back(DVI);
755 }
756
757 LoadAndStorePromoter::run(Insts);
758 AI.eraseFromParent();
759 while (!DDIs.empty())
760 DDIs.pop_back_val()->eraseFromParent();
761 while (!DVIs.empty())
762 DVIs.pop_back_val()->eraseFromParent();
763 }
764
765 virtual bool isInstInList(Instruction *I,
766 const SmallVectorImpl<Instruction*> &Insts) const {
767 if (LoadInst *LI = dyn_cast<LoadInst>(I))
768 return LI->getOperand(0) == &AI;
769 return cast<StoreInst>(I)->getPointerOperand() == &AI;
770 }
771
772 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000773 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000774 E = DDIs.end(); I != E; ++I) {
775 DbgDeclareInst *DDI = *I;
776 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
777 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
778 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
779 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
780 }
Craig Topper31ee5862013-07-03 15:07:05 +0000781 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000782 E = DVIs.end(); I != E; ++I) {
783 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000784 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000785 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
786 // If an argument is zero extended then use argument directly. The ZExt
787 // may be zapped by an optimization pass in future.
788 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
789 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000790 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000791 Arg = dyn_cast<Argument>(SExt->getOperand(0));
792 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000793 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000794 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000795 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000796 } else {
797 continue;
798 }
799 Instruction *DbgVal =
800 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
801 Inst);
802 DbgVal->setDebugLoc(DVI->getDebugLoc());
803 }
804 }
805};
806} // end anon namespace
807
808
809namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000810/// \brief An optimization pass providing Scalar Replacement of Aggregates.
811///
812/// This pass takes allocations which can be completely analyzed (that is, they
813/// don't escape) and tries to turn them into scalar SSA values. There are
814/// a few steps to this process.
815///
816/// 1) It takes allocations of aggregates and analyzes the ways in which they
817/// are used to try to split them into smaller allocations, ideally of
818/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000819/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000820/// 2) It will transform accesses into forms which are suitable for SSA value
821/// promotion. This can be replacing a memset with a scalar store of an
822/// integer value, or it can involve speculating operations on a PHI or
823/// select to be a PHI or select of the results.
824/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
825/// onto insert and extract operations on a vector value, and convert them to
826/// this form. By doing so, it will enable promotion of vector aggregates to
827/// SSA vector values.
828class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000829 const bool RequiresDomTree;
830
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000831 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000832 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000833 DominatorTree *DT;
834
835 /// \brief Worklist of alloca instructions to simplify.
836 ///
837 /// Each alloca in the function is added to this. Each new alloca formed gets
838 /// added to it as well to recursively simplify unless that alloca can be
839 /// directly promoted. Finally, each time we rewrite a use of an alloca other
840 /// the one being actively rewritten, we add it back onto the list if not
841 /// already present to ensure it is re-visited.
842 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
843
844 /// \brief A collection of instructions to delete.
845 /// We try to batch deletions to simplify code and make things a bit more
846 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000847 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000848
Chandler Carruthac8317f2012-10-04 12:33:50 +0000849 /// \brief Post-promotion worklist.
850 ///
851 /// Sometimes we discover an alloca which has a high probability of becoming
852 /// viable for SROA after a round of promotion takes place. In those cases,
853 /// the alloca is enqueued here for re-processing.
854 ///
855 /// Note that we have to be very careful to clear allocas out of this list in
856 /// the event they are deleted.
857 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
858
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000859 /// \brief A collection of alloca instructions we can directly promote.
860 std::vector<AllocaInst *> PromotableAllocas;
861
Chandler Carruthf0546402013-07-18 07:15:00 +0000862 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
863 ///
864 /// All of these PHIs have been checked for the safety of speculation and by
865 /// being speculated will allow promoting allocas currently in the promotable
866 /// queue.
867 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
868
869 /// \brief A worklist of select instructions to speculate prior to promoting
870 /// allocas.
871 ///
872 /// All of these select instructions have been checked for the safety of
873 /// speculation and by being speculated will allow promoting allocas
874 /// currently in the promotable queue.
875 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
876
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000877public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000878 SROA(bool RequiresDomTree = true)
879 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000880 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000881 initializeSROAPass(*PassRegistry::getPassRegistry());
882 }
883 bool runOnFunction(Function &F);
884 void getAnalysisUsage(AnalysisUsage &AU) const;
885
886 const char *getPassName() const { return "SROA"; }
887 static char ID;
888
889private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000890 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000891 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000892
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000893 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
894 AllocaSlices::iterator B, AllocaSlices::iterator E,
895 int64_t BeginOffset, int64_t EndOffset,
896 ArrayRef<AllocaSlices::iterator> SplitUses);
897 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000898 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +0000899 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000900 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000901};
902}
903
904char SROA::ID = 0;
905
Chandler Carruth70b44c52012-09-15 11:43:14 +0000906FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
907 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000908}
909
910INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
911 false, false)
912INITIALIZE_PASS_DEPENDENCY(DominatorTree)
913INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
914 false, false)
915
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000916/// Walk the range of a partitioning looking for a common type to cover this
917/// sequence of slices.
918static Type *findCommonType(AllocaSlices::const_iterator B,
919 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +0000920 uint64_t EndOffset) {
921 Type *Ty = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000922 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000923 Use *U = I->getUse();
924 if (isa<IntrinsicInst>(*U->getUser()))
925 continue;
926 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
927 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000928
Chandler Carruthf0546402013-07-18 07:15:00 +0000929 Type *UserTy = 0;
930 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
931 UserTy = LI->getType();
932 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
933 UserTy = SI->getValueOperand()->getType();
934 else
935 return 0; // Bail if we have weird uses.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000936
Chandler Carruthf0546402013-07-18 07:15:00 +0000937 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
938 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000939 // this for split integer operations where we want to use the type of the
Chandler Carruthf0546402013-07-18 07:15:00 +0000940 // entity causing the split.
941 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
942 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +0000943
Chandler Carruthf0546402013-07-18 07:15:00 +0000944 // If we have found an integer type use covering the alloca, use that
945 // regardless of the other types, as integers are often used for a
946 // "bucket
947 // of bits" type.
948 return ITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000949 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000950
951 if (Ty && Ty != UserTy)
952 return 0;
953
954 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000955 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000956 return Ty;
957}
Chandler Carruthe3899f22013-07-15 17:36:21 +0000958
Chandler Carruthf0546402013-07-18 07:15:00 +0000959/// PHI instructions that use an alloca and are subsequently loaded can be
960/// rewritten to load both input pointers in the pred blocks and then PHI the
961/// results, allowing the load of the alloca to be promoted.
962/// From this:
963/// %P2 = phi [i32* %Alloca, i32* %Other]
964/// %V = load i32* %P2
965/// to:
966/// %V1 = load i32* %Alloca -> will be mem2reg'd
967/// ...
968/// %V2 = load i32* %Other
969/// ...
970/// %V = phi [i32 %V1, i32 %V2]
971///
972/// We can do this to a select if its only uses are loads and if the operands
973/// to the select can be loaded unconditionally.
974///
975/// FIXME: This should be hoisted into a generic utility, likely in
976/// Transforms/Util/Local.h
977static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +0000978 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000979 // For now, we can only do this promotion if the load is in the same block
980 // as the PHI, and if there are no stores between the phi and load.
981 // TODO: Allow recursive phi users.
982 // TODO: Allow stores.
983 BasicBlock *BB = PN.getParent();
984 unsigned MaxAlign = 0;
985 bool HaveLoad = false;
986 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
987 ++UI) {
988 LoadInst *LI = dyn_cast<LoadInst>(*UI);
989 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000990 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +0000991
Chandler Carruthf0546402013-07-18 07:15:00 +0000992 // For now we only allow loads in the same block as the PHI. This is
993 // a common case that happens when instcombine merges two loads through
994 // a PHI.
995 if (LI->getParent() != BB)
996 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +0000997
Chandler Carruthf0546402013-07-18 07:15:00 +0000998 // Ensure that there are no instructions between the PHI and the load that
999 // could store.
1000 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1001 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001002 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001003
Chandler Carruthf0546402013-07-18 07:15:00 +00001004 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1005 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001006 }
1007
Chandler Carruthf0546402013-07-18 07:15:00 +00001008 if (!HaveLoad)
1009 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001010
Chandler Carruthf0546402013-07-18 07:15:00 +00001011 // We can only transform this if it is safe to push the loads into the
1012 // predecessor blocks. The only thing to watch out for is that we can't put
1013 // a possibly trapping load in the predecessor if it is a critical edge.
1014 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1015 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1016 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001017
Chandler Carruthf0546402013-07-18 07:15:00 +00001018 // If the value is produced by the terminator of the predecessor (an
1019 // invoke) or it has side-effects, there is no valid place to put a load
1020 // in the predecessor.
1021 if (TI == InVal || TI->mayHaveSideEffects())
1022 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001023
Chandler Carruthf0546402013-07-18 07:15:00 +00001024 // If the predecessor has a single successor, then the edge isn't
1025 // critical.
1026 if (TI->getNumSuccessors() == 1)
1027 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001028
Chandler Carruthf0546402013-07-18 07:15:00 +00001029 // If this pointer is always safe to load, or if we can prove that there
1030 // is already a load in the block, then we can move the load to the pred
1031 // block.
1032 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001033 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001034 continue;
1035
1036 return false;
1037 }
1038
1039 return true;
1040}
1041
1042static void speculatePHINodeLoads(PHINode &PN) {
1043 DEBUG(dbgs() << " original: " << PN << "\n");
1044
1045 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1046 IRBuilderTy PHIBuilder(&PN);
1047 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1048 PN.getName() + ".sroa.speculated");
1049
1050 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1051 // matter which one we get and if any differ.
1052 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1053 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1054 unsigned Align = SomeLoad->getAlignment();
1055
1056 // Rewrite all loads of the PN to use the new PHI.
1057 while (!PN.use_empty()) {
1058 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1059 LI->replaceAllUsesWith(NewPN);
1060 LI->eraseFromParent();
1061 }
1062
1063 // Inject loads into all of the pred blocks.
1064 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1065 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1066 TerminatorInst *TI = Pred->getTerminator();
1067 Value *InVal = PN.getIncomingValue(Idx);
1068 IRBuilderTy PredBuilder(TI);
1069
1070 LoadInst *Load = PredBuilder.CreateLoad(
1071 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1072 ++NumLoadsSpeculated;
1073 Load->setAlignment(Align);
1074 if (TBAATag)
1075 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1076 NewPN->addIncoming(Load, Pred);
1077 }
1078
1079 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1080 PN.eraseFromParent();
1081}
1082
1083/// Select instructions that use an alloca and are subsequently loaded can be
1084/// rewritten to load both input pointers and then select between the result,
1085/// allowing the load of the alloca to be promoted.
1086/// From this:
1087/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1088/// %V = load i32* %P2
1089/// to:
1090/// %V1 = load i32* %Alloca -> will be mem2reg'd
1091/// %V2 = load i32* %Other
1092/// %V = select i1 %cond, i32 %V1, i32 %V2
1093///
1094/// We can do this to a select if its only uses are loads and if the operand
1095/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001096static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001097 Value *TValue = SI.getTrueValue();
1098 Value *FValue = SI.getFalseValue();
1099 bool TDerefable = TValue->isDereferenceablePointer();
1100 bool FDerefable = FValue->isDereferenceablePointer();
1101
1102 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1103 ++UI) {
1104 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1105 if (LI == 0 || !LI->isSimple())
1106 return false;
1107
1108 // Both operands to the select need to be dereferencable, either
1109 // absolutely (e.g. allocas) or at this point because we can see other
1110 // accesses to it.
1111 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001112 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001113 return false;
1114 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001115 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001116 return false;
1117 }
1118
1119 return true;
1120}
1121
1122static void speculateSelectInstLoads(SelectInst &SI) {
1123 DEBUG(dbgs() << " original: " << SI << "\n");
1124
1125 IRBuilderTy IRB(&SI);
1126 Value *TV = SI.getTrueValue();
1127 Value *FV = SI.getFalseValue();
1128 // Replace the loads of the select with a select of two loads.
1129 while (!SI.use_empty()) {
1130 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1131 assert(LI->isSimple() && "We only speculate simple loads");
1132
1133 IRB.SetInsertPoint(LI);
1134 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001135 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001136 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001137 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001138 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001139
Chandler Carruthf0546402013-07-18 07:15:00 +00001140 // Transfer alignment and TBAA info if present.
1141 TL->setAlignment(LI->getAlignment());
1142 FL->setAlignment(LI->getAlignment());
1143 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1144 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1145 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001146 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001147
1148 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1149 LI->getName() + ".sroa.speculated");
1150
1151 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1152 LI->replaceAllUsesWith(V);
1153 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001154 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001155 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001156}
1157
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001158/// \brief Build a GEP out of a base pointer and indices.
1159///
1160/// This will return the BasePtr if that is valid, or build a new GEP
1161/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001162static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001163 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001164 if (Indices.empty())
1165 return BasePtr;
1166
1167 // A single zero index is a no-op, so check for this and avoid building a GEP
1168 // in that case.
1169 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1170 return BasePtr;
1171
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001172 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001173}
1174
1175/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1176/// TargetTy without changing the offset of the pointer.
1177///
1178/// This routine assumes we've already established a properly offset GEP with
1179/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1180/// zero-indices down through type layers until we find one the same as
1181/// TargetTy. If we can't find one with the same type, we at least try to use
1182/// one with the same size. If none of that works, we just produce the GEP as
1183/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001184static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001185 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001186 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001187 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001188 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001189
1190 // See if we can descend into a struct and locate a field with the correct
1191 // type.
1192 unsigned NumLayers = 0;
1193 Type *ElementTy = Ty;
1194 do {
1195 if (ElementTy->isPointerTy())
1196 break;
1197 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1198 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001199 // Note that we use the default address space as this index is over an
1200 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001201 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001202 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001203 if (STy->element_begin() == STy->element_end())
1204 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001205 ElementTy = *STy->element_begin();
1206 Indices.push_back(IRB.getInt32(0));
1207 } else {
1208 break;
1209 }
1210 ++NumLayers;
1211 } while (ElementTy != TargetTy);
1212 if (ElementTy != TargetTy)
1213 Indices.erase(Indices.end() - NumLayers, Indices.end());
1214
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001215 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001216}
1217
1218/// \brief Recursively compute indices for a natural GEP.
1219///
1220/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1221/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001222static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001223 Value *Ptr, Type *Ty, APInt &Offset,
1224 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001225 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001226 if (Offset == 0)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001227 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001228
1229 // We can't recurse through pointer types.
1230 if (Ty->isPointerTy())
1231 return 0;
1232
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001233 // We try to analyze GEPs over vectors here, but note that these GEPs are
1234 // extremely poorly defined currently. The long-term goal is to remove GEPing
1235 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001236 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001237 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001238 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001239 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001240 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001241 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001242 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1243 return 0;
1244 Offset -= NumSkippedElements * ElementSize;
1245 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001246 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001247 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001248 }
1249
1250 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1251 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001252 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001253 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001254 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1255 return 0;
1256
1257 Offset -= NumSkippedElements * ElementSize;
1258 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001259 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001260 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001261 }
1262
1263 StructType *STy = dyn_cast<StructType>(Ty);
1264 if (!STy)
1265 return 0;
1266
Chandler Carruth90a735d2013-07-19 07:21:28 +00001267 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001268 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001269 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001270 return 0;
1271 unsigned Index = SL->getElementContainingOffset(StructOffset);
1272 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1273 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001274 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001275 return 0; // The offset points into alignment padding.
1276
1277 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001278 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001279 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001280}
1281
1282/// \brief Get a natural GEP from a base pointer to a particular offset and
1283/// resulting in a particular type.
1284///
1285/// The goal is to produce a "natural" looking GEP that works with the existing
1286/// composite types to arrive at the appropriate offset and element type for
1287/// a pointer. TargetTy is the element type the returned GEP should point-to if
1288/// possible. We recurse by decreasing Offset, adding the appropriate index to
1289/// Indices, and setting Ty to the result subtype.
1290///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001291/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001292static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001293 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001294 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001295 PointerType *Ty = cast<PointerType>(Ptr->getType());
1296
1297 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1298 // an i8.
1299 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1300 return 0;
1301
1302 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001303 if (!ElementTy->isSized())
1304 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001305 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001306 if (ElementSize == 0)
1307 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001308 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001309
1310 Offset -= NumSkippedElements * ElementSize;
1311 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001312 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001313 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001314}
1315
1316/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1317/// resulting pointer has PointerTy.
1318///
1319/// This tries very hard to compute a "natural" GEP which arrives at the offset
1320/// and produces the pointer type desired. Where it cannot, it will try to use
1321/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1322/// fails, it will try to use an existing i8* and GEP to the byte offset and
1323/// bitcast to the type.
1324///
1325/// The strategy for finding the more natural GEPs is to peel off layers of the
1326/// pointer, walking back through bit casts and GEPs, searching for a base
1327/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001328/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001329/// a single GEP as possible, thus making each GEP more independent of the
1330/// surrounding code.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001331static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001332 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001333 // Even though we don't look through PHI nodes, we could be called on an
1334 // instruction in an unreachable block, which may be on a cycle.
1335 SmallPtrSet<Value *, 4> Visited;
1336 Visited.insert(Ptr);
1337 SmallVector<Value *, 4> Indices;
1338
1339 // We may end up computing an offset pointer that has the wrong type. If we
1340 // never are able to compute one directly that has the correct type, we'll
1341 // fall back to it, so keep it around here.
1342 Value *OffsetPtr = 0;
1343
1344 // Remember any i8 pointer we come across to re-use if we need to do a raw
1345 // byte offset.
1346 Value *Int8Ptr = 0;
1347 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1348
1349 Type *TargetTy = PointerTy->getPointerElementType();
1350
1351 do {
1352 // First fold any existing GEPs into the offset.
1353 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1354 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001355 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001356 break;
1357 Offset += GEPOffset;
1358 Ptr = GEP->getPointerOperand();
1359 if (!Visited.insert(Ptr))
1360 break;
1361 }
1362
1363 // See if we can perform a natural GEP here.
1364 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001365 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001366 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001367 if (P->getType() == PointerTy) {
1368 // Zap any offset pointer that we ended up computing in previous rounds.
1369 if (OffsetPtr && OffsetPtr->use_empty())
1370 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1371 I->eraseFromParent();
1372 return P;
1373 }
1374 if (!OffsetPtr) {
1375 OffsetPtr = P;
1376 }
1377 }
1378
1379 // Stash this pointer if we've found an i8*.
1380 if (Ptr->getType()->isIntegerTy(8)) {
1381 Int8Ptr = Ptr;
1382 Int8PtrOffset = Offset;
1383 }
1384
1385 // Peel off a layer of the pointer and update the offset appropriately.
1386 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1387 Ptr = cast<Operator>(Ptr)->getOperand(0);
1388 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1389 if (GA->mayBeOverridden())
1390 break;
1391 Ptr = GA->getAliasee();
1392 } else {
1393 break;
1394 }
1395 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1396 } while (Visited.insert(Ptr));
1397
1398 if (!OffsetPtr) {
1399 if (!Int8Ptr) {
1400 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001401 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001402 Int8PtrOffset = Offset;
1403 }
1404
1405 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1406 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001407 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001408 }
1409 Ptr = OffsetPtr;
1410
1411 // On the off chance we were targeting i8*, guard the bitcast here.
1412 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001413 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414
1415 return Ptr;
1416}
1417
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001418/// \brief Test whether we can convert a value from the old to the new type.
1419///
1420/// This predicate should be used to guard calls to convertValue in order to
1421/// ensure that we only try to convert viable values. The strategy is that we
1422/// will peel off single element struct and array wrappings to get to an
1423/// underlying value, and convert that value.
1424static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1425 if (OldTy == NewTy)
1426 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001427 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1428 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1429 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1430 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001431 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1432 return false;
1433 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1434 return false;
1435
1436 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1437 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1438 return true;
1439 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1440 return true;
1441 return false;
1442 }
1443
1444 return true;
1445}
1446
1447/// \brief Generic routine to convert an SSA value to a value of a different
1448/// type.
1449///
1450/// This will try various different casting techniques, such as bitcasts,
1451/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1452/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001453static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001454 Type *Ty) {
1455 assert(canConvertValue(DL, V->getType(), Ty) &&
1456 "Value not convertable to type");
1457 if (V->getType() == Ty)
1458 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001459 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1460 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1461 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1462 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001463 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1464 return IRB.CreateIntToPtr(V, Ty);
1465 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1466 return IRB.CreatePtrToInt(V, Ty);
1467
1468 return IRB.CreateBitCast(V, Ty);
1469}
1470
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001471/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001472///
1473/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001474/// for a single slice.
1475static bool isVectorPromotionViableForSlice(
1476 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1477 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1478 AllocaSlices::const_iterator I) {
1479 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001480 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001481 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001482 uint64_t BeginIndex = BeginOffset / ElementSize;
1483 if (BeginIndex * ElementSize != BeginOffset ||
1484 BeginIndex >= Ty->getNumElements())
1485 return false;
1486 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001487 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001488 uint64_t EndIndex = EndOffset / ElementSize;
1489 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1490 return false;
1491
1492 assert(EndIndex > BeginIndex && "Empty vector!");
1493 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001494 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001495 (NumElements == 1) ? Ty->getElementType()
1496 : VectorType::get(Ty->getElementType(), NumElements);
1497
1498 Type *SplitIntTy =
1499 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1500
1501 Use *U = I->getUse();
1502
1503 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1504 if (MI->isVolatile())
1505 return false;
1506 if (!I->isSplittable())
1507 return false; // Skip any unsplittable intrinsics.
1508 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1509 // Disable vector promotion when there are loads or stores of an FCA.
1510 return false;
1511 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1512 if (LI->isVolatile())
1513 return false;
1514 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001515 if (SliceBeginOffset > I->beginOffset() ||
1516 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001517 assert(LTy->isIntegerTy());
1518 LTy = SplitIntTy;
1519 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001520 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001521 return false;
1522 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1523 if (SI->isVolatile())
1524 return false;
1525 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001526 if (SliceBeginOffset > I->beginOffset() ||
1527 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001528 assert(STy->isIntegerTy());
1529 STy = SplitIntTy;
1530 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001531 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001532 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001533 } else {
1534 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001535 }
1536
1537 return true;
1538}
1539
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001540/// \brief Test whether the given alloca partitioning and range of slices can be
1541/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001542///
1543/// This is a quick test to check whether we can rewrite a particular alloca
1544/// partition (and its newly formed alloca) into a vector alloca with only
1545/// whole-vector loads and stores such that it could be promoted to a vector
1546/// SSA value. We only can ensure this for a limited set of operations, and we
1547/// don't want to do the rewrites unless we are confident that the result will
1548/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001549static bool
1550isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1551 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1552 AllocaSlices::const_iterator I,
1553 AllocaSlices::const_iterator E,
1554 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001555 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1556 if (!Ty)
1557 return false;
1558
Chandler Carruth90a735d2013-07-19 07:21:28 +00001559 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001560
1561 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1562 // that aren't byte sized.
1563 if (ElementSize % 8)
1564 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001565 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001566 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001567 ElementSize /= 8;
1568
Chandler Carruthf0546402013-07-18 07:15:00 +00001569 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001570 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1571 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001572 return false;
1573
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001574 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1575 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001576 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001577 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1578 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001579 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001580
1581 return true;
1582}
1583
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001584/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001585///
1586/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001587/// test below on a single slice of the alloca.
1588static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1589 Type *AllocaTy,
1590 uint64_t AllocBeginOffset,
1591 uint64_t Size, AllocaSlices &S,
1592 AllocaSlices::const_iterator I,
1593 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001594 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1595 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1596
1597 // We can't reasonably handle cases where the load or store extends past
1598 // the end of the aloca's type and into its padding.
1599 if (RelEnd > Size)
1600 return false;
1601
1602 Use *U = I->getUse();
1603
1604 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1605 if (LI->isVolatile())
1606 return false;
1607 if (RelBegin == 0 && RelEnd == Size)
1608 WholeAllocaOp = true;
1609 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001610 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001611 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001612 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001613 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001614 // Non-integer loads need to be convertible from the alloca type so that
1615 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001616 return false;
1617 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001618 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1619 Type *ValueTy = SI->getValueOperand()->getType();
1620 if (SI->isVolatile())
1621 return false;
1622 if (RelBegin == 0 && RelEnd == Size)
1623 WholeAllocaOp = true;
1624 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001625 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001626 return false;
1627 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001628 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001629 // Non-integer stores need to be convertible to the alloca type so that
1630 // they are promotable.
1631 return false;
1632 }
1633 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1634 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1635 return false;
1636 if (!I->isSplittable())
1637 return false; // Skip any unsplittable intrinsics.
1638 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1639 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1640 II->getIntrinsicID() != Intrinsic::lifetime_end)
1641 return false;
1642 } else {
1643 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001644 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001645
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001646 return true;
1647}
1648
Chandler Carruth435c4e02012-10-15 08:40:30 +00001649/// \brief Test whether the given alloca partition's integer operations can be
1650/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001651///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001652/// This is a quick test to check whether we can rewrite the integer loads and
1653/// stores to a particular alloca into wider loads and stores and be able to
1654/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001655static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001656isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001657 uint64_t AllocBeginOffset, AllocaSlices &S,
1658 AllocaSlices::const_iterator I,
1659 AllocaSlices::const_iterator E,
1660 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001661 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001662 // Don't create integer types larger than the maximum bitwidth.
1663 if (SizeInBits > IntegerType::MAX_INT_BITS)
1664 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001665
1666 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001667 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001668 return false;
1669
Chandler Carruth58d05562012-10-25 04:37:07 +00001670 // We need to ensure that an integer type with the appropriate bitwidth can
1671 // be converted to the alloca type, whatever that is. We don't want to force
1672 // the alloca itself to have an integer type if there is a more suitable one.
1673 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001674 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1675 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001676 return false;
1677
Chandler Carruth90a735d2013-07-19 07:21:28 +00001678 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001679
Chandler Carruthf0546402013-07-18 07:15:00 +00001680 // While examining uses, we ensure that the alloca has a covering load or
1681 // store. We don't want to widen the integer operations only to fail to
1682 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001683 // later). However, if there are only splittable uses, go ahead and assume
1684 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001685 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001686
Chandler Carruthf0546402013-07-18 07:15:00 +00001687 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001688 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1689 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001690 return false;
1691
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001692 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1693 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001694 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001695 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1696 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001697 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001698
Chandler Carruth92924fd2012-09-24 00:34:20 +00001699 return WholeAllocaOp;
1700}
1701
Chandler Carruthd177f862013-03-20 07:30:36 +00001702static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001703 IntegerType *Ty, uint64_t Offset,
1704 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001705 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001706 IntegerType *IntTy = cast<IntegerType>(V->getType());
1707 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1708 "Element extends past full value");
1709 uint64_t ShAmt = 8*Offset;
1710 if (DL.isBigEndian())
1711 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001712 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001713 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001714 DEBUG(dbgs() << " shifted: " << *V << "\n");
1715 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001716 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1717 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001718 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001719 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001720 DEBUG(dbgs() << " trunced: " << *V << "\n");
1721 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001722 return V;
1723}
1724
Chandler Carruthd177f862013-03-20 07:30:36 +00001725static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001726 Value *V, uint64_t Offset, const Twine &Name) {
1727 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1728 IntegerType *Ty = cast<IntegerType>(V->getType());
1729 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1730 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001731 DEBUG(dbgs() << " start: " << *V << "\n");
1732 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001733 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001734 DEBUG(dbgs() << " extended: " << *V << "\n");
1735 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001736 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1737 "Element store outside of alloca store");
1738 uint64_t ShAmt = 8*Offset;
1739 if (DL.isBigEndian())
1740 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001741 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001742 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001743 DEBUG(dbgs() << " shifted: " << *V << "\n");
1744 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001745
1746 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1747 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1748 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001749 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001750 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001751 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001752 }
1753 return V;
1754}
1755
Chandler Carruthd177f862013-03-20 07:30:36 +00001756static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001757 unsigned BeginIndex, unsigned EndIndex,
1758 const Twine &Name) {
1759 VectorType *VecTy = cast<VectorType>(V->getType());
1760 unsigned NumElements = EndIndex - BeginIndex;
1761 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1762
1763 if (NumElements == VecTy->getNumElements())
1764 return V;
1765
1766 if (NumElements == 1) {
1767 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1768 Name + ".extract");
1769 DEBUG(dbgs() << " extract: " << *V << "\n");
1770 return V;
1771 }
1772
1773 SmallVector<Constant*, 8> Mask;
1774 Mask.reserve(NumElements);
1775 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1776 Mask.push_back(IRB.getInt32(i));
1777 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1778 ConstantVector::get(Mask),
1779 Name + ".extract");
1780 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1781 return V;
1782}
1783
Chandler Carruthd177f862013-03-20 07:30:36 +00001784static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001785 unsigned BeginIndex, const Twine &Name) {
1786 VectorType *VecTy = cast<VectorType>(Old->getType());
1787 assert(VecTy && "Can only insert a vector into a vector");
1788
1789 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1790 if (!Ty) {
1791 // Single element to insert.
1792 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1793 Name + ".insert");
1794 DEBUG(dbgs() << " insert: " << *V << "\n");
1795 return V;
1796 }
1797
1798 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1799 "Too many elements!");
1800 if (Ty->getNumElements() == VecTy->getNumElements()) {
1801 assert(V->getType() == VecTy && "Vector type mismatch");
1802 return V;
1803 }
1804 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1805
1806 // When inserting a smaller vector into the larger to store, we first
1807 // use a shuffle vector to widen it with undef elements, and then
1808 // a second shuffle vector to select between the loaded vector and the
1809 // incoming vector.
1810 SmallVector<Constant*, 8> Mask;
1811 Mask.reserve(VecTy->getNumElements());
1812 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1813 if (i >= BeginIndex && i < EndIndex)
1814 Mask.push_back(IRB.getInt32(i - BeginIndex));
1815 else
1816 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1817 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1818 ConstantVector::get(Mask),
1819 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001820 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001821
1822 Mask.clear();
1823 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001824 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1825
1826 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1827
1828 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001829 return V;
1830}
1831
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001832namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001833/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1834/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001835///
1836/// Also implements the rewriting to vector-based accesses when the partition
1837/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1838/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001839class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001840 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001841 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1842 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001843
Chandler Carruth90a735d2013-07-19 07:21:28 +00001844 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001845 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001846 SROA &Pass;
1847 AllocaInst &OldAI, &NewAI;
1848 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001849 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001850
1851 // If we are rewriting an alloca partition which can be written as pure
1852 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001853 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001854 // - The new alloca is exactly the size of the vector type here.
1855 // - The accesses all either map to the entire vector or to a single
1856 // element.
1857 // - The set of accessing instructions is only one of those handled above
1858 // in isVectorPromotionViable. Generally these are the same access kinds
1859 // which are promotable via mem2reg.
1860 VectorType *VecTy;
1861 Type *ElementTy;
1862 uint64_t ElementSize;
1863
Chandler Carruth92924fd2012-09-24 00:34:20 +00001864 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00001865 // alloca's integer operations should be widened to this integer type due to
1866 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00001867 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00001868 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00001869
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001870 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001871 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001872 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001873 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00001874 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001875 Instruction *OldPtr;
1876
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001877 // Utility IR builder, whose name prefix is setup for each visited use, and
1878 // the insertion point is set to point to the user.
1879 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001880
1881public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001882 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1883 AllocaInst &OldAI, AllocaInst &NewAI,
1884 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1885 bool IsVectorPromotable = false,
1886 bool IsIntegerPromotable = false)
1887 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00001888 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1889 NewAllocaTy(NewAI.getAllocatedType()),
1890 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1891 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001892 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00001893 IntTy(IsIntegerPromotable
1894 ? Type::getIntNTy(
1895 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00001896 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001897 : 0),
1898 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1899 OldPtr(), IRB(NewAI.getContext(), ConstantFolder()) {
1900 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
1931private:
Chandler Carruthf0546402013-07-18 07:15:00 +00001932 // Make sure the other visit overloads are visible.
1933 using Base::visit;
1934
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001935 // Every instruction which can end up as a user must have a rewrite rule.
1936 bool visitInstruction(Instruction &I) {
1937 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1938 llvm_unreachable("No rewrite rule for this instruction!");
1939 }
1940
Chandler Carruthf0546402013-07-18 07:15:00 +00001941 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
1942 Type *PointerTy) {
1943 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001944 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00001945 Offset - NewAllocaBeginOffset),
1946 PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001947 }
1948
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001949 /// \brief Compute suitable alignment to access an offset into the new alloca.
1950 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00001951 unsigned NewAIAlign = NewAI.getAlignment();
1952 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00001953 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00001954 return MinAlign(NewAIAlign, Offset);
1955 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001956
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001957 /// \brief Compute suitable alignment to access a type at an offset of the
1958 /// new alloca.
1959 ///
1960 /// \returns zero if the type's ABI alignment is a suitable alignment,
1961 /// otherwise returns the maximal suitable alignment.
1962 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
1963 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001964 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00001965 }
1966
Chandler Carruth845b73c2012-11-21 08:16:30 +00001967 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001968 assert(VecTy && "Can only call getIndex when rewriting a vector");
1969 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1970 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1971 uint32_t Index = RelOffset / ElementSize;
1972 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00001973 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001974 }
1975
1976 void deleteIfTriviallyDead(Value *V) {
1977 Instruction *I = cast<Instruction>(V);
1978 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00001979 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001980 }
1981
Chandler Carruthf0546402013-07-18 07:15:00 +00001982 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
1983 uint64_t NewEndOffset) {
1984 unsigned BeginIndex = getIndex(NewBeginOffset);
1985 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00001986 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001987
1988 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001989 "load");
1990 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00001991 }
1992
Chandler Carruthf0546402013-07-18 07:15:00 +00001993 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
1994 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001995 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00001996 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001997 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001998 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00001999 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002000 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2001 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2002 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002003 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002004 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002005 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002006 }
2007
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002008 bool visitLoadInst(LoadInst &LI) {
2009 DEBUG(dbgs() << " original: " << LI << "\n");
2010 Value *OldOp = LI.getOperand(0);
2011 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002012
Chandler Carruthf0546402013-07-18 07:15:00 +00002013 // Compute the intersecting offset range.
2014 assert(BeginOffset < NewAllocaEndOffset);
2015 assert(EndOffset > NewAllocaBeginOffset);
2016 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2017 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2018
2019 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002020
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002021 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2022 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002023 bool IsPtrAdjusted = false;
2024 Value *V;
2025 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002026 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002027 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002028 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2029 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002030 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002031 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002032 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002033 } else {
2034 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002035 V = IRB.CreateAlignedLoad(
2036 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2037 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2038 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002039 IsPtrAdjusted = true;
2040 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002041 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002042
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002043 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002044 assert(!LI.isVolatile());
2045 assert(LI.getType()->isIntegerTy() &&
2046 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002047 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002048 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002049 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002050 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002051 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002052 // Move the insertion point just past the load so that we can refer to it.
2053 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002054 // Create a placeholder value with the same type as LI to use as the
2055 // basis for the new value. This allows us to replace the uses of LI with
2056 // the computed value, and then replace the placeholder with LI, leaving
2057 // LI only used for this computation.
2058 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002059 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002060 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002061 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002062 LI.replaceAllUsesWith(V);
2063 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002064 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002065 } else {
2066 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002067 }
2068
Chandler Carruth18db7952012-11-20 01:12:50 +00002069 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002070 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002071 DEBUG(dbgs() << " to: " << *V << "\n");
2072 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002073 }
2074
Chandler Carruthf0546402013-07-18 07:15:00 +00002075 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2076 uint64_t NewBeginOffset,
2077 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002078 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002079 unsigned BeginIndex = getIndex(NewBeginOffset);
2080 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002081 assert(EndIndex > BeginIndex && "Empty vector!");
2082 unsigned NumElements = EndIndex - BeginIndex;
2083 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002084 Type *SliceTy =
2085 (NumElements == 1) ? ElementTy
2086 : VectorType::get(ElementTy, NumElements);
2087 if (V->getType() != SliceTy)
2088 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002089
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002090 // Mix in the existing elements.
2091 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2092 "load");
2093 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2094 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002095 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002096 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002097
2098 (void)Store;
2099 DEBUG(dbgs() << " to: " << *Store << "\n");
2100 return true;
2101 }
2102
Chandler Carruthf0546402013-07-18 07:15:00 +00002103 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2104 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002105 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002106 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002107 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002108 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002109 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002110 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002111 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2112 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002113 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002114 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002115 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002116 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002117 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002118 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002119 (void)Store;
2120 DEBUG(dbgs() << " to: " << *Store << "\n");
2121 return true;
2122 }
2123
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002124 bool visitStoreInst(StoreInst &SI) {
2125 DEBUG(dbgs() << " original: " << SI << "\n");
2126 Value *OldOp = SI.getOperand(1);
2127 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002128
Chandler Carruth18db7952012-11-20 01:12:50 +00002129 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002130
Chandler Carruthac8317f2012-10-04 12:33:50 +00002131 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2132 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002133 if (V->getType()->isPointerTy())
2134 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002135 Pass.PostPromotionWorklist.insert(AI);
2136
Chandler Carruthf0546402013-07-18 07:15:00 +00002137 // Compute the intersecting offset range.
2138 assert(BeginOffset < NewAllocaEndOffset);
2139 assert(EndOffset > NewAllocaBeginOffset);
2140 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2141 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2142
2143 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002144 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002145 assert(!SI.isVolatile());
2146 assert(V->getType()->isIntegerTy() &&
2147 "Only integer type loads and stores are split");
2148 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002149 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002150 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002151 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002152 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002153 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002154 }
2155
Chandler Carruth18db7952012-11-20 01:12:50 +00002156 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002157 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2158 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002159 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002160 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002161
Chandler Carruth18db7952012-11-20 01:12:50 +00002162 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002163 if (NewBeginOffset == NewAllocaBeginOffset &&
2164 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002165 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2166 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002167 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2168 SI.isVolatile());
2169 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002170 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2171 V->getType()->getPointerTo());
2172 NewSI = IRB.CreateAlignedStore(
2173 V, NewPtr, getOffsetTypeAlign(
2174 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2175 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002176 }
2177 (void)NewSI;
2178 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002179 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002180
2181 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2182 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002183 }
2184
Chandler Carruth514f34f2012-12-17 04:07:30 +00002185 /// \brief Compute an integer value from splatting an i8 across the given
2186 /// number of bytes.
2187 ///
2188 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2189 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002190 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002191 ///
2192 /// \param V The i8 value to splat.
2193 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002194 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002195 assert(Size > 0 && "Expected a positive number of bytes.");
2196 IntegerType *VTy = cast<IntegerType>(V->getType());
2197 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2198 if (Size == 1)
2199 return V;
2200
2201 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002202 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002203 ConstantExpr::getUDiv(
2204 Constant::getAllOnesValue(SplatIntTy),
2205 ConstantExpr::getZExt(
2206 Constant::getAllOnesValue(V->getType()),
2207 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002208 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002209 return V;
2210 }
2211
Chandler Carruthccca5042012-12-17 04:07:37 +00002212 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002213 Value *getVectorSplat(Value *V, unsigned NumElements) {
2214 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002215 DEBUG(dbgs() << " splat: " << *V << "\n");
2216 return V;
2217 }
2218
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002219 bool visitMemSetInst(MemSetInst &II) {
2220 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002221 assert(II.getRawDest() == OldPtr);
2222
2223 // If the memset has a variable size, it cannot be split, just adjust the
2224 // pointer to the new alloca.
2225 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002226 assert(!IsSplit);
2227 assert(BeginOffset >= NewAllocaBeginOffset);
2228 II.setDest(
2229 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002230 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002231 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002232
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002233 deleteIfTriviallyDead(OldPtr);
2234 return false;
2235 }
2236
2237 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002238 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002239
2240 Type *AllocaTy = NewAI.getAllocatedType();
2241 Type *ScalarTy = AllocaTy->getScalarType();
2242
Chandler Carruthf0546402013-07-18 07:15:00 +00002243 // Compute the intersecting offset range.
2244 assert(BeginOffset < NewAllocaEndOffset);
2245 assert(EndOffset > NewAllocaBeginOffset);
2246 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2247 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002248 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002249
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002250 // If this doesn't map cleanly onto the alloca type, and that type isn't
2251 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002252 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002253 (BeginOffset > NewAllocaBeginOffset ||
2254 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002255 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002256 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2257 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002258 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002259 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2260 CallInst *New = IRB.CreateMemSet(
2261 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002262 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002263 (void)New;
2264 DEBUG(dbgs() << " to: " << *New << "\n");
2265 return false;
2266 }
2267
2268 // If we can represent this as a simple value, we have to build the actual
2269 // value to store, which requires expanding the byte present in memset to
2270 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002271 // splatting the byte to a sufficiently wide integer, splatting it across
2272 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002273 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002274
Chandler Carruthccca5042012-12-17 04:07:37 +00002275 if (VecTy) {
2276 // If this is a memset of a vectorized alloca, insert it.
2277 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002278
Chandler Carruthf0546402013-07-18 07:15:00 +00002279 unsigned BeginIndex = getIndex(NewBeginOffset);
2280 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002281 assert(EndIndex > BeginIndex && "Empty vector!");
2282 unsigned NumElements = EndIndex - BeginIndex;
2283 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2284
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002285 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002286 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2287 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002288 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002289 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002290
Chandler Carruthce4562b2012-12-17 13:41:21 +00002291 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002292 "oldload");
2293 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002294 } else if (IntTy) {
2295 // If this is a memset on an alloca where we can widen stores, insert the
2296 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002297 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002298
Chandler Carruthf0546402013-07-18 07:15:00 +00002299 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002300 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002301
2302 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2303 EndOffset != NewAllocaBeginOffset)) {
2304 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002305 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002306 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002307 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002308 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002309 } else {
2310 assert(V->getType() == IntTy &&
2311 "Wrong type for an alloca wide integer!");
2312 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002313 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002314 } else {
2315 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002316 assert(NewBeginOffset == NewAllocaBeginOffset);
2317 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002318
Chandler Carruth90a735d2013-07-19 07:21:28 +00002319 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002320 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002321 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002322
Chandler Carruth90a735d2013-07-19 07:21:28 +00002323 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002324 }
2325
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002326 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002327 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002328 (void)New;
2329 DEBUG(dbgs() << " to: " << *New << "\n");
2330 return !II.isVolatile();
2331 }
2332
2333 bool visitMemTransferInst(MemTransferInst &II) {
2334 // Rewriting of memory transfer instructions can be a bit tricky. We break
2335 // them into two categories: split intrinsics and unsplit intrinsics.
2336
2337 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002338
Chandler Carruthf0546402013-07-18 07:15:00 +00002339 // Compute the intersecting offset range.
2340 assert(BeginOffset < NewAllocaEndOffset);
2341 assert(EndOffset > NewAllocaBeginOffset);
2342 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2343 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2344
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002345 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2346 bool IsDest = II.getRawDest() == OldPtr;
2347
Chandler Carruth176ca712012-10-01 12:16:54 +00002348 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002349 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002350 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002351
2352 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002353 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002354 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002355 Align =
2356 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2357 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002358
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002359 // For unsplit intrinsics, we simply modify the source and destination
2360 // pointers in place. This isn't just an optimization, it is a matter of
2361 // correctness. With unsplit intrinsics we may be dealing with transfers
2362 // within a single alloca before SROA ran, or with transfers that have
2363 // a variable length. We may also be dealing with memmove instead of
2364 // memcpy, and so simply updating the pointers is the necessary for us to
2365 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002366 if (!IsSplittable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002367 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2368 if (IsDest)
Chandler Carruthf0546402013-07-18 07:15:00 +00002369 II.setDest(
2370 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002371 else
Chandler Carruthf0546402013-07-18 07:15:00 +00002372 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2373 II.getRawSource()->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002374
Chandler Carruth208124f2012-09-26 10:59:22 +00002375 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002376 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002377
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002378 DEBUG(dbgs() << " to: " << II << "\n");
2379 deleteIfTriviallyDead(OldOp);
2380 return false;
2381 }
2382 // For split transfer intrinsics we have an incredibly useful assurance:
2383 // the source and destination do not reside within the same alloca, and at
2384 // least one of them does not escape. This means that we can replace
2385 // memmove with memcpy, and we don't need to worry about all manner of
2386 // downsides to splitting and transforming the operations.
2387
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388 // If this doesn't map cleanly onto the alloca type, and that type isn't
2389 // a single value type, just emit a memcpy.
2390 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002391 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2392 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002393 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002394
2395 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2396 // size hasn't been shrunk based on analysis of the viable range, this is
2397 // a no-op.
2398 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002399 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002400 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002401
2402 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002403 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002404 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002405 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002406 return false;
2407 }
2408 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002409 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002410
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002411 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2412 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002413 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002414 if (AllocaInst *AI
2415 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002416 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002417
2418 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002419 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2420 : II.getRawDest()->getType();
2421
2422 // Compute the other pointer, folding as much as possible to produce
2423 // a single, simple GEP in most cases.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002424 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002425
Chandler Carruthf0546402013-07-18 07:15:00 +00002426 Value *OurPtr = getAdjustedAllocaPtr(
2427 IRB, NewBeginOffset,
2428 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002429 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002430 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002431
2432 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2433 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002434 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002435 (void)New;
2436 DEBUG(dbgs() << " to: " << *New << "\n");
2437 return false;
2438 }
2439
Chandler Carruth08e5f492012-10-03 08:26:28 +00002440 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2441 // is equivalent to 1, but that isn't true if we end up rewriting this as
2442 // a load or store.
2443 if (!Align)
2444 Align = 1;
2445
Chandler Carruthf0546402013-07-18 07:15:00 +00002446 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2447 NewEndOffset == NewAllocaEndOffset;
2448 uint64_t Size = NewEndOffset - NewBeginOffset;
2449 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2450 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002451 unsigned NumElements = EndIndex - BeginIndex;
2452 IntegerType *SubIntTy
2453 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2454
2455 Type *OtherPtrTy = NewAI.getType();
2456 if (VecTy && !IsWholeAlloca) {
2457 if (NumElements == 1)
2458 OtherPtrTy = VecTy->getElementType();
2459 else
2460 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2461
2462 OtherPtrTy = OtherPtrTy->getPointerTo();
2463 } else if (IntTy && !IsWholeAlloca) {
2464 OtherPtrTy = SubIntTy->getPointerTo();
2465 }
2466
Chandler Carruth90a735d2013-07-19 07:21:28 +00002467 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002468 Value *DstPtr = &NewAI;
2469 if (!IsDest)
2470 std::swap(SrcPtr, DstPtr);
2471
2472 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002473 if (VecTy && !IsWholeAlloca && !IsDest) {
2474 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002475 "load");
2476 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002477 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002478 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002479 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002480 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002481 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002482 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002483 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002484 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002485 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002486 }
2487
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002488 if (VecTy && !IsWholeAlloca && IsDest) {
2489 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002490 "oldload");
2491 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002492 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002493 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002494 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002495 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002496 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002497 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2498 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002499 }
2500
Chandler Carruth871ba722012-09-26 10:27:46 +00002501 StoreInst *Store = cast<StoreInst>(
2502 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2503 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002504 DEBUG(dbgs() << " to: " << *Store << "\n");
2505 return !II.isVolatile();
2506 }
2507
2508 bool visitIntrinsicInst(IntrinsicInst &II) {
2509 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2510 II.getIntrinsicID() == Intrinsic::lifetime_end);
2511 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002512 assert(II.getArgOperand(1) == OldPtr);
2513
Chandler Carruthf0546402013-07-18 07:15:00 +00002514 // Compute the intersecting offset range.
2515 assert(BeginOffset < NewAllocaEndOffset);
2516 assert(EndOffset > NewAllocaBeginOffset);
2517 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2518 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2519
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002520 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002521 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002522
2523 ConstantInt *Size
2524 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002525 NewEndOffset - NewBeginOffset);
2526 Value *Ptr =
2527 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002528 Value *New;
2529 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2530 New = IRB.CreateLifetimeStart(Ptr, Size);
2531 else
2532 New = IRB.CreateLifetimeEnd(Ptr, Size);
2533
Edwin Vane82f80d42013-01-29 17:42:24 +00002534 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002535 DEBUG(dbgs() << " to: " << *New << "\n");
2536 return true;
2537 }
2538
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002539 bool visitPHINode(PHINode &PN) {
2540 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002541 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2542 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002543
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002544 // We would like to compute a new pointer in only one place, but have it be
2545 // as local as possible to the PHI. To do that, we re-use the location of
2546 // the old pointer, which necessarily must be in the right position to
2547 // dominate the PHI.
Chandler Carruthd177f862013-03-20 07:30:36 +00002548 IRBuilderTy PtrBuilder(cast<Instruction>(OldPtr));
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002549 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2550 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002551
Chandler Carruthf0546402013-07-18 07:15:00 +00002552 Value *NewPtr =
2553 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002554 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002555 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556
Chandler Carruth82a57542012-10-01 10:54:05 +00002557 DEBUG(dbgs() << " to: " << PN << "\n");
2558 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002559
2560 // Check whether we can speculate this PHI node, and if so remember that
2561 // fact and return that this alloca remains viable for promotion to an SSA
2562 // value.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002563 if (isSafePHIToSpeculate(PN, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002564 Pass.SpeculatablePHIs.insert(&PN);
2565 return true;
2566 }
2567
2568 return false; // PHIs can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002569 }
2570
2571 bool visitSelectInst(SelectInst &SI) {
2572 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002573 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2574 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002575 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2576 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002577
Chandler Carruthf0546402013-07-18 07:15:00 +00002578 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002579 // Replace the operands which were using the old pointer.
2580 if (SI.getOperand(1) == OldPtr)
2581 SI.setOperand(1, NewPtr);
2582 if (SI.getOperand(2) == OldPtr)
2583 SI.setOperand(2, NewPtr);
2584
Chandler Carruth82a57542012-10-01 10:54:05 +00002585 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002586 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002587
2588 // Check whether we can speculate this select instruction, and if so
2589 // remember that fact and return that this alloca remains viable for
2590 // promotion to an SSA value.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002591 if (isSafeSelectToSpeculate(SI, &DL)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002592 Pass.SpeculatableSelects.insert(&SI);
2593 return true;
2594 }
2595
2596 return false; // Selects can't be promoted on their own.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002597 }
2598
2599};
2600}
2601
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002602namespace {
2603/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2604///
2605/// This pass aggressively rewrites all aggregate loads and stores on
2606/// a particular pointer (or any pointer derived from it which we can identify)
2607/// with scalar loads and stores.
2608class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2609 // Befriend the base class so it can delegate to private visit methods.
2610 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2611
Chandler Carruth90a735d2013-07-19 07:21:28 +00002612 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002613
2614 /// Queue of pointer uses to analyze and potentially rewrite.
2615 SmallVector<Use *, 8> Queue;
2616
2617 /// Set to prevent us from cycling with phi nodes and loops.
2618 SmallPtrSet<User *, 8> Visited;
2619
2620 /// The current pointer use being rewritten. This is used to dig up the used
2621 /// value (as opposed to the user).
2622 Use *U;
2623
2624public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002625 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002626
2627 /// Rewrite loads and stores through a pointer and all pointers derived from
2628 /// it.
2629 bool rewrite(Instruction &I) {
2630 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2631 enqueueUsers(I);
2632 bool Changed = false;
2633 while (!Queue.empty()) {
2634 U = Queue.pop_back_val();
2635 Changed |= visit(cast<Instruction>(U->getUser()));
2636 }
2637 return Changed;
2638 }
2639
2640private:
2641 /// Enqueue all the users of the given instruction for further processing.
2642 /// This uses a set to de-duplicate users.
2643 void enqueueUsers(Instruction &I) {
2644 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2645 ++UI)
2646 if (Visited.insert(*UI))
2647 Queue.push_back(&UI.getUse());
2648 }
2649
2650 // Conservative default is to not rewrite anything.
2651 bool visitInstruction(Instruction &I) { return false; }
2652
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002653 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002654 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002655 class OpSplitter {
2656 protected:
2657 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002658 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002659 /// The indices which to be used with insert- or extractvalue to select the
2660 /// appropriate value within the aggregate.
2661 SmallVector<unsigned, 4> Indices;
2662 /// The indices to a GEP instruction which will move Ptr to the correct slot
2663 /// within the aggregate.
2664 SmallVector<Value *, 4> GEPIndices;
2665 /// The base pointer of the original op, used as a base for GEPing the
2666 /// split operations.
2667 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002668
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002669 /// Initialize the splitter with an insertion point, Ptr and start with a
2670 /// single zero GEP index.
2671 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002672 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002673
2674 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002675 /// \brief Generic recursive split emission routine.
2676 ///
2677 /// This method recursively splits an aggregate op (load or store) into
2678 /// scalar or vector ops. It splits recursively until it hits a single value
2679 /// and emits that single value operation via the template argument.
2680 ///
2681 /// The logic of this routine relies on GEPs and insertvalue and
2682 /// extractvalue all operating with the same fundamental index list, merely
2683 /// formatted differently (GEPs need actual values).
2684 ///
2685 /// \param Ty The type being split recursively into smaller ops.
2686 /// \param Agg The aggregate value being built up or stored, depending on
2687 /// whether this is splitting a load or a store respectively.
2688 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2689 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002690 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002691
2692 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2693 unsigned OldSize = Indices.size();
2694 (void)OldSize;
2695 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2696 ++Idx) {
2697 assert(Indices.size() == OldSize && "Did not return to the old size");
2698 Indices.push_back(Idx);
2699 GEPIndices.push_back(IRB.getInt32(Idx));
2700 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2701 GEPIndices.pop_back();
2702 Indices.pop_back();
2703 }
2704 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002705 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002706
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002707 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2708 unsigned OldSize = Indices.size();
2709 (void)OldSize;
2710 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2711 ++Idx) {
2712 assert(Indices.size() == OldSize && "Did not return to the old size");
2713 Indices.push_back(Idx);
2714 GEPIndices.push_back(IRB.getInt32(Idx));
2715 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2716 GEPIndices.pop_back();
2717 Indices.pop_back();
2718 }
2719 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002720 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002721
2722 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002723 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002724 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002725
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002726 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002727 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002728 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002729
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002730 /// Emit a leaf load of a single value. This is called at the leaves of the
2731 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002732 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002733 assert(Ty->isSingleValueType());
2734 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002735 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2736 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002737 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2738 DEBUG(dbgs() << " to: " << *Load << "\n");
2739 }
2740 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002741
2742 bool visitLoadInst(LoadInst &LI) {
2743 assert(LI.getPointerOperand() == *U);
2744 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2745 return false;
2746
2747 // We have an aggregate being loaded, split it apart.
2748 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002749 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002750 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002751 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002752 LI.replaceAllUsesWith(V);
2753 LI.eraseFromParent();
2754 return true;
2755 }
2756
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002757 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002758 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002759 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002760
2761 /// Emit a leaf store of a single value. This is called at the leaves of the
2762 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002763 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002764 assert(Ty->isSingleValueType());
2765 // Extract the single value and store it using the indices.
2766 Value *Store = IRB.CreateStore(
2767 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2768 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2769 (void)Store;
2770 DEBUG(dbgs() << " to: " << *Store << "\n");
2771 }
2772 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002773
2774 bool visitStoreInst(StoreInst &SI) {
2775 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2776 return false;
2777 Value *V = SI.getValueOperand();
2778 if (V->getType()->isSingleValueType())
2779 return false;
2780
2781 // We have an aggregate being stored, split it apart.
2782 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002783 StoreOpSplitter Splitter(&SI, *U);
2784 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002785 SI.eraseFromParent();
2786 return true;
2787 }
2788
2789 bool visitBitCastInst(BitCastInst &BC) {
2790 enqueueUsers(BC);
2791 return false;
2792 }
2793
2794 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2795 enqueueUsers(GEPI);
2796 return false;
2797 }
2798
2799 bool visitPHINode(PHINode &PN) {
2800 enqueueUsers(PN);
2801 return false;
2802 }
2803
2804 bool visitSelectInst(SelectInst &SI) {
2805 enqueueUsers(SI);
2806 return false;
2807 }
2808};
2809}
2810
Chandler Carruthba931992012-10-13 10:49:33 +00002811/// \brief Strip aggregate type wrapping.
2812///
2813/// This removes no-op aggregate types wrapping an underlying type. It will
2814/// strip as many layers of types as it can without changing either the type
2815/// size or the allocated size.
2816static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2817 if (Ty->isSingleValueType())
2818 return Ty;
2819
2820 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2821 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2822
2823 Type *InnerTy;
2824 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2825 InnerTy = ArrTy->getElementType();
2826 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2827 const StructLayout *SL = DL.getStructLayout(STy);
2828 unsigned Index = SL->getElementContainingOffset(0);
2829 InnerTy = STy->getElementType(Index);
2830 } else {
2831 return Ty;
2832 }
2833
2834 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2835 TypeSize > DL.getTypeSizeInBits(InnerTy))
2836 return Ty;
2837
2838 return stripAggregateTypeWrapping(DL, InnerTy);
2839}
2840
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002841/// \brief Try to find a partition of the aggregate type passed in for a given
2842/// offset and size.
2843///
2844/// This recurses through the aggregate type and tries to compute a subtype
2845/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002846/// of an array, it will even compute a new array type for that sub-section,
2847/// and the same for structs.
2848///
2849/// Note that this routine is very strict and tries to find a partition of the
2850/// type which produces the *exact* right offset and size. It is not forgiving
2851/// when the size or offset cause either end of type-based partition to be off.
2852/// Also, this is a best-effort routine. It is reasonable to give up and not
2853/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002854static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002855 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002856 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2857 return stripAggregateTypeWrapping(DL, Ty);
2858 if (Offset > DL.getTypeAllocSize(Ty) ||
2859 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00002860 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002861
2862 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2863 // We can't partition pointers...
2864 if (SeqTy->isPointerTy())
2865 return 0;
2866
2867 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00002868 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002869 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002870 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002871 if (NumSkippedElements >= ArrTy->getNumElements())
2872 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002873 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002874 if (NumSkippedElements >= VecTy->getNumElements())
2875 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00002876 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002877 Offset -= NumSkippedElements * ElementSize;
2878
2879 // First check if we need to recurse.
2880 if (Offset > 0 || Size < ElementSize) {
2881 // Bail if the partition ends in a different array element.
2882 if ((Offset + Size) > ElementSize)
2883 return 0;
2884 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002885 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002886 }
2887 assert(Offset == 0);
2888
2889 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002890 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002891 assert(Size > ElementSize);
2892 uint64_t NumElements = Size / ElementSize;
2893 if (NumElements * ElementSize != Size)
2894 return 0;
2895 return ArrayType::get(ElementTy, NumElements);
2896 }
2897
2898 StructType *STy = dyn_cast<StructType>(Ty);
2899 if (!STy)
2900 return 0;
2901
Chandler Carruth90a735d2013-07-19 07:21:28 +00002902 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002903 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002904 return 0;
2905 uint64_t EndOffset = Offset + Size;
2906 if (EndOffset > SL->getSizeInBytes())
2907 return 0;
2908
2909 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002910 Offset -= SL->getElementOffset(Index);
2911
2912 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002913 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002914 if (Offset >= ElementSize)
2915 return 0; // The offset points into alignment padding.
2916
2917 // See if any partition must be contained by the element.
2918 if (Offset > 0 || Size < ElementSize) {
2919 if ((Offset + Size) > ElementSize)
2920 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002921 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002922 }
2923 assert(Offset == 0);
2924
2925 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002926 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002927
2928 StructType::element_iterator EI = STy->element_begin() + Index,
2929 EE = STy->element_end();
2930 if (EndOffset < SL->getSizeInBytes()) {
2931 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2932 if (Index == EndIndex)
2933 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00002934
2935 // Don't try to form "natural" types if the elements don't line up with the
2936 // expected size.
2937 // FIXME: We could potentially recurse down through the last element in the
2938 // sub-struct to find a natural end point.
2939 if (SL->getElementOffset(EndIndex) != EndOffset)
2940 return 0;
2941
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002942 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002943 EE = STy->element_begin() + EndIndex;
2944 }
2945
2946 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002947 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002948 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002949 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00002950 if (Size != SubSL->getSizeInBytes())
2951 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002952
Chandler Carruth054a40a2012-09-14 11:08:31 +00002953 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002954}
2955
2956/// \brief Rewrite an alloca partition's users.
2957///
2958/// This routine drives both of the rewriting goals of the SROA pass. It tries
2959/// to rewrite uses of an alloca partition to be conducive for SSA value
2960/// promotion. If the partition needs a new, more refined alloca, this will
2961/// build that new alloca, preserving as much type information as possible, and
2962/// rewrite the uses of the old alloca to point at the new one and have the
2963/// appropriate new offsets. It also evaluates how successful the rewrite was
2964/// at enabling promotion and if it was successful queues the alloca to be
2965/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002966bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
2967 AllocaSlices::iterator B, AllocaSlices::iterator E,
2968 int64_t BeginOffset, int64_t EndOffset,
2969 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002970 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002971 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00002972
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002973 // Try to compute a friendly type for this partition of the alloca. This
2974 // won't always succeed, in which case we fall back to a legal integer type
2975 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002976 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00002977 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002978 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
2979 SliceTy = CommonUseTy;
2980 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002981 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002982 BeginOffset, SliceSize))
2983 SliceTy = TypePartitionTy;
2984 if ((!SliceTy || (SliceTy->isArrayTy() &&
2985 SliceTy->getArrayElementType()->isIntegerTy())) &&
2986 DL->isLegalInteger(SliceSize * 8))
2987 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
2988 if (!SliceTy)
2989 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
2990 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00002991
2992 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002993 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00002994
2995 bool IsIntegerPromotable =
2996 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002997 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002998
2999 // Check for the case where we're going to rewrite to a new alloca of the
3000 // exact same type as the original, and with the same access offsets. In that
3001 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003002 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003003 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003004 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003005 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003006 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003007 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003008 // FIXME: We should be able to bail at this point with "nothing changed".
3009 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003010 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003011 unsigned Alignment = AI.getAlignment();
3012 if (!Alignment) {
3013 // The minimum alignment which users can rely on when the explicit
3014 // alignment is omitted or zero is that required by the ABI for this
3015 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003016 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003017 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003018 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003019 // If we will get at least this much alignment from the type alone, leave
3020 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003021 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003022 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003023 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3024 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003025 ++NumNewAllocas;
3026 }
3027
3028 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003029 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3030 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031
Chandler Carruthf0546402013-07-18 07:15:00 +00003032 // Track the high watermark on several worklists that are only relevant for
3033 // promoted allocas. We will reset it to this point if the alloca is not in
3034 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003035 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruthf0546402013-07-18 07:15:00 +00003036 unsigned SPOldSize = SpeculatablePHIs.size();
3037 unsigned SSOldSize = SpeculatableSelects.size();
Chandler Carruthac8317f2012-10-04 12:33:50 +00003038
Chandler Carruth6c321c12013-07-19 10:57:36 +00003039#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3040 unsigned NumUses = 0;
3041#endif
3042
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003043 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3044 EndOffset, IsVectorPromotable,
3045 IsIntegerPromotable);
Chandler Carruthf0546402013-07-18 07:15:00 +00003046 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003047 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3048 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003049 SUI != SUE; ++SUI) {
3050 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003051 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003052 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003053#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3054 ++NumUses;
3055#endif
Chandler Carruthf0546402013-07-18 07:15:00 +00003056 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003057 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003058 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003059 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003060 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003061#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3062 ++NumUses;
3063#endif
Chandler Carruthf0546402013-07-18 07:15:00 +00003064 }
3065
Chandler Carruth6c321c12013-07-19 10:57:36 +00003066#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3067 NumAllocaPartitionUses += NumUses;
3068 MaxUsesPerAllocaPartition =
3069 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3070#endif
3071
Chandler Carruthf0546402013-07-18 07:15:00 +00003072 if (Promotable && (SpeculatablePHIs.size() > SPOldSize ||
3073 SpeculatableSelects.size() > SSOldSize)) {
3074 // If we have a promotable alloca except for some unspeculated loads below
3075 // PHIs or Selects, iterate once. We will speculate the loads and on the
3076 // next iteration rewrite them into a promotable form.
3077 Worklist.insert(NewAI);
3078 } else if (Promotable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003079 DEBUG(dbgs() << " and queuing for promotion\n");
3080 PromotableAllocas.push_back(NewAI);
3081 } else if (NewAI != &AI) {
3082 // If we can't promote the alloca, iterate on it to check for new
3083 // refinements exposed by splitting the current alloca. Don't iterate on an
3084 // alloca which didn't actually change and didn't get promoted.
Chandler Carruthf0546402013-07-18 07:15:00 +00003085 // FIXME: We should actually track whether the rewriter changed anything.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003086 Worklist.insert(NewAI);
3087 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003088
3089 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthf0546402013-07-18 07:15:00 +00003090 if (!Promotable) {
Chandler Carruthac8317f2012-10-04 12:33:50 +00003091 while (PostPromotionWorklist.size() > PPWOldSize)
3092 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003093 while (SpeculatablePHIs.size() > SPOldSize)
3094 SpeculatablePHIs.pop_back();
3095 while (SpeculatableSelects.size() > SSOldSize)
3096 SpeculatableSelects.pop_back();
3097 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003098
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003099 return true;
3100}
3101
Chandler Carruthf0546402013-07-18 07:15:00 +00003102namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003103struct IsSliceEndLessOrEqualTo {
3104 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003105
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003106 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003107
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003108 bool operator()(const AllocaSlices::iterator &I) {
3109 return I->endOffset() <= UpperBound;
3110 }
3111};
Chandler Carruthf0546402013-07-18 07:15:00 +00003112}
3113
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003114static void
3115removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3116 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003117 if (Offset >= MaxSplitUseEndOffset) {
3118 SplitUses.clear();
3119 MaxSplitUseEndOffset = 0;
3120 return;
3121 }
3122
3123 size_t SplitUsesOldSize = SplitUses.size();
3124 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003125 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003126 SplitUses.end());
3127 if (SplitUsesOldSize == SplitUses.size())
3128 return;
3129
3130 // Recompute the max. While this is linear, so is remove_if.
3131 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003132 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003133 SUI = SplitUses.begin(),
3134 SUE = SplitUses.end();
3135 SUI != SUE; ++SUI)
3136 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3137}
3138
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003139/// \brief Walks the slices of an alloca and form partitions based on them,
3140/// rewriting each of their uses.
3141bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3142 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003143 return false;
3144
Chandler Carruth6c321c12013-07-19 10:57:36 +00003145#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3146 unsigned NumPartitions = 0;
3147#endif
3148
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003149 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003150 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003151 uint64_t MaxSplitUseEndOffset = 0;
3152
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003153 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003154
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003155 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3156 SI != SE; SI = SJ) {
3157 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003158
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003159 if (!SI->isSplittable()) {
3160 // When we're forming an unsplittable region, it must always start at the
3161 // first slice and will extend through its end.
3162 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003163
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003164 // Form a partition including all of the overlapping slices with this
3165 // unsplittable slice.
3166 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3167 if (!SJ->isSplittable())
3168 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3169 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003170 }
3171 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003172 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003173
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003174 // Collect all of the overlapping splittable slices.
3175 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3176 SJ->isSplittable()) {
3177 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3178 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003179 }
3180
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003181 // Back up MaxEndOffset and SJ if we ended the span early when
3182 // encountering an unsplittable slice.
3183 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3184 assert(!SJ->isSplittable());
3185 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003186 }
3187 }
3188
3189 // Check if we have managed to move the end offset forward yet. If so,
3190 // we'll have to rewrite uses and erase old split uses.
3191 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003192 // Rewrite a sequence of overlapping slices.
3193 Changed |=
3194 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003195#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3196 ++NumPartitions;
3197#endif
Chandler Carruthf0546402013-07-18 07:15:00 +00003198
3199 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3200 }
3201
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003202 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003203 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003204 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3205 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3206 SplitUses.push_back(SK);
3207 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003208 }
3209
3210 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003211 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003212 break;
3213
3214 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003215 // the next slice.
3216 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3217 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003218 continue;
3219 }
3220
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003221 // Even if we have split slices, if the next slice is splittable and the
3222 // split slices reach it, we can simply set up the beginning offset of the
3223 // next iteration to bridge between them.
3224 if (SJ != SE && SJ->isSplittable() &&
3225 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003226 BeginOffset = MaxEndOffset;
3227 continue;
3228 }
3229
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003230 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3231 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003232 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003233 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003234
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003235 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3236 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003237#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3238 ++NumPartitions;
3239#endif
3240
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003241 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003242 break; // Skip the rest, we don't need to do any cleanup.
3243
3244 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3245 PostSplitEndOffset);
3246
3247 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003248 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003249 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003250
Chandler Carruth6c321c12013-07-19 10:57:36 +00003251#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
3252 NumAllocaPartitions += NumPartitions;
3253 MaxPartitionsPerAlloca =
3254 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3255#endif
3256
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003257 return Changed;
3258}
3259
3260/// \brief Analyze an alloca for SROA.
3261///
3262/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003263/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003264/// rewritten as needed.
3265bool SROA::runOnAlloca(AllocaInst &AI) {
3266 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3267 ++NumAllocasAnalyzed;
3268
3269 // Special case dead allocas, as they're trivial.
3270 if (AI.use_empty()) {
3271 AI.eraseFromParent();
3272 return true;
3273 }
3274
3275 // Skip alloca forms that this analysis can't handle.
3276 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003277 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003278 return false;
3279
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003280 bool Changed = false;
3281
3282 // First, split any FCA loads and stores touching this alloca to promote
3283 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003284 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003285 Changed |= AggRewriter.rewrite(AI);
3286
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003287 // Build the slices using a recursive instruction-visiting builder.
3288 AllocaSlices S(*DL, AI);
3289 DEBUG(S.print(dbgs()));
3290 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003291 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003292
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003293 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003294 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3295 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003296 DI != DE; ++DI) {
3297 Changed = true;
3298 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003299 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003300 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003301 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3302 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003303 DO != DE; ++DO) {
3304 Value *OldV = **DO;
3305 // Clobber the use with an undef value.
3306 **DO = UndefValue::get(OldV->getType());
3307 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3308 if (isInstructionTriviallyDead(OldI)) {
3309 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003310 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003311 }
3312 }
3313
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003314 // No slices to split. Leave the dead alloca for a later pass to clean up.
3315 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003316 return Changed;
3317
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003318 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003319
3320 DEBUG(dbgs() << " Speculating PHIs\n");
3321 while (!SpeculatablePHIs.empty())
3322 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3323
3324 DEBUG(dbgs() << " Speculating Selects\n");
3325 while (!SpeculatableSelects.empty())
3326 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3327
3328 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003329}
3330
Chandler Carruth19450da2012-09-14 10:26:38 +00003331/// \brief Delete the dead instructions accumulated in this run.
3332///
3333/// Recursively deletes the dead instructions we've accumulated. This is done
3334/// at the very end to maximize locality of the recursive delete and to
3335/// minimize the problems of invalidated instruction pointers as such pointers
3336/// are used heavily in the intermediate stages of the algorithm.
3337///
3338/// We also record the alloca instructions deleted here so that they aren't
3339/// subsequently handed to mem2reg to promote.
3340void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003341 while (!DeadInsts.empty()) {
3342 Instruction *I = DeadInsts.pop_back_val();
3343 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3344
Chandler Carruth58d05562012-10-25 04:37:07 +00003345 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3346
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003347 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3348 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3349 // Zero out the operand and see if it becomes trivially dead.
3350 *OI = 0;
3351 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003352 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003353 }
3354
3355 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3356 DeletedAllocas.insert(AI);
3357
3358 ++NumDeleted;
3359 I->eraseFromParent();
3360 }
3361}
3362
Chandler Carruth70b44c52012-09-15 11:43:14 +00003363/// \brief Promote the allocas, using the best available technique.
3364///
3365/// This attempts to promote whatever allocas have been identified as viable in
3366/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3367/// If there is a domtree available, we attempt to promote using the full power
3368/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3369/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003370/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003371bool SROA::promoteAllocas(Function &F) {
3372 if (PromotableAllocas.empty())
3373 return false;
3374
3375 NumPromoted += PromotableAllocas.size();
3376
3377 if (DT && !ForceSSAUpdater) {
3378 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3379 PromoteMemToReg(PromotableAllocas, *DT);
3380 PromotableAllocas.clear();
3381 return true;
3382 }
3383
3384 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3385 SSAUpdater SSA;
3386 DIBuilder DIB(*F.getParent());
3387 SmallVector<Instruction*, 64> Insts;
3388
3389 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3390 AllocaInst *AI = PromotableAllocas[Idx];
3391 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3392 UI != UE;) {
3393 Instruction *I = cast<Instruction>(*UI++);
3394 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3395 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3396 // leading to them) here. Eventually it should use them to optimize the
3397 // scalar values produced.
3398 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3399 assert(onlyUsedByLifetimeMarkers(I) &&
3400 "Found a bitcast used outside of a lifetime marker.");
3401 while (!I->use_empty())
3402 cast<Instruction>(*I->use_begin())->eraseFromParent();
3403 I->eraseFromParent();
3404 continue;
3405 }
3406 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3407 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3408 II->getIntrinsicID() == Intrinsic::lifetime_end);
3409 II->eraseFromParent();
3410 continue;
3411 }
3412
3413 Insts.push_back(I);
3414 }
3415 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3416 Insts.clear();
3417 }
3418
3419 PromotableAllocas.clear();
3420 return true;
3421}
3422
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003423namespace {
3424 /// \brief A predicate to test whether an alloca belongs to a set.
3425 class IsAllocaInSet {
3426 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3427 const SetType &Set;
3428
3429 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003430 typedef AllocaInst *argument_type;
3431
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003432 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003433 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003434 };
3435}
3436
3437bool SROA::runOnFunction(Function &F) {
3438 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3439 C = &F.getContext();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003440 DL = getAnalysisIfAvailable<DataLayout>();
3441 if (!DL) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003442 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3443 return false;
3444 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003445 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003446
3447 BasicBlock &EntryBB = F.getEntryBlock();
3448 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3449 I != E; ++I)
3450 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3451 Worklist.insert(AI);
3452
3453 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003454 // A set of deleted alloca instruction pointers which should be removed from
3455 // the list of promotable allocas.
3456 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3457
Chandler Carruthac8317f2012-10-04 12:33:50 +00003458 do {
3459 while (!Worklist.empty()) {
3460 Changed |= runOnAlloca(*Worklist.pop_back_val());
3461 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003462
Chandler Carruthac8317f2012-10-04 12:33:50 +00003463 // Remove the deleted allocas from various lists so that we don't try to
3464 // continue processing them.
3465 if (!DeletedAllocas.empty()) {
3466 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3467 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3468 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3469 PromotableAllocas.end(),
3470 IsAllocaInSet(DeletedAllocas)),
3471 PromotableAllocas.end());
3472 DeletedAllocas.clear();
3473 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003474 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003475
Chandler Carruthac8317f2012-10-04 12:33:50 +00003476 Changed |= promoteAllocas(F);
3477
3478 Worklist = PostPromotionWorklist;
3479 PostPromotionWorklist.clear();
3480 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003481
3482 return Changed;
3483}
3484
3485void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003486 if (RequiresDomTree)
3487 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003488 AU.setPreservesCFG();
3489}