blob: 2ecc517d485bb17cf3c3aa225e3b63d083a97689 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000035#include "llvm/DIBuilder.h"
36#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Constants.h"
38#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#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 Carruth83cee772014-02-25 03:59:29 +000054#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include "llvm/Transforms/Utils/SSAUpdater.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000059
60#if __cplusplus >= 201103L && !defined(NDEBUG)
61// We only use this for a debug check in C++11
62#include <random>
63#endif
64
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065using namespace llvm;
66
67STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000068STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000069STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
70STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
71STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000072STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
73STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000074STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000075STATISTIC(NumDeleted, "Number of instructions deleted");
76STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000077
Chandler Carruth70b44c52012-09-15 11:43:14 +000078/// Hidden option to force the pass to not use DomTree and mem2reg, instead
79/// forming SSA values through the SSAUpdater infrastructure.
80static cl::opt<bool>
81ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
82
Chandler Carruth83cee772014-02-25 03:59:29 +000083/// Hidden option to enable randomly shuffling the slices to help uncover
84/// instability in their order.
85static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
86 cl::init(false), cl::Hidden);
87
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000088/// Hidden option to experiment with completely strict handling of inbounds
89/// GEPs.
90static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
91 cl::init(false), cl::Hidden);
92
Chandler Carruth1b398ae2012-09-14 09:22:59 +000093namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000094/// \brief A custom IRBuilder inserter which prefixes all names if they are
95/// preserved.
96template <bool preserveNames = true>
97class IRBuilderPrefixedInserter :
98 public IRBuilderDefaultInserter<preserveNames> {
99 std::string Prefix;
100
101public:
102 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
103
104protected:
105 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
106 BasicBlock::iterator InsertPt) const {
107 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
108 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
109 }
110};
111
112// Specialization for not preserving the name is trivial.
113template <>
114class IRBuilderPrefixedInserter<false> :
115 public IRBuilderDefaultInserter<false> {
116public:
117 void SetNamePrefix(const Twine &P) {}
118};
119
Chandler Carruthd177f862013-03-20 07:30:36 +0000120/// \brief Provide a typedef for IRBuilder that drops names in release builds.
121#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000122typedef llvm::IRBuilder<true, ConstantFolder,
123 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000124#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000125typedef llvm::IRBuilder<false, ConstantFolder,
126 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000127#endif
128}
129
130namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000131/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000132///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000133/// This structure represents a slice of an alloca used by some instruction. It
134/// stores both the begin and end offsets of this use, a pointer to the use
135/// itself, and a flag indicating whether we can classify the use as splittable
136/// or not when forming partitions of the alloca.
137class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000138 /// \brief The beginning offset of the range.
139 uint64_t BeginOffset;
140
141 /// \brief The ending offset, not included in the range.
142 uint64_t EndOffset;
143
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000144 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000145 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000147
148public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000149 Slice() : BeginOffset(), EndOffset() {}
150 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000151 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000152 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000153
154 uint64_t beginOffset() const { return BeginOffset; }
155 uint64_t endOffset() const { return EndOffset; }
156
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000157 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
158 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000159
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000160 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000161
162 bool isDead() const { return getUse() == 0; }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000163 void kill() { UseAndIsSplittable.setPointer(0); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000164
165 /// \brief Support for ordering ranges.
166 ///
167 /// This provides an ordering over ranges such that start offsets are
168 /// always increasing, and within equal start offsets, the end offsets are
169 /// decreasing. Thus the spanning range comes first in a cluster with the
170 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000171 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000172 if (beginOffset() < RHS.beginOffset()) return true;
173 if (beginOffset() > RHS.beginOffset()) return false;
174 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
175 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000176 return false;
177 }
178
179 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000181 uint64_t RHSOffset) {
182 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000183 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000184 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000185 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000186 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000187 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000188
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000189 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000190 return isSplittable() == RHS.isSplittable() &&
191 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000192 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000193 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000194};
Chandler Carruthf0546402013-07-18 07:15:00 +0000195} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000196
197namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000198template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000199template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000200 static const bool value = true;
201};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000202}
203
204namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000205/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000206///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000207/// This class represents the slices of an alloca which are formed by its
208/// various uses. If a pointer escapes, we can't fully build a representation
209/// for the slices used and we reflect that in this structure. The uses are
210/// stored, sorted by increasing beginning offset and with unsplittable slices
211/// starting at a particular offset before splittable slices.
212class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000213public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000214 /// \brief Construct the slices of a particular alloca.
215 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000216
217 /// \brief Test whether a pointer to the allocation escapes our analysis.
218 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000219 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000220 /// ignored.
221 bool isEscaped() const { return PointerEscapingInstr; }
222
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000223 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000224 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000225 typedef SmallVectorImpl<Slice>::iterator iterator;
226 iterator begin() { return Slices.begin(); }
227 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000228
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000229 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
230 const_iterator begin() const { return Slices.begin(); }
231 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000232 /// @}
233
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000234 /// \brief Allow iterating the dead users for this alloca.
235 ///
236 /// These are instructions which will never actually use the alloca as they
237 /// are outside the allocated range. They are safe to replace with undef and
238 /// delete.
239 /// @{
240 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
241 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
242 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
243 /// @}
244
Chandler Carruth93a21e72012-09-14 10:18:49 +0000245 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000246 ///
247 /// These are operands which have cannot actually be used to refer to the
248 /// alloca as they are outside its range and the user doesn't correct for
249 /// that. These mostly consist of PHI node inputs and the like which we just
250 /// need to replace with undef.
251 /// @{
252 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
253 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
254 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
255 /// @}
256
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000257#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000258 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000259 void printSlice(raw_ostream &OS, const_iterator I,
260 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000261 void printUse(raw_ostream &OS, const_iterator I,
262 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000264 void dump(const_iterator I) const;
265 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000266#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000267
268private:
269 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000270 class SliceBuilder;
271 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000272
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000273#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000274 /// \brief Handle to alloca instruction to simplify method interfaces.
275 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000276#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000277
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000278 /// \brief The instruction responsible for this alloca not having a known set
279 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000280 ///
281 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000282 /// store a pointer to that here and abort trying to form slices of the
283 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000284 Instruction *PointerEscapingInstr;
285
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000286 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000287 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000288 /// We store a vector of the slices formed by uses of the alloca here. This
289 /// vector is sorted by increasing begin offset, and then the unsplittable
290 /// slices before the splittable ones. See the Slice inner class for more
291 /// details.
292 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000293
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294 /// \brief Instructions which will become dead if we rewrite the alloca.
295 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000296 /// Note that these are not separated by slice. This is because we expect an
297 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
298 /// all these instructions can simply be removed and replaced with undef as
299 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000300 SmallVector<Instruction *, 8> DeadUsers;
301
302 /// \brief Operands which will become dead if we rewrite the alloca.
303 ///
304 /// These are operands that in their particular use can be replaced with
305 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
306 /// to PHI nodes and the like. They aren't entirely dead (there might be
307 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
308 /// want to swap this particular input for undef to simplify the use lists of
309 /// the alloca.
310 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000311};
312}
313
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000314static Value *foldSelectInst(SelectInst &SI) {
315 // If the condition being selected on is a constant or the same value is
316 // being selected between, fold the select. Yes this does (rarely) happen
317 // early on.
318 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
319 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000320 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000321 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000322
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000323 return 0;
324}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000325
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000326/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000327///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000328/// This class builds a set of alloca slices by recursively visiting the uses
329/// of an alloca and making a slice for each load and store at each offset.
330class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
331 friend class PtrUseVisitor<SliceBuilder>;
332 friend class InstVisitor<SliceBuilder>;
333 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000334
335 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000336 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000337
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000338 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000339 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
340
341 /// \brief Set to de-duplicate dead instructions found in the use walk.
342 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000343
344public:
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000345 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000346 : PtrUseVisitor<SliceBuilder>(DL),
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000347 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000348
349private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000350 void markAsDead(Instruction &I) {
351 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000352 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000353 }
354
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000355 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000356 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000357 // Completely skip uses which have a zero size or start either before or
358 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000359 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000360 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000361 << " which has zero size or starts outside of the "
362 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000363 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000364 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000365 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000366 }
367
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000368 uint64_t BeginOffset = Offset.getZExtValue();
369 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000370
371 // Clamp the end offset to the end of the allocation. Note that this is
372 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000373 // This may appear superficially to be something we could ignore entirely,
374 // but that is not so! There may be widened loads or PHI-node uses where
375 // some instructions are dead but not others. We can't completely ignore
376 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000377 assert(AllocSize >= BeginOffset); // Established above.
378 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000379 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
380 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000381 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000382 << " use: " << I << "\n");
383 EndOffset = AllocSize;
384 }
385
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000386 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000387 }
388
389 void visitBitCastInst(BitCastInst &BC) {
390 if (BC.use_empty())
391 return markAsDead(BC);
392
393 return Base::visitBitCastInst(BC);
394 }
395
396 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
397 if (GEPI.use_empty())
398 return markAsDead(GEPI);
399
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000400 if (SROAStrictInbounds && GEPI.isInBounds()) {
401 // FIXME: This is a manually un-factored variant of the basic code inside
402 // of GEPs with checking of the inbounds invariant specified in the
403 // langref in a very strict sense. If we ever want to enable
404 // SROAStrictInbounds, this code should be factored cleanly into
405 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
406 // by writing out the code here where we have tho underlying allocation
407 // size readily available.
408 APInt GEPOffset = Offset;
409 for (gep_type_iterator GTI = gep_type_begin(GEPI),
410 GTE = gep_type_end(GEPI);
411 GTI != GTE; ++GTI) {
412 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
413 if (!OpC)
414 break;
415
416 // Handle a struct index, which adds its field offset to the pointer.
417 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
418 unsigned ElementIdx = OpC->getZExtValue();
419 const StructLayout *SL = DL.getStructLayout(STy);
420 GEPOffset +=
421 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
422 } else {
423 // For array or vector indices, scale the index by the size of the type.
424 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
425 GEPOffset += Index * APInt(Offset.getBitWidth(),
426 DL.getTypeAllocSize(GTI.getIndexedType()));
427 }
428
429 // If this index has computed an intermediate pointer which is not
430 // inbounds, then the result of the GEP is a poison value and we can
431 // delete it and all uses.
432 if (GEPOffset.ugt(AllocSize))
433 return markAsDead(GEPI);
434 }
435 }
436
Chandler Carruthf0546402013-07-18 07:15:00 +0000437 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000438 }
439
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000440 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000441 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000442 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000443 // and cover the entire alloca. This prevents us from splitting over
444 // eagerly.
445 // FIXME: In the great blue eventually, we should eagerly split all integer
446 // loads and stores, and then have a separate step that merges adjacent
447 // alloca partitions into a single partition suitable for integer widening.
448 // Or we should skip the merge step and rely on GVN and other passes to
449 // merge adjacent loads and stores that survive mem2reg.
450 bool IsSplittable =
451 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000452
453 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000454 }
455
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000456 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000457 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
458 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000459
460 if (!IsOffsetKnown)
461 return PI.setAborted(&LI);
462
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000463 uint64_t Size = DL.getTypeStoreSize(LI.getType());
464 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000465 }
466
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000467 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000468 Value *ValOp = SI.getValueOperand();
469 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000470 return PI.setEscapedAndAborted(&SI);
471 if (!IsOffsetKnown)
472 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000473
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000474 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
475
476 // If this memory access can be shown to *statically* extend outside the
477 // bounds of of the allocation, it's behavior is undefined, so simply
478 // ignore it. Note that this is more strict than the generic clamping
479 // behavior of insertUse. We also try to handle cases which might run the
480 // risk of overflow.
481 // FIXME: We should instead consider the pointer to have escaped if this
482 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000483 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000484 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
485 << " which extends past the end of the " << AllocSize
486 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000487 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000488 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000489 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000490 }
491
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000492 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
493 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000494 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000495 }
496
497
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000498 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000499 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000500 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000501 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000502 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000503 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000504 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000505
506 if (!IsOffsetKnown)
507 return PI.setAborted(&II);
508
509 insertUse(II, Offset,
510 Length ? Length->getLimitedValue()
511 : AllocSize - Offset.getLimitedValue(),
512 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000513 }
514
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000515 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000516 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000517 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000518 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000519 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000520
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000521 // Because we can visit these intrinsics twice, also check to see if the
522 // first time marked this instruction as dead. If so, skip it.
523 if (VisitedDeadInsts.count(&II))
524 return;
525
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000526 if (!IsOffsetKnown)
527 return PI.setAborted(&II);
528
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000529 // This side of the transfer is completely out-of-bounds, and so we can
530 // nuke the entire transfer. However, we also need to nuke the other side
531 // if already added to our partitions.
532 // FIXME: Yet another place we really should bypass this when
533 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000534 if (Offset.uge(AllocSize)) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000535 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
536 if (MTPI != MemTransferSliceMap.end())
537 S.Slices[MTPI->second].kill();
538 return markAsDead(II);
539 }
540
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000541 uint64_t RawOffset = Offset.getLimitedValue();
542 uint64_t Size = Length ? Length->getLimitedValue()
543 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000544
Chandler Carruthf0546402013-07-18 07:15:00 +0000545 // Check for the special case where the same exact value is used for both
546 // source and dest.
547 if (*U == II.getRawDest() && *U == II.getRawSource()) {
548 // For non-volatile transfers this is a no-op.
549 if (!II.isVolatile())
550 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000551
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000552 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000553 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000554
Chandler Carruthf0546402013-07-18 07:15:00 +0000555 // If we have seen both source and destination for a mem transfer, then
556 // they both point to the same alloca.
557 bool Inserted;
558 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
559 llvm::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000560 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000561 unsigned PrevIdx = MTPI->second;
562 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000563 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000564
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000565 // Check if the begin offsets match and this is a non-volatile transfer.
566 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000567 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
568 PrevP.kill();
569 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000570 }
571
572 // Otherwise we have an offset transfer within the same alloca. We can't
573 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000574 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000575 }
576
Chandler Carruthe3899f22013-07-15 17:36:21 +0000577 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000578 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000579
Chandler Carruthf0546402013-07-18 07:15:00 +0000580 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000581 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
582 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000583 }
584
585 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000586 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000587 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000588 void visitIntrinsicInst(IntrinsicInst &II) {
589 if (!IsOffsetKnown)
590 return PI.setAborted(&II);
591
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000592 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
593 II.getIntrinsicID() == Intrinsic::lifetime_end) {
594 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000595 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
596 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000597 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000598 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000599 }
600
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000601 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000602 }
603
604 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
605 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000606 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000607 // are considered unsplittable and the size is the maximum loaded or stored
608 // size.
609 SmallPtrSet<Instruction *, 4> Visited;
610 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
611 Visited.insert(Root);
612 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000613 // If there are no loads or stores, the access is dead. We mark that as
614 // a size zero access.
615 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000616 do {
617 Instruction *I, *UsedI;
618 llvm::tie(UsedI, I) = Uses.pop_back_val();
619
620 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000621 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000622 continue;
623 }
624 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
625 Value *Op = SI->getOperand(0);
626 if (Op == UsedI)
627 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000628 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000629 continue;
630 }
631
632 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
633 if (!GEP->hasAllZeroIndices())
634 return GEP;
635 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
636 !isa<SelectInst>(I)) {
637 return I;
638 }
639
640 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
641 ++UI)
642 if (Visited.insert(cast<Instruction>(*UI)))
643 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
644 } while (!Uses.empty());
645
646 return 0;
647 }
648
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000649 void visitPHINode(PHINode &PN) {
650 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000651 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000652 if (!IsOffsetKnown)
653 return PI.setAborted(&PN);
654
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000655 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000656 uint64_t &PHISize = PHIOrSelectSizes[&PN];
657 if (!PHISize) {
658 // This is a new PHI node, check for an unsafe use of the PHI node.
659 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
660 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661 }
662
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000663 // For PHI and select operands outside the alloca, we can't nuke the entire
664 // phi or select -- the other side might still be relevant, so we special
665 // case them here and use a separate structure to track the operands
666 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000667 // FIXME: This should instead be escaped in the event we're instrumenting
668 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000669 if (Offset.uge(AllocSize)) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000670 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000671 return;
672 }
673
Chandler Carruthf0546402013-07-18 07:15:00 +0000674 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000675 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000676
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000677 void visitSelectInst(SelectInst &SI) {
678 if (SI.use_empty())
679 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000680 if (Value *Result = foldSelectInst(SI)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000681 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000682 // If the result of the constant fold will be the pointer, recurse
683 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000684 enqueueUsers(SI);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000685 else
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000686 // Otherwise the operand to the select is dead, and we can replace it
687 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000688 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000689
690 return;
691 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 if (!IsOffsetKnown)
693 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000694
Chandler Carruthf0546402013-07-18 07:15:00 +0000695 // See if we already have computed info on this node.
696 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
697 if (!SelectSize) {
698 // This is a new Select, check for an unsafe use of it.
699 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
700 return PI.setAborted(UnsafeI);
701 }
702
703 // For PHI and select operands outside the alloca, we can't nuke the entire
704 // phi or select -- the other side might still be relevant, so we special
705 // case them here and use a separate structure to track the operands
706 // themselves which should be replaced with undef.
707 // FIXME: This should instead be escaped in the event we're instrumenting
708 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000709 if (Offset.uge(AllocSize)) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000710 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000711 return;
712 }
713
714 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000715 }
716
Chandler Carruthf0546402013-07-18 07:15:00 +0000717 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000718 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000719 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000720 }
721};
722
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000723AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000724 :
725#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
726 AI(AI),
727#endif
728 PointerEscapingInstr(0) {
729 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000730 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000731 if (PtrI.isEscaped() || PtrI.isAborted()) {
732 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000733 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000734 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
735 : PtrI.getAbortingInst();
736 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000737 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000738 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000739
Benjamin Kramer08e50702013-07-20 08:38:34 +0000740 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
741 std::mem_fun_ref(&Slice::isDead)),
742 Slices.end());
743
Chandler Carruth83cee772014-02-25 03:59:29 +0000744#if __cplusplus >= 201103L && !defined(NDEBUG)
745 if (SROARandomShuffleSlices) {
746 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
747 std::shuffle(Slices.begin(), Slices.end(), MT);
748 }
749#endif
750
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000751 // Sort the uses. This arranges for the offsets to be in ascending order,
752 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000753 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000754}
755
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000756#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
757
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000758void AllocaSlices::print(raw_ostream &OS, const_iterator I,
759 StringRef Indent) const {
760 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000761 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000762}
763
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000764void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
765 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000766 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000767 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000768 << (I->isSplittable() ? " (splittable)" : "") << "\n";
769}
770
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000771void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
772 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000773 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000774}
775
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000776void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000778 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000779 << " A pointer to this alloca escaped by:\n"
780 << " " << *PointerEscapingInstr << "\n";
781 return;
782 }
783
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000784 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000785 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000786 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787}
788
Alp Tokerf929e092014-01-04 22:47:48 +0000789LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
790 print(dbgs(), I);
791}
792LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000793
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000794#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
795
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000796namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000797/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
798///
799/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
800/// the loads and stores of an alloca instruction, as well as updating its
801/// debug information. This is used when a domtree is unavailable and thus
802/// mem2reg in its full form can't be used to handle promotion of allocas to
803/// scalar values.
804class AllocaPromoter : public LoadAndStorePromoter {
805 AllocaInst &AI;
806 DIBuilder &DIB;
807
808 SmallVector<DbgDeclareInst *, 4> DDIs;
809 SmallVector<DbgValueInst *, 4> DVIs;
810
811public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000812 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000813 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000814 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000815
816 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000817 // Retain the debug information attached to the alloca for use when
818 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000819 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
820 for (Value::use_iterator UI = DebugNode->use_begin(),
821 UE = DebugNode->use_end();
822 UI != UE; ++UI)
823 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
824 DDIs.push_back(DDI);
825 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
826 DVIs.push_back(DVI);
827 }
828
829 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000830
831 // While we have the debug information, clear it off of the alloca. The
832 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000833 while (!DDIs.empty())
834 DDIs.pop_back_val()->eraseFromParent();
835 while (!DVIs.empty())
836 DVIs.pop_back_val()->eraseFromParent();
837 }
838
839 virtual bool isInstInList(Instruction *I,
840 const SmallVectorImpl<Instruction*> &Insts) const {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000841 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000842 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000843 Ptr = LI->getOperand(0);
844 else
845 Ptr = cast<StoreInst>(I)->getPointerOperand();
846
847 // Only used to detect cycles, which will be rare and quickly found as
848 // we're walking up a chain of defs rather than down through uses.
849 SmallPtrSet<Value *, 4> Visited;
850
851 do {
852 if (Ptr == &AI)
853 return true;
854
855 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
856 Ptr = BCI->getOperand(0);
857 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
858 Ptr = GEPI->getPointerOperand();
859 else
860 return false;
861
862 } while (Visited.insert(Ptr));
863
864 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000865 }
866
867 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000868 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000869 E = DDIs.end(); I != E; ++I) {
870 DbgDeclareInst *DDI = *I;
871 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
872 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
873 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
874 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
875 }
Craig Topper31ee5862013-07-03 15:07:05 +0000876 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000877 E = DVIs.end(); I != E; ++I) {
878 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000879 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000880 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
881 // If an argument is zero extended then use argument directly. The ZExt
882 // may be zapped by an optimization pass in future.
883 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
884 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000885 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000886 Arg = dyn_cast<Argument>(SExt->getOperand(0));
887 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000888 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000889 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000890 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000891 } else {
892 continue;
893 }
894 Instruction *DbgVal =
895 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
896 Inst);
897 DbgVal->setDebugLoc(DVI->getDebugLoc());
898 }
899 }
900};
901} // end anon namespace
902
903
904namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000905/// \brief An optimization pass providing Scalar Replacement of Aggregates.
906///
907/// This pass takes allocations which can be completely analyzed (that is, they
908/// don't escape) and tries to turn them into scalar SSA values. There are
909/// a few steps to this process.
910///
911/// 1) It takes allocations of aggregates and analyzes the ways in which they
912/// are used to try to split them into smaller allocations, ideally of
913/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000914/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000915/// 2) It will transform accesses into forms which are suitable for SSA value
916/// promotion. This can be replacing a memset with a scalar store of an
917/// integer value, or it can involve speculating operations on a PHI or
918/// select to be a PHI or select of the results.
919/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
920/// onto insert and extract operations on a vector value, and convert them to
921/// this form. By doing so, it will enable promotion of vector aggregates to
922/// SSA vector values.
923class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000924 const bool RequiresDomTree;
925
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000926 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000927 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000928 DominatorTree *DT;
929
930 /// \brief Worklist of alloca instructions to simplify.
931 ///
932 /// Each alloca in the function is added to this. Each new alloca formed gets
933 /// added to it as well to recursively simplify unless that alloca can be
934 /// directly promoted. Finally, each time we rewrite a use of an alloca other
935 /// the one being actively rewritten, we add it back onto the list if not
936 /// already present to ensure it is re-visited.
937 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
938
939 /// \brief A collection of instructions to delete.
940 /// We try to batch deletions to simplify code and make things a bit more
941 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000942 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000943
Chandler Carruthac8317f2012-10-04 12:33:50 +0000944 /// \brief Post-promotion worklist.
945 ///
946 /// Sometimes we discover an alloca which has a high probability of becoming
947 /// viable for SROA after a round of promotion takes place. In those cases,
948 /// the alloca is enqueued here for re-processing.
949 ///
950 /// Note that we have to be very careful to clear allocas out of this list in
951 /// the event they are deleted.
952 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
953
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000954 /// \brief A collection of alloca instructions we can directly promote.
955 std::vector<AllocaInst *> PromotableAllocas;
956
Chandler Carruthf0546402013-07-18 07:15:00 +0000957 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
958 ///
959 /// All of these PHIs have been checked for the safety of speculation and by
960 /// being speculated will allow promoting allocas currently in the promotable
961 /// queue.
962 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
963
964 /// \brief A worklist of select instructions to speculate prior to promoting
965 /// allocas.
966 ///
967 /// All of these select instructions have been checked for the safety of
968 /// speculation and by being speculated will allow promoting allocas
969 /// currently in the promotable queue.
970 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
971
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000972public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000973 SROA(bool RequiresDomTree = true)
974 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000975 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000976 initializeSROAPass(*PassRegistry::getPassRegistry());
977 }
978 bool runOnFunction(Function &F);
979 void getAnalysisUsage(AnalysisUsage &AU) const;
980
981 const char *getPassName() const { return "SROA"; }
982 static char ID;
983
984private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000985 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000986 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000987
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000988 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
989 AllocaSlices::iterator B, AllocaSlices::iterator E,
990 int64_t BeginOffset, int64_t EndOffset,
991 ArrayRef<AllocaSlices::iterator> SplitUses);
992 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000993 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000994 void clobberUse(Use &U);
Chandler Carruth19450da2012-09-14 10:26:38 +0000995 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000996 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000997};
998}
999
1000char SROA::ID = 0;
1001
Chandler Carruth70b44c52012-09-15 11:43:14 +00001002FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1003 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001004}
1005
1006INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1007 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +00001008INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001009INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1010 false, false)
1011
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001012/// Walk the range of a partitioning looking for a common type to cover this
1013/// sequence of slices.
1014static Type *findCommonType(AllocaSlices::const_iterator B,
1015 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001016 uint64_t EndOffset) {
1017 Type *Ty = 0;
Chandler Carruth4de31542014-01-21 23:16:05 +00001018 bool TyIsCommon = true;
1019 IntegerType *ITy = 0;
1020
1021 // Note that we need to look at *every* alloca slice's Use to ensure we
1022 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001023 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001024 Use *U = I->getUse();
1025 if (isa<IntrinsicInst>(*U->getUser()))
1026 continue;
1027 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1028 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001029
Chandler Carruthf0546402013-07-18 07:15:00 +00001030 Type *UserTy = 0;
Chandler Carrutha1262002013-11-19 09:03:18 +00001031 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001033 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001034 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001035 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001036
Chandler Carruth4de31542014-01-21 23:16:05 +00001037 if (!UserTy || (Ty && Ty != UserTy))
1038 TyIsCommon = false; // Give up on anything but an iN type.
1039 else
1040 Ty = UserTy;
1041
1042 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001043 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001044 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001045 // entity causing the split. Also skip if the type is not a byte width
1046 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001047 if (UserITy->getBitWidth() % 8 != 0 ||
1048 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001049 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001050
Chandler Carruth4de31542014-01-21 23:16:05 +00001051 // Track the largest bitwidth integer type used in this way in case there
1052 // is no common type.
1053 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1054 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001055 }
1056 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001057
1058 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001059}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001060
Chandler Carruthf0546402013-07-18 07:15:00 +00001061/// PHI instructions that use an alloca and are subsequently loaded can be
1062/// rewritten to load both input pointers in the pred blocks and then PHI the
1063/// results, allowing the load of the alloca to be promoted.
1064/// From this:
1065/// %P2 = phi [i32* %Alloca, i32* %Other]
1066/// %V = load i32* %P2
1067/// to:
1068/// %V1 = load i32* %Alloca -> will be mem2reg'd
1069/// ...
1070/// %V2 = load i32* %Other
1071/// ...
1072/// %V = phi [i32 %V1, i32 %V2]
1073///
1074/// We can do this to a select if its only uses are loads and if the operands
1075/// to the select can be loaded unconditionally.
1076///
1077/// FIXME: This should be hoisted into a generic utility, likely in
1078/// Transforms/Util/Local.h
1079static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +00001080 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001081 // For now, we can only do this promotion if the load is in the same block
1082 // as the PHI, and if there are no stores between the phi and load.
1083 // TODO: Allow recursive phi users.
1084 // TODO: Allow stores.
1085 BasicBlock *BB = PN.getParent();
1086 unsigned MaxAlign = 0;
1087 bool HaveLoad = false;
1088 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1089 ++UI) {
1090 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1091 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001092 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001093
Chandler Carruthf0546402013-07-18 07:15:00 +00001094 // For now we only allow loads in the same block as the PHI. This is
1095 // a common case that happens when instcombine merges two loads through
1096 // a PHI.
1097 if (LI->getParent() != BB)
1098 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001099
Chandler Carruthf0546402013-07-18 07:15:00 +00001100 // Ensure that there are no instructions between the PHI and the load that
1101 // could store.
1102 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1103 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001104 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001105
Chandler Carruthf0546402013-07-18 07:15:00 +00001106 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1107 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001108 }
1109
Chandler Carruthf0546402013-07-18 07:15:00 +00001110 if (!HaveLoad)
1111 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001112
Chandler Carruthf0546402013-07-18 07:15:00 +00001113 // We can only transform this if it is safe to push the loads into the
1114 // predecessor blocks. The only thing to watch out for is that we can't put
1115 // a possibly trapping load in the predecessor if it is a critical edge.
1116 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1117 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1118 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001119
Chandler Carruthf0546402013-07-18 07:15:00 +00001120 // If the value is produced by the terminator of the predecessor (an
1121 // invoke) or it has side-effects, there is no valid place to put a load
1122 // in the predecessor.
1123 if (TI == InVal || TI->mayHaveSideEffects())
1124 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001125
Chandler Carruthf0546402013-07-18 07:15:00 +00001126 // If the predecessor has a single successor, then the edge isn't
1127 // critical.
1128 if (TI->getNumSuccessors() == 1)
1129 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001130
Chandler Carruthf0546402013-07-18 07:15:00 +00001131 // If this pointer is always safe to load, or if we can prove that there
1132 // is already a load in the block, then we can move the load to the pred
1133 // block.
1134 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001135 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001136 continue;
1137
1138 return false;
1139 }
1140
1141 return true;
1142}
1143
1144static void speculatePHINodeLoads(PHINode &PN) {
1145 DEBUG(dbgs() << " original: " << PN << "\n");
1146
1147 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1148 IRBuilderTy PHIBuilder(&PN);
1149 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1150 PN.getName() + ".sroa.speculated");
1151
1152 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1153 // matter which one we get and if any differ.
1154 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1155 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1156 unsigned Align = SomeLoad->getAlignment();
1157
1158 // Rewrite all loads of the PN to use the new PHI.
1159 while (!PN.use_empty()) {
1160 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1161 LI->replaceAllUsesWith(NewPN);
1162 LI->eraseFromParent();
1163 }
1164
1165 // Inject loads into all of the pred blocks.
1166 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1167 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1168 TerminatorInst *TI = Pred->getTerminator();
1169 Value *InVal = PN.getIncomingValue(Idx);
1170 IRBuilderTy PredBuilder(TI);
1171
1172 LoadInst *Load = PredBuilder.CreateLoad(
1173 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1174 ++NumLoadsSpeculated;
1175 Load->setAlignment(Align);
1176 if (TBAATag)
1177 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1178 NewPN->addIncoming(Load, Pred);
1179 }
1180
1181 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1182 PN.eraseFromParent();
1183}
1184
1185/// Select instructions that use an alloca and are subsequently loaded can be
1186/// rewritten to load both input pointers and then select between the result,
1187/// allowing the load of the alloca to be promoted.
1188/// From this:
1189/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1190/// %V = load i32* %P2
1191/// to:
1192/// %V1 = load i32* %Alloca -> will be mem2reg'd
1193/// %V2 = load i32* %Other
1194/// %V = select i1 %cond, i32 %V1, i32 %V2
1195///
1196/// We can do this to a select if its only uses are loads and if the operand
1197/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001198static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001199 Value *TValue = SI.getTrueValue();
1200 Value *FValue = SI.getFalseValue();
1201 bool TDerefable = TValue->isDereferenceablePointer();
1202 bool FDerefable = FValue->isDereferenceablePointer();
1203
1204 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1205 ++UI) {
1206 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1207 if (LI == 0 || !LI->isSimple())
1208 return false;
1209
1210 // Both operands to the select need to be dereferencable, either
1211 // absolutely (e.g. allocas) or at this point because we can see other
1212 // accesses to it.
1213 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001214 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001215 return false;
1216 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001217 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001218 return false;
1219 }
1220
1221 return true;
1222}
1223
1224static void speculateSelectInstLoads(SelectInst &SI) {
1225 DEBUG(dbgs() << " original: " << SI << "\n");
1226
1227 IRBuilderTy IRB(&SI);
1228 Value *TV = SI.getTrueValue();
1229 Value *FV = SI.getFalseValue();
1230 // Replace the loads of the select with a select of two loads.
1231 while (!SI.use_empty()) {
1232 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1233 assert(LI->isSimple() && "We only speculate simple loads");
1234
1235 IRB.SetInsertPoint(LI);
1236 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001237 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001238 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001239 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001240 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001241
Chandler Carruthf0546402013-07-18 07:15:00 +00001242 // Transfer alignment and TBAA info if present.
1243 TL->setAlignment(LI->getAlignment());
1244 FL->setAlignment(LI->getAlignment());
1245 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1246 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1247 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001248 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001249
1250 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1251 LI->getName() + ".sroa.speculated");
1252
1253 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1254 LI->replaceAllUsesWith(V);
1255 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001256 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001257 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001258}
1259
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001260/// \brief Build a GEP out of a base pointer and indices.
1261///
1262/// This will return the BasePtr if that is valid, or build a new GEP
1263/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001264static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001265 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001266 if (Indices.empty())
1267 return BasePtr;
1268
1269 // A single zero index is a no-op, so check for this and avoid building a GEP
1270 // in that case.
1271 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1272 return BasePtr;
1273
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001274 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001275}
1276
1277/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1278/// TargetTy without changing the offset of the pointer.
1279///
1280/// This routine assumes we've already established a properly offset GEP with
1281/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1282/// zero-indices down through type layers until we find one the same as
1283/// TargetTy. If we can't find one with the same type, we at least try to use
1284/// one with the same size. If none of that works, we just produce the GEP as
1285/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001286static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001287 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001288 SmallVectorImpl<Value *> &Indices,
1289 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001290 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001291 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001292
1293 // See if we can descend into a struct and locate a field with the correct
1294 // type.
1295 unsigned NumLayers = 0;
1296 Type *ElementTy = Ty;
1297 do {
1298 if (ElementTy->isPointerTy())
1299 break;
1300 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1301 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001302 // Note that we use the default address space as this index is over an
1303 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001304 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001305 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001306 if (STy->element_begin() == STy->element_end())
1307 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001308 ElementTy = *STy->element_begin();
1309 Indices.push_back(IRB.getInt32(0));
1310 } else {
1311 break;
1312 }
1313 ++NumLayers;
1314 } while (ElementTy != TargetTy);
1315 if (ElementTy != TargetTy)
1316 Indices.erase(Indices.end() - NumLayers, Indices.end());
1317
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001318 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001319}
1320
1321/// \brief Recursively compute indices for a natural GEP.
1322///
1323/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1324/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001325static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001326 Value *Ptr, Type *Ty, APInt &Offset,
1327 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001328 SmallVectorImpl<Value *> &Indices,
1329 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001330 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001331 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001332
1333 // We can't recurse through pointer types.
1334 if (Ty->isPointerTy())
1335 return 0;
1336
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001337 // We try to analyze GEPs over vectors here, but note that these GEPs are
1338 // extremely poorly defined currently. The long-term goal is to remove GEPing
1339 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001340 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001341 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001343 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001344 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001345 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001346 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1347 return 0;
1348 Offset -= NumSkippedElements * ElementSize;
1349 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001350 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001351 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001352 }
1353
1354 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1355 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001356 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001357 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001358 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1359 return 0;
1360
1361 Offset -= NumSkippedElements * ElementSize;
1362 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001363 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001364 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001365 }
1366
1367 StructType *STy = dyn_cast<StructType>(Ty);
1368 if (!STy)
1369 return 0;
1370
Chandler Carruth90a735d2013-07-19 07:21:28 +00001371 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001372 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001373 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001374 return 0;
1375 unsigned Index = SL->getElementContainingOffset(StructOffset);
1376 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1377 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001378 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001379 return 0; // The offset points into alignment padding.
1380
1381 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001382 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001383 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001384}
1385
1386/// \brief Get a natural GEP from a base pointer to a particular offset and
1387/// resulting in a particular type.
1388///
1389/// The goal is to produce a "natural" looking GEP that works with the existing
1390/// composite types to arrive at the appropriate offset and element type for
1391/// a pointer. TargetTy is the element type the returned GEP should point-to if
1392/// possible. We recurse by decreasing Offset, adding the appropriate index to
1393/// Indices, and setting Ty to the result subtype.
1394///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001395/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001396static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001398 SmallVectorImpl<Value *> &Indices,
1399 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 PointerType *Ty = cast<PointerType>(Ptr->getType());
1401
1402 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1403 // an i8.
1404 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1405 return 0;
1406
1407 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001408 if (!ElementTy->isSized())
1409 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001410 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001411 if (ElementSize == 0)
1412 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001413 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414
1415 Offset -= NumSkippedElements * ElementSize;
1416 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001417 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001418 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001419}
1420
1421/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1422/// resulting pointer has PointerTy.
1423///
1424/// This tries very hard to compute a "natural" GEP which arrives at the offset
1425/// and produces the pointer type desired. Where it cannot, it will try to use
1426/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1427/// fails, it will try to use an existing i8* and GEP to the byte offset and
1428/// bitcast to the type.
1429///
1430/// The strategy for finding the more natural GEPs is to peel off layers of the
1431/// pointer, walking back through bit casts and GEPs, searching for a base
1432/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001433/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001434/// a single GEP as possible, thus making each GEP more independent of the
1435/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001436static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1437 APInt Offset, Type *PointerTy,
1438 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001439 // Even though we don't look through PHI nodes, we could be called on an
1440 // instruction in an unreachable block, which may be on a cycle.
1441 SmallPtrSet<Value *, 4> Visited;
1442 Visited.insert(Ptr);
1443 SmallVector<Value *, 4> Indices;
1444
1445 // We may end up computing an offset pointer that has the wrong type. If we
1446 // never are able to compute one directly that has the correct type, we'll
1447 // fall back to it, so keep it around here.
1448 Value *OffsetPtr = 0;
1449
1450 // Remember any i8 pointer we come across to re-use if we need to do a raw
1451 // byte offset.
1452 Value *Int8Ptr = 0;
1453 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1454
1455 Type *TargetTy = PointerTy->getPointerElementType();
1456
1457 do {
1458 // First fold any existing GEPs into the offset.
1459 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1460 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001461 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001462 break;
1463 Offset += GEPOffset;
1464 Ptr = GEP->getPointerOperand();
1465 if (!Visited.insert(Ptr))
1466 break;
1467 }
1468
1469 // See if we can perform a natural GEP here.
1470 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001471 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001472 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001473 if (P->getType() == PointerTy) {
1474 // Zap any offset pointer that we ended up computing in previous rounds.
1475 if (OffsetPtr && OffsetPtr->use_empty())
1476 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1477 I->eraseFromParent();
1478 return P;
1479 }
1480 if (!OffsetPtr) {
1481 OffsetPtr = P;
1482 }
1483 }
1484
1485 // Stash this pointer if we've found an i8*.
1486 if (Ptr->getType()->isIntegerTy(8)) {
1487 Int8Ptr = Ptr;
1488 Int8PtrOffset = Offset;
1489 }
1490
1491 // Peel off a layer of the pointer and update the offset appropriately.
1492 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1493 Ptr = cast<Operator>(Ptr)->getOperand(0);
1494 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1495 if (GA->mayBeOverridden())
1496 break;
1497 Ptr = GA->getAliasee();
1498 } else {
1499 break;
1500 }
1501 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1502 } while (Visited.insert(Ptr));
1503
1504 if (!OffsetPtr) {
1505 if (!Int8Ptr) {
1506 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001507 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508 Int8PtrOffset = Offset;
1509 }
1510
1511 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1512 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001513 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001514 }
1515 Ptr = OffsetPtr;
1516
1517 // On the off chance we were targeting i8*, guard the bitcast here.
1518 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001519 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001520
1521 return Ptr;
1522}
1523
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001524/// \brief Test whether we can convert a value from the old to the new type.
1525///
1526/// This predicate should be used to guard calls to convertValue in order to
1527/// ensure that we only try to convert viable values. The strategy is that we
1528/// will peel off single element struct and array wrappings to get to an
1529/// underlying value, and convert that value.
1530static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1531 if (OldTy == NewTy)
1532 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001533 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1534 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1535 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1536 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001537 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1538 return false;
1539 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1540 return false;
1541
Benjamin Kramer56262592013-09-22 11:24:58 +00001542 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001543 // of pointers and integers.
1544 OldTy = OldTy->getScalarType();
1545 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001546 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1547 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1548 return true;
1549 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1550 return true;
1551 return false;
1552 }
1553
1554 return true;
1555}
1556
1557/// \brief Generic routine to convert an SSA value to a value of a different
1558/// type.
1559///
1560/// This will try various different casting techniques, such as bitcasts,
1561/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1562/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001563static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001564 Type *NewTy) {
1565 Type *OldTy = V->getType();
1566 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1567
1568 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001569 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001570
1571 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1572 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001573 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1574 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001575
Benjamin Kramer90901a32013-09-21 20:36:04 +00001576 // See if we need inttoptr for this type pair. A cast involving both scalars
1577 // and vectors requires and additional bitcast.
1578 if (OldTy->getScalarType()->isIntegerTy() &&
1579 NewTy->getScalarType()->isPointerTy()) {
1580 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1581 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1582 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1583 NewTy);
1584
1585 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1586 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1587 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1588 NewTy);
1589
1590 return IRB.CreateIntToPtr(V, NewTy);
1591 }
1592
1593 // See if we need ptrtoint for this type pair. A cast involving both scalars
1594 // and vectors requires and additional bitcast.
1595 if (OldTy->getScalarType()->isPointerTy() &&
1596 NewTy->getScalarType()->isIntegerTy()) {
1597 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1598 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1599 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1600 NewTy);
1601
1602 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1603 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1604 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1605 NewTy);
1606
1607 return IRB.CreatePtrToInt(V, NewTy);
1608 }
1609
1610 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001611}
1612
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001613/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001614///
1615/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001616/// for a single slice.
1617static bool isVectorPromotionViableForSlice(
1618 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1619 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1620 AllocaSlices::const_iterator I) {
1621 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001622 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001623 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001624 uint64_t BeginIndex = BeginOffset / ElementSize;
1625 if (BeginIndex * ElementSize != BeginOffset ||
1626 BeginIndex >= Ty->getNumElements())
1627 return false;
1628 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001629 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001630 uint64_t EndIndex = EndOffset / ElementSize;
1631 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1632 return false;
1633
1634 assert(EndIndex > BeginIndex && "Empty vector!");
1635 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001636 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001637 (NumElements == 1) ? Ty->getElementType()
1638 : VectorType::get(Ty->getElementType(), NumElements);
1639
1640 Type *SplitIntTy =
1641 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1642
1643 Use *U = I->getUse();
1644
1645 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1646 if (MI->isVolatile())
1647 return false;
1648 if (!I->isSplittable())
1649 return false; // Skip any unsplittable intrinsics.
1650 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1651 // Disable vector promotion when there are loads or stores of an FCA.
1652 return false;
1653 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1654 if (LI->isVolatile())
1655 return false;
1656 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001657 if (SliceBeginOffset > I->beginOffset() ||
1658 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001659 assert(LTy->isIntegerTy());
1660 LTy = SplitIntTy;
1661 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001662 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001663 return false;
1664 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1665 if (SI->isVolatile())
1666 return false;
1667 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001668 if (SliceBeginOffset > I->beginOffset() ||
1669 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001670 assert(STy->isIntegerTy());
1671 STy = SplitIntTy;
1672 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001673 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001674 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001675 } else {
1676 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001677 }
1678
1679 return true;
1680}
1681
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001682/// \brief Test whether the given alloca partitioning and range of slices can be
1683/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001684///
1685/// This is a quick test to check whether we can rewrite a particular alloca
1686/// partition (and its newly formed alloca) into a vector alloca with only
1687/// whole-vector loads and stores such that it could be promoted to a vector
1688/// SSA value. We only can ensure this for a limited set of operations, and we
1689/// don't want to do the rewrites unless we are confident that the result will
1690/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001691static bool
1692isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1693 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1694 AllocaSlices::const_iterator I,
1695 AllocaSlices::const_iterator E,
1696 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001697 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1698 if (!Ty)
1699 return false;
1700
Chandler Carruth90a735d2013-07-19 07:21:28 +00001701 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001702
1703 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1704 // that aren't byte sized.
1705 if (ElementSize % 8)
1706 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001707 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001708 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001709 ElementSize /= 8;
1710
Chandler Carruthf0546402013-07-18 07:15:00 +00001711 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001712 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1713 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001714 return false;
1715
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001716 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1717 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001718 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001719 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1720 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001721 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001722
1723 return true;
1724}
1725
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001726/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001727///
1728/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001729/// test below on a single slice of the alloca.
1730static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1731 Type *AllocaTy,
1732 uint64_t AllocBeginOffset,
1733 uint64_t Size, AllocaSlices &S,
1734 AllocaSlices::const_iterator I,
1735 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001736 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1737 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1738
1739 // We can't reasonably handle cases where the load or store extends past
1740 // the end of the aloca's type and into its padding.
1741 if (RelEnd > Size)
1742 return false;
1743
1744 Use *U = I->getUse();
1745
1746 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1747 if (LI->isVolatile())
1748 return false;
1749 if (RelBegin == 0 && RelEnd == Size)
1750 WholeAllocaOp = true;
1751 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001752 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001753 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001754 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001755 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001756 // Non-integer loads need to be convertible from the alloca type so that
1757 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001758 return false;
1759 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001760 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1761 Type *ValueTy = SI->getValueOperand()->getType();
1762 if (SI->isVolatile())
1763 return false;
1764 if (RelBegin == 0 && RelEnd == Size)
1765 WholeAllocaOp = true;
1766 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001767 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001768 return false;
1769 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001770 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001771 // Non-integer stores need to be convertible to the alloca type so that
1772 // they are promotable.
1773 return false;
1774 }
1775 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1776 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1777 return false;
1778 if (!I->isSplittable())
1779 return false; // Skip any unsplittable intrinsics.
1780 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1781 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1782 II->getIntrinsicID() != Intrinsic::lifetime_end)
1783 return false;
1784 } else {
1785 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001786 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001787
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001788 return true;
1789}
1790
Chandler Carruth435c4e02012-10-15 08:40:30 +00001791/// \brief Test whether the given alloca partition's integer operations can be
1792/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001793///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001794/// This is a quick test to check whether we can rewrite the integer loads and
1795/// stores to a particular alloca into wider loads and stores and be able to
1796/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001797static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001798isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001799 uint64_t AllocBeginOffset, AllocaSlices &S,
1800 AllocaSlices::const_iterator I,
1801 AllocaSlices::const_iterator E,
1802 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001803 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001804 // Don't create integer types larger than the maximum bitwidth.
1805 if (SizeInBits > IntegerType::MAX_INT_BITS)
1806 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001807
1808 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001809 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001810 return false;
1811
Chandler Carruth58d05562012-10-25 04:37:07 +00001812 // We need to ensure that an integer type with the appropriate bitwidth can
1813 // be converted to the alloca type, whatever that is. We don't want to force
1814 // the alloca itself to have an integer type if there is a more suitable one.
1815 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001816 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1817 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001818 return false;
1819
Chandler Carruth90a735d2013-07-19 07:21:28 +00001820 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001821
Chandler Carruthf0546402013-07-18 07:15:00 +00001822 // While examining uses, we ensure that the alloca has a covering load or
1823 // store. We don't want to widen the integer operations only to fail to
1824 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001825 // later). However, if there are only splittable uses, go ahead and assume
1826 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001827 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001828
Chandler Carruthf0546402013-07-18 07:15:00 +00001829 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001830 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1831 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001832 return false;
1833
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001834 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1835 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001836 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001837 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1838 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001839 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001840
Chandler Carruth92924fd2012-09-24 00:34:20 +00001841 return WholeAllocaOp;
1842}
1843
Chandler Carruthd177f862013-03-20 07:30:36 +00001844static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001845 IntegerType *Ty, uint64_t Offset,
1846 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001847 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001848 IntegerType *IntTy = cast<IntegerType>(V->getType());
1849 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1850 "Element extends past full value");
1851 uint64_t ShAmt = 8*Offset;
1852 if (DL.isBigEndian())
1853 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001854 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001855 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001856 DEBUG(dbgs() << " shifted: " << *V << "\n");
1857 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001858 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1859 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001860 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001861 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001862 DEBUG(dbgs() << " trunced: " << *V << "\n");
1863 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001864 return V;
1865}
1866
Chandler Carruthd177f862013-03-20 07:30:36 +00001867static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001868 Value *V, uint64_t Offset, const Twine &Name) {
1869 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1870 IntegerType *Ty = cast<IntegerType>(V->getType());
1871 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1872 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001873 DEBUG(dbgs() << " start: " << *V << "\n");
1874 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001875 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001876 DEBUG(dbgs() << " extended: " << *V << "\n");
1877 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001878 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1879 "Element store outside of alloca store");
1880 uint64_t ShAmt = 8*Offset;
1881 if (DL.isBigEndian())
1882 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001883 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001884 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001885 DEBUG(dbgs() << " shifted: " << *V << "\n");
1886 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001887
1888 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1889 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1890 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001891 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001892 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001893 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001894 }
1895 return V;
1896}
1897
Chandler Carruthd177f862013-03-20 07:30:36 +00001898static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001899 unsigned BeginIndex, unsigned EndIndex,
1900 const Twine &Name) {
1901 VectorType *VecTy = cast<VectorType>(V->getType());
1902 unsigned NumElements = EndIndex - BeginIndex;
1903 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1904
1905 if (NumElements == VecTy->getNumElements())
1906 return V;
1907
1908 if (NumElements == 1) {
1909 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1910 Name + ".extract");
1911 DEBUG(dbgs() << " extract: " << *V << "\n");
1912 return V;
1913 }
1914
1915 SmallVector<Constant*, 8> Mask;
1916 Mask.reserve(NumElements);
1917 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1918 Mask.push_back(IRB.getInt32(i));
1919 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1920 ConstantVector::get(Mask),
1921 Name + ".extract");
1922 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1923 return V;
1924}
1925
Chandler Carruthd177f862013-03-20 07:30:36 +00001926static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001927 unsigned BeginIndex, const Twine &Name) {
1928 VectorType *VecTy = cast<VectorType>(Old->getType());
1929 assert(VecTy && "Can only insert a vector into a vector");
1930
1931 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1932 if (!Ty) {
1933 // Single element to insert.
1934 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1935 Name + ".insert");
1936 DEBUG(dbgs() << " insert: " << *V << "\n");
1937 return V;
1938 }
1939
1940 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1941 "Too many elements!");
1942 if (Ty->getNumElements() == VecTy->getNumElements()) {
1943 assert(V->getType() == VecTy && "Vector type mismatch");
1944 return V;
1945 }
1946 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1947
1948 // When inserting a smaller vector into the larger to store, we first
1949 // use a shuffle vector to widen it with undef elements, and then
1950 // a second shuffle vector to select between the loaded vector and the
1951 // incoming vector.
1952 SmallVector<Constant*, 8> Mask;
1953 Mask.reserve(VecTy->getNumElements());
1954 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1955 if (i >= BeginIndex && i < EndIndex)
1956 Mask.push_back(IRB.getInt32(i - BeginIndex));
1957 else
1958 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1959 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1960 ConstantVector::get(Mask),
1961 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001962 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001963
1964 Mask.clear();
1965 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001966 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1967
1968 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1969
1970 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001971 return V;
1972}
1973
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001974namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001975/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1976/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001977///
1978/// Also implements the rewriting to vector-based accesses when the partition
1979/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1980/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001981class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001982 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001983 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1984 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001985
Chandler Carruth90a735d2013-07-19 07:21:28 +00001986 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001987 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001988 SROA &Pass;
1989 AllocaInst &OldAI, &NewAI;
1990 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001991 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001992
1993 // If we are rewriting an alloca partition which can be written as pure
1994 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001995 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001996 // - The new alloca is exactly the size of the vector type here.
1997 // - The accesses all either map to the entire vector or to a single
1998 // element.
1999 // - The set of accessing instructions is only one of those handled above
2000 // in isVectorPromotionViable. Generally these are the same access kinds
2001 // which are promotable via mem2reg.
2002 VectorType *VecTy;
2003 Type *ElementTy;
2004 uint64_t ElementSize;
2005
Chandler Carruth92924fd2012-09-24 00:34:20 +00002006 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002007 // alloca's integer operations should be widened to this integer type due to
2008 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002009 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002010 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002011
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002012 // The original offset of the slice currently being rewritten relative to
2013 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002014 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002015 // The new offsets of the slice currently being rewritten relative to the
2016 // original alloca.
2017 uint64_t NewBeginOffset, NewEndOffset;
2018
2019 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002020 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002021 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002022 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002023 Instruction *OldPtr;
2024
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002025 // Track post-rewrite users which are PHI nodes and Selects.
2026 SmallPtrSetImpl<PHINode *> &PHIUsers;
2027 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002028
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002029 // Utility IR builder, whose name prefix is setup for each visited use, and
2030 // the insertion point is set to point to the user.
2031 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002032
2033public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002034 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
2035 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002036 uint64_t NewAllocaBeginOffset,
2037 uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
2038 bool IsIntegerPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002039 SmallPtrSetImpl<PHINode *> &PHIUsers,
2040 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002041 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002042 NewAllocaBeginOffset(NewAllocaBeginOffset),
2043 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002044 NewAllocaTy(NewAI.getAllocatedType()),
2045 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
2046 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002047 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002048 IntTy(IsIntegerPromotable
2049 ? Type::getIntNTy(
2050 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002051 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00002052 : 0),
2053 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002054 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002055 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002056 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002057 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002058 "Only multiple-of-8 sized vector elements are viable");
2059 ++NumVectorized;
2060 }
2061 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
2062 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002063 }
2064
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002065 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002066 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002067 BeginOffset = I->beginOffset();
2068 EndOffset = I->endOffset();
2069 IsSplittable = I->isSplittable();
2070 IsSplit =
2071 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002072
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002073 // Compute the intersecting offset range.
2074 assert(BeginOffset < NewAllocaEndOffset);
2075 assert(EndOffset > NewAllocaBeginOffset);
2076 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2077 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2078
2079 SliceSize = NewEndOffset - NewBeginOffset;
2080
Chandler Carruthf0546402013-07-18 07:15:00 +00002081 OldUse = I->getUse();
2082 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002083
Chandler Carruthf0546402013-07-18 07:15:00 +00002084 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2085 IRB.SetInsertPoint(OldUserI);
2086 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2087 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2088
2089 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2090 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002091 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002092 return CanSROA;
2093 }
2094
2095private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002096 // Make sure the other visit overloads are visible.
2097 using Base::visit;
2098
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002099 // Every instruction which can end up as a user must have a rewrite rule.
2100 bool visitInstruction(Instruction &I) {
2101 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2102 llvm_unreachable("No rewrite rule for this instruction!");
2103 }
2104
Chandler Carruthf0546402013-07-18 07:15:00 +00002105 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2106 Type *PointerTy) {
2107 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002108#ifndef NDEBUG
2109 StringRef OldName = OldPtr->getName();
2110 // Skip through the last '.sroa.' component of the name.
2111 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2112 if (LastSROAPrefix != StringRef::npos) {
2113 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2114 // Look for an SROA slice index.
2115 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2116 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2117 // Strip the index and look for the offset.
2118 OldName = OldName.substr(IndexEnd + 1);
2119 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2120 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2121 // Strip the offset.
2122 OldName = OldName.substr(OffsetEnd + 1);
2123 }
2124 }
2125 // Strip any SROA suffixes as well.
2126 OldName = OldName.substr(0, OldName.find(".sroa_"));
2127#endif
Chandler Carruth90a735d2013-07-19 07:21:28 +00002128 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002129 Offset - NewAllocaBeginOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002130 PointerTy,
2131#ifndef NDEBUG
2132 Twine(OldName) + "."
2133#else
2134 Twine()
2135#endif
2136 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002137 }
2138
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002139 /// \brief Compute suitable alignment to access an offset into the new alloca.
2140 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002141 unsigned NewAIAlign = NewAI.getAlignment();
2142 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002143 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00002144 return MinAlign(NewAIAlign, Offset);
2145 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002146
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002147 /// \brief Compute suitable alignment to access a type at an offset of the
2148 /// new alloca.
2149 ///
2150 /// \returns zero if the type's ABI alignment is a suitable alignment,
2151 /// otherwise returns the maximal suitable alignment.
2152 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2153 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002154 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002155 }
2156
Chandler Carruth845b73c2012-11-21 08:16:30 +00002157 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002158 assert(VecTy && "Can only call getIndex when rewriting a vector");
2159 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2160 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2161 uint32_t Index = RelOffset / ElementSize;
2162 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002163 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002164 }
2165
2166 void deleteIfTriviallyDead(Value *V) {
2167 Instruction *I = cast<Instruction>(V);
2168 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002169 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002170 }
2171
Chandler Carruthea27cf02014-02-26 04:25:04 +00002172 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002173 unsigned BeginIndex = getIndex(NewBeginOffset);
2174 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002175 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002176
2177 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002178 "load");
2179 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002180 }
2181
Chandler Carruthea27cf02014-02-26 04:25:04 +00002182 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002183 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002184 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002185 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002186 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002187 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002188 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2189 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2190 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002191 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002192 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002193 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002194 }
2195
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002196 bool visitLoadInst(LoadInst &LI) {
2197 DEBUG(dbgs() << " original: " << LI << "\n");
2198 Value *OldOp = LI.getOperand(0);
2199 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002200
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002201 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002202 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002203 bool IsPtrAdjusted = false;
2204 Value *V;
2205 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002206 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002207 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002208 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002209 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002210 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002211 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002212 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002213 } else {
2214 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002215 V = IRB.CreateAlignedLoad(
2216 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2217 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002218 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002219 IsPtrAdjusted = true;
2220 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002221 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002222
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002223 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002224 assert(!LI.isVolatile());
2225 assert(LI.getType()->isIntegerTy() &&
2226 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002227 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002228 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002229 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002230 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002231 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002232 // Move the insertion point just past the load so that we can refer to it.
2233 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002234 // Create a placeholder value with the same type as LI to use as the
2235 // basis for the new value. This allows us to replace the uses of LI with
2236 // the computed value, and then replace the placeholder with LI, leaving
2237 // LI only used for this computation.
2238 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002239 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002240 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002241 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002242 LI.replaceAllUsesWith(V);
2243 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002244 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002245 } else {
2246 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002247 }
2248
Chandler Carruth18db7952012-11-20 01:12:50 +00002249 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002250 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002251 DEBUG(dbgs() << " to: " << *V << "\n");
2252 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002253 }
2254
Chandler Carruthea27cf02014-02-26 04:25:04 +00002255 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002256 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002257 unsigned BeginIndex = getIndex(NewBeginOffset);
2258 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002259 assert(EndIndex > BeginIndex && "Empty vector!");
2260 unsigned NumElements = EndIndex - BeginIndex;
2261 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002262 Type *SliceTy =
2263 (NumElements == 1) ? ElementTy
2264 : VectorType::get(ElementTy, NumElements);
2265 if (V->getType() != SliceTy)
2266 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002267
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002268 // Mix in the existing elements.
2269 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2270 "load");
2271 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2272 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002273 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002274 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002275
2276 (void)Store;
2277 DEBUG(dbgs() << " to: " << *Store << "\n");
2278 return true;
2279 }
2280
Chandler Carruthea27cf02014-02-26 04:25:04 +00002281 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002282 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002283 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002284 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002285 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002286 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002287 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002288 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2289 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002290 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002291 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002292 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002293 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002294 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002295 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002296 (void)Store;
2297 DEBUG(dbgs() << " to: " << *Store << "\n");
2298 return true;
2299 }
2300
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002301 bool visitStoreInst(StoreInst &SI) {
2302 DEBUG(dbgs() << " original: " << SI << "\n");
2303 Value *OldOp = SI.getOperand(1);
2304 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002305
Chandler Carruth18db7952012-11-20 01:12:50 +00002306 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002307
Chandler Carruthac8317f2012-10-04 12:33:50 +00002308 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2309 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002310 if (V->getType()->isPointerTy())
2311 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002312 Pass.PostPromotionWorklist.insert(AI);
2313
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002314 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002315 assert(!SI.isVolatile());
2316 assert(V->getType()->isIntegerTy() &&
2317 "Only integer type loads and stores are split");
2318 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002319 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002320 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002321 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002322 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002323 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002324 }
2325
Chandler Carruth18db7952012-11-20 01:12:50 +00002326 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002327 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002328 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002329 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002330
Chandler Carruth18db7952012-11-20 01:12:50 +00002331 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002332 if (NewBeginOffset == NewAllocaBeginOffset &&
2333 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002334 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2335 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002336 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2337 SI.isVolatile());
2338 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002339 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2340 V->getType()->getPointerTo());
2341 NewSI = IRB.CreateAlignedStore(
Chandler Carruth7625c542014-02-25 11:07:58 +00002342 V, NewPtr, getOffsetTypeAlign(V->getType(),
2343 NewBeginOffset - NewAllocaBeginOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002344 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002345 }
2346 (void)NewSI;
2347 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002348 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002349
2350 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2351 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002352 }
2353
Chandler Carruth514f34f2012-12-17 04:07:30 +00002354 /// \brief Compute an integer value from splatting an i8 across the given
2355 /// number of bytes.
2356 ///
2357 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2358 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002359 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002360 ///
2361 /// \param V The i8 value to splat.
2362 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002363 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002364 assert(Size > 0 && "Expected a positive number of bytes.");
2365 IntegerType *VTy = cast<IntegerType>(V->getType());
2366 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2367 if (Size == 1)
2368 return V;
2369
2370 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002371 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002372 ConstantExpr::getUDiv(
2373 Constant::getAllOnesValue(SplatIntTy),
2374 ConstantExpr::getZExt(
2375 Constant::getAllOnesValue(V->getType()),
2376 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002377 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002378 return V;
2379 }
2380
Chandler Carruthccca5042012-12-17 04:07:37 +00002381 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002382 Value *getVectorSplat(Value *V, unsigned NumElements) {
2383 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002384 DEBUG(dbgs() << " splat: " << *V << "\n");
2385 return V;
2386 }
2387
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388 bool visitMemSetInst(MemSetInst &II) {
2389 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002390 assert(II.getRawDest() == OldPtr);
2391
2392 // If the memset has a variable size, it cannot be split, just adjust the
2393 // pointer to the new alloca.
2394 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002395 assert(!IsSplit);
2396 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth8183a502014-02-25 11:08:02 +00002397 II.setDest(getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002398 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002399 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002400
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002401 deleteIfTriviallyDead(OldPtr);
2402 return false;
2403 }
2404
2405 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002406 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002407
2408 Type *AllocaTy = NewAI.getAllocatedType();
2409 Type *ScalarTy = AllocaTy->getScalarType();
2410
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002411 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002412
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002413 // If this doesn't map cleanly onto the alloca type, and that type isn't
2414 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002415 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002416 (BeginOffset > NewAllocaBeginOffset ||
2417 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002418 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002419 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2420 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002421 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002422 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2423 CallInst *New = IRB.CreateMemSet(
Chandler Carruth8183a502014-02-25 11:08:02 +00002424 getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002425 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002426 (void)New;
2427 DEBUG(dbgs() << " to: " << *New << "\n");
2428 return false;
2429 }
2430
2431 // If we can represent this as a simple value, we have to build the actual
2432 // value to store, which requires expanding the byte present in memset to
2433 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002434 // splatting the byte to a sufficiently wide integer, splatting it across
2435 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002436 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002437
Chandler Carruthccca5042012-12-17 04:07:37 +00002438 if (VecTy) {
2439 // If this is a memset of a vectorized alloca, insert it.
2440 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002441
Chandler Carruthf0546402013-07-18 07:15:00 +00002442 unsigned BeginIndex = getIndex(NewBeginOffset);
2443 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002444 assert(EndIndex > BeginIndex && "Empty vector!");
2445 unsigned NumElements = EndIndex - BeginIndex;
2446 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2447
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002448 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002449 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2450 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002451 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002452 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002453
Chandler Carruthce4562b2012-12-17 13:41:21 +00002454 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002455 "oldload");
2456 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002457 } else if (IntTy) {
2458 // If this is a memset on an alloca where we can widen stores, insert the
2459 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002460 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002461
Chandler Carruthf0546402013-07-18 07:15:00 +00002462 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002463 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002464
2465 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2466 EndOffset != NewAllocaBeginOffset)) {
2467 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002468 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002469 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002470 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002471 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002472 } else {
2473 assert(V->getType() == IntTy &&
2474 "Wrong type for an alloca wide integer!");
2475 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002476 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002477 } else {
2478 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002479 assert(NewBeginOffset == NewAllocaBeginOffset);
2480 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002481
Chandler Carruth90a735d2013-07-19 07:21:28 +00002482 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002483 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002484 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002485
Chandler Carruth90a735d2013-07-19 07:21:28 +00002486 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002487 }
2488
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002489 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002490 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002491 (void)New;
2492 DEBUG(dbgs() << " to: " << *New << "\n");
2493 return !II.isVolatile();
2494 }
2495
2496 bool visitMemTransferInst(MemTransferInst &II) {
2497 // Rewriting of memory transfer instructions can be a bit tricky. We break
2498 // them into two categories: split intrinsics and unsplit intrinsics.
2499
2500 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002501
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002502 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002503 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002504 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002505
Chandler Carruth176ca712012-10-01 12:16:54 +00002506 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002507 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002508 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002509
2510 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002511 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002512 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002513 Align =
2514 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2515 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002516
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002517 // For unsplit intrinsics, we simply modify the source and destination
2518 // pointers in place. This isn't just an optimization, it is a matter of
2519 // correctness. With unsplit intrinsics we may be dealing with transfers
2520 // within a single alloca before SROA ran, or with transfers that have
2521 // a variable length. We may also be dealing with memmove instead of
2522 // memcpy, and so simply updating the pointers is the necessary for us to
2523 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002524 if (!IsSplittable) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002525 Value *AdjustedPtr =
2526 getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002527 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002528 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002529 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002530 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002531
Chandler Carruth208124f2012-09-26 10:59:22 +00002532 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002533 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002534
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002535 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002536 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002537 return false;
2538 }
2539 // For split transfer intrinsics we have an incredibly useful assurance:
2540 // the source and destination do not reside within the same alloca, and at
2541 // least one of them does not escape. This means that we can replace
2542 // memmove with memcpy, and we don't need to worry about all manner of
2543 // downsides to splitting and transforming the operations.
2544
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002545 // If this doesn't map cleanly onto the alloca type, and that type isn't
2546 // a single value type, just emit a memcpy.
2547 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002548 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2549 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002550 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002551
2552 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2553 // size hasn't been shrunk based on analysis of the viable range, this is
2554 // a no-op.
2555 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002557 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002558
2559 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002560 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002561 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002562 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002563 return false;
2564 }
2565 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002566 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002567
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002568 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2569 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002570 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002571 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002572 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2573 assert(AI != &OldAI && AI != &NewAI &&
2574 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002575 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002576 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002577
2578 if (EmitMemCpy) {
Rafael Espindola8eee97d2014-02-14 19:02:01 +00002579 Type *OtherPtrTy = OtherPtr->getType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002580
2581 // Compute the other pointer, folding as much as possible to produce
2582 // a single, simple GEP in most cases.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002583 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy,
2584 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002585
Chandler Carruth8183a502014-02-25 11:08:02 +00002586 Value *OurPtr =
2587 getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002588 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002589 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002590
2591 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2592 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002593 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002594 (void)New;
2595 DEBUG(dbgs() << " to: " << *New << "\n");
2596 return false;
2597 }
2598
Chandler Carruth08e5f492012-10-03 08:26:28 +00002599 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2600 // is equivalent to 1, but that isn't true if we end up rewriting this as
2601 // a load or store.
2602 if (!Align)
2603 Align = 1;
2604
Chandler Carruthf0546402013-07-18 07:15:00 +00002605 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2606 NewEndOffset == NewAllocaEndOffset;
2607 uint64_t Size = NewEndOffset - NewBeginOffset;
2608 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2609 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002610 unsigned NumElements = EndIndex - BeginIndex;
2611 IntegerType *SubIntTy
2612 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2613
2614 Type *OtherPtrTy = NewAI.getType();
2615 if (VecTy && !IsWholeAlloca) {
2616 if (NumElements == 1)
2617 OtherPtrTy = VecTy->getElementType();
2618 else
2619 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2620
2621 OtherPtrTy = OtherPtrTy->getPointerTo();
2622 } else if (IntTy && !IsWholeAlloca) {
2623 OtherPtrTy = SubIntTy->getPointerTo();
2624 }
2625
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002626 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy,
2627 OtherPtr->getName() + ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002628 Value *DstPtr = &NewAI;
2629 if (!IsDest)
2630 std::swap(SrcPtr, DstPtr);
2631
2632 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002633 if (VecTy && !IsWholeAlloca && !IsDest) {
2634 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002635 "load");
2636 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002637 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002638 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002639 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002640 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002641 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002642 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002643 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002644 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002645 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002646 }
2647
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002648 if (VecTy && !IsWholeAlloca && IsDest) {
2649 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002650 "oldload");
2651 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002652 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002653 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002654 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002655 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002656 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002657 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2658 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002659 }
2660
Chandler Carruth871ba722012-09-26 10:27:46 +00002661 StoreInst *Store = cast<StoreInst>(
2662 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2663 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002664 DEBUG(dbgs() << " to: " << *Store << "\n");
2665 return !II.isVolatile();
2666 }
2667
2668 bool visitIntrinsicInst(IntrinsicInst &II) {
2669 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2670 II.getIntrinsicID() == Intrinsic::lifetime_end);
2671 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002672 assert(II.getArgOperand(1) == OldPtr);
2673
2674 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002675 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002676
2677 ConstantInt *Size
2678 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002679 NewEndOffset - NewBeginOffset);
Chandler Carruth8183a502014-02-25 11:08:02 +00002680 Value *Ptr = getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002681 Value *New;
2682 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2683 New = IRB.CreateLifetimeStart(Ptr, Size);
2684 else
2685 New = IRB.CreateLifetimeEnd(Ptr, Size);
2686
Edwin Vane82f80d42013-01-29 17:42:24 +00002687 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002688 DEBUG(dbgs() << " to: " << *New << "\n");
2689 return true;
2690 }
2691
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002692 bool visitPHINode(PHINode &PN) {
2693 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002694 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2695 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002696
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002697 // We would like to compute a new pointer in only one place, but have it be
2698 // as local as possible to the PHI. To do that, we re-use the location of
2699 // the old pointer, which necessarily must be in the right position to
2700 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002701 IRBuilderTy PtrBuilder(IRB);
2702 PtrBuilder.SetInsertPoint(OldPtr);
2703 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002704
Chandler Carruthf0546402013-07-18 07:15:00 +00002705 Value *NewPtr =
2706 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002707 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002708 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002709
Chandler Carruth82a57542012-10-01 10:54:05 +00002710 DEBUG(dbgs() << " to: " << PN << "\n");
2711 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002712
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002713 // PHIs can't be promoted on their own, but often can be speculated. We
2714 // check the speculation outside of the rewriter so that we see the
2715 // fully-rewritten alloca.
2716 PHIUsers.insert(&PN);
2717 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002718 }
2719
2720 bool visitSelectInst(SelectInst &SI) {
2721 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002722 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2723 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002724 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2725 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002726
Chandler Carruthf0546402013-07-18 07:15:00 +00002727 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002728 // Replace the operands which were using the old pointer.
2729 if (SI.getOperand(1) == OldPtr)
2730 SI.setOperand(1, NewPtr);
2731 if (SI.getOperand(2) == OldPtr)
2732 SI.setOperand(2, NewPtr);
2733
Chandler Carruth82a57542012-10-01 10:54:05 +00002734 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002735 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002736
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002737 // Selects can't be promoted on their own, but often can be speculated. We
2738 // check the speculation outside of the rewriter so that we see the
2739 // fully-rewritten alloca.
2740 SelectUsers.insert(&SI);
2741 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002742 }
2743
2744};
2745}
2746
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002747namespace {
2748/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2749///
2750/// This pass aggressively rewrites all aggregate loads and stores on
2751/// a particular pointer (or any pointer derived from it which we can identify)
2752/// with scalar loads and stores.
2753class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2754 // Befriend the base class so it can delegate to private visit methods.
2755 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2756
Chandler Carruth90a735d2013-07-19 07:21:28 +00002757 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002758
2759 /// Queue of pointer uses to analyze and potentially rewrite.
2760 SmallVector<Use *, 8> Queue;
2761
2762 /// Set to prevent us from cycling with phi nodes and loops.
2763 SmallPtrSet<User *, 8> Visited;
2764
2765 /// The current pointer use being rewritten. This is used to dig up the used
2766 /// value (as opposed to the user).
2767 Use *U;
2768
2769public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002770 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002771
2772 /// Rewrite loads and stores through a pointer and all pointers derived from
2773 /// it.
2774 bool rewrite(Instruction &I) {
2775 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2776 enqueueUsers(I);
2777 bool Changed = false;
2778 while (!Queue.empty()) {
2779 U = Queue.pop_back_val();
2780 Changed |= visit(cast<Instruction>(U->getUser()));
2781 }
2782 return Changed;
2783 }
2784
2785private:
2786 /// Enqueue all the users of the given instruction for further processing.
2787 /// This uses a set to de-duplicate users.
2788 void enqueueUsers(Instruction &I) {
2789 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2790 ++UI)
2791 if (Visited.insert(*UI))
2792 Queue.push_back(&UI.getUse());
2793 }
2794
2795 // Conservative default is to not rewrite anything.
2796 bool visitInstruction(Instruction &I) { return false; }
2797
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002798 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002799 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002800 class OpSplitter {
2801 protected:
2802 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002803 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002804 /// The indices which to be used with insert- or extractvalue to select the
2805 /// appropriate value within the aggregate.
2806 SmallVector<unsigned, 4> Indices;
2807 /// The indices to a GEP instruction which will move Ptr to the correct slot
2808 /// within the aggregate.
2809 SmallVector<Value *, 4> GEPIndices;
2810 /// The base pointer of the original op, used as a base for GEPing the
2811 /// split operations.
2812 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002813
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002814 /// Initialize the splitter with an insertion point, Ptr and start with a
2815 /// single zero GEP index.
2816 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002817 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002818
2819 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002820 /// \brief Generic recursive split emission routine.
2821 ///
2822 /// This method recursively splits an aggregate op (load or store) into
2823 /// scalar or vector ops. It splits recursively until it hits a single value
2824 /// and emits that single value operation via the template argument.
2825 ///
2826 /// The logic of this routine relies on GEPs and insertvalue and
2827 /// extractvalue all operating with the same fundamental index list, merely
2828 /// formatted differently (GEPs need actual values).
2829 ///
2830 /// \param Ty The type being split recursively into smaller ops.
2831 /// \param Agg The aggregate value being built up or stored, depending on
2832 /// whether this is splitting a load or a store respectively.
2833 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2834 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002835 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002836
2837 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2838 unsigned OldSize = Indices.size();
2839 (void)OldSize;
2840 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2841 ++Idx) {
2842 assert(Indices.size() == OldSize && "Did not return to the old size");
2843 Indices.push_back(Idx);
2844 GEPIndices.push_back(IRB.getInt32(Idx));
2845 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2846 GEPIndices.pop_back();
2847 Indices.pop_back();
2848 }
2849 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002850 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002851
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002852 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2853 unsigned OldSize = Indices.size();
2854 (void)OldSize;
2855 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2856 ++Idx) {
2857 assert(Indices.size() == OldSize && "Did not return to the old size");
2858 Indices.push_back(Idx);
2859 GEPIndices.push_back(IRB.getInt32(Idx));
2860 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2861 GEPIndices.pop_back();
2862 Indices.pop_back();
2863 }
2864 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002865 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002866
2867 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002868 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002869 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002870
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002871 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002872 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002873 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002874
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002875 /// Emit a leaf load of a single value. This is called at the leaves of the
2876 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002877 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002878 assert(Ty->isSingleValueType());
2879 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002880 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2881 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002882 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2883 DEBUG(dbgs() << " to: " << *Load << "\n");
2884 }
2885 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002886
2887 bool visitLoadInst(LoadInst &LI) {
2888 assert(LI.getPointerOperand() == *U);
2889 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2890 return false;
2891
2892 // We have an aggregate being loaded, split it apart.
2893 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002894 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002895 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002896 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002897 LI.replaceAllUsesWith(V);
2898 LI.eraseFromParent();
2899 return true;
2900 }
2901
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002902 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002903 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002904 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002905
2906 /// Emit a leaf store of a single value. This is called at the leaves of the
2907 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002908 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002909 assert(Ty->isSingleValueType());
2910 // Extract the single value and store it using the indices.
2911 Value *Store = IRB.CreateStore(
2912 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2913 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2914 (void)Store;
2915 DEBUG(dbgs() << " to: " << *Store << "\n");
2916 }
2917 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002918
2919 bool visitStoreInst(StoreInst &SI) {
2920 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2921 return false;
2922 Value *V = SI.getValueOperand();
2923 if (V->getType()->isSingleValueType())
2924 return false;
2925
2926 // We have an aggregate being stored, split it apart.
2927 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002928 StoreOpSplitter Splitter(&SI, *U);
2929 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002930 SI.eraseFromParent();
2931 return true;
2932 }
2933
2934 bool visitBitCastInst(BitCastInst &BC) {
2935 enqueueUsers(BC);
2936 return false;
2937 }
2938
2939 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2940 enqueueUsers(GEPI);
2941 return false;
2942 }
2943
2944 bool visitPHINode(PHINode &PN) {
2945 enqueueUsers(PN);
2946 return false;
2947 }
2948
2949 bool visitSelectInst(SelectInst &SI) {
2950 enqueueUsers(SI);
2951 return false;
2952 }
2953};
2954}
2955
Chandler Carruthba931992012-10-13 10:49:33 +00002956/// \brief Strip aggregate type wrapping.
2957///
2958/// This removes no-op aggregate types wrapping an underlying type. It will
2959/// strip as many layers of types as it can without changing either the type
2960/// size or the allocated size.
2961static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2962 if (Ty->isSingleValueType())
2963 return Ty;
2964
2965 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2966 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2967
2968 Type *InnerTy;
2969 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2970 InnerTy = ArrTy->getElementType();
2971 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2972 const StructLayout *SL = DL.getStructLayout(STy);
2973 unsigned Index = SL->getElementContainingOffset(0);
2974 InnerTy = STy->getElementType(Index);
2975 } else {
2976 return Ty;
2977 }
2978
2979 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2980 TypeSize > DL.getTypeSizeInBits(InnerTy))
2981 return Ty;
2982
2983 return stripAggregateTypeWrapping(DL, InnerTy);
2984}
2985
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002986/// \brief Try to find a partition of the aggregate type passed in for a given
2987/// offset and size.
2988///
2989/// This recurses through the aggregate type and tries to compute a subtype
2990/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002991/// of an array, it will even compute a new array type for that sub-section,
2992/// and the same for structs.
2993///
2994/// Note that this routine is very strict and tries to find a partition of the
2995/// type which produces the *exact* right offset and size. It is not forgiving
2996/// when the size or offset cause either end of type-based partition to be off.
2997/// Also, this is a best-effort routine. It is reasonable to give up and not
2998/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002999static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003000 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003001 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3002 return stripAggregateTypeWrapping(DL, Ty);
3003 if (Offset > DL.getTypeAllocSize(Ty) ||
3004 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00003005 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003006
3007 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3008 // We can't partition pointers...
3009 if (SeqTy->isPointerTy())
3010 return 0;
3011
3012 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003013 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003014 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003015 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003016 if (NumSkippedElements >= ArrTy->getNumElements())
3017 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003018 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019 if (NumSkippedElements >= VecTy->getNumElements())
3020 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003021 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003022 Offset -= NumSkippedElements * ElementSize;
3023
3024 // First check if we need to recurse.
3025 if (Offset > 0 || Size < ElementSize) {
3026 // Bail if the partition ends in a different array element.
3027 if ((Offset + Size) > ElementSize)
3028 return 0;
3029 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003030 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031 }
3032 assert(Offset == 0);
3033
3034 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003035 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003036 assert(Size > ElementSize);
3037 uint64_t NumElements = Size / ElementSize;
3038 if (NumElements * ElementSize != Size)
3039 return 0;
3040 return ArrayType::get(ElementTy, NumElements);
3041 }
3042
3043 StructType *STy = dyn_cast<StructType>(Ty);
3044 if (!STy)
3045 return 0;
3046
Chandler Carruth90a735d2013-07-19 07:21:28 +00003047 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003048 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003049 return 0;
3050 uint64_t EndOffset = Offset + Size;
3051 if (EndOffset > SL->getSizeInBytes())
3052 return 0;
3053
3054 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003055 Offset -= SL->getElementOffset(Index);
3056
3057 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003058 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003059 if (Offset >= ElementSize)
3060 return 0; // The offset points into alignment padding.
3061
3062 // See if any partition must be contained by the element.
3063 if (Offset > 0 || Size < ElementSize) {
3064 if ((Offset + Size) > ElementSize)
3065 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003066 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003067 }
3068 assert(Offset == 0);
3069
3070 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003071 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003072
3073 StructType::element_iterator EI = STy->element_begin() + Index,
3074 EE = STy->element_end();
3075 if (EndOffset < SL->getSizeInBytes()) {
3076 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3077 if (Index == EndIndex)
3078 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003079
3080 // Don't try to form "natural" types if the elements don't line up with the
3081 // expected size.
3082 // FIXME: We could potentially recurse down through the last element in the
3083 // sub-struct to find a natural end point.
3084 if (SL->getElementOffset(EndIndex) != EndOffset)
3085 return 0;
3086
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003087 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003088 EE = STy->element_begin() + EndIndex;
3089 }
3090
3091 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003092 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003093 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003094 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003095 if (Size != SubSL->getSizeInBytes())
3096 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003097
Chandler Carruth054a40a2012-09-14 11:08:31 +00003098 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003099}
3100
3101/// \brief Rewrite an alloca partition's users.
3102///
3103/// This routine drives both of the rewriting goals of the SROA pass. It tries
3104/// to rewrite uses of an alloca partition to be conducive for SSA value
3105/// promotion. If the partition needs a new, more refined alloca, this will
3106/// build that new alloca, preserving as much type information as possible, and
3107/// rewrite the uses of the old alloca to point at the new one and have the
3108/// appropriate new offsets. It also evaluates how successful the rewrite was
3109/// at enabling promotion and if it was successful queues the alloca to be
3110/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003111bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3112 AllocaSlices::iterator B, AllocaSlices::iterator E,
3113 int64_t BeginOffset, int64_t EndOffset,
3114 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003115 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003116 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003117
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003118 // Try to compute a friendly type for this partition of the alloca. This
3119 // won't always succeed, in which case we fall back to a legal integer type
3120 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003121 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00003122 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003123 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3124 SliceTy = CommonUseTy;
3125 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003126 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003127 BeginOffset, SliceSize))
3128 SliceTy = TypePartitionTy;
3129 if ((!SliceTy || (SliceTy->isArrayTy() &&
3130 SliceTy->getArrayElementType()->isIntegerTy())) &&
3131 DL->isLegalInteger(SliceSize * 8))
3132 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3133 if (!SliceTy)
3134 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3135 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003136
3137 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003138 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003139
3140 bool IsIntegerPromotable =
3141 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003142 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003143
3144 // Check for the case where we're going to rewrite to a new alloca of the
3145 // exact same type as the original, and with the same access offsets. In that
3146 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003147 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003148 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003149 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003150 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003151 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003152 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003153 // FIXME: We should be able to bail at this point with "nothing changed".
3154 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003155 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003156 unsigned Alignment = AI.getAlignment();
3157 if (!Alignment) {
3158 // The minimum alignment which users can rely on when the explicit
3159 // alignment is omitted or zero is that required by the ABI for this
3160 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003161 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003162 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003163 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003164 // If we will get at least this much alignment from the type alone, leave
3165 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003166 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003167 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003168 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3169 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003170 ++NumNewAllocas;
3171 }
3172
3173 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003174 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3175 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003176
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003177 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003178 // promoted allocas. We will reset it to this point if the alloca is not in
3179 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003180 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003181 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003182 SmallPtrSet<PHINode *, 8> PHIUsers;
3183 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003184
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003185 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3186 EndOffset, IsVectorPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003187 IsIntegerPromotable, PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003188 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003189 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3190 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003191 SUI != SUE; ++SUI) {
3192 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003193 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003194 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003195 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003196 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003197 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003198 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003199 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003200 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003201 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003202 }
3203
Chandler Carruth6c321c12013-07-19 10:57:36 +00003204 NumAllocaPartitionUses += NumUses;
3205 MaxUsesPerAllocaPartition =
3206 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003207
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003208 // Now that we've processed all the slices in the new partition, check if any
3209 // PHIs or Selects would block promotion.
3210 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3211 E = PHIUsers.end();
3212 I != E; ++I)
3213 if (!isSafePHIToSpeculate(**I, DL)) {
3214 Promotable = false;
3215 PHIUsers.clear();
3216 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003217 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003218 }
3219 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3220 E = SelectUsers.end();
3221 I != E; ++I)
3222 if (!isSafeSelectToSpeculate(**I, DL)) {
3223 Promotable = false;
3224 PHIUsers.clear();
3225 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003226 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003227 }
3228
3229 if (Promotable) {
3230 if (PHIUsers.empty() && SelectUsers.empty()) {
3231 // Promote the alloca.
3232 PromotableAllocas.push_back(NewAI);
3233 } else {
3234 // If we have either PHIs or Selects to speculate, add them to those
3235 // worklists and re-queue the new alloca so that we promote in on the
3236 // next iteration.
3237 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3238 E = PHIUsers.end();
3239 I != E; ++I)
3240 SpeculatablePHIs.insert(*I);
3241 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3242 E = SelectUsers.end();
3243 I != E; ++I)
3244 SpeculatableSelects.insert(*I);
3245 Worklist.insert(NewAI);
3246 }
3247 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003248 // If we can't promote the alloca, iterate on it to check for new
3249 // refinements exposed by splitting the current alloca. Don't iterate on an
3250 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003251 if (NewAI != &AI)
3252 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003253
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003254 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003255 while (PostPromotionWorklist.size() > PPWOldSize)
3256 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003257 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003258
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003259 return true;
3260}
3261
Chandler Carruthf0546402013-07-18 07:15:00 +00003262namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003263struct IsSliceEndLessOrEqualTo {
3264 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003265
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003266 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003267
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003268 bool operator()(const AllocaSlices::iterator &I) {
3269 return I->endOffset() <= UpperBound;
3270 }
3271};
Chandler Carruthf0546402013-07-18 07:15:00 +00003272}
3273
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003274static void
3275removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3276 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003277 if (Offset >= MaxSplitUseEndOffset) {
3278 SplitUses.clear();
3279 MaxSplitUseEndOffset = 0;
3280 return;
3281 }
3282
3283 size_t SplitUsesOldSize = SplitUses.size();
3284 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003285 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003286 SplitUses.end());
3287 if (SplitUsesOldSize == SplitUses.size())
3288 return;
3289
3290 // Recompute the max. While this is linear, so is remove_if.
3291 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003292 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003293 SUI = SplitUses.begin(),
3294 SUE = SplitUses.end();
3295 SUI != SUE; ++SUI)
3296 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3297}
3298
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003299/// \brief Walks the slices of an alloca and form partitions based on them,
3300/// rewriting each of their uses.
3301bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3302 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003303 return false;
3304
Chandler Carruth6c321c12013-07-19 10:57:36 +00003305 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003306 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003307 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003308 uint64_t MaxSplitUseEndOffset = 0;
3309
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003310 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003311
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003312 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3313 SI != SE; SI = SJ) {
3314 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003315
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003316 if (!SI->isSplittable()) {
3317 // When we're forming an unsplittable region, it must always start at the
3318 // first slice and will extend through its end.
3319 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003320
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003321 // Form a partition including all of the overlapping slices with this
3322 // unsplittable slice.
3323 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3324 if (!SJ->isSplittable())
3325 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3326 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003327 }
3328 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003329 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003330
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003331 // Collect all of the overlapping splittable slices.
3332 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3333 SJ->isSplittable()) {
3334 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3335 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003336 }
3337
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003338 // Back up MaxEndOffset and SJ if we ended the span early when
3339 // encountering an unsplittable slice.
3340 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3341 assert(!SJ->isSplittable());
3342 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003343 }
3344 }
3345
3346 // Check if we have managed to move the end offset forward yet. If so,
3347 // we'll have to rewrite uses and erase old split uses.
3348 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003349 // Rewrite a sequence of overlapping slices.
3350 Changed |=
3351 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003352 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003353
3354 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3355 }
3356
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003357 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003358 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003359 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3360 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3361 SplitUses.push_back(SK);
3362 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003363 }
3364
3365 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003366 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003367 break;
3368
3369 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003370 // the next slice.
3371 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3372 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003373 continue;
3374 }
3375
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003376 // Even if we have split slices, if the next slice is splittable and the
3377 // split slices reach it, we can simply set up the beginning offset of the
3378 // next iteration to bridge between them.
3379 if (SJ != SE && SJ->isSplittable() &&
3380 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003381 BeginOffset = MaxEndOffset;
3382 continue;
3383 }
3384
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003385 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3386 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003387 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003388 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003389
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003390 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3391 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003392 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003393
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003394 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003395 break; // Skip the rest, we don't need to do any cleanup.
3396
3397 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3398 PostSplitEndOffset);
3399
3400 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003401 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003402 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003403
Chandler Carruth6c321c12013-07-19 10:57:36 +00003404 NumAllocaPartitions += NumPartitions;
3405 MaxPartitionsPerAlloca =
3406 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003407
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003408 return Changed;
3409}
3410
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003411/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3412void SROA::clobberUse(Use &U) {
3413 Value *OldV = U;
3414 // Replace the use with an undef value.
3415 U = UndefValue::get(OldV->getType());
3416
3417 // Check for this making an instruction dead. We have to garbage collect
3418 // all the dead instructions to ensure the uses of any alloca end up being
3419 // minimal.
3420 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3421 if (isInstructionTriviallyDead(OldI)) {
3422 DeadInsts.insert(OldI);
3423 }
3424}
3425
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003426/// \brief Analyze an alloca for SROA.
3427///
3428/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003429/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003430/// rewritten as needed.
3431bool SROA::runOnAlloca(AllocaInst &AI) {
3432 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3433 ++NumAllocasAnalyzed;
3434
3435 // Special case dead allocas, as they're trivial.
3436 if (AI.use_empty()) {
3437 AI.eraseFromParent();
3438 return true;
3439 }
3440
3441 // Skip alloca forms that this analysis can't handle.
3442 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003443 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003444 return false;
3445
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003446 bool Changed = false;
3447
3448 // First, split any FCA loads and stores touching this alloca to promote
3449 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003450 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003451 Changed |= AggRewriter.rewrite(AI);
3452
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003453 // Build the slices using a recursive instruction-visiting builder.
3454 AllocaSlices S(*DL, AI);
3455 DEBUG(S.print(dbgs()));
3456 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003457 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003458
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003459 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003460 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3461 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003462 DI != DE; ++DI) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003463 // Free up everything used by this instruction.
3464 for (User::op_iterator DOI = (*DI)->op_begin(), DOE = (*DI)->op_end();
3465 DOI != DOE; ++DOI)
3466 clobberUse(*DOI);
3467
3468 // Now replace the uses of this instruction.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003469 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003470
3471 // And mark it for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003472 DeadInsts.insert(*DI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003473 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003474 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003475 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3476 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003477 DO != DE; ++DO) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003478 clobberUse(**DO);
3479 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003480 }
3481
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003482 // No slices to split. Leave the dead alloca for a later pass to clean up.
3483 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003484 return Changed;
3485
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003486 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003487
3488 DEBUG(dbgs() << " Speculating PHIs\n");
3489 while (!SpeculatablePHIs.empty())
3490 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3491
3492 DEBUG(dbgs() << " Speculating Selects\n");
3493 while (!SpeculatableSelects.empty())
3494 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3495
3496 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003497}
3498
Chandler Carruth19450da2012-09-14 10:26:38 +00003499/// \brief Delete the dead instructions accumulated in this run.
3500///
3501/// Recursively deletes the dead instructions we've accumulated. This is done
3502/// at the very end to maximize locality of the recursive delete and to
3503/// minimize the problems of invalidated instruction pointers as such pointers
3504/// are used heavily in the intermediate stages of the algorithm.
3505///
3506/// We also record the alloca instructions deleted here so that they aren't
3507/// subsequently handed to mem2reg to promote.
3508void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003509 while (!DeadInsts.empty()) {
3510 Instruction *I = DeadInsts.pop_back_val();
3511 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3512
Chandler Carruth58d05562012-10-25 04:37:07 +00003513 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3514
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003515 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3516 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3517 // Zero out the operand and see if it becomes trivially dead.
3518 *OI = 0;
3519 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003520 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003521 }
3522
3523 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3524 DeletedAllocas.insert(AI);
3525
3526 ++NumDeleted;
3527 I->eraseFromParent();
3528 }
3529}
3530
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003531static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003532 SmallVectorImpl<Instruction *> &Worklist,
3533 SmallPtrSet<Instruction *, 8> &Visited) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003534 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3535 ++UI)
Chandler Carruth45b136f2013-08-11 01:03:18 +00003536 if (Visited.insert(cast<Instruction>(*UI)))
3537 Worklist.push_back(cast<Instruction>(*UI));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003538}
3539
Chandler Carruth70b44c52012-09-15 11:43:14 +00003540/// \brief Promote the allocas, using the best available technique.
3541///
3542/// This attempts to promote whatever allocas have been identified as viable in
3543/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3544/// If there is a domtree available, we attempt to promote using the full power
3545/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3546/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003547/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003548bool SROA::promoteAllocas(Function &F) {
3549 if (PromotableAllocas.empty())
3550 return false;
3551
3552 NumPromoted += PromotableAllocas.size();
3553
3554 if (DT && !ForceSSAUpdater) {
3555 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Nick Lewyckyc7776f72013-08-13 22:51:58 +00003556 PromoteMemToReg(PromotableAllocas, *DT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003557 PromotableAllocas.clear();
3558 return true;
3559 }
3560
3561 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3562 SSAUpdater SSA;
3563 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003564 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003565
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003566 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003567 SmallVector<Instruction *, 8> Worklist;
3568 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003569 SmallVector<Instruction *, 32> DeadInsts;
3570
Chandler Carruth70b44c52012-09-15 11:43:14 +00003571 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3572 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003573 Insts.clear();
3574 Worklist.clear();
3575 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003576
Chandler Carruth45b136f2013-08-11 01:03:18 +00003577 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003578
Chandler Carruth45b136f2013-08-11 01:03:18 +00003579 while (!Worklist.empty()) {
3580 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003581
Chandler Carruth70b44c52012-09-15 11:43:14 +00003582 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3583 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3584 // leading to them) here. Eventually it should use them to optimize the
3585 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003586 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003587 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3588 II->getIntrinsicID() == Intrinsic::lifetime_end);
3589 II->eraseFromParent();
3590 continue;
3591 }
3592
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003593 // Push the loads and stores we find onto the list. SROA will already
3594 // have validated that all loads and stores are viable candidates for
3595 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003596 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003597 assert(LI->getType() == AI->getAllocatedType());
3598 Insts.push_back(LI);
3599 continue;
3600 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003601 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003602 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3603 Insts.push_back(SI);
3604 continue;
3605 }
3606
3607 // For everything else, we know that only no-op bitcasts and GEPs will
3608 // make it this far, just recurse through them and recall them for later
3609 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003610 DeadInsts.push_back(I);
3611 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003612 }
3613 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003614 while (!DeadInsts.empty())
3615 DeadInsts.pop_back_val()->eraseFromParent();
3616 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003617 }
3618
3619 PromotableAllocas.clear();
3620 return true;
3621}
3622
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003623namespace {
3624 /// \brief A predicate to test whether an alloca belongs to a set.
3625 class IsAllocaInSet {
3626 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3627 const SetType &Set;
3628
3629 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003630 typedef AllocaInst *argument_type;
3631
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003632 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003633 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003634 };
3635}
3636
3637bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003638 if (skipOptnoneFunction(F))
3639 return false;
3640
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003641 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3642 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003643 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3644 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003645 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3646 return false;
3647 }
Rafael Espindola93512512014-02-25 17:30:31 +00003648 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003649 DominatorTreeWrapperPass *DTWP =
3650 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3651 DT = DTWP ? &DTWP->getDomTree() : 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003652
3653 BasicBlock &EntryBB = F.getEntryBlock();
3654 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3655 I != E; ++I)
3656 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3657 Worklist.insert(AI);
3658
3659 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003660 // A set of deleted alloca instruction pointers which should be removed from
3661 // the list of promotable allocas.
3662 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3663
Chandler Carruthac8317f2012-10-04 12:33:50 +00003664 do {
3665 while (!Worklist.empty()) {
3666 Changed |= runOnAlloca(*Worklist.pop_back_val());
3667 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003668
Chandler Carruthac8317f2012-10-04 12:33:50 +00003669 // Remove the deleted allocas from various lists so that we don't try to
3670 // continue processing them.
3671 if (!DeletedAllocas.empty()) {
3672 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3673 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3674 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3675 PromotableAllocas.end(),
3676 IsAllocaInSet(DeletedAllocas)),
3677 PromotableAllocas.end());
3678 DeletedAllocas.clear();
3679 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003680 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003681
Chandler Carruthac8317f2012-10-04 12:33:50 +00003682 Changed |= promoteAllocas(F);
3683
3684 Worklist = PostPromotionWorklist;
3685 PostPromotionWorklist.clear();
3686 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003687
3688 return Changed;
3689}
3690
3691void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003692 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003693 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003694 AU.setPreservesCFG();
3695}