blob: 01320e22a3d5f3a7c6942b229d061d9f0de2e61e [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 Carruthe41e7b72012-12-10 08:28:39 +0000359 if (Size == 0 || Offset.isNegative() || 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.
483 if (Offset.isNegative() || Size > AllocSize ||
484 Offset.ugt(AllocSize - Size)) {
485 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
486 << " which extends past the end of the " << AllocSize
487 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000488 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000489 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000490 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000491 }
492
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000493 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
494 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000495 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000496 }
497
498
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000499 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000500 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000501 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000502 if ((Length && Length->getValue() == 0) ||
503 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
504 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000505 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000506
507 if (!IsOffsetKnown)
508 return PI.setAborted(&II);
509
510 insertUse(II, Offset,
511 Length ? Length->getLimitedValue()
512 : AllocSize - Offset.getLimitedValue(),
513 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000514 }
515
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000516 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000517 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000518 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000519 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000520 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000521
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000522 // Because we can visit these intrinsics twice, also check to see if the
523 // first time marked this instruction as dead. If so, skip it.
524 if (VisitedDeadInsts.count(&II))
525 return;
526
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000527 if (!IsOffsetKnown)
528 return PI.setAborted(&II);
529
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000530 // This side of the transfer is completely out-of-bounds, and so we can
531 // nuke the entire transfer. However, we also need to nuke the other side
532 // if already added to our partitions.
533 // FIXME: Yet another place we really should bypass this when
534 // instrumenting for ASan.
535 if (!Offset.isNegative() && Offset.uge(AllocSize)) {
536 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
537 if (MTPI != MemTransferSliceMap.end())
538 S.Slices[MTPI->second].kill();
539 return markAsDead(II);
540 }
541
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000542 uint64_t RawOffset = Offset.getLimitedValue();
543 uint64_t Size = Length ? Length->getLimitedValue()
544 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000545
Chandler Carruthf0546402013-07-18 07:15:00 +0000546 // Check for the special case where the same exact value is used for both
547 // source and dest.
548 if (*U == II.getRawDest() && *U == II.getRawSource()) {
549 // For non-volatile transfers this is a no-op.
550 if (!II.isVolatile())
551 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000552
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000553 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000554 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000555
Chandler Carruthf0546402013-07-18 07:15:00 +0000556 // If we have seen both source and destination for a mem transfer, then
557 // they both point to the same alloca.
558 bool Inserted;
559 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
560 llvm::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000561 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000562 unsigned PrevIdx = MTPI->second;
563 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000564 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000565
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000566 // Check if the begin offsets match and this is a non-volatile transfer.
567 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000568 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
569 PrevP.kill();
570 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000571 }
572
573 // Otherwise we have an offset transfer within the same alloca. We can't
574 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000575 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000576 }
577
Chandler Carruthe3899f22013-07-15 17:36:21 +0000578 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000579 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000580
Chandler Carruthf0546402013-07-18 07:15:00 +0000581 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000582 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
583 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000584 }
585
586 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000587 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000588 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000589 void visitIntrinsicInst(IntrinsicInst &II) {
590 if (!IsOffsetKnown)
591 return PI.setAborted(&II);
592
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000593 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
594 II.getIntrinsicID() == Intrinsic::lifetime_end) {
595 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000596 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
597 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000598 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000599 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000600 }
601
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000602 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603 }
604
605 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
606 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000607 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000608 // are considered unsplittable and the size is the maximum loaded or stored
609 // size.
610 SmallPtrSet<Instruction *, 4> Visited;
611 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
612 Visited.insert(Root);
613 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000614 // If there are no loads or stores, the access is dead. We mark that as
615 // a size zero access.
616 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000617 do {
618 Instruction *I, *UsedI;
619 llvm::tie(UsedI, I) = Uses.pop_back_val();
620
621 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000622 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000623 continue;
624 }
625 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
626 Value *Op = SI->getOperand(0);
627 if (Op == UsedI)
628 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000630 continue;
631 }
632
633 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
634 if (!GEP->hasAllZeroIndices())
635 return GEP;
636 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
637 !isa<SelectInst>(I)) {
638 return I;
639 }
640
641 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
642 ++UI)
643 if (Visited.insert(cast<Instruction>(*UI)))
644 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
645 } while (!Uses.empty());
646
647 return 0;
648 }
649
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000650 void visitPHINode(PHINode &PN) {
651 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000652 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000653 if (!IsOffsetKnown)
654 return PI.setAborted(&PN);
655
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000656 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000657 uint64_t &PHISize = PHIOrSelectSizes[&PN];
658 if (!PHISize) {
659 // This is a new PHI node, check for an unsafe use of the PHI node.
660 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
661 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000662 }
663
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000664 // For PHI and select operands outside the alloca, we can't nuke the entire
665 // phi or select -- the other side might still be relevant, so we special
666 // case them here and use a separate structure to track the operands
667 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000668 // FIXME: This should instead be escaped in the event we're instrumenting
669 // for address sanitization.
670 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000671 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000672 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000673 return;
674 }
675
Chandler Carruthf0546402013-07-18 07:15:00 +0000676 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000677 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000678
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000679 void visitSelectInst(SelectInst &SI) {
680 if (SI.use_empty())
681 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000682 if (Value *Result = foldSelectInst(SI)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000683 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000684 // If the result of the constant fold will be the pointer, recurse
685 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000686 enqueueUsers(SI);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000687 else
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000688 // Otherwise the operand to the select is dead, and we can replace it
689 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000690 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000691
692 return;
693 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000694 if (!IsOffsetKnown)
695 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000696
Chandler Carruthf0546402013-07-18 07:15:00 +0000697 // See if we already have computed info on this node.
698 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
699 if (!SelectSize) {
700 // This is a new Select, check for an unsafe use of it.
701 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
702 return PI.setAborted(UnsafeI);
703 }
704
705 // For PHI and select operands outside the alloca, we can't nuke the entire
706 // phi or select -- the other side might still be relevant, so we special
707 // case them here and use a separate structure to track the operands
708 // themselves which should be replaced with undef.
709 // FIXME: This should instead be escaped in the event we're instrumenting
710 // for address sanitization.
711 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
712 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000713 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000714 return;
715 }
716
717 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000718 }
719
Chandler Carruthf0546402013-07-18 07:15:00 +0000720 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000721 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000722 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000723 }
724};
725
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000726AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000727 :
728#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
729 AI(AI),
730#endif
731 PointerEscapingInstr(0) {
732 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000733 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000734 if (PtrI.isEscaped() || PtrI.isAborted()) {
735 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000736 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000737 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
738 : PtrI.getAbortingInst();
739 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000740 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000741 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000742
Benjamin Kramer08e50702013-07-20 08:38:34 +0000743 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
744 std::mem_fun_ref(&Slice::isDead)),
745 Slices.end());
746
Chandler Carruth83cee772014-02-25 03:59:29 +0000747#if __cplusplus >= 201103L && !defined(NDEBUG)
748 if (SROARandomShuffleSlices) {
749 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
750 std::shuffle(Slices.begin(), Slices.end(), MT);
751 }
752#endif
753
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000754 // Sort the uses. This arranges for the offsets to be in ascending order,
755 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000756 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000757}
758
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000759#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
760
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000761void AllocaSlices::print(raw_ostream &OS, const_iterator I,
762 StringRef Indent) const {
763 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000764 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000765}
766
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000767void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
768 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000769 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000770 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000771 << (I->isSplittable() ? " (splittable)" : "") << "\n";
772}
773
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000774void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
775 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000776 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777}
778
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000779void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000780 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000781 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000782 << " A pointer to this alloca escaped by:\n"
783 << " " << *PointerEscapingInstr << "\n";
784 return;
785 }
786
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000787 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000788 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000789 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000790}
791
Alp Tokerf929e092014-01-04 22:47:48 +0000792LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
793 print(dbgs(), I);
794}
795LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000796
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000797#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
798
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000799namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000800/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
801///
802/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
803/// the loads and stores of an alloca instruction, as well as updating its
804/// debug information. This is used when a domtree is unavailable and thus
805/// mem2reg in its full form can't be used to handle promotion of allocas to
806/// scalar values.
807class AllocaPromoter : public LoadAndStorePromoter {
808 AllocaInst &AI;
809 DIBuilder &DIB;
810
811 SmallVector<DbgDeclareInst *, 4> DDIs;
812 SmallVector<DbgValueInst *, 4> DVIs;
813
814public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000815 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000816 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000817 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000818
819 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000820 // Retain the debug information attached to the alloca for use when
821 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000822 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
823 for (Value::use_iterator UI = DebugNode->use_begin(),
824 UE = DebugNode->use_end();
825 UI != UE; ++UI)
826 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
827 DDIs.push_back(DDI);
828 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
829 DVIs.push_back(DVI);
830 }
831
832 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000833
834 // While we have the debug information, clear it off of the alloca. The
835 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000836 while (!DDIs.empty())
837 DDIs.pop_back_val()->eraseFromParent();
838 while (!DVIs.empty())
839 DVIs.pop_back_val()->eraseFromParent();
840 }
841
842 virtual bool isInstInList(Instruction *I,
843 const SmallVectorImpl<Instruction*> &Insts) const {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000844 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000845 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000846 Ptr = LI->getOperand(0);
847 else
848 Ptr = cast<StoreInst>(I)->getPointerOperand();
849
850 // Only used to detect cycles, which will be rare and quickly found as
851 // we're walking up a chain of defs rather than down through uses.
852 SmallPtrSet<Value *, 4> Visited;
853
854 do {
855 if (Ptr == &AI)
856 return true;
857
858 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
859 Ptr = BCI->getOperand(0);
860 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
861 Ptr = GEPI->getPointerOperand();
862 else
863 return false;
864
865 } while (Visited.insert(Ptr));
866
867 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000868 }
869
870 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +0000871 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000872 E = DDIs.end(); I != E; ++I) {
873 DbgDeclareInst *DDI = *I;
874 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
875 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
876 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
877 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
878 }
Craig Topper31ee5862013-07-03 15:07:05 +0000879 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000880 E = DVIs.end(); I != E; ++I) {
881 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000882 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000883 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
884 // If an argument is zero extended then use argument directly. The ZExt
885 // may be zapped by an optimization pass in future.
886 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
887 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000888 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000889 Arg = dyn_cast<Argument>(SExt->getOperand(0));
890 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000891 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000892 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000893 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000894 } else {
895 continue;
896 }
897 Instruction *DbgVal =
898 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
899 Inst);
900 DbgVal->setDebugLoc(DVI->getDebugLoc());
901 }
902 }
903};
904} // end anon namespace
905
906
907namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000908/// \brief An optimization pass providing Scalar Replacement of Aggregates.
909///
910/// This pass takes allocations which can be completely analyzed (that is, they
911/// don't escape) and tries to turn them into scalar SSA values. There are
912/// a few steps to this process.
913///
914/// 1) It takes allocations of aggregates and analyzes the ways in which they
915/// are used to try to split them into smaller allocations, ideally of
916/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000917/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000918/// 2) It will transform accesses into forms which are suitable for SSA value
919/// promotion. This can be replacing a memset with a scalar store of an
920/// integer value, or it can involve speculating operations on a PHI or
921/// select to be a PHI or select of the results.
922/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
923/// onto insert and extract operations on a vector value, and convert them to
924/// this form. By doing so, it will enable promotion of vector aggregates to
925/// SSA vector values.
926class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000927 const bool RequiresDomTree;
928
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000929 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000930 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000931 DominatorTree *DT;
932
933 /// \brief Worklist of alloca instructions to simplify.
934 ///
935 /// Each alloca in the function is added to this. Each new alloca formed gets
936 /// added to it as well to recursively simplify unless that alloca can be
937 /// directly promoted. Finally, each time we rewrite a use of an alloca other
938 /// the one being actively rewritten, we add it back onto the list if not
939 /// already present to ensure it is re-visited.
940 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
941
942 /// \brief A collection of instructions to delete.
943 /// We try to batch deletions to simplify code and make things a bit more
944 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000945 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000946
Chandler Carruthac8317f2012-10-04 12:33:50 +0000947 /// \brief Post-promotion worklist.
948 ///
949 /// Sometimes we discover an alloca which has a high probability of becoming
950 /// viable for SROA after a round of promotion takes place. In those cases,
951 /// the alloca is enqueued here for re-processing.
952 ///
953 /// Note that we have to be very careful to clear allocas out of this list in
954 /// the event they are deleted.
955 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
956
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000957 /// \brief A collection of alloca instructions we can directly promote.
958 std::vector<AllocaInst *> PromotableAllocas;
959
Chandler Carruthf0546402013-07-18 07:15:00 +0000960 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
961 ///
962 /// All of these PHIs have been checked for the safety of speculation and by
963 /// being speculated will allow promoting allocas currently in the promotable
964 /// queue.
965 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
966
967 /// \brief A worklist of select instructions to speculate prior to promoting
968 /// allocas.
969 ///
970 /// All of these select instructions have been checked for the safety of
971 /// speculation and by being speculated will allow promoting allocas
972 /// currently in the promotable queue.
973 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
974
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000975public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000976 SROA(bool RequiresDomTree = true)
977 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Chandler Carruth90a735d2013-07-19 07:21:28 +0000978 C(0), DL(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000979 initializeSROAPass(*PassRegistry::getPassRegistry());
980 }
981 bool runOnFunction(Function &F);
982 void getAnalysisUsage(AnalysisUsage &AU) const;
983
984 const char *getPassName() const { return "SROA"; }
985 static char ID;
986
987private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000988 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000989 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000990
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000991 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
992 AllocaSlices::iterator B, AllocaSlices::iterator E,
993 int64_t BeginOffset, int64_t EndOffset,
994 ArrayRef<AllocaSlices::iterator> SplitUses);
995 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000996 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000997 void clobberUse(Use &U);
Chandler Carruth19450da2012-09-14 10:26:38 +0000998 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000999 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001000};
1001}
1002
1003char SROA::ID = 0;
1004
Chandler Carruth70b44c52012-09-15 11:43:14 +00001005FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1006 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001007}
1008
1009INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1010 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +00001011INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001012INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1013 false, false)
1014
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001015/// Walk the range of a partitioning looking for a common type to cover this
1016/// sequence of slices.
1017static Type *findCommonType(AllocaSlices::const_iterator B,
1018 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001019 uint64_t EndOffset) {
1020 Type *Ty = 0;
Chandler Carruth4de31542014-01-21 23:16:05 +00001021 bool TyIsCommon = true;
1022 IntegerType *ITy = 0;
1023
1024 // Note that we need to look at *every* alloca slice's Use to ensure we
1025 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001026 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001027 Use *U = I->getUse();
1028 if (isa<IntrinsicInst>(*U->getUser()))
1029 continue;
1030 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1031 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001032
Chandler Carruthf0546402013-07-18 07:15:00 +00001033 Type *UserTy = 0;
Chandler Carrutha1262002013-11-19 09:03:18 +00001034 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001035 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001036 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001037 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001038 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001039
Chandler Carruth4de31542014-01-21 23:16:05 +00001040 if (!UserTy || (Ty && Ty != UserTy))
1041 TyIsCommon = false; // Give up on anything but an iN type.
1042 else
1043 Ty = UserTy;
1044
1045 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001046 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001047 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001048 // entity causing the split. Also skip if the type is not a byte width
1049 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001050 if (UserITy->getBitWidth() % 8 != 0 ||
1051 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001052 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001053
Chandler Carruth4de31542014-01-21 23:16:05 +00001054 // Track the largest bitwidth integer type used in this way in case there
1055 // is no common type.
1056 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1057 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001058 }
1059 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001060
1061 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001062}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001063
Chandler Carruthf0546402013-07-18 07:15:00 +00001064/// PHI instructions that use an alloca and are subsequently loaded can be
1065/// rewritten to load both input pointers in the pred blocks and then PHI the
1066/// results, allowing the load of the alloca to be promoted.
1067/// From this:
1068/// %P2 = phi [i32* %Alloca, i32* %Other]
1069/// %V = load i32* %P2
1070/// to:
1071/// %V1 = load i32* %Alloca -> will be mem2reg'd
1072/// ...
1073/// %V2 = load i32* %Other
1074/// ...
1075/// %V = phi [i32 %V1, i32 %V2]
1076///
1077/// We can do this to a select if its only uses are loads and if the operands
1078/// to the select can be loaded unconditionally.
1079///
1080/// FIXME: This should be hoisted into a generic utility, likely in
1081/// Transforms/Util/Local.h
1082static bool isSafePHIToSpeculate(PHINode &PN,
Chandler Carruth90a735d2013-07-19 07:21:28 +00001083 const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001084 // For now, we can only do this promotion if the load is in the same block
1085 // as the PHI, and if there are no stores between the phi and load.
1086 // TODO: Allow recursive phi users.
1087 // TODO: Allow stores.
1088 BasicBlock *BB = PN.getParent();
1089 unsigned MaxAlign = 0;
1090 bool HaveLoad = false;
1091 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1092 ++UI) {
1093 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1094 if (LI == 0 || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001095 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001096
Chandler Carruthf0546402013-07-18 07:15:00 +00001097 // For now we only allow loads in the same block as the PHI. This is
1098 // a common case that happens when instcombine merges two loads through
1099 // a PHI.
1100 if (LI->getParent() != BB)
1101 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001102
Chandler Carruthf0546402013-07-18 07:15:00 +00001103 // Ensure that there are no instructions between the PHI and the load that
1104 // could store.
1105 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1106 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001107 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001108
Chandler Carruthf0546402013-07-18 07:15:00 +00001109 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1110 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001111 }
1112
Chandler Carruthf0546402013-07-18 07:15:00 +00001113 if (!HaveLoad)
1114 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001115
Chandler Carruthf0546402013-07-18 07:15:00 +00001116 // We can only transform this if it is safe to push the loads into the
1117 // predecessor blocks. The only thing to watch out for is that we can't put
1118 // a possibly trapping load in the predecessor if it is a critical edge.
1119 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1120 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1121 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001122
Chandler Carruthf0546402013-07-18 07:15:00 +00001123 // If the value is produced by the terminator of the predecessor (an
1124 // invoke) or it has side-effects, there is no valid place to put a load
1125 // in the predecessor.
1126 if (TI == InVal || TI->mayHaveSideEffects())
1127 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001128
Chandler Carruthf0546402013-07-18 07:15:00 +00001129 // If the predecessor has a single successor, then the edge isn't
1130 // critical.
1131 if (TI->getNumSuccessors() == 1)
1132 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001133
Chandler Carruthf0546402013-07-18 07:15:00 +00001134 // If this pointer is always safe to load, or if we can prove that there
1135 // is already a load in the block, then we can move the load to the pred
1136 // block.
1137 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001138 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001139 continue;
1140
1141 return false;
1142 }
1143
1144 return true;
1145}
1146
1147static void speculatePHINodeLoads(PHINode &PN) {
1148 DEBUG(dbgs() << " original: " << PN << "\n");
1149
1150 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1151 IRBuilderTy PHIBuilder(&PN);
1152 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1153 PN.getName() + ".sroa.speculated");
1154
1155 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1156 // matter which one we get and if any differ.
1157 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1158 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1159 unsigned Align = SomeLoad->getAlignment();
1160
1161 // Rewrite all loads of the PN to use the new PHI.
1162 while (!PN.use_empty()) {
1163 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1164 LI->replaceAllUsesWith(NewPN);
1165 LI->eraseFromParent();
1166 }
1167
1168 // Inject loads into all of the pred blocks.
1169 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1170 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1171 TerminatorInst *TI = Pred->getTerminator();
1172 Value *InVal = PN.getIncomingValue(Idx);
1173 IRBuilderTy PredBuilder(TI);
1174
1175 LoadInst *Load = PredBuilder.CreateLoad(
1176 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1177 ++NumLoadsSpeculated;
1178 Load->setAlignment(Align);
1179 if (TBAATag)
1180 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1181 NewPN->addIncoming(Load, Pred);
1182 }
1183
1184 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1185 PN.eraseFromParent();
1186}
1187
1188/// Select instructions that use an alloca and are subsequently loaded can be
1189/// rewritten to load both input pointers and then select between the result,
1190/// allowing the load of the alloca to be promoted.
1191/// From this:
1192/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1193/// %V = load i32* %P2
1194/// to:
1195/// %V1 = load i32* %Alloca -> will be mem2reg'd
1196/// %V2 = load i32* %Other
1197/// %V = select i1 %cond, i32 %V1, i32 %V2
1198///
1199/// We can do this to a select if its only uses are loads and if the operand
1200/// to the select can be loaded unconditionally.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001201static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001202 Value *TValue = SI.getTrueValue();
1203 Value *FValue = SI.getFalseValue();
1204 bool TDerefable = TValue->isDereferenceablePointer();
1205 bool FDerefable = FValue->isDereferenceablePointer();
1206
1207 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1208 ++UI) {
1209 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1210 if (LI == 0 || !LI->isSimple())
1211 return false;
1212
1213 // Both operands to the select need to be dereferencable, either
1214 // absolutely (e.g. allocas) or at this point because we can see other
1215 // accesses to it.
1216 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001217 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001218 return false;
1219 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001220 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001221 return false;
1222 }
1223
1224 return true;
1225}
1226
1227static void speculateSelectInstLoads(SelectInst &SI) {
1228 DEBUG(dbgs() << " original: " << SI << "\n");
1229
1230 IRBuilderTy IRB(&SI);
1231 Value *TV = SI.getTrueValue();
1232 Value *FV = SI.getFalseValue();
1233 // Replace the loads of the select with a select of two loads.
1234 while (!SI.use_empty()) {
1235 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1236 assert(LI->isSimple() && "We only speculate simple loads");
1237
1238 IRB.SetInsertPoint(LI);
1239 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001240 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001241 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001242 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001243 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001244
Chandler Carruthf0546402013-07-18 07:15:00 +00001245 // Transfer alignment and TBAA info if present.
1246 TL->setAlignment(LI->getAlignment());
1247 FL->setAlignment(LI->getAlignment());
1248 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1249 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1250 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001251 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001252
1253 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1254 LI->getName() + ".sroa.speculated");
1255
1256 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1257 LI->replaceAllUsesWith(V);
1258 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001259 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001260 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001261}
1262
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001263/// \brief Build a GEP out of a base pointer and indices.
1264///
1265/// This will return the BasePtr if that is valid, or build a new GEP
1266/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001267static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001268 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001269 if (Indices.empty())
1270 return BasePtr;
1271
1272 // A single zero index is a no-op, so check for this and avoid building a GEP
1273 // in that case.
1274 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1275 return BasePtr;
1276
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001277 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001278}
1279
1280/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1281/// TargetTy without changing the offset of the pointer.
1282///
1283/// This routine assumes we've already established a properly offset GEP with
1284/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1285/// zero-indices down through type layers until we find one the same as
1286/// TargetTy. If we can't find one with the same type, we at least try to use
1287/// one with the same size. If none of that works, we just produce the GEP as
1288/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001289static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001290 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001291 SmallVectorImpl<Value *> &Indices,
1292 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001293 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001294 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001295
1296 // See if we can descend into a struct and locate a field with the correct
1297 // type.
1298 unsigned NumLayers = 0;
1299 Type *ElementTy = Ty;
1300 do {
1301 if (ElementTy->isPointerTy())
1302 break;
1303 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1304 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001305 // Note that we use the default address space as this index is over an
1306 // array or a vector, not a pointer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001307 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001308 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001309 if (STy->element_begin() == STy->element_end())
1310 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001311 ElementTy = *STy->element_begin();
1312 Indices.push_back(IRB.getInt32(0));
1313 } else {
1314 break;
1315 }
1316 ++NumLayers;
1317 } while (ElementTy != TargetTy);
1318 if (ElementTy != TargetTy)
1319 Indices.erase(Indices.end() - NumLayers, Indices.end());
1320
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001321 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001322}
1323
1324/// \brief Recursively compute indices for a natural GEP.
1325///
1326/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1327/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001328static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001329 Value *Ptr, Type *Ty, APInt &Offset,
1330 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001331 SmallVectorImpl<Value *> &Indices,
1332 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001333 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001334 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001335
1336 // We can't recurse through pointer types.
1337 if (Ty->isPointerTy())
1338 return 0;
1339
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001340 // We try to analyze GEPs over vectors here, but note that these GEPs are
1341 // extremely poorly defined currently. The long-term goal is to remove GEPing
1342 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001343 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001344 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001345 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001346 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001347 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001348 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001349 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1350 return 0;
1351 Offset -= NumSkippedElements * ElementSize;
1352 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001353 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001354 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001355 }
1356
1357 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1358 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001359 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001360 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001361 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1362 return 0;
1363
1364 Offset -= NumSkippedElements * ElementSize;
1365 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001366 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001367 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001368 }
1369
1370 StructType *STy = dyn_cast<StructType>(Ty);
1371 if (!STy)
1372 return 0;
1373
Chandler Carruth90a735d2013-07-19 07:21:28 +00001374 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001375 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001376 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001377 return 0;
1378 unsigned Index = SL->getElementContainingOffset(StructOffset);
1379 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1380 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001381 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001382 return 0; // The offset points into alignment padding.
1383
1384 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001385 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001386 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001387}
1388
1389/// \brief Get a natural GEP from a base pointer to a particular offset and
1390/// resulting in a particular type.
1391///
1392/// The goal is to produce a "natural" looking GEP that works with the existing
1393/// composite types to arrive at the appropriate offset and element type for
1394/// a pointer. TargetTy is the element type the returned GEP should point-to if
1395/// possible. We recurse by decreasing Offset, adding the appropriate index to
1396/// Indices, and setting Ty to the result subtype.
1397///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001398/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001399static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001401 SmallVectorImpl<Value *> &Indices,
1402 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001403 PointerType *Ty = cast<PointerType>(Ptr->getType());
1404
1405 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1406 // an i8.
1407 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1408 return 0;
1409
1410 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001411 if (!ElementTy->isSized())
1412 return 0; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001413 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414 if (ElementSize == 0)
1415 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001416 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001417
1418 Offset -= NumSkippedElements * ElementSize;
1419 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001420 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001421 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001422}
1423
1424/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1425/// resulting pointer has PointerTy.
1426///
1427/// This tries very hard to compute a "natural" GEP which arrives at the offset
1428/// and produces the pointer type desired. Where it cannot, it will try to use
1429/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1430/// fails, it will try to use an existing i8* and GEP to the byte offset and
1431/// bitcast to the type.
1432///
1433/// The strategy for finding the more natural GEPs is to peel off layers of the
1434/// pointer, walking back through bit casts and GEPs, searching for a base
1435/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001436/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001437/// a single GEP as possible, thus making each GEP more independent of the
1438/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001439static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1440 APInt Offset, Type *PointerTy,
1441 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001442 // Even though we don't look through PHI nodes, we could be called on an
1443 // instruction in an unreachable block, which may be on a cycle.
1444 SmallPtrSet<Value *, 4> Visited;
1445 Visited.insert(Ptr);
1446 SmallVector<Value *, 4> Indices;
1447
1448 // We may end up computing an offset pointer that has the wrong type. If we
1449 // never are able to compute one directly that has the correct type, we'll
1450 // fall back to it, so keep it around here.
1451 Value *OffsetPtr = 0;
1452
1453 // Remember any i8 pointer we come across to re-use if we need to do a raw
1454 // byte offset.
1455 Value *Int8Ptr = 0;
1456 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1457
1458 Type *TargetTy = PointerTy->getPointerElementType();
1459
1460 do {
1461 // First fold any existing GEPs into the offset.
1462 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1463 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001464 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001465 break;
1466 Offset += GEPOffset;
1467 Ptr = GEP->getPointerOperand();
1468 if (!Visited.insert(Ptr))
1469 break;
1470 }
1471
1472 // See if we can perform a natural GEP here.
1473 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001474 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001475 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001476 if (P->getType() == PointerTy) {
1477 // Zap any offset pointer that we ended up computing in previous rounds.
1478 if (OffsetPtr && OffsetPtr->use_empty())
1479 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1480 I->eraseFromParent();
1481 return P;
1482 }
1483 if (!OffsetPtr) {
1484 OffsetPtr = P;
1485 }
1486 }
1487
1488 // Stash this pointer if we've found an i8*.
1489 if (Ptr->getType()->isIntegerTy(8)) {
1490 Int8Ptr = Ptr;
1491 Int8PtrOffset = Offset;
1492 }
1493
1494 // Peel off a layer of the pointer and update the offset appropriately.
1495 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1496 Ptr = cast<Operator>(Ptr)->getOperand(0);
1497 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1498 if (GA->mayBeOverridden())
1499 break;
1500 Ptr = GA->getAliasee();
1501 } else {
1502 break;
1503 }
1504 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1505 } while (Visited.insert(Ptr));
1506
1507 if (!OffsetPtr) {
1508 if (!Int8Ptr) {
1509 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001510 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001511 Int8PtrOffset = Offset;
1512 }
1513
1514 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1515 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001516 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001517 }
1518 Ptr = OffsetPtr;
1519
1520 // On the off chance we were targeting i8*, guard the bitcast here.
1521 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001522 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001523
1524 return Ptr;
1525}
1526
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001527/// \brief Test whether we can convert a value from the old to the new type.
1528///
1529/// This predicate should be used to guard calls to convertValue in order to
1530/// ensure that we only try to convert viable values. The strategy is that we
1531/// will peel off single element struct and array wrappings to get to an
1532/// underlying value, and convert that value.
1533static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1534 if (OldTy == NewTy)
1535 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001536 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1537 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1538 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1539 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001540 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1541 return false;
1542 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1543 return false;
1544
Benjamin Kramer56262592013-09-22 11:24:58 +00001545 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001546 // of pointers and integers.
1547 OldTy = OldTy->getScalarType();
1548 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001549 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1550 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1551 return true;
1552 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1553 return true;
1554 return false;
1555 }
1556
1557 return true;
1558}
1559
1560/// \brief Generic routine to convert an SSA value to a value of a different
1561/// type.
1562///
1563/// This will try various different casting techniques, such as bitcasts,
1564/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1565/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001566static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001567 Type *NewTy) {
1568 Type *OldTy = V->getType();
1569 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1570
1571 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001572 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001573
1574 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1575 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001576 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1577 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001578
Benjamin Kramer90901a32013-09-21 20:36:04 +00001579 // See if we need inttoptr for this type pair. A cast involving both scalars
1580 // and vectors requires and additional bitcast.
1581 if (OldTy->getScalarType()->isIntegerTy() &&
1582 NewTy->getScalarType()->isPointerTy()) {
1583 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1584 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1585 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1586 NewTy);
1587
1588 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1589 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1590 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1591 NewTy);
1592
1593 return IRB.CreateIntToPtr(V, NewTy);
1594 }
1595
1596 // See if we need ptrtoint for this type pair. A cast involving both scalars
1597 // and vectors requires and additional bitcast.
1598 if (OldTy->getScalarType()->isPointerTy() &&
1599 NewTy->getScalarType()->isIntegerTy()) {
1600 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1601 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1602 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1603 NewTy);
1604
1605 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1606 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1607 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1608 NewTy);
1609
1610 return IRB.CreatePtrToInt(V, NewTy);
1611 }
1612
1613 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001614}
1615
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001616/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001617///
1618/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001619/// for a single slice.
1620static bool isVectorPromotionViableForSlice(
1621 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1622 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1623 AllocaSlices::const_iterator I) {
1624 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001625 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001626 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001627 uint64_t BeginIndex = BeginOffset / ElementSize;
1628 if (BeginIndex * ElementSize != BeginOffset ||
1629 BeginIndex >= Ty->getNumElements())
1630 return false;
1631 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001632 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001633 uint64_t EndIndex = EndOffset / ElementSize;
1634 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1635 return false;
1636
1637 assert(EndIndex > BeginIndex && "Empty vector!");
1638 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001639 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001640 (NumElements == 1) ? Ty->getElementType()
1641 : VectorType::get(Ty->getElementType(), NumElements);
1642
1643 Type *SplitIntTy =
1644 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1645
1646 Use *U = I->getUse();
1647
1648 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1649 if (MI->isVolatile())
1650 return false;
1651 if (!I->isSplittable())
1652 return false; // Skip any unsplittable intrinsics.
1653 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1654 // Disable vector promotion when there are loads or stores of an FCA.
1655 return false;
1656 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1657 if (LI->isVolatile())
1658 return false;
1659 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001660 if (SliceBeginOffset > I->beginOffset() ||
1661 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001662 assert(LTy->isIntegerTy());
1663 LTy = SplitIntTy;
1664 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001665 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001666 return false;
1667 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1668 if (SI->isVolatile())
1669 return false;
1670 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001671 if (SliceBeginOffset > I->beginOffset() ||
1672 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001673 assert(STy->isIntegerTy());
1674 STy = SplitIntTy;
1675 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001676 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001677 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001678 } else {
1679 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001680 }
1681
1682 return true;
1683}
1684
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001685/// \brief Test whether the given alloca partitioning and range of slices can be
1686/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001687///
1688/// This is a quick test to check whether we can rewrite a particular alloca
1689/// partition (and its newly formed alloca) into a vector alloca with only
1690/// whole-vector loads and stores such that it could be promoted to a vector
1691/// SSA value. We only can ensure this for a limited set of operations, and we
1692/// don't want to do the rewrites unless we are confident that the result will
1693/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001694static bool
1695isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1696 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1697 AllocaSlices::const_iterator I,
1698 AllocaSlices::const_iterator E,
1699 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001700 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1701 if (!Ty)
1702 return false;
1703
Chandler Carruth90a735d2013-07-19 07:21:28 +00001704 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001705
1706 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1707 // that aren't byte sized.
1708 if (ElementSize % 8)
1709 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001710 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001711 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001712 ElementSize /= 8;
1713
Chandler Carruthf0546402013-07-18 07:15:00 +00001714 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001715 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1716 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001717 return false;
1718
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001719 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1720 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001721 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001722 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1723 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001724 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001725
1726 return true;
1727}
1728
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001729/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001730///
1731/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001732/// test below on a single slice of the alloca.
1733static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1734 Type *AllocaTy,
1735 uint64_t AllocBeginOffset,
1736 uint64_t Size, AllocaSlices &S,
1737 AllocaSlices::const_iterator I,
1738 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001739 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1740 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1741
1742 // We can't reasonably handle cases where the load or store extends past
1743 // the end of the aloca's type and into its padding.
1744 if (RelEnd > Size)
1745 return false;
1746
1747 Use *U = I->getUse();
1748
1749 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1750 if (LI->isVolatile())
1751 return false;
1752 if (RelBegin == 0 && RelEnd == Size)
1753 WholeAllocaOp = true;
1754 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001755 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001756 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001757 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001758 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001759 // Non-integer loads need to be convertible from the alloca type so that
1760 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001761 return false;
1762 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001763 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1764 Type *ValueTy = SI->getValueOperand()->getType();
1765 if (SI->isVolatile())
1766 return false;
1767 if (RelBegin == 0 && RelEnd == Size)
1768 WholeAllocaOp = true;
1769 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001770 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001771 return false;
1772 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001773 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001774 // Non-integer stores need to be convertible to the alloca type so that
1775 // they are promotable.
1776 return false;
1777 }
1778 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1779 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1780 return false;
1781 if (!I->isSplittable())
1782 return false; // Skip any unsplittable intrinsics.
1783 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1784 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1785 II->getIntrinsicID() != Intrinsic::lifetime_end)
1786 return false;
1787 } else {
1788 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001789 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001790
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001791 return true;
1792}
1793
Chandler Carruth435c4e02012-10-15 08:40:30 +00001794/// \brief Test whether the given alloca partition's integer operations can be
1795/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001796///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001797/// This is a quick test to check whether we can rewrite the integer loads and
1798/// stores to a particular alloca into wider loads and stores and be able to
1799/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001800static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001801isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001802 uint64_t AllocBeginOffset, AllocaSlices &S,
1803 AllocaSlices::const_iterator I,
1804 AllocaSlices::const_iterator E,
1805 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001806 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001807 // Don't create integer types larger than the maximum bitwidth.
1808 if (SizeInBits > IntegerType::MAX_INT_BITS)
1809 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001810
1811 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001812 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001813 return false;
1814
Chandler Carruth58d05562012-10-25 04:37:07 +00001815 // We need to ensure that an integer type with the appropriate bitwidth can
1816 // be converted to the alloca type, whatever that is. We don't want to force
1817 // the alloca itself to have an integer type if there is a more suitable one.
1818 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001819 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1820 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001821 return false;
1822
Chandler Carruth90a735d2013-07-19 07:21:28 +00001823 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001824
Chandler Carruthf0546402013-07-18 07:15:00 +00001825 // While examining uses, we ensure that the alloca has a covering load or
1826 // store. We don't want to widen the integer operations only to fail to
1827 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001828 // later). However, if there are only splittable uses, go ahead and assume
1829 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001830 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001831
Chandler Carruthf0546402013-07-18 07:15:00 +00001832 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001833 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1834 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001835 return false;
1836
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001837 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1838 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001839 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001840 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1841 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001842 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001843
Chandler Carruth92924fd2012-09-24 00:34:20 +00001844 return WholeAllocaOp;
1845}
1846
Chandler Carruthd177f862013-03-20 07:30:36 +00001847static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001848 IntegerType *Ty, uint64_t Offset,
1849 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001850 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001851 IntegerType *IntTy = cast<IntegerType>(V->getType());
1852 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1853 "Element extends past full value");
1854 uint64_t ShAmt = 8*Offset;
1855 if (DL.isBigEndian())
1856 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001857 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001858 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001859 DEBUG(dbgs() << " shifted: " << *V << "\n");
1860 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001861 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1862 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001863 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001864 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001865 DEBUG(dbgs() << " trunced: " << *V << "\n");
1866 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001867 return V;
1868}
1869
Chandler Carruthd177f862013-03-20 07:30:36 +00001870static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001871 Value *V, uint64_t Offset, const Twine &Name) {
1872 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1873 IntegerType *Ty = cast<IntegerType>(V->getType());
1874 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1875 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001876 DEBUG(dbgs() << " start: " << *V << "\n");
1877 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001878 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001879 DEBUG(dbgs() << " extended: " << *V << "\n");
1880 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001881 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1882 "Element store outside of alloca store");
1883 uint64_t ShAmt = 8*Offset;
1884 if (DL.isBigEndian())
1885 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001886 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001887 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001888 DEBUG(dbgs() << " shifted: " << *V << "\n");
1889 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001890
1891 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1892 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1893 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001894 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001895 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001896 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001897 }
1898 return V;
1899}
1900
Chandler Carruthd177f862013-03-20 07:30:36 +00001901static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001902 unsigned BeginIndex, unsigned EndIndex,
1903 const Twine &Name) {
1904 VectorType *VecTy = cast<VectorType>(V->getType());
1905 unsigned NumElements = EndIndex - BeginIndex;
1906 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1907
1908 if (NumElements == VecTy->getNumElements())
1909 return V;
1910
1911 if (NumElements == 1) {
1912 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1913 Name + ".extract");
1914 DEBUG(dbgs() << " extract: " << *V << "\n");
1915 return V;
1916 }
1917
1918 SmallVector<Constant*, 8> Mask;
1919 Mask.reserve(NumElements);
1920 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1921 Mask.push_back(IRB.getInt32(i));
1922 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1923 ConstantVector::get(Mask),
1924 Name + ".extract");
1925 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1926 return V;
1927}
1928
Chandler Carruthd177f862013-03-20 07:30:36 +00001929static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001930 unsigned BeginIndex, const Twine &Name) {
1931 VectorType *VecTy = cast<VectorType>(Old->getType());
1932 assert(VecTy && "Can only insert a vector into a vector");
1933
1934 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1935 if (!Ty) {
1936 // Single element to insert.
1937 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1938 Name + ".insert");
1939 DEBUG(dbgs() << " insert: " << *V << "\n");
1940 return V;
1941 }
1942
1943 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1944 "Too many elements!");
1945 if (Ty->getNumElements() == VecTy->getNumElements()) {
1946 assert(V->getType() == VecTy && "Vector type mismatch");
1947 return V;
1948 }
1949 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1950
1951 // When inserting a smaller vector into the larger to store, we first
1952 // use a shuffle vector to widen it with undef elements, and then
1953 // a second shuffle vector to select between the loaded vector and the
1954 // incoming vector.
1955 SmallVector<Constant*, 8> Mask;
1956 Mask.reserve(VecTy->getNumElements());
1957 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1958 if (i >= BeginIndex && i < EndIndex)
1959 Mask.push_back(IRB.getInt32(i - BeginIndex));
1960 else
1961 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1962 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1963 ConstantVector::get(Mask),
1964 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001965 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001966
1967 Mask.clear();
1968 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001969 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1970
1971 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1972
1973 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001974 return V;
1975}
1976
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001977namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001978/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1979/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001980///
1981/// Also implements the rewriting to vector-based accesses when the partition
1982/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1983/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001984class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001985 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001986 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1987 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001988
Chandler Carruth90a735d2013-07-19 07:21:28 +00001989 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001990 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001991 SROA &Pass;
1992 AllocaInst &OldAI, &NewAI;
1993 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001994 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001995
1996 // If we are rewriting an alloca partition which can be written as pure
1997 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001998 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001999 // - The new alloca is exactly the size of the vector type here.
2000 // - The accesses all either map to the entire vector or to a single
2001 // element.
2002 // - The set of accessing instructions is only one of those handled above
2003 // in isVectorPromotionViable. Generally these are the same access kinds
2004 // which are promotable via mem2reg.
2005 VectorType *VecTy;
2006 Type *ElementTy;
2007 uint64_t ElementSize;
2008
Chandler Carruth92924fd2012-09-24 00:34:20 +00002009 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002010 // alloca's integer operations should be widened to this integer type due to
2011 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002012 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002013 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002014
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002015 // The offset of the slice currently being rewritten.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002016 uint64_t BeginOffset, EndOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002017 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002018 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002019 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002020 Instruction *OldPtr;
2021
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002022 // Track post-rewrite users which are PHI nodes and Selects.
2023 SmallPtrSetImpl<PHINode *> &PHIUsers;
2024 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002025
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002026 // Utility IR builder, whose name prefix is setup for each visited use, and
2027 // the insertion point is set to point to the user.
2028 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002029
2030public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002031 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
2032 AllocaInst &OldAI, AllocaInst &NewAI,
2033 uint64_t NewBeginOffset, uint64_t NewEndOffset,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002034 bool IsVectorPromotable, bool IsIntegerPromotable,
2035 SmallPtrSetImpl<PHINode *> &PHIUsers,
2036 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002037 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthf0546402013-07-18 07:15:00 +00002038 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
2039 NewAllocaTy(NewAI.getAllocatedType()),
2040 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
2041 ElementTy(VecTy ? VecTy->getElementType() : 0),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002042 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002043 IntTy(IsIntegerPromotable
2044 ? Type::getIntNTy(
2045 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002046 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Chandler Carruthf0546402013-07-18 07:15:00 +00002047 : 0),
2048 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002049 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002050 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002051 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002052 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002053 "Only multiple-of-8 sized vector elements are viable");
2054 ++NumVectorized;
2055 }
2056 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
2057 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002058 }
2059
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002060 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002061 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002062 BeginOffset = I->beginOffset();
2063 EndOffset = I->endOffset();
2064 IsSplittable = I->isSplittable();
2065 IsSplit =
2066 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002067
Chandler Carruthf0546402013-07-18 07:15:00 +00002068 OldUse = I->getUse();
2069 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002070
Chandler Carruthf0546402013-07-18 07:15:00 +00002071 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2072 IRB.SetInsertPoint(OldUserI);
2073 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2074 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2075
2076 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2077 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002078 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002079 return CanSROA;
2080 }
2081
2082private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002083 // Make sure the other visit overloads are visible.
2084 using Base::visit;
2085
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002086 // Every instruction which can end up as a user must have a rewrite rule.
2087 bool visitInstruction(Instruction &I) {
2088 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2089 llvm_unreachable("No rewrite rule for this instruction!");
2090 }
2091
Chandler Carruthf0546402013-07-18 07:15:00 +00002092 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2093 Type *PointerTy) {
2094 assert(Offset >= NewAllocaBeginOffset);
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002095#ifndef NDEBUG
2096 StringRef OldName = OldPtr->getName();
2097 // Skip through the last '.sroa.' component of the name.
2098 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2099 if (LastSROAPrefix != StringRef::npos) {
2100 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2101 // Look for an SROA slice index.
2102 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2103 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2104 // Strip the index and look for the offset.
2105 OldName = OldName.substr(IndexEnd + 1);
2106 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2107 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2108 // Strip the offset.
2109 OldName = OldName.substr(OffsetEnd + 1);
2110 }
2111 }
2112 // Strip any SROA suffixes as well.
2113 OldName = OldName.substr(0, OldName.find(".sroa_"));
2114#endif
Chandler Carruth90a735d2013-07-19 07:21:28 +00002115 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002116 Offset - NewAllocaBeginOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002117 PointerTy,
2118#ifndef NDEBUG
2119 Twine(OldName) + "."
2120#else
2121 Twine()
2122#endif
2123 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002124 }
2125
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002126 /// \brief Compute suitable alignment to access an offset into the new alloca.
2127 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002128 unsigned NewAIAlign = NewAI.getAlignment();
2129 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002130 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth176ca712012-10-01 12:16:54 +00002131 return MinAlign(NewAIAlign, Offset);
2132 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002133
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002134 /// \brief Compute suitable alignment to access a type at an offset of the
2135 /// new alloca.
2136 ///
2137 /// \returns zero if the type's ABI alignment is a suitable alignment,
2138 /// otherwise returns the maximal suitable alignment.
2139 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2140 unsigned Align = getOffsetAlign(Offset);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002141 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002142 }
2143
Chandler Carruth845b73c2012-11-21 08:16:30 +00002144 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002145 assert(VecTy && "Can only call getIndex when rewriting a vector");
2146 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2147 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2148 uint32_t Index = RelOffset / ElementSize;
2149 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002150 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002151 }
2152
2153 void deleteIfTriviallyDead(Value *V) {
2154 Instruction *I = cast<Instruction>(V);
2155 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002156 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002157 }
2158
Chandler Carruthf0546402013-07-18 07:15:00 +00002159 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2160 uint64_t NewEndOffset) {
2161 unsigned BeginIndex = getIndex(NewBeginOffset);
2162 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002163 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002164
2165 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002166 "load");
2167 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002168 }
2169
Chandler Carruthf0546402013-07-18 07:15:00 +00002170 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2171 uint64_t NewEndOffset) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002172 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002173 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002174 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002175 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002176 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002177 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2178 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2179 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002180 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002181 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002182 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002183 }
2184
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002185 bool visitLoadInst(LoadInst &LI) {
2186 DEBUG(dbgs() << " original: " << LI << "\n");
2187 Value *OldOp = LI.getOperand(0);
2188 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002189
Chandler Carruthf0546402013-07-18 07:15:00 +00002190 // Compute the intersecting offset range.
2191 assert(BeginOffset < NewAllocaEndOffset);
2192 assert(EndOffset > NewAllocaBeginOffset);
2193 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2194 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2195
2196 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002197
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002198 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2199 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002200 bool IsPtrAdjusted = false;
2201 Value *V;
2202 if (VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002203 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002204 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002205 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2206 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002207 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002208 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002209 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002210 } else {
2211 Type *LTy = TargetTy->getPointerTo();
Chandler Carruthf0546402013-07-18 07:15:00 +00002212 V = IRB.CreateAlignedLoad(
2213 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2214 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002215 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002216 IsPtrAdjusted = true;
2217 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002218 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002219
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002220 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002221 assert(!LI.isVolatile());
2222 assert(LI.getType()->isIntegerTy() &&
2223 "Only integer type loads and stores are split");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002224 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002225 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002226 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002227 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002228 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002229 // Move the insertion point just past the load so that we can refer to it.
2230 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002231 // Create a placeholder value with the same type as LI to use as the
2232 // basis for the new value. This allows us to replace the uses of LI with
2233 // the computed value, and then replace the placeholder with LI, leaving
2234 // LI only used for this computation.
2235 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002236 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002237 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002238 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002239 LI.replaceAllUsesWith(V);
2240 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002241 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002242 } else {
2243 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002244 }
2245
Chandler Carruth18db7952012-11-20 01:12:50 +00002246 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002247 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002248 DEBUG(dbgs() << " to: " << *V << "\n");
2249 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002250 }
2251
Chandler Carruthf0546402013-07-18 07:15:00 +00002252 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2253 uint64_t NewBeginOffset,
2254 uint64_t NewEndOffset) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002255 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002256 unsigned BeginIndex = getIndex(NewBeginOffset);
2257 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002258 assert(EndIndex > BeginIndex && "Empty vector!");
2259 unsigned NumElements = EndIndex - BeginIndex;
2260 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002261 Type *SliceTy =
2262 (NumElements == 1) ? ElementTy
2263 : VectorType::get(ElementTy, NumElements);
2264 if (V->getType() != SliceTy)
2265 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002266
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002267 // Mix in the existing elements.
2268 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2269 "load");
2270 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2271 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002272 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002273 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002274
2275 (void)Store;
2276 DEBUG(dbgs() << " to: " << *Store << "\n");
2277 return true;
2278 }
2279
Chandler Carruthf0546402013-07-18 07:15:00 +00002280 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2281 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
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 Carruthf0546402013-07-18 07:15:00 +00002314 // Compute the intersecting offset range.
2315 assert(BeginOffset < NewAllocaEndOffset);
2316 assert(EndOffset > NewAllocaBeginOffset);
2317 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2318 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2319
2320 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002321 if (Size < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002322 assert(!SI.isVolatile());
2323 assert(V->getType()->isIntegerTy() &&
2324 "Only integer type loads and stores are split");
2325 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002326 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002327 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002328 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002329 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002330 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002331 }
2332
Chandler Carruth18db7952012-11-20 01:12:50 +00002333 if (VecTy)
Chandler Carruthf0546402013-07-18 07:15:00 +00002334 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2335 NewEndOffset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002336 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthf0546402013-07-18 07:15:00 +00002337 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002338
Chandler Carruth18db7952012-11-20 01:12:50 +00002339 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002340 if (NewBeginOffset == NewAllocaBeginOffset &&
2341 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002342 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2343 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002344 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2345 SI.isVolatile());
2346 } else {
Chandler Carruthf0546402013-07-18 07:15:00 +00002347 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2348 V->getType()->getPointerTo());
2349 NewSI = IRB.CreateAlignedStore(
Chandler Carruth7625c542014-02-25 11:07:58 +00002350 V, NewPtr, getOffsetTypeAlign(V->getType(),
2351 NewBeginOffset - NewAllocaBeginOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002352 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002353 }
2354 (void)NewSI;
2355 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002356 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002357
2358 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2359 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002360 }
2361
Chandler Carruth514f34f2012-12-17 04:07:30 +00002362 /// \brief Compute an integer value from splatting an i8 across the given
2363 /// number of bytes.
2364 ///
2365 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2366 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002367 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002368 ///
2369 /// \param V The i8 value to splat.
2370 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002371 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002372 assert(Size > 0 && "Expected a positive number of bytes.");
2373 IntegerType *VTy = cast<IntegerType>(V->getType());
2374 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2375 if (Size == 1)
2376 return V;
2377
2378 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002379 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002380 ConstantExpr::getUDiv(
2381 Constant::getAllOnesValue(SplatIntTy),
2382 ConstantExpr::getZExt(
2383 Constant::getAllOnesValue(V->getType()),
2384 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002385 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002386 return V;
2387 }
2388
Chandler Carruthccca5042012-12-17 04:07:37 +00002389 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002390 Value *getVectorSplat(Value *V, unsigned NumElements) {
2391 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002392 DEBUG(dbgs() << " splat: " << *V << "\n");
2393 return V;
2394 }
2395
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002396 bool visitMemSetInst(MemSetInst &II) {
2397 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002398 assert(II.getRawDest() == OldPtr);
2399
2400 // If the memset has a variable size, it cannot be split, just adjust the
2401 // pointer to the new alloca.
2402 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002403 assert(!IsSplit);
2404 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth8183a502014-02-25 11:08:02 +00002405 II.setDest(getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002406 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002407 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
Chandler Carruth208124f2012-09-26 10:59:22 +00002408
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002409 deleteIfTriviallyDead(OldPtr);
2410 return false;
2411 }
2412
2413 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002414 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002415
2416 Type *AllocaTy = NewAI.getAllocatedType();
2417 Type *ScalarTy = AllocaTy->getScalarType();
2418
Chandler Carruthf0546402013-07-18 07:15:00 +00002419 // Compute the intersecting offset range.
2420 assert(BeginOffset < NewAllocaEndOffset);
2421 assert(EndOffset > NewAllocaBeginOffset);
2422 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2423 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002424 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002425
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002426 // If this doesn't map cleanly onto the alloca type, and that type isn't
2427 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002428 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002429 (BeginOffset > NewAllocaBeginOffset ||
2430 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002431 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002432 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2433 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002434 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002435 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2436 CallInst *New = IRB.CreateMemSet(
Chandler Carruth8183a502014-02-25 11:08:02 +00002437 getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType()),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002438 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002439 (void)New;
2440 DEBUG(dbgs() << " to: " << *New << "\n");
2441 return false;
2442 }
2443
2444 // If we can represent this as a simple value, we have to build the actual
2445 // value to store, which requires expanding the byte present in memset to
2446 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002447 // splatting the byte to a sufficiently wide integer, splatting it across
2448 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002449 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002450
Chandler Carruthccca5042012-12-17 04:07:37 +00002451 if (VecTy) {
2452 // If this is a memset of a vectorized alloca, insert it.
2453 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002454
Chandler Carruthf0546402013-07-18 07:15:00 +00002455 unsigned BeginIndex = getIndex(NewBeginOffset);
2456 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002457 assert(EndIndex > BeginIndex && "Empty vector!");
2458 unsigned NumElements = EndIndex - BeginIndex;
2459 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2460
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002461 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002462 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2463 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002464 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002465 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002466
Chandler Carruthce4562b2012-12-17 13:41:21 +00002467 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002468 "oldload");
2469 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002470 } else if (IntTy) {
2471 // If this is a memset on an alloca where we can widen stores, insert the
2472 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002473 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002474
Chandler Carruthf0546402013-07-18 07:15:00 +00002475 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002476 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002477
2478 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2479 EndOffset != NewAllocaBeginOffset)) {
2480 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002481 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002482 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002483 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002484 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002485 } else {
2486 assert(V->getType() == IntTy &&
2487 "Wrong type for an alloca wide integer!");
2488 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002489 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002490 } else {
2491 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002492 assert(NewBeginOffset == NewAllocaBeginOffset);
2493 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002494
Chandler Carruth90a735d2013-07-19 07:21:28 +00002495 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002496 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002497 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002498
Chandler Carruth90a735d2013-07-19 07:21:28 +00002499 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500 }
2501
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002502 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002503 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002504 (void)New;
2505 DEBUG(dbgs() << " to: " << *New << "\n");
2506 return !II.isVolatile();
2507 }
2508
2509 bool visitMemTransferInst(MemTransferInst &II) {
2510 // Rewriting of memory transfer instructions can be a bit tricky. We break
2511 // them into two categories: split intrinsics and unsplit intrinsics.
2512
2513 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002514
Chandler Carruthf0546402013-07-18 07:15:00 +00002515 // Compute the intersecting offset range.
2516 assert(BeginOffset < NewAllocaEndOffset);
2517 assert(EndOffset > NewAllocaBeginOffset);
2518 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2519 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2520
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002521 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002522 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002523 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002524
Chandler Carruth176ca712012-10-01 12:16:54 +00002525 // Compute the relative offset within the transfer.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002526 unsigned IntPtrWidth = DL.getPointerSizeInBits();
Chandler Carruthf0546402013-07-18 07:15:00 +00002527 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002528
2529 unsigned Align = II.getAlignment();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002530 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth176ca712012-10-01 12:16:54 +00002531 if (Align > 1)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002532 Align =
2533 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2534 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
Chandler Carruth176ca712012-10-01 12:16:54 +00002535
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002536 // For unsplit intrinsics, we simply modify the source and destination
2537 // pointers in place. This isn't just an optimization, it is a matter of
2538 // correctness. With unsplit intrinsics we may be dealing with transfers
2539 // within a single alloca before SROA ran, or with transfers that have
2540 // a variable length. We may also be dealing with memmove instead of
2541 // memcpy, and so simply updating the pointers is the necessary for us to
2542 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002543 if (!IsSplittable) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002544 Value *AdjustedPtr =
2545 getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002546 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002547 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002548 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002549 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002550
Chandler Carruth208124f2012-09-26 10:59:22 +00002551 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002552 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002553
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002554 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002555 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556 return false;
2557 }
2558 // For split transfer intrinsics we have an incredibly useful assurance:
2559 // the source and destination do not reside within the same alloca, and at
2560 // least one of them does not escape. This means that we can replace
2561 // memmove with memcpy, and we don't need to worry about all manner of
2562 // downsides to splitting and transforming the operations.
2563
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002564 // If this doesn't map cleanly onto the alloca type, and that type isn't
2565 // a single value type, just emit a memcpy.
2566 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002567 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2568 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002569 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002570
2571 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2572 // size hasn't been shrunk based on analysis of the viable range, this is
2573 // a no-op.
2574 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002575 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002576 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002577
2578 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002579 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002580 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002581 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002582 return false;
2583 }
2584 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002585 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002586
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002587 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2588 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002589 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002590 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002591 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2592 assert(AI != &OldAI && AI != &NewAI &&
2593 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002594 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002595 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002596
2597 if (EmitMemCpy) {
Rafael Espindola8eee97d2014-02-14 19:02:01 +00002598 Type *OtherPtrTy = OtherPtr->getType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002599
2600 // Compute the other pointer, folding as much as possible to produce
2601 // a single, simple GEP in most cases.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002602 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy,
2603 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002604
Chandler Carruth8183a502014-02-25 11:08:02 +00002605 Value *OurPtr =
2606 getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002607 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002608 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002609
2610 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2611 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002612 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002613 (void)New;
2614 DEBUG(dbgs() << " to: " << *New << "\n");
2615 return false;
2616 }
2617
Chandler Carruth08e5f492012-10-03 08:26:28 +00002618 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2619 // is equivalent to 1, but that isn't true if we end up rewriting this as
2620 // a load or store.
2621 if (!Align)
2622 Align = 1;
2623
Chandler Carruthf0546402013-07-18 07:15:00 +00002624 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2625 NewEndOffset == NewAllocaEndOffset;
2626 uint64_t Size = NewEndOffset - NewBeginOffset;
2627 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2628 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002629 unsigned NumElements = EndIndex - BeginIndex;
2630 IntegerType *SubIntTy
2631 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2632
2633 Type *OtherPtrTy = NewAI.getType();
2634 if (VecTy && !IsWholeAlloca) {
2635 if (NumElements == 1)
2636 OtherPtrTy = VecTy->getElementType();
2637 else
2638 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2639
2640 OtherPtrTy = OtherPtrTy->getPointerTo();
2641 } else if (IntTy && !IsWholeAlloca) {
2642 OtherPtrTy = SubIntTy->getPointerTo();
2643 }
2644
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002645 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy,
2646 OtherPtr->getName() + ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002647 Value *DstPtr = &NewAI;
2648 if (!IsDest)
2649 std::swap(SrcPtr, DstPtr);
2650
2651 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002652 if (VecTy && !IsWholeAlloca && !IsDest) {
2653 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002654 "load");
2655 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002656 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002657 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002658 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002659 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002660 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002661 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002662 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002663 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002664 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002665 }
2666
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002667 if (VecTy && !IsWholeAlloca && IsDest) {
2668 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002669 "oldload");
2670 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002671 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002672 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002673 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002674 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002675 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002676 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2677 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002678 }
2679
Chandler Carruth871ba722012-09-26 10:27:46 +00002680 StoreInst *Store = cast<StoreInst>(
2681 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2682 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002683 DEBUG(dbgs() << " to: " << *Store << "\n");
2684 return !II.isVolatile();
2685 }
2686
2687 bool visitIntrinsicInst(IntrinsicInst &II) {
2688 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2689 II.getIntrinsicID() == Intrinsic::lifetime_end);
2690 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002691 assert(II.getArgOperand(1) == OldPtr);
2692
Chandler Carruthf0546402013-07-18 07:15:00 +00002693 // Compute the intersecting offset range.
2694 assert(BeginOffset < NewAllocaEndOffset);
2695 assert(EndOffset > NewAllocaBeginOffset);
2696 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2697 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2698
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002699 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002700 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002701
2702 ConstantInt *Size
2703 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002704 NewEndOffset - NewBeginOffset);
Chandler Carruth8183a502014-02-25 11:08:02 +00002705 Value *Ptr = getAdjustedAllocaPtr(IRB, NewBeginOffset, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002706 Value *New;
2707 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2708 New = IRB.CreateLifetimeStart(Ptr, Size);
2709 else
2710 New = IRB.CreateLifetimeEnd(Ptr, Size);
2711
Edwin Vane82f80d42013-01-29 17:42:24 +00002712 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002713 DEBUG(dbgs() << " to: " << *New << "\n");
2714 return true;
2715 }
2716
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717 bool visitPHINode(PHINode &PN) {
2718 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002719 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2720 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002721
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002722 // We would like to compute a new pointer in only one place, but have it be
2723 // as local as possible to the PHI. To do that, we re-use the location of
2724 // the old pointer, which necessarily must be in the right position to
2725 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002726 IRBuilderTy PtrBuilder(IRB);
2727 PtrBuilder.SetInsertPoint(OldPtr);
2728 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002729
Chandler Carruthf0546402013-07-18 07:15:00 +00002730 Value *NewPtr =
2731 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002732 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002733 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002734
Chandler Carruth82a57542012-10-01 10:54:05 +00002735 DEBUG(dbgs() << " to: " << PN << "\n");
2736 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002737
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002738 // PHIs can't be promoted on their own, but often can be speculated. We
2739 // check the speculation outside of the rewriter so that we see the
2740 // fully-rewritten alloca.
2741 PHIUsers.insert(&PN);
2742 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002743 }
2744
2745 bool visitSelectInst(SelectInst &SI) {
2746 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002747 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2748 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002749 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2750 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002751
Chandler Carruthf0546402013-07-18 07:15:00 +00002752 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002753 // Replace the operands which were using the old pointer.
2754 if (SI.getOperand(1) == OldPtr)
2755 SI.setOperand(1, NewPtr);
2756 if (SI.getOperand(2) == OldPtr)
2757 SI.setOperand(2, NewPtr);
2758
Chandler Carruth82a57542012-10-01 10:54:05 +00002759 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002760 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002761
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002762 // Selects can't be promoted on their own, but often can be speculated. We
2763 // check the speculation outside of the rewriter so that we see the
2764 // fully-rewritten alloca.
2765 SelectUsers.insert(&SI);
2766 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002767 }
2768
2769};
2770}
2771
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002772namespace {
2773/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2774///
2775/// This pass aggressively rewrites all aggregate loads and stores on
2776/// a particular pointer (or any pointer derived from it which we can identify)
2777/// with scalar loads and stores.
2778class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2779 // Befriend the base class so it can delegate to private visit methods.
2780 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2781
Chandler Carruth90a735d2013-07-19 07:21:28 +00002782 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002783
2784 /// Queue of pointer uses to analyze and potentially rewrite.
2785 SmallVector<Use *, 8> Queue;
2786
2787 /// Set to prevent us from cycling with phi nodes and loops.
2788 SmallPtrSet<User *, 8> Visited;
2789
2790 /// The current pointer use being rewritten. This is used to dig up the used
2791 /// value (as opposed to the user).
2792 Use *U;
2793
2794public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002795 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002796
2797 /// Rewrite loads and stores through a pointer and all pointers derived from
2798 /// it.
2799 bool rewrite(Instruction &I) {
2800 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2801 enqueueUsers(I);
2802 bool Changed = false;
2803 while (!Queue.empty()) {
2804 U = Queue.pop_back_val();
2805 Changed |= visit(cast<Instruction>(U->getUser()));
2806 }
2807 return Changed;
2808 }
2809
2810private:
2811 /// Enqueue all the users of the given instruction for further processing.
2812 /// This uses a set to de-duplicate users.
2813 void enqueueUsers(Instruction &I) {
2814 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2815 ++UI)
2816 if (Visited.insert(*UI))
2817 Queue.push_back(&UI.getUse());
2818 }
2819
2820 // Conservative default is to not rewrite anything.
2821 bool visitInstruction(Instruction &I) { return false; }
2822
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002823 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002824 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002825 class OpSplitter {
2826 protected:
2827 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002828 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002829 /// The indices which to be used with insert- or extractvalue to select the
2830 /// appropriate value within the aggregate.
2831 SmallVector<unsigned, 4> Indices;
2832 /// The indices to a GEP instruction which will move Ptr to the correct slot
2833 /// within the aggregate.
2834 SmallVector<Value *, 4> GEPIndices;
2835 /// The base pointer of the original op, used as a base for GEPing the
2836 /// split operations.
2837 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002838
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002839 /// Initialize the splitter with an insertion point, Ptr and start with a
2840 /// single zero GEP index.
2841 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002842 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002843
2844 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002845 /// \brief Generic recursive split emission routine.
2846 ///
2847 /// This method recursively splits an aggregate op (load or store) into
2848 /// scalar or vector ops. It splits recursively until it hits a single value
2849 /// and emits that single value operation via the template argument.
2850 ///
2851 /// The logic of this routine relies on GEPs and insertvalue and
2852 /// extractvalue all operating with the same fundamental index list, merely
2853 /// formatted differently (GEPs need actual values).
2854 ///
2855 /// \param Ty The type being split recursively into smaller ops.
2856 /// \param Agg The aggregate value being built up or stored, depending on
2857 /// whether this is splitting a load or a store respectively.
2858 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2859 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002860 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002861
2862 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2863 unsigned OldSize = Indices.size();
2864 (void)OldSize;
2865 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2866 ++Idx) {
2867 assert(Indices.size() == OldSize && "Did not return to the old size");
2868 Indices.push_back(Idx);
2869 GEPIndices.push_back(IRB.getInt32(Idx));
2870 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2871 GEPIndices.pop_back();
2872 Indices.pop_back();
2873 }
2874 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002875 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002876
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002877 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2878 unsigned OldSize = Indices.size();
2879 (void)OldSize;
2880 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2881 ++Idx) {
2882 assert(Indices.size() == OldSize && "Did not return to the old size");
2883 Indices.push_back(Idx);
2884 GEPIndices.push_back(IRB.getInt32(Idx));
2885 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2886 GEPIndices.pop_back();
2887 Indices.pop_back();
2888 }
2889 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002890 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002891
2892 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002893 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002894 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002895
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002896 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002897 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002898 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002899
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002900 /// Emit a leaf load of a single value. This is called at the leaves of the
2901 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002902 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002903 assert(Ty->isSingleValueType());
2904 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002905 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2906 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002907 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2908 DEBUG(dbgs() << " to: " << *Load << "\n");
2909 }
2910 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002911
2912 bool visitLoadInst(LoadInst &LI) {
2913 assert(LI.getPointerOperand() == *U);
2914 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2915 return false;
2916
2917 // We have an aggregate being loaded, split it apart.
2918 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002919 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002920 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002921 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002922 LI.replaceAllUsesWith(V);
2923 LI.eraseFromParent();
2924 return true;
2925 }
2926
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002927 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002928 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002929 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002930
2931 /// Emit a leaf store of a single value. This is called at the leaves of the
2932 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002933 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002934 assert(Ty->isSingleValueType());
2935 // Extract the single value and store it using the indices.
2936 Value *Store = IRB.CreateStore(
2937 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2938 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2939 (void)Store;
2940 DEBUG(dbgs() << " to: " << *Store << "\n");
2941 }
2942 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002943
2944 bool visitStoreInst(StoreInst &SI) {
2945 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2946 return false;
2947 Value *V = SI.getValueOperand();
2948 if (V->getType()->isSingleValueType())
2949 return false;
2950
2951 // We have an aggregate being stored, split it apart.
2952 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002953 StoreOpSplitter Splitter(&SI, *U);
2954 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002955 SI.eraseFromParent();
2956 return true;
2957 }
2958
2959 bool visitBitCastInst(BitCastInst &BC) {
2960 enqueueUsers(BC);
2961 return false;
2962 }
2963
2964 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2965 enqueueUsers(GEPI);
2966 return false;
2967 }
2968
2969 bool visitPHINode(PHINode &PN) {
2970 enqueueUsers(PN);
2971 return false;
2972 }
2973
2974 bool visitSelectInst(SelectInst &SI) {
2975 enqueueUsers(SI);
2976 return false;
2977 }
2978};
2979}
2980
Chandler Carruthba931992012-10-13 10:49:33 +00002981/// \brief Strip aggregate type wrapping.
2982///
2983/// This removes no-op aggregate types wrapping an underlying type. It will
2984/// strip as many layers of types as it can without changing either the type
2985/// size or the allocated size.
2986static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2987 if (Ty->isSingleValueType())
2988 return Ty;
2989
2990 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2991 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2992
2993 Type *InnerTy;
2994 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2995 InnerTy = ArrTy->getElementType();
2996 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2997 const StructLayout *SL = DL.getStructLayout(STy);
2998 unsigned Index = SL->getElementContainingOffset(0);
2999 InnerTy = STy->getElementType(Index);
3000 } else {
3001 return Ty;
3002 }
3003
3004 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3005 TypeSize > DL.getTypeSizeInBits(InnerTy))
3006 return Ty;
3007
3008 return stripAggregateTypeWrapping(DL, InnerTy);
3009}
3010
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003011/// \brief Try to find a partition of the aggregate type passed in for a given
3012/// offset and size.
3013///
3014/// This recurses through the aggregate type and tries to compute a subtype
3015/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003016/// of an array, it will even compute a new array type for that sub-section,
3017/// and the same for structs.
3018///
3019/// Note that this routine is very strict and tries to find a partition of the
3020/// type which produces the *exact* right offset and size. It is not forgiving
3021/// when the size or offset cause either end of type-based partition to be off.
3022/// Also, this is a best-effort routine. It is reasonable to give up and not
3023/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003024static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003025 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003026 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3027 return stripAggregateTypeWrapping(DL, Ty);
3028 if (Offset > DL.getTypeAllocSize(Ty) ||
3029 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Chandler Carruth58d05562012-10-25 04:37:07 +00003030 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031
3032 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3033 // We can't partition pointers...
3034 if (SeqTy->isPointerTy())
3035 return 0;
3036
3037 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003038 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003039 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003040 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003041 if (NumSkippedElements >= ArrTy->getNumElements())
3042 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003043 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003044 if (NumSkippedElements >= VecTy->getNumElements())
3045 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003046 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003047 Offset -= NumSkippedElements * ElementSize;
3048
3049 // First check if we need to recurse.
3050 if (Offset > 0 || Size < ElementSize) {
3051 // Bail if the partition ends in a different array element.
3052 if ((Offset + Size) > ElementSize)
3053 return 0;
3054 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003055 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003056 }
3057 assert(Offset == 0);
3058
3059 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003060 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003061 assert(Size > ElementSize);
3062 uint64_t NumElements = Size / ElementSize;
3063 if (NumElements * ElementSize != Size)
3064 return 0;
3065 return ArrayType::get(ElementTy, NumElements);
3066 }
3067
3068 StructType *STy = dyn_cast<StructType>(Ty);
3069 if (!STy)
3070 return 0;
3071
Chandler Carruth90a735d2013-07-19 07:21:28 +00003072 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003073 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003074 return 0;
3075 uint64_t EndOffset = Offset + Size;
3076 if (EndOffset > SL->getSizeInBytes())
3077 return 0;
3078
3079 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003080 Offset -= SL->getElementOffset(Index);
3081
3082 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003083 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003084 if (Offset >= ElementSize)
3085 return 0; // The offset points into alignment padding.
3086
3087 // See if any partition must be contained by the element.
3088 if (Offset > 0 || Size < ElementSize) {
3089 if ((Offset + Size) > ElementSize)
3090 return 0;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003091 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003092 }
3093 assert(Offset == 0);
3094
3095 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003096 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003097
3098 StructType::element_iterator EI = STy->element_begin() + Index,
3099 EE = STy->element_end();
3100 if (EndOffset < SL->getSizeInBytes()) {
3101 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3102 if (Index == EndIndex)
3103 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003104
3105 // Don't try to form "natural" types if the elements don't line up with the
3106 // expected size.
3107 // FIXME: We could potentially recurse down through the last element in the
3108 // sub-struct to find a natural end point.
3109 if (SL->getElementOffset(EndIndex) != EndOffset)
3110 return 0;
3111
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003112 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003113 EE = STy->element_begin() + EndIndex;
3114 }
3115
3116 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003117 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003118 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003119 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003120 if (Size != SubSL->getSizeInBytes())
3121 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003122
Chandler Carruth054a40a2012-09-14 11:08:31 +00003123 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003124}
3125
3126/// \brief Rewrite an alloca partition's users.
3127///
3128/// This routine drives both of the rewriting goals of the SROA pass. It tries
3129/// to rewrite uses of an alloca partition to be conducive for SSA value
3130/// promotion. If the partition needs a new, more refined alloca, this will
3131/// build that new alloca, preserving as much type information as possible, and
3132/// rewrite the uses of the old alloca to point at the new one and have the
3133/// appropriate new offsets. It also evaluates how successful the rewrite was
3134/// at enabling promotion and if it was successful queues the alloca to be
3135/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003136bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3137 AllocaSlices::iterator B, AllocaSlices::iterator E,
3138 int64_t BeginOffset, int64_t EndOffset,
3139 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003140 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003141 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003142
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003143 // Try to compute a friendly type for this partition of the alloca. This
3144 // won't always succeed, in which case we fall back to a legal integer type
3145 // or an i8 array of an appropriate size.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003146 Type *SliceTy = 0;
Chandler Carruthf0546402013-07-18 07:15:00 +00003147 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003148 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3149 SliceTy = CommonUseTy;
3150 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003151 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003152 BeginOffset, SliceSize))
3153 SliceTy = TypePartitionTy;
3154 if ((!SliceTy || (SliceTy->isArrayTy() &&
3155 SliceTy->getArrayElementType()->isIntegerTy())) &&
3156 DL->isLegalInteger(SliceSize * 8))
3157 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3158 if (!SliceTy)
3159 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3160 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003161
3162 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003163 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003164
3165 bool IsIntegerPromotable =
3166 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003167 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003168
3169 // Check for the case where we're going to rewrite to a new alloca of the
3170 // exact same type as the original, and with the same access offsets. In that
3171 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003172 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003173 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003174 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003175 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003176 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003177 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003178 // FIXME: We should be able to bail at this point with "nothing changed".
3179 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003180 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003181 unsigned Alignment = AI.getAlignment();
3182 if (!Alignment) {
3183 // The minimum alignment which users can rely on when the explicit
3184 // alignment is omitted or zero is that required by the ABI for this
3185 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003186 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003187 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003188 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003189 // If we will get at least this much alignment from the type alone, leave
3190 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003191 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003192 Alignment = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003193 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3194 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003195 ++NumNewAllocas;
3196 }
3197
3198 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003199 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3200 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003201
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003202 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003203 // promoted allocas. We will reset it to this point if the alloca is not in
3204 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003205 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003206 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003207 SmallPtrSet<PHINode *, 8> PHIUsers;
3208 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003209
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003210 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3211 EndOffset, IsVectorPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003212 IsIntegerPromotable, PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003213 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003214 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3215 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003216 SUI != SUE; ++SUI) {
3217 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003218 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003219 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003220 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003221 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003222 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003223 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003224 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003225 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003226 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003227 }
3228
Chandler Carruth6c321c12013-07-19 10:57:36 +00003229 NumAllocaPartitionUses += NumUses;
3230 MaxUsesPerAllocaPartition =
3231 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003232
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003233 // Now that we've processed all the slices in the new partition, check if any
3234 // PHIs or Selects would block promotion.
3235 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3236 E = PHIUsers.end();
3237 I != E; ++I)
3238 if (!isSafePHIToSpeculate(**I, DL)) {
3239 Promotable = false;
3240 PHIUsers.clear();
3241 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003242 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003243 }
3244 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3245 E = SelectUsers.end();
3246 I != E; ++I)
3247 if (!isSafeSelectToSpeculate(**I, DL)) {
3248 Promotable = false;
3249 PHIUsers.clear();
3250 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003251 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003252 }
3253
3254 if (Promotable) {
3255 if (PHIUsers.empty() && SelectUsers.empty()) {
3256 // Promote the alloca.
3257 PromotableAllocas.push_back(NewAI);
3258 } else {
3259 // If we have either PHIs or Selects to speculate, add them to those
3260 // worklists and re-queue the new alloca so that we promote in on the
3261 // next iteration.
3262 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3263 E = PHIUsers.end();
3264 I != E; ++I)
3265 SpeculatablePHIs.insert(*I);
3266 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3267 E = SelectUsers.end();
3268 I != E; ++I)
3269 SpeculatableSelects.insert(*I);
3270 Worklist.insert(NewAI);
3271 }
3272 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003273 // If we can't promote the alloca, iterate on it to check for new
3274 // refinements exposed by splitting the current alloca. Don't iterate on an
3275 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003276 if (NewAI != &AI)
3277 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003278
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003279 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003280 while (PostPromotionWorklist.size() > PPWOldSize)
3281 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003282 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003283
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003284 return true;
3285}
3286
Chandler Carruthf0546402013-07-18 07:15:00 +00003287namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003288struct IsSliceEndLessOrEqualTo {
3289 uint64_t UpperBound;
Chandler Carruthf0546402013-07-18 07:15:00 +00003290
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003291 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
Chandler Carruthf0546402013-07-18 07:15:00 +00003292
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003293 bool operator()(const AllocaSlices::iterator &I) {
3294 return I->endOffset() <= UpperBound;
3295 }
3296};
Chandler Carruthf0546402013-07-18 07:15:00 +00003297}
3298
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003299static void
3300removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3301 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003302 if (Offset >= MaxSplitUseEndOffset) {
3303 SplitUses.clear();
3304 MaxSplitUseEndOffset = 0;
3305 return;
3306 }
3307
3308 size_t SplitUsesOldSize = SplitUses.size();
3309 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003310 IsSliceEndLessOrEqualTo(Offset)),
Chandler Carruthf0546402013-07-18 07:15:00 +00003311 SplitUses.end());
3312 if (SplitUsesOldSize == SplitUses.size())
3313 return;
3314
3315 // Recompute the max. While this is linear, so is remove_if.
3316 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003317 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003318 SUI = SplitUses.begin(),
3319 SUE = SplitUses.end();
3320 SUI != SUE; ++SUI)
3321 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3322}
3323
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003324/// \brief Walks the slices of an alloca and form partitions based on them,
3325/// rewriting each of their uses.
3326bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3327 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003328 return false;
3329
Chandler Carruth6c321c12013-07-19 10:57:36 +00003330 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003331 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003332 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003333 uint64_t MaxSplitUseEndOffset = 0;
3334
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003335 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003336
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003337 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3338 SI != SE; SI = SJ) {
3339 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003340
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003341 if (!SI->isSplittable()) {
3342 // When we're forming an unsplittable region, it must always start at the
3343 // first slice and will extend through its end.
3344 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003345
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003346 // Form a partition including all of the overlapping slices with this
3347 // unsplittable slice.
3348 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3349 if (!SJ->isSplittable())
3350 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3351 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003352 }
3353 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003354 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003355
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003356 // Collect all of the overlapping splittable slices.
3357 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3358 SJ->isSplittable()) {
3359 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3360 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003361 }
3362
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003363 // Back up MaxEndOffset and SJ if we ended the span early when
3364 // encountering an unsplittable slice.
3365 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3366 assert(!SJ->isSplittable());
3367 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003368 }
3369 }
3370
3371 // Check if we have managed to move the end offset forward yet. If so,
3372 // we'll have to rewrite uses and erase old split uses.
3373 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003374 // Rewrite a sequence of overlapping slices.
3375 Changed |=
3376 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003377 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003378
3379 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3380 }
3381
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003382 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003383 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003384 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3385 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3386 SplitUses.push_back(SK);
3387 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003388 }
3389
3390 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003391 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003392 break;
3393
3394 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003395 // the next slice.
3396 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3397 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003398 continue;
3399 }
3400
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003401 // Even if we have split slices, if the next slice is splittable and the
3402 // split slices reach it, we can simply set up the beginning offset of the
3403 // next iteration to bridge between them.
3404 if (SJ != SE && SJ->isSplittable() &&
3405 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003406 BeginOffset = MaxEndOffset;
3407 continue;
3408 }
3409
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003410 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3411 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003412 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003413 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003414
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003415 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3416 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003417 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003418
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003419 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003420 break; // Skip the rest, we don't need to do any cleanup.
3421
3422 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3423 PostSplitEndOffset);
3424
3425 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003426 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003427 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003428
Chandler Carruth6c321c12013-07-19 10:57:36 +00003429 NumAllocaPartitions += NumPartitions;
3430 MaxPartitionsPerAlloca =
3431 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003432
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003433 return Changed;
3434}
3435
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003436/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3437void SROA::clobberUse(Use &U) {
3438 Value *OldV = U;
3439 // Replace the use with an undef value.
3440 U = UndefValue::get(OldV->getType());
3441
3442 // Check for this making an instruction dead. We have to garbage collect
3443 // all the dead instructions to ensure the uses of any alloca end up being
3444 // minimal.
3445 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3446 if (isInstructionTriviallyDead(OldI)) {
3447 DeadInsts.insert(OldI);
3448 }
3449}
3450
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003451/// \brief Analyze an alloca for SROA.
3452///
3453/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003454/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003455/// rewritten as needed.
3456bool SROA::runOnAlloca(AllocaInst &AI) {
3457 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3458 ++NumAllocasAnalyzed;
3459
3460 // Special case dead allocas, as they're trivial.
3461 if (AI.use_empty()) {
3462 AI.eraseFromParent();
3463 return true;
3464 }
3465
3466 // Skip alloca forms that this analysis can't handle.
3467 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003468 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003469 return false;
3470
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003471 bool Changed = false;
3472
3473 // First, split any FCA loads and stores touching this alloca to promote
3474 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003475 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003476 Changed |= AggRewriter.rewrite(AI);
3477
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003478 // Build the slices using a recursive instruction-visiting builder.
3479 AllocaSlices S(*DL, AI);
3480 DEBUG(S.print(dbgs()));
3481 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003482 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003483
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003484 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003485 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3486 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003487 DI != DE; ++DI) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003488 // Free up everything used by this instruction.
3489 for (User::op_iterator DOI = (*DI)->op_begin(), DOE = (*DI)->op_end();
3490 DOI != DOE; ++DOI)
3491 clobberUse(*DOI);
3492
3493 // Now replace the uses of this instruction.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003494 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003495
3496 // And mark it for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003497 DeadInsts.insert(*DI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003498 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003499 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003500 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3501 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003502 DO != DE; ++DO) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003503 clobberUse(**DO);
3504 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003505 }
3506
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003507 // No slices to split. Leave the dead alloca for a later pass to clean up.
3508 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003509 return Changed;
3510
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003511 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003512
3513 DEBUG(dbgs() << " Speculating PHIs\n");
3514 while (!SpeculatablePHIs.empty())
3515 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3516
3517 DEBUG(dbgs() << " Speculating Selects\n");
3518 while (!SpeculatableSelects.empty())
3519 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3520
3521 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003522}
3523
Chandler Carruth19450da2012-09-14 10:26:38 +00003524/// \brief Delete the dead instructions accumulated in this run.
3525///
3526/// Recursively deletes the dead instructions we've accumulated. This is done
3527/// at the very end to maximize locality of the recursive delete and to
3528/// minimize the problems of invalidated instruction pointers as such pointers
3529/// are used heavily in the intermediate stages of the algorithm.
3530///
3531/// We also record the alloca instructions deleted here so that they aren't
3532/// subsequently handed to mem2reg to promote.
3533void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003534 while (!DeadInsts.empty()) {
3535 Instruction *I = DeadInsts.pop_back_val();
3536 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3537
Chandler Carruth58d05562012-10-25 04:37:07 +00003538 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3539
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003540 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3541 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3542 // Zero out the operand and see if it becomes trivially dead.
3543 *OI = 0;
3544 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003545 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003546 }
3547
3548 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3549 DeletedAllocas.insert(AI);
3550
3551 ++NumDeleted;
3552 I->eraseFromParent();
3553 }
3554}
3555
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003556static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003557 SmallVectorImpl<Instruction *> &Worklist,
3558 SmallPtrSet<Instruction *, 8> &Visited) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003559 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3560 ++UI)
Chandler Carruth45b136f2013-08-11 01:03:18 +00003561 if (Visited.insert(cast<Instruction>(*UI)))
3562 Worklist.push_back(cast<Instruction>(*UI));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003563}
3564
Chandler Carruth70b44c52012-09-15 11:43:14 +00003565/// \brief Promote the allocas, using the best available technique.
3566///
3567/// This attempts to promote whatever allocas have been identified as viable in
3568/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3569/// If there is a domtree available, we attempt to promote using the full power
3570/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3571/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003572/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003573bool SROA::promoteAllocas(Function &F) {
3574 if (PromotableAllocas.empty())
3575 return false;
3576
3577 NumPromoted += PromotableAllocas.size();
3578
3579 if (DT && !ForceSSAUpdater) {
3580 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Nick Lewyckyc7776f72013-08-13 22:51:58 +00003581 PromoteMemToReg(PromotableAllocas, *DT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003582 PromotableAllocas.clear();
3583 return true;
3584 }
3585
3586 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3587 SSAUpdater SSA;
3588 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003589 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003590
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003591 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003592 SmallVector<Instruction *, 8> Worklist;
3593 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003594 SmallVector<Instruction *, 32> DeadInsts;
3595
Chandler Carruth70b44c52012-09-15 11:43:14 +00003596 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3597 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003598 Insts.clear();
3599 Worklist.clear();
3600 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003601
Chandler Carruth45b136f2013-08-11 01:03:18 +00003602 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003603
Chandler Carruth45b136f2013-08-11 01:03:18 +00003604 while (!Worklist.empty()) {
3605 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003606
Chandler Carruth70b44c52012-09-15 11:43:14 +00003607 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3608 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3609 // leading to them) here. Eventually it should use them to optimize the
3610 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003611 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003612 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3613 II->getIntrinsicID() == Intrinsic::lifetime_end);
3614 II->eraseFromParent();
3615 continue;
3616 }
3617
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003618 // Push the loads and stores we find onto the list. SROA will already
3619 // have validated that all loads and stores are viable candidates for
3620 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003621 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003622 assert(LI->getType() == AI->getAllocatedType());
3623 Insts.push_back(LI);
3624 continue;
3625 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003626 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003627 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3628 Insts.push_back(SI);
3629 continue;
3630 }
3631
3632 // For everything else, we know that only no-op bitcasts and GEPs will
3633 // make it this far, just recurse through them and recall them for later
3634 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003635 DeadInsts.push_back(I);
3636 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003637 }
3638 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003639 while (!DeadInsts.empty())
3640 DeadInsts.pop_back_val()->eraseFromParent();
3641 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003642 }
3643
3644 PromotableAllocas.clear();
3645 return true;
3646}
3647
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003648namespace {
3649 /// \brief A predicate to test whether an alloca belongs to a set.
3650 class IsAllocaInSet {
3651 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3652 const SetType &Set;
3653
3654 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003655 typedef AllocaInst *argument_type;
3656
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003657 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003658 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003659 };
3660}
3661
3662bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003663 if (skipOptnoneFunction(F))
3664 return false;
3665
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003666 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3667 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003668 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3669 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003670 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3671 return false;
3672 }
Rafael Espindola93512512014-02-25 17:30:31 +00003673 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003674 DominatorTreeWrapperPass *DTWP =
3675 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3676 DT = DTWP ? &DTWP->getDomTree() : 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003677
3678 BasicBlock &EntryBB = F.getEntryBlock();
3679 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3680 I != E; ++I)
3681 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3682 Worklist.insert(AI);
3683
3684 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003685 // A set of deleted alloca instruction pointers which should be removed from
3686 // the list of promotable allocas.
3687 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3688
Chandler Carruthac8317f2012-10-04 12:33:50 +00003689 do {
3690 while (!Worklist.empty()) {
3691 Changed |= runOnAlloca(*Worklist.pop_back_val());
3692 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003693
Chandler Carruthac8317f2012-10-04 12:33:50 +00003694 // Remove the deleted allocas from various lists so that we don't try to
3695 // continue processing them.
3696 if (!DeletedAllocas.empty()) {
3697 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3698 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3699 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3700 PromotableAllocas.end(),
3701 IsAllocaInSet(DeletedAllocas)),
3702 PromotableAllocas.end());
3703 DeletedAllocas.clear();
3704 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003705 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003706
Chandler Carruthac8317f2012-10-04 12:33:50 +00003707 Changed |= promoteAllocas(F);
3708
3709 Worklist = PostPromotionWorklist;
3710 PostPromotionWorklist.clear();
3711 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003712
3713 return Changed;
3714}
3715
3716void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003717 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003718 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003719 AU.setPreservesCFG();
3720}