blob: ada44cd5d28e4352a7cb4c73fb21ad5523eb700a [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth1b398ae2012-09-14 09:22:59 +000026#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Hal Finkel60db0582014-09-07 18:57:58 +000031#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000036#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Chandler 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"
Chandler Carruth7da14f12014-03-06 03:23:41 +000043#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Operator.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
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "sroa"
68
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000070STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000071STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000074STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000077STATISTIC(NumDeleted, "Number of instructions deleted");
78STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079
Chandler Carruth70b44c52012-09-15 11:43:14 +000080/// Hidden option to force the pass to not use DomTree and mem2reg, instead
81/// forming SSA values through the SSAUpdater infrastructure.
82static cl::opt<bool>
83ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
84
Chandler Carruth83cee772014-02-25 03:59:29 +000085/// Hidden option to enable randomly shuffling the slices to help uncover
86/// instability in their order.
87static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88 cl::init(false), cl::Hidden);
89
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000090/// Hidden option to experiment with completely strict handling of inbounds
91/// GEPs.
92static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
93 cl::init(false), cl::Hidden);
94
Chandler Carruth1b398ae2012-09-14 09:22:59 +000095namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000096/// \brief A custom IRBuilder inserter which prefixes all names if they are
97/// preserved.
98template <bool preserveNames = true>
99class IRBuilderPrefixedInserter :
100 public IRBuilderDefaultInserter<preserveNames> {
101 std::string Prefix;
102
103public:
104 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
105
106protected:
107 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108 BasicBlock::iterator InsertPt) const {
109 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
111 }
112};
113
114// Specialization for not preserving the name is trivial.
115template <>
116class IRBuilderPrefixedInserter<false> :
117 public IRBuilderDefaultInserter<false> {
118public:
119 void SetNamePrefix(const Twine &P) {}
120};
121
Chandler Carruthd177f862013-03-20 07:30:36 +0000122/// \brief Provide a typedef for IRBuilder that drops names in release builds.
123#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000124typedef llvm::IRBuilder<true, ConstantFolder,
125 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000126#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000127typedef llvm::IRBuilder<false, ConstantFolder,
128 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000129#endif
130}
131
132namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000133/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000134///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135/// This structure represents a slice of an alloca used by some instruction. It
136/// stores both the begin and end offsets of this use, a pointer to the use
137/// itself, and a flag indicating whether we can classify the use as splittable
138/// or not when forming partitions of the alloca.
139class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000140 /// \brief The beginning offset of the range.
141 uint64_t BeginOffset;
142
143 /// \brief The ending offset, not included in the range.
144 uint64_t EndOffset;
145
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000147 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000148 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000149
150public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000151 Slice() : BeginOffset(), EndOffset() {}
152 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000153 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000155
156 uint64_t beginOffset() const { return BeginOffset; }
157 uint64_t endOffset() const { return EndOffset; }
158
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000159 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000161
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000162 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000163
Craig Topperf40110f2014-04-25 05:29:35 +0000164 bool isDead() const { return getUse() == nullptr; }
165 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166
167 /// \brief Support for ordering ranges.
168 ///
169 /// This provides an ordering over ranges such that start offsets are
170 /// always increasing, and within equal start offsets, the end offsets are
171 /// decreasing. Thus the spanning range comes first in a cluster with the
172 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000174 if (beginOffset() < RHS.beginOffset()) return true;
175 if (beginOffset() > RHS.beginOffset()) return false;
176 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
177 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000178 return false;
179 }
180
181 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000183 uint64_t RHSOffset) {
184 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000187 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000188 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000190
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000191 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000192 return isSplittable() == RHS.isSplittable() &&
193 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000194 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000195 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000196};
Chandler Carruthf0546402013-07-18 07:15:00 +0000197} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000198
199namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000200template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000201template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000202 static const bool value = true;
203};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000204}
205
206namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000207/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000208///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000209/// This class represents the slices of an alloca which are formed by its
210/// various uses. If a pointer escapes, we can't fully build a representation
211/// for the slices used and we reflect that in this structure. The uses are
212/// stored, sorted by increasing beginning offset and with unsplittable slices
213/// starting at a particular offset before splittable slices.
214class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000216 /// \brief Construct the slices of a particular alloca.
217 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000218
219 /// \brief Test whether a pointer to the allocation escapes our analysis.
220 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000221 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000222 /// ignored.
223 bool isEscaped() const { return PointerEscapingInstr; }
224
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000225 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000226 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000227 typedef SmallVectorImpl<Slice>::iterator iterator;
228 iterator begin() { return Slices.begin(); }
229 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000230
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000231 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
232 const_iterator begin() const { return Slices.begin(); }
233 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000234 /// @}
235
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000236 /// \brief Allow iterating the dead users for this alloca.
237 ///
238 /// These are instructions which will never actually use the alloca as they
239 /// are outside the allocated range. They are safe to replace with undef and
240 /// delete.
241 /// @{
242 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
243 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
244 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
245 /// @}
246
Chandler Carruth93a21e72012-09-14 10:18:49 +0000247 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000248 ///
249 /// These are operands which have cannot actually be used to refer to the
250 /// alloca as they are outside its range and the user doesn't correct for
251 /// that. These mostly consist of PHI node inputs and the like which we just
252 /// need to replace with undef.
253 /// @{
254 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
255 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
256 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
257 /// @}
258
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000259#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000260 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000261 void printSlice(raw_ostream &OS, const_iterator I,
262 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000263 void printUse(raw_ostream &OS, const_iterator I,
264 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000265 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000266 void dump(const_iterator I) const;
267 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000268#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000269
270private:
271 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000272 class SliceBuilder;
273 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000274
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000275#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276 /// \brief Handle to alloca instruction to simplify method interfaces.
277 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000278#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000279
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000280 /// \brief The instruction responsible for this alloca not having a known set
281 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000282 ///
283 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000284 /// store a pointer to that here and abort trying to form slices of the
285 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000286 Instruction *PointerEscapingInstr;
287
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000288 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000289 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000290 /// We store a vector of the slices formed by uses of the alloca here. This
291 /// vector is sorted by increasing begin offset, and then the unsplittable
292 /// slices before the splittable ones. See the Slice inner class for more
293 /// details.
294 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296 /// \brief Instructions which will become dead if we rewrite the alloca.
297 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000298 /// Note that these are not separated by slice. This is because we expect an
299 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
300 /// all these instructions can simply be removed and replaced with undef as
301 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000302 SmallVector<Instruction *, 8> DeadUsers;
303
304 /// \brief Operands which will become dead if we rewrite the alloca.
305 ///
306 /// These are operands that in their particular use can be replaced with
307 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
308 /// to PHI nodes and the like. They aren't entirely dead (there might be
309 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
310 /// want to swap this particular input for undef to simplify the use lists of
311 /// the alloca.
312 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000313};
314}
315
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000316static Value *foldSelectInst(SelectInst &SI) {
317 // If the condition being selected on is a constant or the same value is
318 // being selected between, fold the select. Yes this does (rarely) happen
319 // early on.
320 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
321 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000322 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000323 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000324
Craig Topperf40110f2014-04-25 05:29:35 +0000325 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000326}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000327
Jingyue Wuec33fa92014-08-22 22:45:57 +0000328/// \brief A helper that folds a PHI node or a select.
329static Value *foldPHINodeOrSelectInst(Instruction &I) {
330 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
331 // If PN merges together the same value, return that value.
332 return PN->hasConstantValue();
333 }
334 return foldSelectInst(cast<SelectInst>(I));
335}
336
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000337/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000338///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000339/// This class builds a set of alloca slices by recursively visiting the uses
340/// of an alloca and making a slice for each load and store at each offset.
341class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
342 friend class PtrUseVisitor<SliceBuilder>;
343 friend class InstVisitor<SliceBuilder>;
344 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000345
346 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000347 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000348
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000349 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000350 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
351
352 /// \brief Set to de-duplicate dead instructions found in the use walk.
353 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000354
355public:
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000356 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000357 : PtrUseVisitor<SliceBuilder>(DL),
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000358 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000359
360private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000361 void markAsDead(Instruction &I) {
362 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000363 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000364 }
365
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000366 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000367 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000368 // Completely skip uses which have a zero size or start either before or
369 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000370 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000371 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000372 << " which has zero size or starts outside of the "
373 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000374 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000375 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000376 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000377 }
378
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000379 uint64_t BeginOffset = Offset.getZExtValue();
380 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000381
382 // Clamp the end offset to the end of the allocation. Note that this is
383 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000384 // This may appear superficially to be something we could ignore entirely,
385 // but that is not so! There may be widened loads or PHI-node uses where
386 // some instructions are dead but not others. We can't completely ignore
387 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000388 assert(AllocSize >= BeginOffset); // Established above.
389 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000390 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
391 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000392 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000393 << " use: " << I << "\n");
394 EndOffset = AllocSize;
395 }
396
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000397 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000398 }
399
400 void visitBitCastInst(BitCastInst &BC) {
401 if (BC.use_empty())
402 return markAsDead(BC);
403
404 return Base::visitBitCastInst(BC);
405 }
406
407 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
408 if (GEPI.use_empty())
409 return markAsDead(GEPI);
410
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000411 if (SROAStrictInbounds && GEPI.isInBounds()) {
412 // FIXME: This is a manually un-factored variant of the basic code inside
413 // of GEPs with checking of the inbounds invariant specified in the
414 // langref in a very strict sense. If we ever want to enable
415 // SROAStrictInbounds, this code should be factored cleanly into
416 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
417 // by writing out the code here where we have tho underlying allocation
418 // size readily available.
419 APInt GEPOffset = Offset;
420 for (gep_type_iterator GTI = gep_type_begin(GEPI),
421 GTE = gep_type_end(GEPI);
422 GTI != GTE; ++GTI) {
423 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
424 if (!OpC)
425 break;
426
427 // Handle a struct index, which adds its field offset to the pointer.
428 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
429 unsigned ElementIdx = OpC->getZExtValue();
430 const StructLayout *SL = DL.getStructLayout(STy);
431 GEPOffset +=
432 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
433 } else {
434 // For array or vector indices, scale the index by the size of the type.
435 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
436 GEPOffset += Index * APInt(Offset.getBitWidth(),
437 DL.getTypeAllocSize(GTI.getIndexedType()));
438 }
439
440 // If this index has computed an intermediate pointer which is not
441 // inbounds, then the result of the GEP is a poison value and we can
442 // delete it and all uses.
443 if (GEPOffset.ugt(AllocSize))
444 return markAsDead(GEPI);
445 }
446 }
447
Chandler Carruthf0546402013-07-18 07:15:00 +0000448 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000449 }
450
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000451 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000452 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000453 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000454 // and cover the entire alloca. This prevents us from splitting over
455 // eagerly.
456 // FIXME: In the great blue eventually, we should eagerly split all integer
457 // loads and stores, and then have a separate step that merges adjacent
458 // alloca partitions into a single partition suitable for integer widening.
459 // Or we should skip the merge step and rely on GVN and other passes to
460 // merge adjacent loads and stores that survive mem2reg.
461 bool IsSplittable =
462 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000463
464 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000465 }
466
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000467 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000468 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
469 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000470
471 if (!IsOffsetKnown)
472 return PI.setAborted(&LI);
473
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000474 uint64_t Size = DL.getTypeStoreSize(LI.getType());
475 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000476 }
477
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000478 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000479 Value *ValOp = SI.getValueOperand();
480 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000481 return PI.setEscapedAndAborted(&SI);
482 if (!IsOffsetKnown)
483 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000484
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000485 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
486
487 // If this memory access can be shown to *statically* extend outside the
488 // bounds of of the allocation, it's behavior is undefined, so simply
489 // ignore it. Note that this is more strict than the generic clamping
490 // behavior of insertUse. We also try to handle cases which might run the
491 // risk of overflow.
492 // FIXME: We should instead consider the pointer to have escaped if this
493 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000494 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000495 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
496 << " which extends past the end of the " << AllocSize
497 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000498 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000499 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000500 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000501 }
502
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000503 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
504 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000505 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000506 }
507
508
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000509 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000510 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000511 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000512 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000513 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000514 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000515 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000516
517 if (!IsOffsetKnown)
518 return PI.setAborted(&II);
519
520 insertUse(II, Offset,
521 Length ? Length->getLimitedValue()
522 : AllocSize - Offset.getLimitedValue(),
523 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000524 }
525
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000526 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000527 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000528 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000529 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000530 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000531
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000532 // Because we can visit these intrinsics twice, also check to see if the
533 // first time marked this instruction as dead. If so, skip it.
534 if (VisitedDeadInsts.count(&II))
535 return;
536
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000537 if (!IsOffsetKnown)
538 return PI.setAborted(&II);
539
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000540 // This side of the transfer is completely out-of-bounds, and so we can
541 // nuke the entire transfer. However, we also need to nuke the other side
542 // if already added to our partitions.
543 // FIXME: Yet another place we really should bypass this when
544 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000545 if (Offset.uge(AllocSize)) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000546 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
547 if (MTPI != MemTransferSliceMap.end())
548 S.Slices[MTPI->second].kill();
549 return markAsDead(II);
550 }
551
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000552 uint64_t RawOffset = Offset.getLimitedValue();
553 uint64_t Size = Length ? Length->getLimitedValue()
554 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000555
Chandler Carruthf0546402013-07-18 07:15:00 +0000556 // Check for the special case where the same exact value is used for both
557 // source and dest.
558 if (*U == II.getRawDest() && *U == II.getRawSource()) {
559 // For non-volatile transfers this is a no-op.
560 if (!II.isVolatile())
561 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000562
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000563 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000564 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000565
Chandler Carruthf0546402013-07-18 07:15:00 +0000566 // If we have seen both source and destination for a mem transfer, then
567 // they both point to the same alloca.
568 bool Inserted;
569 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000570 std::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000571 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000572 unsigned PrevIdx = MTPI->second;
573 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000574 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000575
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000576 // Check if the begin offsets match and this is a non-volatile transfer.
577 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000578 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
579 PrevP.kill();
580 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000581 }
582
583 // Otherwise we have an offset transfer within the same alloca. We can't
584 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000585 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000586 }
587
Chandler Carruthe3899f22013-07-15 17:36:21 +0000588 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000589 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000590
Chandler Carruthf0546402013-07-18 07:15:00 +0000591 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000592 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
593 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000594 }
595
596 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000597 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000598 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000599 void visitIntrinsicInst(IntrinsicInst &II) {
600 if (!IsOffsetKnown)
601 return PI.setAborted(&II);
602
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
604 II.getIntrinsicID() == Intrinsic::lifetime_end) {
605 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000606 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
607 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000608 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000609 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000610 }
611
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000612 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000613 }
614
615 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
616 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000617 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000618 // are considered unsplittable and the size is the maximum loaded or stored
619 // size.
620 SmallPtrSet<Instruction *, 4> Visited;
621 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
622 Visited.insert(Root);
623 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000624 // If there are no loads or stores, the access is dead. We mark that as
625 // a size zero access.
626 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000627 do {
628 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000629 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000630
631 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000632 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000633 continue;
634 }
635 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
636 Value *Op = SI->getOperand(0);
637 if (Op == UsedI)
638 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000639 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000640 continue;
641 }
642
643 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
644 if (!GEP->hasAllZeroIndices())
645 return GEP;
646 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
647 !isa<SelectInst>(I)) {
648 return I;
649 }
650
Chandler Carruthcdf47882014-03-09 03:16:01 +0000651 for (User *U : I->users())
652 if (Visited.insert(cast<Instruction>(U)))
653 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000654 } while (!Uses.empty());
655
Craig Topperf40110f2014-04-25 05:29:35 +0000656 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000657 }
658
Jingyue Wuec33fa92014-08-22 22:45:57 +0000659 void visitPHINodeOrSelectInst(Instruction &I) {
660 assert(isa<PHINode>(I) || isa<SelectInst>(I));
661 if (I.use_empty())
662 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000663
Jingyue Wuec33fa92014-08-22 22:45:57 +0000664 // TODO: We could use SimplifyInstruction here to fold PHINodes and
665 // SelectInsts. However, doing so requires to change the current
666 // dead-operand-tracking mechanism. For instance, suppose neither loading
667 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
668 // trap either. However, if we simply replace %U with undef using the
669 // current dead-operand-tracking mechanism, "load (select undef, undef,
670 // %other)" may trap because the select may return the first operand
671 // "undef".
672 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000673 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000674 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000675 // through the PHI/select as if we had RAUW'ed it.
676 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000677 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000678 // Otherwise the operand to the PHI/select is dead, and we can replace
679 // it with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000680 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000681
682 return;
683 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000684
Chandler Carruthf0546402013-07-18 07:15:00 +0000685 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000686 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000687
Chandler Carruthf0546402013-07-18 07:15:00 +0000688 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000689 uint64_t &Size = PHIOrSelectSizes[&I];
690 if (!Size) {
691 // This is a new PHI/Select, check for an unsafe use of it.
692 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000693 return PI.setAborted(UnsafeI);
694 }
695
696 // For PHI and select operands outside the alloca, we can't nuke the entire
697 // phi or select -- the other side might still be relevant, so we special
698 // case them here and use a separate structure to track the operands
699 // themselves which should be replaced with undef.
700 // FIXME: This should instead be escaped in the event we're instrumenting
701 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000702 if (Offset.uge(AllocSize)) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000703 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000704 return;
705 }
706
Jingyue Wuec33fa92014-08-22 22:45:57 +0000707 insertUse(I, Offset, Size);
708 }
709
710 void visitPHINode(PHINode &PN) {
711 visitPHINodeOrSelectInst(PN);
712 }
713
714 void visitSelectInst(SelectInst &SI) {
715 visitPHINodeOrSelectInst(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000716 }
717
Chandler Carruthf0546402013-07-18 07:15:00 +0000718 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000719 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000720 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000721 }
722};
723
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000724AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000725 :
726#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
727 AI(AI),
728#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000729 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000730 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000731 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000732 if (PtrI.isEscaped() || PtrI.isAborted()) {
733 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000734 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000735 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
736 : PtrI.getAbortingInst();
737 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000738 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000739 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000740
Benjamin Kramer08e50702013-07-20 08:38:34 +0000741 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
742 std::mem_fun_ref(&Slice::isDead)),
743 Slices.end());
744
Chandler Carruth83cee772014-02-25 03:59:29 +0000745#if __cplusplus >= 201103L && !defined(NDEBUG)
746 if (SROARandomShuffleSlices) {
747 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
748 std::shuffle(Slices.begin(), Slices.end(), MT);
749 }
750#endif
751
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000752 // Sort the uses. This arranges for the offsets to be in ascending order,
753 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000754 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000755}
756
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000757#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
758
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000759void AllocaSlices::print(raw_ostream &OS, const_iterator I,
760 StringRef Indent) const {
761 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000762 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000763}
764
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000765void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
766 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000767 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000768 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000769 << (I->isSplittable() ? " (splittable)" : "") << "\n";
770}
771
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000772void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
773 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000774 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000775}
776
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000777void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000778 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000779 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000780 << " A pointer to this alloca escaped by:\n"
781 << " " << *PointerEscapingInstr << "\n";
782 return;
783 }
784
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000785 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000786 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000788}
789
Alp Tokerf929e092014-01-04 22:47:48 +0000790LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
791 print(dbgs(), I);
792}
793LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000794
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000795#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
796
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000797namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000798/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
799///
800/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
801/// the loads and stores of an alloca instruction, as well as updating its
802/// debug information. This is used when a domtree is unavailable and thus
803/// mem2reg in its full form can't be used to handle promotion of allocas to
804/// scalar values.
805class AllocaPromoter : public LoadAndStorePromoter {
806 AllocaInst &AI;
807 DIBuilder &DIB;
808
809 SmallVector<DbgDeclareInst *, 4> DDIs;
810 SmallVector<DbgValueInst *, 4> DVIs;
811
812public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000813 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000814 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000815 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000816
817 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000818 // Retain the debug information attached to the alloca for use when
819 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000820 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000821 for (User *U : DebugNode->users())
822 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000823 DDIs.push_back(DDI);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000824 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000825 DVIs.push_back(DVI);
826 }
827
828 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000829
830 // While we have the debug information, clear it off of the alloca. The
831 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000832 while (!DDIs.empty())
833 DDIs.pop_back_val()->eraseFromParent();
834 while (!DVIs.empty())
835 DVIs.pop_back_val()->eraseFromParent();
836 }
837
Craig Topper3e4c6972014-03-05 09:10:37 +0000838 bool isInstInList(Instruction *I,
839 const SmallVectorImpl<Instruction*> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000840 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000841 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000842 Ptr = LI->getOperand(0);
843 else
844 Ptr = cast<StoreInst>(I)->getPointerOperand();
845
846 // Only used to detect cycles, which will be rare and quickly found as
847 // we're walking up a chain of defs rather than down through uses.
848 SmallPtrSet<Value *, 4> Visited;
849
850 do {
851 if (Ptr == &AI)
852 return true;
853
854 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
855 Ptr = BCI->getOperand(0);
856 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
857 Ptr = GEPI->getPointerOperand();
858 else
859 return false;
860
861 } while (Visited.insert(Ptr));
862
863 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000864 }
865
Craig Topper3e4c6972014-03-05 09:10:37 +0000866 void updateDebugInfo(Instruction *Inst) const override {
Craig Topper31ee5862013-07-03 15:07:05 +0000867 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000868 E = DDIs.end(); I != E; ++I) {
869 DbgDeclareInst *DDI = *I;
870 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
871 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
872 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
873 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
874 }
Craig Topper31ee5862013-07-03 15:07:05 +0000875 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000876 E = DVIs.end(); I != E; ++I) {
877 DbgValueInst *DVI = *I;
Craig Topperf40110f2014-04-25 05:29:35 +0000878 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000879 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
880 // If an argument is zero extended then use argument directly. The ZExt
881 // may be zapped by an optimization pass in future.
882 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
883 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000884 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000885 Arg = dyn_cast<Argument>(SExt->getOperand(0));
886 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000887 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000888 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000889 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000890 } else {
891 continue;
892 }
893 Instruction *DbgVal =
894 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
895 Inst);
896 DbgVal->setDebugLoc(DVI->getDebugLoc());
897 }
898 }
899};
900} // end anon namespace
901
902
903namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000904/// \brief An optimization pass providing Scalar Replacement of Aggregates.
905///
906/// This pass takes allocations which can be completely analyzed (that is, they
907/// don't escape) and tries to turn them into scalar SSA values. There are
908/// a few steps to this process.
909///
910/// 1) It takes allocations of aggregates and analyzes the ways in which they
911/// are used to try to split them into smaller allocations, ideally of
912/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000913/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000914/// 2) It will transform accesses into forms which are suitable for SSA value
915/// promotion. This can be replacing a memset with a scalar store of an
916/// integer value, or it can involve speculating operations on a PHI or
917/// select to be a PHI or select of the results.
918/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
919/// onto insert and extract operations on a vector value, and convert them to
920/// this form. By doing so, it will enable promotion of vector aggregates to
921/// SSA vector values.
922class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000923 const bool RequiresDomTree;
924
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000925 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000926 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000927 DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +0000928 AssumptionTracker *AT;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000929
930 /// \brief Worklist of alloca instructions to simplify.
931 ///
932 /// Each alloca in the function is added to this. Each new alloca formed gets
933 /// added to it as well to recursively simplify unless that alloca can be
934 /// directly promoted. Finally, each time we rewrite a use of an alloca other
935 /// the one being actively rewritten, we add it back onto the list if not
936 /// already present to ensure it is re-visited.
937 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
938
939 /// \brief A collection of instructions to delete.
940 /// We try to batch deletions to simplify code and make things a bit more
941 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000942 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000943
Chandler Carruthac8317f2012-10-04 12:33:50 +0000944 /// \brief Post-promotion worklist.
945 ///
946 /// Sometimes we discover an alloca which has a high probability of becoming
947 /// viable for SROA after a round of promotion takes place. In those cases,
948 /// the alloca is enqueued here for re-processing.
949 ///
950 /// Note that we have to be very careful to clear allocas out of this list in
951 /// the event they are deleted.
952 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
953
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000954 /// \brief A collection of alloca instructions we can directly promote.
955 std::vector<AllocaInst *> PromotableAllocas;
956
Chandler Carruthf0546402013-07-18 07:15:00 +0000957 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
958 ///
959 /// All of these PHIs have been checked for the safety of speculation and by
960 /// being speculated will allow promoting allocas currently in the promotable
961 /// queue.
962 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
963
964 /// \brief A worklist of select instructions to speculate prior to promoting
965 /// allocas.
966 ///
967 /// All of these select instructions have been checked for the safety of
968 /// speculation and by being speculated will allow promoting allocas
969 /// currently in the promotable queue.
970 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
971
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000972public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000973 SROA(bool RequiresDomTree = true)
974 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Craig Topperf40110f2014-04-25 05:29:35 +0000975 C(nullptr), DL(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000976 initializeSROAPass(*PassRegistry::getPassRegistry());
977 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000978 bool runOnFunction(Function &F) override;
979 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000980
Craig Topper3e4c6972014-03-05 09:10:37 +0000981 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000982 static char ID;
983
984private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000985 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000986 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000987
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000988 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
989 AllocaSlices::iterator B, AllocaSlices::iterator E,
990 int64_t BeginOffset, int64_t EndOffset,
991 ArrayRef<AllocaSlices::iterator> SplitUses);
992 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000993 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000994 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +0000995 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000996 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000997};
998}
999
1000char SROA::ID = 0;
1001
Chandler Carruth70b44c52012-09-15 11:43:14 +00001002FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1003 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001004}
1005
1006INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1007 false, false)
Hal Finkel60db0582014-09-07 18:57:58 +00001008INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chandler Carruth73523022014-01-13 13:07:17 +00001009INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001010INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1011 false, false)
1012
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001013/// Walk the range of a partitioning looking for a common type to cover this
1014/// sequence of slices.
1015static Type *findCommonType(AllocaSlices::const_iterator B,
1016 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001017 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001018 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001019 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001020 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001021
1022 // Note that we need to look at *every* alloca slice's Use to ensure we
1023 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001024 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001025 Use *U = I->getUse();
1026 if (isa<IntrinsicInst>(*U->getUser()))
1027 continue;
1028 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1029 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001030
Craig Topperf40110f2014-04-25 05:29:35 +00001031 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001032 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001033 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001034 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001035 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001036 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001037
Chandler Carruth4de31542014-01-21 23:16:05 +00001038 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001039 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001040 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001041 // entity causing the split. Also skip if the type is not a byte width
1042 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001043 if (UserITy->getBitWidth() % 8 != 0 ||
1044 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001045 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001046
Chandler Carruth4de31542014-01-21 23:16:05 +00001047 // Track the largest bitwidth integer type used in this way in case there
1048 // is no common type.
1049 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1050 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001051 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001052
1053 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1054 // depend on types skipped above.
1055 if (!UserTy || (Ty && Ty != UserTy))
1056 TyIsCommon = false; // Give up on anything but an iN type.
1057 else
1058 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001059 }
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,
Craig Topperf40110f2014-04-25 05:29:35 +00001083 const DataLayout *DL = nullptr) {
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;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001091 for (User *U : PN.users()) {
1092 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001093 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001094 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001095
Chandler Carruthf0546402013-07-18 07:15:00 +00001096 // For now we only allow loads in the same block as the PHI. This is
1097 // a common case that happens when instcombine merges two loads through
1098 // a PHI.
1099 if (LI->getParent() != BB)
1100 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001101
Chandler Carruthf0546402013-07-18 07:15:00 +00001102 // Ensure that there are no instructions between the PHI and the load that
1103 // could store.
1104 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1105 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001106 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001107
Chandler Carruthf0546402013-07-18 07:15:00 +00001108 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1109 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001110 }
1111
Chandler Carruthf0546402013-07-18 07:15:00 +00001112 if (!HaveLoad)
1113 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001114
Chandler Carruthf0546402013-07-18 07:15:00 +00001115 // We can only transform this if it is safe to push the loads into the
1116 // predecessor blocks. The only thing to watch out for is that we can't put
1117 // a possibly trapping load in the predecessor if it is a critical edge.
1118 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1119 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1120 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001121
Chandler Carruthf0546402013-07-18 07:15:00 +00001122 // If the value is produced by the terminator of the predecessor (an
1123 // invoke) or it has side-effects, there is no valid place to put a load
1124 // in the predecessor.
1125 if (TI == InVal || TI->mayHaveSideEffects())
1126 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001127
Chandler Carruthf0546402013-07-18 07:15:00 +00001128 // If the predecessor has a single successor, then the edge isn't
1129 // critical.
1130 if (TI->getNumSuccessors() == 1)
1131 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001132
Chandler Carruthf0546402013-07-18 07:15:00 +00001133 // If this pointer is always safe to load, or if we can prove that there
1134 // is already a load in the block, then we can move the load to the pred
1135 // block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001136 if (InVal->isDereferenceablePointer(DL) ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001137 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001138 continue;
1139
1140 return false;
1141 }
1142
1143 return true;
1144}
1145
1146static void speculatePHINodeLoads(PHINode &PN) {
1147 DEBUG(dbgs() << " original: " << PN << "\n");
1148
1149 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1150 IRBuilderTy PHIBuilder(&PN);
1151 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1152 PN.getName() + ".sroa.speculated");
1153
Hal Finkelcc39b672014-07-24 12:16:19 +00001154 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001155 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001156 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001157
1158 AAMDNodes AATags;
1159 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001160 unsigned Align = SomeLoad->getAlignment();
1161
1162 // Rewrite all loads of the PN to use the new PHI.
1163 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001164 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001165 LI->replaceAllUsesWith(NewPN);
1166 LI->eraseFromParent();
1167 }
1168
1169 // Inject loads into all of the pred blocks.
1170 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1171 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1172 TerminatorInst *TI = Pred->getTerminator();
1173 Value *InVal = PN.getIncomingValue(Idx);
1174 IRBuilderTy PredBuilder(TI);
1175
1176 LoadInst *Load = PredBuilder.CreateLoad(
1177 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1178 ++NumLoadsSpeculated;
1179 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001180 if (AATags)
1181 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001182 NewPN->addIncoming(Load, Pred);
1183 }
1184
1185 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1186 PN.eraseFromParent();
1187}
1188
1189/// Select instructions that use an alloca and are subsequently loaded can be
1190/// rewritten to load both input pointers and then select between the result,
1191/// allowing the load of the alloca to be promoted.
1192/// From this:
1193/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1194/// %V = load i32* %P2
1195/// to:
1196/// %V1 = load i32* %Alloca -> will be mem2reg'd
1197/// %V2 = load i32* %Other
1198/// %V = select i1 %cond, i32 %V1, i32 %V2
1199///
1200/// We can do this to a select if its only uses are loads and if the operand
1201/// to the select can be loaded unconditionally.
Craig Topperf40110f2014-04-25 05:29:35 +00001202static bool isSafeSelectToSpeculate(SelectInst &SI,
1203 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001204 Value *TValue = SI.getTrueValue();
1205 Value *FValue = SI.getFalseValue();
Hal Finkel2e42c342014-07-10 05:27:53 +00001206 bool TDerefable = TValue->isDereferenceablePointer(DL);
1207 bool FDerefable = FValue->isDereferenceablePointer(DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001208
Chandler Carruthcdf47882014-03-09 03:16:01 +00001209 for (User *U : SI.users()) {
1210 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001211 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001212 return false;
1213
1214 // Both operands to the select need to be dereferencable, either
1215 // absolutely (e.g. allocas) or at this point because we can see other
1216 // accesses to it.
1217 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001218 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001219 return false;
1220 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001221 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001222 return false;
1223 }
1224
1225 return true;
1226}
1227
1228static void speculateSelectInstLoads(SelectInst &SI) {
1229 DEBUG(dbgs() << " original: " << SI << "\n");
1230
1231 IRBuilderTy IRB(&SI);
1232 Value *TV = SI.getTrueValue();
1233 Value *FV = SI.getFalseValue();
1234 // Replace the loads of the select with a select of two loads.
1235 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001236 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001237 assert(LI->isSimple() && "We only speculate simple loads");
1238
1239 IRB.SetInsertPoint(LI);
1240 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001241 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001242 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001243 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001244 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001245
Hal Finkelcc39b672014-07-24 12:16:19 +00001246 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001247 TL->setAlignment(LI->getAlignment());
1248 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001249
1250 AAMDNodes Tags;
1251 LI->getAAMetadata(Tags);
1252 if (Tags) {
1253 TL->setAAMetadata(Tags);
1254 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001255 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001256
1257 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1258 LI->getName() + ".sroa.speculated");
1259
1260 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1261 LI->replaceAllUsesWith(V);
1262 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001263 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001264 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001265}
1266
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001267/// \brief Build a GEP out of a base pointer and indices.
1268///
1269/// This will return the BasePtr if that is valid, or build a new GEP
1270/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001271static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001272 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001273 if (Indices.empty())
1274 return BasePtr;
1275
1276 // A single zero index is a no-op, so check for this and avoid building a GEP
1277 // in that case.
1278 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1279 return BasePtr;
1280
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001281 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001282}
1283
1284/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1285/// TargetTy without changing the offset of the pointer.
1286///
1287/// This routine assumes we've already established a properly offset GEP with
1288/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1289/// zero-indices down through type layers until we find one the same as
1290/// TargetTy. If we can't find one with the same type, we at least try to use
1291/// one with the same size. If none of that works, we just produce the GEP as
1292/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001293static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001294 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001295 SmallVectorImpl<Value *> &Indices,
1296 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001297 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001298 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001299
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001300 // Pointer size to use for the indices.
1301 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1302
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001303 // See if we can descend into a struct and locate a field with the correct
1304 // type.
1305 unsigned NumLayers = 0;
1306 Type *ElementTy = Ty;
1307 do {
1308 if (ElementTy->isPointerTy())
1309 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001310
1311 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1312 ElementTy = ArrayTy->getElementType();
1313 Indices.push_back(IRB.getIntN(PtrSize, 0));
1314 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1315 ElementTy = VectorTy->getElementType();
1316 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001317 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001318 if (STy->element_begin() == STy->element_end())
1319 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001320 ElementTy = *STy->element_begin();
1321 Indices.push_back(IRB.getInt32(0));
1322 } else {
1323 break;
1324 }
1325 ++NumLayers;
1326 } while (ElementTy != TargetTy);
1327 if (ElementTy != TargetTy)
1328 Indices.erase(Indices.end() - NumLayers, Indices.end());
1329
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001330 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001331}
1332
1333/// \brief Recursively compute indices for a natural GEP.
1334///
1335/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1336/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001337static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001338 Value *Ptr, Type *Ty, APInt &Offset,
1339 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001340 SmallVectorImpl<Value *> &Indices,
1341 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001343 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001344
1345 // We can't recurse through pointer types.
1346 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001347 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001348
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001349 // We try to analyze GEPs over vectors here, but note that these GEPs are
1350 // extremely poorly defined currently. The long-term goal is to remove GEPing
1351 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001352 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001353 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001354 if (ElementSizeInBits % 8 != 0) {
1355 // GEPs over non-multiple of 8 size vector elements are invalid.
1356 return nullptr;
1357 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001358 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001359 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001360 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001361 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001362 Offset -= NumSkippedElements * ElementSize;
1363 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001364 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001365 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001366 }
1367
1368 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1369 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001370 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001371 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001372 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001373 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001374
1375 Offset -= NumSkippedElements * ElementSize;
1376 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001377 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001378 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001379 }
1380
1381 StructType *STy = dyn_cast<StructType>(Ty);
1382 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001383 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001384
Chandler Carruth90a735d2013-07-19 07:21:28 +00001385 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001386 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001387 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001388 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001389 unsigned Index = SL->getElementContainingOffset(StructOffset);
1390 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1391 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001392 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001393 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001394
1395 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001396 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001397 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001398}
1399
1400/// \brief Get a natural GEP from a base pointer to a particular offset and
1401/// resulting in a particular type.
1402///
1403/// The goal is to produce a "natural" looking GEP that works with the existing
1404/// composite types to arrive at the appropriate offset and element type for
1405/// a pointer. TargetTy is the element type the returned GEP should point-to if
1406/// possible. We recurse by decreasing Offset, adding the appropriate index to
1407/// Indices, and setting Ty to the result subtype.
1408///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001409/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001410static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001411 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001412 SmallVectorImpl<Value *> &Indices,
1413 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414 PointerType *Ty = cast<PointerType>(Ptr->getType());
1415
1416 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1417 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001418 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001419 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001420
1421 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001422 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001423 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001424 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001425 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001426 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001427 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001428
1429 Offset -= NumSkippedElements * ElementSize;
1430 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001431 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001432 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001433}
1434
1435/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1436/// resulting pointer has PointerTy.
1437///
1438/// This tries very hard to compute a "natural" GEP which arrives at the offset
1439/// and produces the pointer type desired. Where it cannot, it will try to use
1440/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1441/// fails, it will try to use an existing i8* and GEP to the byte offset and
1442/// bitcast to the type.
1443///
1444/// The strategy for finding the more natural GEPs is to peel off layers of the
1445/// pointer, walking back through bit casts and GEPs, searching for a base
1446/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001447/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001448/// a single GEP as possible, thus making each GEP more independent of the
1449/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001450static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1451 APInt Offset, Type *PointerTy,
1452 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001453 // Even though we don't look through PHI nodes, we could be called on an
1454 // instruction in an unreachable block, which may be on a cycle.
1455 SmallPtrSet<Value *, 4> Visited;
1456 Visited.insert(Ptr);
1457 SmallVector<Value *, 4> Indices;
1458
1459 // We may end up computing an offset pointer that has the wrong type. If we
1460 // never are able to compute one directly that has the correct type, we'll
1461 // fall back to it, so keep it around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001462 Value *OffsetPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001463
1464 // Remember any i8 pointer we come across to re-use if we need to do a raw
1465 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001466 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001467 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1468
1469 Type *TargetTy = PointerTy->getPointerElementType();
1470
1471 do {
1472 // First fold any existing GEPs into the offset.
1473 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1474 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001475 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001476 break;
1477 Offset += GEPOffset;
1478 Ptr = GEP->getPointerOperand();
1479 if (!Visited.insert(Ptr))
1480 break;
1481 }
1482
1483 // See if we can perform a natural GEP here.
1484 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001485 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001486 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001487 if (P->getType() == PointerTy) {
1488 // Zap any offset pointer that we ended up computing in previous rounds.
1489 if (OffsetPtr && OffsetPtr->use_empty())
1490 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1491 I->eraseFromParent();
1492 return P;
1493 }
1494 if (!OffsetPtr) {
1495 OffsetPtr = P;
1496 }
1497 }
1498
1499 // Stash this pointer if we've found an i8*.
1500 if (Ptr->getType()->isIntegerTy(8)) {
1501 Int8Ptr = Ptr;
1502 Int8PtrOffset = Offset;
1503 }
1504
1505 // Peel off a layer of the pointer and update the offset appropriately.
1506 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1507 Ptr = cast<Operator>(Ptr)->getOperand(0);
1508 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1509 if (GA->mayBeOverridden())
1510 break;
1511 Ptr = GA->getAliasee();
1512 } else {
1513 break;
1514 }
1515 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1516 } while (Visited.insert(Ptr));
1517
1518 if (!OffsetPtr) {
1519 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001520 Int8Ptr = IRB.CreateBitCast(
1521 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1522 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001523 Int8PtrOffset = Offset;
1524 }
1525
1526 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1527 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001528 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001529 }
1530 Ptr = OffsetPtr;
1531
1532 // On the off chance we were targeting i8*, guard the bitcast here.
1533 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001534 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001535
1536 return Ptr;
1537}
1538
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001539/// \brief Test whether we can convert a value from the old to the new type.
1540///
1541/// This predicate should be used to guard calls to convertValue in order to
1542/// ensure that we only try to convert viable values. The strategy is that we
1543/// will peel off single element struct and array wrappings to get to an
1544/// underlying value, and convert that value.
1545static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1546 if (OldTy == NewTy)
1547 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001548 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1549 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1550 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1551 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001552 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1553 return false;
1554 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1555 return false;
1556
Benjamin Kramer56262592013-09-22 11:24:58 +00001557 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001558 // of pointers and integers.
1559 OldTy = OldTy->getScalarType();
1560 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001561 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1562 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1563 return true;
1564 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1565 return true;
1566 return false;
1567 }
1568
1569 return true;
1570}
1571
1572/// \brief Generic routine to convert an SSA value to a value of a different
1573/// type.
1574///
1575/// This will try various different casting techniques, such as bitcasts,
1576/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1577/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001578static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001579 Type *NewTy) {
1580 Type *OldTy = V->getType();
1581 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1582
1583 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001584 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001585
1586 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1587 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001588 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1589 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001590
Benjamin Kramer90901a32013-09-21 20:36:04 +00001591 // See if we need inttoptr for this type pair. A cast involving both scalars
1592 // and vectors requires and additional bitcast.
1593 if (OldTy->getScalarType()->isIntegerTy() &&
1594 NewTy->getScalarType()->isPointerTy()) {
1595 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1596 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1597 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1598 NewTy);
1599
1600 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1601 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1602 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1603 NewTy);
1604
1605 return IRB.CreateIntToPtr(V, NewTy);
1606 }
1607
1608 // See if we need ptrtoint for this type pair. A cast involving both scalars
1609 // and vectors requires and additional bitcast.
1610 if (OldTy->getScalarType()->isPointerTy() &&
1611 NewTy->getScalarType()->isIntegerTy()) {
1612 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1613 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1614 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1615 NewTy);
1616
1617 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1618 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1619 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1620 NewTy);
1621
1622 return IRB.CreatePtrToInt(V, NewTy);
1623 }
1624
1625 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001626}
1627
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001628/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001629///
1630/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001631/// for a single slice.
1632static bool isVectorPromotionViableForSlice(
1633 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1634 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1635 AllocaSlices::const_iterator I) {
1636 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001637 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001638 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001639 uint64_t BeginIndex = BeginOffset / ElementSize;
1640 if (BeginIndex * ElementSize != BeginOffset ||
1641 BeginIndex >= Ty->getNumElements())
1642 return false;
1643 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001644 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001645 uint64_t EndIndex = EndOffset / ElementSize;
1646 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1647 return false;
1648
1649 assert(EndIndex > BeginIndex && "Empty vector!");
1650 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001651 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001652 (NumElements == 1) ? Ty->getElementType()
1653 : VectorType::get(Ty->getElementType(), NumElements);
1654
1655 Type *SplitIntTy =
1656 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1657
1658 Use *U = I->getUse();
1659
1660 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1661 if (MI->isVolatile())
1662 return false;
1663 if (!I->isSplittable())
1664 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001665 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1666 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1667 II->getIntrinsicID() != Intrinsic::lifetime_end)
1668 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001669 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1670 // Disable vector promotion when there are loads or stores of an FCA.
1671 return false;
1672 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1673 if (LI->isVolatile())
1674 return false;
1675 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001676 if (SliceBeginOffset > I->beginOffset() ||
1677 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001678 assert(LTy->isIntegerTy());
1679 LTy = SplitIntTy;
1680 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001681 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001682 return false;
1683 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1684 if (SI->isVolatile())
1685 return false;
1686 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001687 if (SliceBeginOffset > I->beginOffset() ||
1688 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001689 assert(STy->isIntegerTy());
1690 STy = SplitIntTy;
1691 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001692 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001693 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001694 } else {
1695 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001696 }
1697
1698 return true;
1699}
1700
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001701/// \brief Test whether the given alloca partitioning and range of slices can be
1702/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001703///
1704/// This is a quick test to check whether we can rewrite a particular alloca
1705/// partition (and its newly formed alloca) into a vector alloca with only
1706/// whole-vector loads and stores such that it could be promoted to a vector
1707/// SSA value. We only can ensure this for a limited set of operations, and we
1708/// don't want to do the rewrites unless we are confident that the result will
1709/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001710static bool
1711isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1712 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1713 AllocaSlices::const_iterator I,
1714 AllocaSlices::const_iterator E,
1715 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001716 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1717 if (!Ty)
1718 return false;
1719
Chandler Carruth90a735d2013-07-19 07:21:28 +00001720 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001721
1722 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1723 // that aren't byte sized.
1724 if (ElementSize % 8)
1725 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001726 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001727 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001728 ElementSize /= 8;
1729
Chandler Carruthf0546402013-07-18 07:15:00 +00001730 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001731 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1732 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001733 return false;
1734
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001735 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1736 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001737 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001738 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1739 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001740 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001741
1742 return true;
1743}
1744
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001745/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001746///
1747/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001748/// test below on a single slice of the alloca.
1749static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1750 Type *AllocaTy,
1751 uint64_t AllocBeginOffset,
1752 uint64_t Size, AllocaSlices &S,
1753 AllocaSlices::const_iterator I,
1754 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001755 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1756 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1757
1758 // We can't reasonably handle cases where the load or store extends past
1759 // the end of the aloca's type and into its padding.
1760 if (RelEnd > Size)
1761 return false;
1762
1763 Use *U = I->getUse();
1764
1765 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1766 if (LI->isVolatile())
1767 return false;
1768 if (RelBegin == 0 && RelEnd == Size)
1769 WholeAllocaOp = true;
1770 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001771 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001772 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001773 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001774 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001775 // Non-integer loads need to be convertible from the alloca type so that
1776 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001777 return false;
1778 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001779 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1780 Type *ValueTy = SI->getValueOperand()->getType();
1781 if (SI->isVolatile())
1782 return false;
1783 if (RelBegin == 0 && RelEnd == Size)
1784 WholeAllocaOp = true;
1785 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001786 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001787 return false;
1788 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001789 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001790 // Non-integer stores need to be convertible to the alloca type so that
1791 // they are promotable.
1792 return false;
1793 }
1794 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1795 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1796 return false;
1797 if (!I->isSplittable())
1798 return false; // Skip any unsplittable intrinsics.
1799 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1800 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1801 II->getIntrinsicID() != Intrinsic::lifetime_end)
1802 return false;
1803 } else {
1804 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001805 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001806
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001807 return true;
1808}
1809
Chandler Carruth435c4e02012-10-15 08:40:30 +00001810/// \brief Test whether the given alloca partition's integer operations can be
1811/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001812///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001813/// This is a quick test to check whether we can rewrite the integer loads and
1814/// stores to a particular alloca into wider loads and stores and be able to
1815/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001816static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001817isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001818 uint64_t AllocBeginOffset, AllocaSlices &S,
1819 AllocaSlices::const_iterator I,
1820 AllocaSlices::const_iterator E,
1821 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001822 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001823 // Don't create integer types larger than the maximum bitwidth.
1824 if (SizeInBits > IntegerType::MAX_INT_BITS)
1825 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001826
1827 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001828 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001829 return false;
1830
Chandler Carruth58d05562012-10-25 04:37:07 +00001831 // We need to ensure that an integer type with the appropriate bitwidth can
1832 // be converted to the alloca type, whatever that is. We don't want to force
1833 // the alloca itself to have an integer type if there is a more suitable one.
1834 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001835 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1836 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001837 return false;
1838
Chandler Carruth90a735d2013-07-19 07:21:28 +00001839 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001840
Chandler Carruthf0546402013-07-18 07:15:00 +00001841 // While examining uses, we ensure that the alloca has a covering load or
1842 // store. We don't want to widen the integer operations only to fail to
1843 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001844 // later). However, if there are only splittable uses, go ahead and assume
1845 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001846 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001847
Chandler Carruthf0546402013-07-18 07:15:00 +00001848 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001849 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1850 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001851 return false;
1852
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001853 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1854 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001855 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001856 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1857 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001858 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001859
Chandler Carruth92924fd2012-09-24 00:34:20 +00001860 return WholeAllocaOp;
1861}
1862
Chandler Carruthd177f862013-03-20 07:30:36 +00001863static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001864 IntegerType *Ty, uint64_t Offset,
1865 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001866 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001867 IntegerType *IntTy = cast<IntegerType>(V->getType());
1868 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1869 "Element extends past full value");
1870 uint64_t ShAmt = 8*Offset;
1871 if (DL.isBigEndian())
1872 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001873 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001874 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001875 DEBUG(dbgs() << " shifted: " << *V << "\n");
1876 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001877 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1878 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001879 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001880 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001881 DEBUG(dbgs() << " trunced: " << *V << "\n");
1882 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001883 return V;
1884}
1885
Chandler Carruthd177f862013-03-20 07:30:36 +00001886static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001887 Value *V, uint64_t Offset, const Twine &Name) {
1888 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1889 IntegerType *Ty = cast<IntegerType>(V->getType());
1890 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1891 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001892 DEBUG(dbgs() << " start: " << *V << "\n");
1893 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001894 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001895 DEBUG(dbgs() << " extended: " << *V << "\n");
1896 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001897 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1898 "Element store outside of alloca store");
1899 uint64_t ShAmt = 8*Offset;
1900 if (DL.isBigEndian())
1901 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001902 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001903 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001904 DEBUG(dbgs() << " shifted: " << *V << "\n");
1905 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001906
1907 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1908 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1909 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001910 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001911 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001912 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001913 }
1914 return V;
1915}
1916
Chandler Carruthd177f862013-03-20 07:30:36 +00001917static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001918 unsigned BeginIndex, unsigned EndIndex,
1919 const Twine &Name) {
1920 VectorType *VecTy = cast<VectorType>(V->getType());
1921 unsigned NumElements = EndIndex - BeginIndex;
1922 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1923
1924 if (NumElements == VecTy->getNumElements())
1925 return V;
1926
1927 if (NumElements == 1) {
1928 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1929 Name + ".extract");
1930 DEBUG(dbgs() << " extract: " << *V << "\n");
1931 return V;
1932 }
1933
1934 SmallVector<Constant*, 8> Mask;
1935 Mask.reserve(NumElements);
1936 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1937 Mask.push_back(IRB.getInt32(i));
1938 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1939 ConstantVector::get(Mask),
1940 Name + ".extract");
1941 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1942 return V;
1943}
1944
Chandler Carruthd177f862013-03-20 07:30:36 +00001945static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001946 unsigned BeginIndex, const Twine &Name) {
1947 VectorType *VecTy = cast<VectorType>(Old->getType());
1948 assert(VecTy && "Can only insert a vector into a vector");
1949
1950 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1951 if (!Ty) {
1952 // Single element to insert.
1953 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1954 Name + ".insert");
1955 DEBUG(dbgs() << " insert: " << *V << "\n");
1956 return V;
1957 }
1958
1959 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1960 "Too many elements!");
1961 if (Ty->getNumElements() == VecTy->getNumElements()) {
1962 assert(V->getType() == VecTy && "Vector type mismatch");
1963 return V;
1964 }
1965 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1966
1967 // When inserting a smaller vector into the larger to store, we first
1968 // use a shuffle vector to widen it with undef elements, and then
1969 // a second shuffle vector to select between the loaded vector and the
1970 // incoming vector.
1971 SmallVector<Constant*, 8> Mask;
1972 Mask.reserve(VecTy->getNumElements());
1973 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1974 if (i >= BeginIndex && i < EndIndex)
1975 Mask.push_back(IRB.getInt32(i - BeginIndex));
1976 else
1977 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1978 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1979 ConstantVector::get(Mask),
1980 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001981 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001982
1983 Mask.clear();
1984 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001985 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1986
1987 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1988
1989 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001990 return V;
1991}
1992
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001993namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001994/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1995/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001996///
1997/// Also implements the rewriting to vector-based accesses when the partition
1998/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1999/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002000class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002001 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002002 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2003 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002004
Chandler Carruth90a735d2013-07-19 07:21:28 +00002005 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002006 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002007 SROA &Pass;
2008 AllocaInst &OldAI, &NewAI;
2009 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002010 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002011
2012 // If we are rewriting an alloca partition which can be written as pure
2013 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002014 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002015 // - The new alloca is exactly the size of the vector type here.
2016 // - The accesses all either map to the entire vector or to a single
2017 // element.
2018 // - The set of accessing instructions is only one of those handled above
2019 // in isVectorPromotionViable. Generally these are the same access kinds
2020 // which are promotable via mem2reg.
2021 VectorType *VecTy;
2022 Type *ElementTy;
2023 uint64_t ElementSize;
2024
Chandler Carruth92924fd2012-09-24 00:34:20 +00002025 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002026 // alloca's integer operations should be widened to this integer type due to
2027 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002028 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002029 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002030
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002031 // The original offset of the slice currently being rewritten relative to
2032 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002033 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002034 // The new offsets of the slice currently being rewritten relative to the
2035 // original alloca.
2036 uint64_t NewBeginOffset, NewEndOffset;
2037
2038 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002039 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002040 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002041 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002042 Instruction *OldPtr;
2043
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002044 // Track post-rewrite users which are PHI nodes and Selects.
2045 SmallPtrSetImpl<PHINode *> &PHIUsers;
2046 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002047
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002048 // Utility IR builder, whose name prefix is setup for each visited use, and
2049 // the insertion point is set to point to the user.
2050 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002051
2052public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002053 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
2054 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002055 uint64_t NewAllocaBeginOffset,
2056 uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
2057 bool IsIntegerPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002058 SmallPtrSetImpl<PHINode *> &PHIUsers,
2059 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002060 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002061 NewAllocaBeginOffset(NewAllocaBeginOffset),
2062 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002063 NewAllocaTy(NewAI.getAllocatedType()),
Craig Topperf40110f2014-04-25 05:29:35 +00002064 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : nullptr),
2065 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002066 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002067 IntTy(IsIntegerPromotable
2068 ? Type::getIntNTy(
2069 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002070 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002071 : nullptr),
Chandler Carruthf0546402013-07-18 07:15:00 +00002072 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002073 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002074 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002075 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002076 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002077 "Only multiple-of-8 sized vector elements are viable");
2078 ++NumVectorized;
2079 }
2080 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
2081 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002082 }
2083
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002084 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002085 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002086 BeginOffset = I->beginOffset();
2087 EndOffset = I->endOffset();
2088 IsSplittable = I->isSplittable();
2089 IsSplit =
2090 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002091
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002092 // Compute the intersecting offset range.
2093 assert(BeginOffset < NewAllocaEndOffset);
2094 assert(EndOffset > NewAllocaBeginOffset);
2095 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2096 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2097
2098 SliceSize = NewEndOffset - NewBeginOffset;
2099
Chandler Carruthf0546402013-07-18 07:15:00 +00002100 OldUse = I->getUse();
2101 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002102
Chandler Carruthf0546402013-07-18 07:15:00 +00002103 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2104 IRB.SetInsertPoint(OldUserI);
2105 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2106 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2107
2108 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2109 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002110 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002111 return CanSROA;
2112 }
2113
2114private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002115 // Make sure the other visit overloads are visible.
2116 using Base::visit;
2117
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002118 // Every instruction which can end up as a user must have a rewrite rule.
2119 bool visitInstruction(Instruction &I) {
2120 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2121 llvm_unreachable("No rewrite rule for this instruction!");
2122 }
2123
Chandler Carruth47954c82014-02-26 05:12:43 +00002124 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2125 // Note that the offset computation can use BeginOffset or NewBeginOffset
2126 // interchangeably for unsplit slices.
2127 assert(IsSplit || BeginOffset == NewBeginOffset);
2128 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2129
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002130#ifndef NDEBUG
2131 StringRef OldName = OldPtr->getName();
2132 // Skip through the last '.sroa.' component of the name.
2133 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2134 if (LastSROAPrefix != StringRef::npos) {
2135 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2136 // Look for an SROA slice index.
2137 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2138 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2139 // Strip the index and look for the offset.
2140 OldName = OldName.substr(IndexEnd + 1);
2141 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2142 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2143 // Strip the offset.
2144 OldName = OldName.substr(OffsetEnd + 1);
2145 }
2146 }
2147 // Strip any SROA suffixes as well.
2148 OldName = OldName.substr(0, OldName.find(".sroa_"));
2149#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002150
2151 return getAdjustedPtr(IRB, DL, &NewAI,
2152 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002153#ifndef NDEBUG
2154 Twine(OldName) + "."
2155#else
2156 Twine()
2157#endif
2158 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002159 }
2160
Chandler Carruth2659e502014-02-26 05:02:19 +00002161 /// \brief Compute suitable alignment to access this slice of the *new* alloca.
2162 ///
2163 /// You can optionally pass a type to this routine and if that type's ABI
2164 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002165 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002166 unsigned NewAIAlign = NewAI.getAlignment();
2167 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002168 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth2659e502014-02-26 05:02:19 +00002169 unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2170 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002171 }
2172
Chandler Carruth845b73c2012-11-21 08:16:30 +00002173 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002174 assert(VecTy && "Can only call getIndex when rewriting a vector");
2175 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2176 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2177 uint32_t Index = RelOffset / ElementSize;
2178 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002179 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002180 }
2181
2182 void deleteIfTriviallyDead(Value *V) {
2183 Instruction *I = cast<Instruction>(V);
2184 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002185 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002186 }
2187
Chandler Carruthea27cf02014-02-26 04:25:04 +00002188 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002189 unsigned BeginIndex = getIndex(NewBeginOffset);
2190 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002191 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002192
2193 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002194 "load");
2195 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002196 }
2197
Chandler Carruthea27cf02014-02-26 04:25:04 +00002198 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002199 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002200 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002201 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002202 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002203 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002204 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2205 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2206 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002207 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002208 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002209 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002210 }
2211
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002212 bool visitLoadInst(LoadInst &LI) {
2213 DEBUG(dbgs() << " original: " << LI << "\n");
2214 Value *OldOp = LI.getOperand(0);
2215 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002216
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002217 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002218 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002219 bool IsPtrAdjusted = false;
2220 Value *V;
2221 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002222 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002223 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002224 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002225 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002226 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002227 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002228 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002229 } else {
2230 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002231 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002232 getSliceAlign(TargetTy), LI.isVolatile(),
2233 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002234 IsPtrAdjusted = true;
2235 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002236 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002237
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002238 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002239 assert(!LI.isVolatile());
2240 assert(LI.getType()->isIntegerTy() &&
2241 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002242 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002243 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002244 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002245 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002246 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002247 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002248 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002249 // Create a placeholder value with the same type as LI to use as the
2250 // basis for the new value. This allows us to replace the uses of LI with
2251 // the computed value, and then replace the placeholder with LI, leaving
2252 // LI only used for this computation.
2253 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002254 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002255 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002256 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002257 LI.replaceAllUsesWith(V);
2258 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002259 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002260 } else {
2261 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002262 }
2263
Chandler Carruth18db7952012-11-20 01:12:50 +00002264 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002265 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002266 DEBUG(dbgs() << " to: " << *V << "\n");
2267 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002268 }
2269
Chandler Carruthea27cf02014-02-26 04:25:04 +00002270 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002271 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002272 unsigned BeginIndex = getIndex(NewBeginOffset);
2273 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002274 assert(EndIndex > BeginIndex && "Empty vector!");
2275 unsigned NumElements = EndIndex - BeginIndex;
2276 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002277 Type *SliceTy =
2278 (NumElements == 1) ? ElementTy
2279 : VectorType::get(ElementTy, NumElements);
2280 if (V->getType() != SliceTy)
2281 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002282
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002283 // Mix in the existing elements.
2284 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2285 "load");
2286 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2287 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002288 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002289 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002290
2291 (void)Store;
2292 DEBUG(dbgs() << " to: " << *Store << "\n");
2293 return true;
2294 }
2295
Chandler Carruthea27cf02014-02-26 04:25:04 +00002296 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002297 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002298 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002299 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002300 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002301 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002302 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002303 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2304 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002305 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002306 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002307 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002308 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002309 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002310 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002311 (void)Store;
2312 DEBUG(dbgs() << " to: " << *Store << "\n");
2313 return true;
2314 }
2315
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002316 bool visitStoreInst(StoreInst &SI) {
2317 DEBUG(dbgs() << " original: " << SI << "\n");
2318 Value *OldOp = SI.getOperand(1);
2319 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002320
Chandler Carruth18db7952012-11-20 01:12:50 +00002321 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002322
Chandler Carruthac8317f2012-10-04 12:33:50 +00002323 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2324 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002325 if (V->getType()->isPointerTy())
2326 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002327 Pass.PostPromotionWorklist.insert(AI);
2328
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002329 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002330 assert(!SI.isVolatile());
2331 assert(V->getType()->isIntegerTy() &&
2332 "Only integer type loads and stores are split");
2333 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002334 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002335 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002336 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002337 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002338 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002339 }
2340
Chandler Carruth18db7952012-11-20 01:12:50 +00002341 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002342 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002343 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002344 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002345
Chandler Carruth18db7952012-11-20 01:12:50 +00002346 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002347 if (NewBeginOffset == NewAllocaBeginOffset &&
2348 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002349 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2350 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002351 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2352 SI.isVolatile());
2353 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002354 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002355 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2356 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002357 }
2358 (void)NewSI;
2359 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002360 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002361
2362 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2363 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002364 }
2365
Chandler Carruth514f34f2012-12-17 04:07:30 +00002366 /// \brief Compute an integer value from splatting an i8 across the given
2367 /// number of bytes.
2368 ///
2369 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2370 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002371 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002372 ///
2373 /// \param V The i8 value to splat.
2374 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002375 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002376 assert(Size > 0 && "Expected a positive number of bytes.");
2377 IntegerType *VTy = cast<IntegerType>(V->getType());
2378 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2379 if (Size == 1)
2380 return V;
2381
2382 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002383 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002384 ConstantExpr::getUDiv(
2385 Constant::getAllOnesValue(SplatIntTy),
2386 ConstantExpr::getZExt(
2387 Constant::getAllOnesValue(V->getType()),
2388 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002389 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002390 return V;
2391 }
2392
Chandler Carruthccca5042012-12-17 04:07:37 +00002393 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002394 Value *getVectorSplat(Value *V, unsigned NumElements) {
2395 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002396 DEBUG(dbgs() << " splat: " << *V << "\n");
2397 return V;
2398 }
2399
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002400 bool visitMemSetInst(MemSetInst &II) {
2401 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002402 assert(II.getRawDest() == OldPtr);
2403
2404 // If the memset has a variable size, it cannot be split, just adjust the
2405 // pointer to the new alloca.
2406 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002407 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002408 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002409 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002410 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002411 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002412
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002413 deleteIfTriviallyDead(OldPtr);
2414 return false;
2415 }
2416
2417 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002418 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002419
2420 Type *AllocaTy = NewAI.getAllocatedType();
2421 Type *ScalarTy = AllocaTy->getScalarType();
2422
2423 // If this doesn't map cleanly onto the alloca type, and that type isn't
2424 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002425 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002426 (BeginOffset > NewAllocaBeginOffset ||
2427 EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002428 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002429 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002430 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2431 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002432 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002433 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2434 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002435 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2436 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002437 (void)New;
2438 DEBUG(dbgs() << " to: " << *New << "\n");
2439 return false;
2440 }
2441
2442 // If we can represent this as a simple value, we have to build the actual
2443 // value to store, which requires expanding the byte present in memset to
2444 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002445 // splatting the byte to a sufficiently wide integer, splatting it across
2446 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002447 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002448
Chandler Carruthccca5042012-12-17 04:07:37 +00002449 if (VecTy) {
2450 // If this is a memset of a vectorized alloca, insert it.
2451 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002452
Chandler Carruthf0546402013-07-18 07:15:00 +00002453 unsigned BeginIndex = getIndex(NewBeginOffset);
2454 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002455 assert(EndIndex > BeginIndex && "Empty vector!");
2456 unsigned NumElements = EndIndex - BeginIndex;
2457 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2458
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002459 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002460 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2461 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002462 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002463 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002464
Chandler Carruthce4562b2012-12-17 13:41:21 +00002465 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002466 "oldload");
2467 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002468 } else if (IntTy) {
2469 // If this is a memset on an alloca where we can widen stores, insert the
2470 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002471 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002472
Chandler Carruthf0546402013-07-18 07:15:00 +00002473 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002474 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002475
2476 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2477 EndOffset != NewAllocaBeginOffset)) {
2478 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002479 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002480 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002481 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002482 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002483 } else {
2484 assert(V->getType() == IntTy &&
2485 "Wrong type for an alloca wide integer!");
2486 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002487 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002488 } else {
2489 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002490 assert(NewBeginOffset == NewAllocaBeginOffset);
2491 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002492
Chandler Carruth90a735d2013-07-19 07:21:28 +00002493 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002494 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002495 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002496
Chandler Carruth90a735d2013-07-19 07:21:28 +00002497 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002498 }
2499
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002500 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002501 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002502 (void)New;
2503 DEBUG(dbgs() << " to: " << *New << "\n");
2504 return !II.isVolatile();
2505 }
2506
2507 bool visitMemTransferInst(MemTransferInst &II) {
2508 // Rewriting of memory transfer instructions can be a bit tricky. We break
2509 // them into two categories: split intrinsics and unsplit intrinsics.
2510
2511 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002512
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002513 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002514 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002515 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002516
Chandler Carruthaa72b932014-02-26 07:29:54 +00002517 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002518
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002519 // For unsplit intrinsics, we simply modify the source and destination
2520 // pointers in place. This isn't just an optimization, it is a matter of
2521 // correctness. With unsplit intrinsics we may be dealing with transfers
2522 // within a single alloca before SROA ran, or with transfers that have
2523 // a variable length. We may also be dealing with memmove instead of
2524 // memcpy, and so simply updating the pointers is the necessary for us to
2525 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002526 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002527 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002528 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002529 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002530 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002531 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002532
Chandler Carruthaa72b932014-02-26 07:29:54 +00002533 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002534 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002535 II.setAlignment(
2536 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002537 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002538
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002539 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002540 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002541 return false;
2542 }
2543 // For split transfer intrinsics we have an incredibly useful assurance:
2544 // the source and destination do not reside within the same alloca, and at
2545 // least one of them does not escape. This means that we can replace
2546 // memmove with memcpy, and we don't need to worry about all manner of
2547 // downsides to splitting and transforming the operations.
2548
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002549 // If this doesn't map cleanly onto the alloca type, and that type isn't
2550 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002551 bool EmitMemCpy =
2552 !VecTy && !IntTy &&
2553 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2554 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2555 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556
2557 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2558 // size hasn't been shrunk based on analysis of the viable range, this is
2559 // a no-op.
2560 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002561 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002562 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002563
2564 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002565 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002566 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002567 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002568 return false;
2569 }
2570 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002571 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002572
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002573 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2574 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002575 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002576 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002577 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2578 assert(AI != &OldAI && AI != &NewAI &&
2579 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002580 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002581 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002582
Chandler Carruth286d87e2014-02-26 08:25:02 +00002583 Type *OtherPtrTy = OtherPtr->getType();
2584 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2585
Chandler Carruth181ed052014-02-26 05:33:36 +00002586 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002587 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002588 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002589 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2590 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002591
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002592 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002593 // Compute the other pointer, folding as much as possible to produce
2594 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002595 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002596 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002597
Chandler Carruth47954c82014-02-26 05:12:43 +00002598 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002599 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002600 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002601
Chandler Carruthaa72b932014-02-26 07:29:54 +00002602 CallInst *New = IRB.CreateMemCpy(
2603 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2604 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002605 (void)New;
2606 DEBUG(dbgs() << " to: " << *New << "\n");
2607 return false;
2608 }
2609
Chandler Carruthf0546402013-07-18 07:15:00 +00002610 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2611 NewEndOffset == NewAllocaEndOffset;
2612 uint64_t Size = NewEndOffset - NewBeginOffset;
2613 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2614 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002615 unsigned NumElements = EndIndex - BeginIndex;
2616 IntegerType *SubIntTy
Craig Topperf40110f2014-04-25 05:29:35 +00002617 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002618
Chandler Carruth286d87e2014-02-26 08:25:02 +00002619 // Reset the other pointer type to match the register type we're going to
2620 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002621 if (VecTy && !IsWholeAlloca) {
2622 if (NumElements == 1)
2623 OtherPtrTy = VecTy->getElementType();
2624 else
2625 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2626
Chandler Carruth286d87e2014-02-26 08:25:02 +00002627 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002628 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002629 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2630 } else {
2631 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002632 }
2633
Chandler Carruth181ed052014-02-26 05:33:36 +00002634 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002635 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002636 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002637 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002638 unsigned DstAlign = SliceAlign;
2639 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002640 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002641 std::swap(SrcAlign, DstAlign);
2642 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002643
2644 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002645 if (VecTy && !IsWholeAlloca && !IsDest) {
2646 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002647 "load");
2648 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002649 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002650 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002651 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002652 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002653 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002654 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002655 } else {
Chandler Carruthaa72b932014-02-26 07:29:54 +00002656 Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002657 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002658 }
2659
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002660 if (VecTy && !IsWholeAlloca && IsDest) {
2661 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002662 "oldload");
2663 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002664 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002665 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002666 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002667 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002668 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002669 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2670 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002671 }
2672
Chandler Carruth871ba722012-09-26 10:27:46 +00002673 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002674 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002675 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002676 DEBUG(dbgs() << " to: " << *Store << "\n");
2677 return !II.isVolatile();
2678 }
2679
2680 bool visitIntrinsicInst(IntrinsicInst &II) {
2681 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2682 II.getIntrinsicID() == Intrinsic::lifetime_end);
2683 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002684 assert(II.getArgOperand(1) == OldPtr);
2685
2686 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002687 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002688
2689 ConstantInt *Size
2690 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002691 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002692 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002693 Value *New;
2694 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2695 New = IRB.CreateLifetimeStart(Ptr, Size);
2696 else
2697 New = IRB.CreateLifetimeEnd(Ptr, Size);
2698
Edwin Vane82f80d42013-01-29 17:42:24 +00002699 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002700 DEBUG(dbgs() << " to: " << *New << "\n");
2701 return true;
2702 }
2703
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002704 bool visitPHINode(PHINode &PN) {
2705 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002706 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2707 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002708
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002709 // We would like to compute a new pointer in only one place, but have it be
2710 // as local as possible to the PHI. To do that, we re-use the location of
2711 // the old pointer, which necessarily must be in the right position to
2712 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002713 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002714 if (isa<PHINode>(OldPtr))
2715 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
2716 else
2717 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002718 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002719
Chandler Carruth47954c82014-02-26 05:12:43 +00002720 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002721 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002722 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002723
Chandler Carruth82a57542012-10-01 10:54:05 +00002724 DEBUG(dbgs() << " to: " << PN << "\n");
2725 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002726
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002727 // PHIs can't be promoted on their own, but often can be speculated. We
2728 // check the speculation outside of the rewriter so that we see the
2729 // fully-rewritten alloca.
2730 PHIUsers.insert(&PN);
2731 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002732 }
2733
2734 bool visitSelectInst(SelectInst &SI) {
2735 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002736 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2737 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002738 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2739 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002740
Chandler Carruth47954c82014-02-26 05:12:43 +00002741 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002742 // Replace the operands which were using the old pointer.
2743 if (SI.getOperand(1) == OldPtr)
2744 SI.setOperand(1, NewPtr);
2745 if (SI.getOperand(2) == OldPtr)
2746 SI.setOperand(2, NewPtr);
2747
Chandler Carruth82a57542012-10-01 10:54:05 +00002748 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002749 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002750
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002751 // Selects can't be promoted on their own, but often can be speculated. We
2752 // check the speculation outside of the rewriter so that we see the
2753 // fully-rewritten alloca.
2754 SelectUsers.insert(&SI);
2755 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002756 }
2757
2758};
2759}
2760
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002761namespace {
2762/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2763///
2764/// This pass aggressively rewrites all aggregate loads and stores on
2765/// a particular pointer (or any pointer derived from it which we can identify)
2766/// with scalar loads and stores.
2767class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2768 // Befriend the base class so it can delegate to private visit methods.
2769 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2770
Chandler Carruth90a735d2013-07-19 07:21:28 +00002771 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002772
2773 /// Queue of pointer uses to analyze and potentially rewrite.
2774 SmallVector<Use *, 8> Queue;
2775
2776 /// Set to prevent us from cycling with phi nodes and loops.
2777 SmallPtrSet<User *, 8> Visited;
2778
2779 /// The current pointer use being rewritten. This is used to dig up the used
2780 /// value (as opposed to the user).
2781 Use *U;
2782
2783public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002784 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002785
2786 /// Rewrite loads and stores through a pointer and all pointers derived from
2787 /// it.
2788 bool rewrite(Instruction &I) {
2789 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2790 enqueueUsers(I);
2791 bool Changed = false;
2792 while (!Queue.empty()) {
2793 U = Queue.pop_back_val();
2794 Changed |= visit(cast<Instruction>(U->getUser()));
2795 }
2796 return Changed;
2797 }
2798
2799private:
2800 /// Enqueue all the users of the given instruction for further processing.
2801 /// This uses a set to de-duplicate users.
2802 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002803 for (Use &U : I.uses())
2804 if (Visited.insert(U.getUser()))
2805 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002806 }
2807
2808 // Conservative default is to not rewrite anything.
2809 bool visitInstruction(Instruction &I) { return false; }
2810
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002811 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002812 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002813 class OpSplitter {
2814 protected:
2815 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002816 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002817 /// The indices which to be used with insert- or extractvalue to select the
2818 /// appropriate value within the aggregate.
2819 SmallVector<unsigned, 4> Indices;
2820 /// The indices to a GEP instruction which will move Ptr to the correct slot
2821 /// within the aggregate.
2822 SmallVector<Value *, 4> GEPIndices;
2823 /// The base pointer of the original op, used as a base for GEPing the
2824 /// split operations.
2825 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002826
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002827 /// Initialize the splitter with an insertion point, Ptr and start with a
2828 /// single zero GEP index.
2829 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002830 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002831
2832 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002833 /// \brief Generic recursive split emission routine.
2834 ///
2835 /// This method recursively splits an aggregate op (load or store) into
2836 /// scalar or vector ops. It splits recursively until it hits a single value
2837 /// and emits that single value operation via the template argument.
2838 ///
2839 /// The logic of this routine relies on GEPs and insertvalue and
2840 /// extractvalue all operating with the same fundamental index list, merely
2841 /// formatted differently (GEPs need actual values).
2842 ///
2843 /// \param Ty The type being split recursively into smaller ops.
2844 /// \param Agg The aggregate value being built up or stored, depending on
2845 /// whether this is splitting a load or a store respectively.
2846 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2847 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002848 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002849
2850 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2851 unsigned OldSize = Indices.size();
2852 (void)OldSize;
2853 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2854 ++Idx) {
2855 assert(Indices.size() == OldSize && "Did not return to the old size");
2856 Indices.push_back(Idx);
2857 GEPIndices.push_back(IRB.getInt32(Idx));
2858 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2859 GEPIndices.pop_back();
2860 Indices.pop_back();
2861 }
2862 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002863 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002864
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002865 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2866 unsigned OldSize = Indices.size();
2867 (void)OldSize;
2868 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2869 ++Idx) {
2870 assert(Indices.size() == OldSize && "Did not return to the old size");
2871 Indices.push_back(Idx);
2872 GEPIndices.push_back(IRB.getInt32(Idx));
2873 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2874 GEPIndices.pop_back();
2875 Indices.pop_back();
2876 }
2877 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002878 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002879
2880 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002881 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002882 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002883
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002884 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002885 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002886 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002887
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002888 /// Emit a leaf load of a single value. This is called at the leaves of the
2889 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002890 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002891 assert(Ty->isSingleValueType());
2892 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002893 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2894 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002895 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2896 DEBUG(dbgs() << " to: " << *Load << "\n");
2897 }
2898 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002899
2900 bool visitLoadInst(LoadInst &LI) {
2901 assert(LI.getPointerOperand() == *U);
2902 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2903 return false;
2904
2905 // We have an aggregate being loaded, split it apart.
2906 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002907 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002908 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002909 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002910 LI.replaceAllUsesWith(V);
2911 LI.eraseFromParent();
2912 return true;
2913 }
2914
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002915 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002916 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002917 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002918
2919 /// Emit a leaf store of a single value. This is called at the leaves of the
2920 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002921 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002922 assert(Ty->isSingleValueType());
2923 // Extract the single value and store it using the indices.
2924 Value *Store = IRB.CreateStore(
2925 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2926 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2927 (void)Store;
2928 DEBUG(dbgs() << " to: " << *Store << "\n");
2929 }
2930 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002931
2932 bool visitStoreInst(StoreInst &SI) {
2933 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2934 return false;
2935 Value *V = SI.getValueOperand();
2936 if (V->getType()->isSingleValueType())
2937 return false;
2938
2939 // We have an aggregate being stored, split it apart.
2940 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002941 StoreOpSplitter Splitter(&SI, *U);
2942 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002943 SI.eraseFromParent();
2944 return true;
2945 }
2946
2947 bool visitBitCastInst(BitCastInst &BC) {
2948 enqueueUsers(BC);
2949 return false;
2950 }
2951
2952 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2953 enqueueUsers(GEPI);
2954 return false;
2955 }
2956
2957 bool visitPHINode(PHINode &PN) {
2958 enqueueUsers(PN);
2959 return false;
2960 }
2961
2962 bool visitSelectInst(SelectInst &SI) {
2963 enqueueUsers(SI);
2964 return false;
2965 }
2966};
2967}
2968
Chandler Carruthba931992012-10-13 10:49:33 +00002969/// \brief Strip aggregate type wrapping.
2970///
2971/// This removes no-op aggregate types wrapping an underlying type. It will
2972/// strip as many layers of types as it can without changing either the type
2973/// size or the allocated size.
2974static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2975 if (Ty->isSingleValueType())
2976 return Ty;
2977
2978 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2979 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2980
2981 Type *InnerTy;
2982 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2983 InnerTy = ArrTy->getElementType();
2984 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2985 const StructLayout *SL = DL.getStructLayout(STy);
2986 unsigned Index = SL->getElementContainingOffset(0);
2987 InnerTy = STy->getElementType(Index);
2988 } else {
2989 return Ty;
2990 }
2991
2992 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2993 TypeSize > DL.getTypeSizeInBits(InnerTy))
2994 return Ty;
2995
2996 return stripAggregateTypeWrapping(DL, InnerTy);
2997}
2998
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002999/// \brief Try to find a partition of the aggregate type passed in for a given
3000/// offset and size.
3001///
3002/// This recurses through the aggregate type and tries to compute a subtype
3003/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003004/// of an array, it will even compute a new array type for that sub-section,
3005/// and the same for structs.
3006///
3007/// Note that this routine is very strict and tries to find a partition of the
3008/// type which produces the *exact* right offset and size. It is not forgiving
3009/// when the size or offset cause either end of type-based partition to be off.
3010/// Also, this is a best-effort routine. It is reasonable to give up and not
3011/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003012static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003013 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003014 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3015 return stripAggregateTypeWrapping(DL, Ty);
3016 if (Offset > DL.getTypeAllocSize(Ty) ||
3017 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003018 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019
3020 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3021 // We can't partition pointers...
3022 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003023 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003024
3025 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003026 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003027 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003028 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003029 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003030 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003031 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003032 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003033 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003034 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003035 Offset -= NumSkippedElements * ElementSize;
3036
3037 // First check if we need to recurse.
3038 if (Offset > 0 || Size < ElementSize) {
3039 // Bail if the partition ends in a different array element.
3040 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003041 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003042 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003043 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003044 }
3045 assert(Offset == 0);
3046
3047 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003048 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003049 assert(Size > ElementSize);
3050 uint64_t NumElements = Size / ElementSize;
3051 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003052 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003053 return ArrayType::get(ElementTy, NumElements);
3054 }
3055
3056 StructType *STy = dyn_cast<StructType>(Ty);
3057 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003058 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003059
Chandler Carruth90a735d2013-07-19 07:21:28 +00003060 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003061 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003062 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003063 uint64_t EndOffset = Offset + Size;
3064 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003065 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003066
3067 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003068 Offset -= SL->getElementOffset(Index);
3069
3070 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003071 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003072 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003073 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003074
3075 // See if any partition must be contained by the element.
3076 if (Offset > 0 || Size < ElementSize) {
3077 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003078 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003079 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003080 }
3081 assert(Offset == 0);
3082
3083 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003084 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003085
3086 StructType::element_iterator EI = STy->element_begin() + Index,
3087 EE = STy->element_end();
3088 if (EndOffset < SL->getSizeInBytes()) {
3089 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3090 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003091 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003092
3093 // Don't try to form "natural" types if the elements don't line up with the
3094 // expected size.
3095 // FIXME: We could potentially recurse down through the last element in the
3096 // sub-struct to find a natural end point.
3097 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003098 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003099
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003100 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003101 EE = STy->element_begin() + EndIndex;
3102 }
3103
3104 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003105 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003106 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003107 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003108 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003109 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003110
Chandler Carruth054a40a2012-09-14 11:08:31 +00003111 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003112}
3113
3114/// \brief Rewrite an alloca partition's users.
3115///
3116/// This routine drives both of the rewriting goals of the SROA pass. It tries
3117/// to rewrite uses of an alloca partition to be conducive for SSA value
3118/// promotion. If the partition needs a new, more refined alloca, this will
3119/// build that new alloca, preserving as much type information as possible, and
3120/// rewrite the uses of the old alloca to point at the new one and have the
3121/// appropriate new offsets. It also evaluates how successful the rewrite was
3122/// at enabling promotion and if it was successful queues the alloca to be
3123/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003124bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3125 AllocaSlices::iterator B, AllocaSlices::iterator E,
3126 int64_t BeginOffset, int64_t EndOffset,
3127 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003128 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003129 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003130
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003131 // Try to compute a friendly type for this partition of the alloca. This
3132 // won't always succeed, in which case we fall back to a legal integer type
3133 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003134 Type *SliceTy = nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00003135 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003136 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3137 SliceTy = CommonUseTy;
3138 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003139 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003140 BeginOffset, SliceSize))
3141 SliceTy = TypePartitionTy;
3142 if ((!SliceTy || (SliceTy->isArrayTy() &&
3143 SliceTy->getArrayElementType()->isIntegerTy())) &&
3144 DL->isLegalInteger(SliceSize * 8))
3145 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3146 if (!SliceTy)
3147 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3148 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003149
3150 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003151 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003152
3153 bool IsIntegerPromotable =
3154 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003155 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003156
3157 // Check for the case where we're going to rewrite to a new alloca of the
3158 // exact same type as the original, and with the same access offsets. In that
3159 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003160 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003161 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003162 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003163 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003164 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003165 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003166 // FIXME: We should be able to bail at this point with "nothing changed".
3167 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003168 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003169 unsigned Alignment = AI.getAlignment();
3170 if (!Alignment) {
3171 // The minimum alignment which users can rely on when the explicit
3172 // alignment is omitted or zero is that required by the ABI for this
3173 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003174 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003175 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003176 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003177 // If we will get at least this much alignment from the type alone, leave
3178 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003179 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003180 Alignment = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003181 NewAI = new AllocaInst(SliceTy, nullptr, Alignment,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003182 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003183 ++NumNewAllocas;
3184 }
3185
3186 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003187 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3188 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003189
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003190 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003191 // promoted allocas. We will reset it to this point if the alloca is not in
3192 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003193 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003194 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003195 SmallPtrSet<PHINode *, 8> PHIUsers;
3196 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003197
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003198 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3199 EndOffset, IsVectorPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003200 IsIntegerPromotable, PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003201 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003202 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3203 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003204 SUI != SUE; ++SUI) {
3205 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003206 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003207 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003208 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003209 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003210 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003211 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003212 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003213 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003214 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003215 }
3216
Chandler Carruth6c321c12013-07-19 10:57:36 +00003217 NumAllocaPartitionUses += NumUses;
3218 MaxUsesPerAllocaPartition =
3219 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003220
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003221 // Now that we've processed all the slices in the new partition, check if any
3222 // PHIs or Selects would block promotion.
3223 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3224 E = PHIUsers.end();
3225 I != E; ++I)
3226 if (!isSafePHIToSpeculate(**I, DL)) {
3227 Promotable = false;
3228 PHIUsers.clear();
3229 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003230 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003231 }
3232 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3233 E = SelectUsers.end();
3234 I != E; ++I)
3235 if (!isSafeSelectToSpeculate(**I, DL)) {
3236 Promotable = false;
3237 PHIUsers.clear();
3238 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003239 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003240 }
3241
3242 if (Promotable) {
3243 if (PHIUsers.empty() && SelectUsers.empty()) {
3244 // Promote the alloca.
3245 PromotableAllocas.push_back(NewAI);
3246 } else {
3247 // If we have either PHIs or Selects to speculate, add them to those
3248 // worklists and re-queue the new alloca so that we promote in on the
3249 // next iteration.
3250 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3251 E = PHIUsers.end();
3252 I != E; ++I)
3253 SpeculatablePHIs.insert(*I);
3254 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3255 E = SelectUsers.end();
3256 I != E; ++I)
3257 SpeculatableSelects.insert(*I);
3258 Worklist.insert(NewAI);
3259 }
3260 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003261 // If we can't promote the alloca, iterate on it to check for new
3262 // refinements exposed by splitting the current alloca. Don't iterate on an
3263 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003264 if (NewAI != &AI)
3265 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003266
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003267 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003268 while (PostPromotionWorklist.size() > PPWOldSize)
3269 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003270 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003271
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003272 return true;
3273}
3274
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003275static void
3276removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3277 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003278 if (Offset >= MaxSplitUseEndOffset) {
3279 SplitUses.clear();
3280 MaxSplitUseEndOffset = 0;
3281 return;
3282 }
3283
3284 size_t SplitUsesOldSize = SplitUses.size();
3285 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003286 [Offset](const AllocaSlices::iterator &I) {
3287 return I->endOffset() <= Offset;
3288 }),
Chandler Carruthf0546402013-07-18 07:15:00 +00003289 SplitUses.end());
3290 if (SplitUsesOldSize == SplitUses.size())
3291 return;
3292
3293 // Recompute the max. While this is linear, so is remove_if.
3294 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003295 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003296 SUI = SplitUses.begin(),
3297 SUE = SplitUses.end();
3298 SUI != SUE; ++SUI)
3299 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3300}
3301
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003302/// \brief Walks the slices of an alloca and form partitions based on them,
3303/// rewriting each of their uses.
3304bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3305 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003306 return false;
3307
Chandler Carruth6c321c12013-07-19 10:57:36 +00003308 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003309 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003310 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003311 uint64_t MaxSplitUseEndOffset = 0;
3312
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003313 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003314
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003315 for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003316 SI != SE; SI = SJ) {
3317 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003318
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003319 if (!SI->isSplittable()) {
3320 // When we're forming an unsplittable region, it must always start at the
3321 // first slice and will extend through its end.
3322 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003323
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003324 // Form a partition including all of the overlapping slices with this
3325 // unsplittable slice.
3326 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3327 if (!SJ->isSplittable())
3328 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3329 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003330 }
3331 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003332 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003333
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003334 // Collect all of the overlapping splittable slices.
3335 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3336 SJ->isSplittable()) {
3337 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3338 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003339 }
3340
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003341 // Back up MaxEndOffset and SJ if we ended the span early when
3342 // encountering an unsplittable slice.
3343 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3344 assert(!SJ->isSplittable());
3345 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003346 }
3347 }
3348
3349 // Check if we have managed to move the end offset forward yet. If so,
3350 // we'll have to rewrite uses and erase old split uses.
3351 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003352 // Rewrite a sequence of overlapping slices.
3353 Changed |=
3354 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003355 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003356
3357 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3358 }
3359
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003360 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003361 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003362 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3363 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3364 SplitUses.push_back(SK);
3365 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003366 }
3367
3368 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003369 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003370 break;
3371
3372 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003373 // the next slice.
3374 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3375 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003376 continue;
3377 }
3378
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003379 // Even if we have split slices, if the next slice is splittable and the
3380 // split slices reach it, we can simply set up the beginning offset of the
3381 // next iteration to bridge between them.
3382 if (SJ != SE && SJ->isSplittable() &&
3383 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003384 BeginOffset = MaxEndOffset;
3385 continue;
3386 }
3387
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003388 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3389 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003390 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003391 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003392
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003393 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3394 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003395 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003396
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003397 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003398 break; // Skip the rest, we don't need to do any cleanup.
3399
3400 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3401 PostSplitEndOffset);
3402
3403 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003404 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003405 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003406
Chandler Carruth6c321c12013-07-19 10:57:36 +00003407 NumAllocaPartitions += NumPartitions;
3408 MaxPartitionsPerAlloca =
3409 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003410
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003411 return Changed;
3412}
3413
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003414/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3415void SROA::clobberUse(Use &U) {
3416 Value *OldV = U;
3417 // Replace the use with an undef value.
3418 U = UndefValue::get(OldV->getType());
3419
3420 // Check for this making an instruction dead. We have to garbage collect
3421 // all the dead instructions to ensure the uses of any alloca end up being
3422 // minimal.
3423 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3424 if (isInstructionTriviallyDead(OldI)) {
3425 DeadInsts.insert(OldI);
3426 }
3427}
3428
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003429/// \brief Analyze an alloca for SROA.
3430///
3431/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003432/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003433/// rewritten as needed.
3434bool SROA::runOnAlloca(AllocaInst &AI) {
3435 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3436 ++NumAllocasAnalyzed;
3437
3438 // Special case dead allocas, as they're trivial.
3439 if (AI.use_empty()) {
3440 AI.eraseFromParent();
3441 return true;
3442 }
3443
3444 // Skip alloca forms that this analysis can't handle.
3445 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003446 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003447 return false;
3448
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003449 bool Changed = false;
3450
3451 // First, split any FCA loads and stores touching this alloca to promote
3452 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003453 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003454 Changed |= AggRewriter.rewrite(AI);
3455
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003456 // Build the slices using a recursive instruction-visiting builder.
3457 AllocaSlices S(*DL, AI);
3458 DEBUG(S.print(dbgs()));
3459 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003460 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003461
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003462 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003463 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3464 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003465 DI != DE; ++DI) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003466 // Free up everything used by this instruction.
Chandler Carruth1583e992014-03-03 10:42:58 +00003467 for (Use &DeadOp : (*DI)->operands())
3468 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003469
3470 // Now replace the uses of this instruction.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003471 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003472
3473 // And mark it for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003474 DeadInsts.insert(*DI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003475 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003476 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003477 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3478 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003479 DO != DE; ++DO) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003480 clobberUse(**DO);
3481 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003482 }
3483
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003484 // No slices to split. Leave the dead alloca for a later pass to clean up.
3485 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003486 return Changed;
3487
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003488 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003489
3490 DEBUG(dbgs() << " Speculating PHIs\n");
3491 while (!SpeculatablePHIs.empty())
3492 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3493
3494 DEBUG(dbgs() << " Speculating Selects\n");
3495 while (!SpeculatableSelects.empty())
3496 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3497
3498 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003499}
3500
Chandler Carruth19450da2012-09-14 10:26:38 +00003501/// \brief Delete the dead instructions accumulated in this run.
3502///
3503/// Recursively deletes the dead instructions we've accumulated. This is done
3504/// at the very end to maximize locality of the recursive delete and to
3505/// minimize the problems of invalidated instruction pointers as such pointers
3506/// are used heavily in the intermediate stages of the algorithm.
3507///
3508/// We also record the alloca instructions deleted here so that they aren't
3509/// subsequently handed to mem2reg to promote.
Craig Topper71b7b682014-08-21 05:55:13 +00003510void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003511 while (!DeadInsts.empty()) {
3512 Instruction *I = DeadInsts.pop_back_val();
3513 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3514
Chandler Carruth58d05562012-10-25 04:37:07 +00003515 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3516
Chandler Carruth1583e992014-03-03 10:42:58 +00003517 for (Use &Operand : I->operands())
3518 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003519 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00003520 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003521 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003522 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003523 }
3524
3525 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3526 DeletedAllocas.insert(AI);
3527
3528 ++NumDeleted;
3529 I->eraseFromParent();
3530 }
3531}
3532
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003533static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003534 SmallVectorImpl<Instruction *> &Worklist,
Craig Topper71b7b682014-08-21 05:55:13 +00003535 SmallPtrSetImpl<Instruction *> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003536 for (User *U : I.users())
3537 if (Visited.insert(cast<Instruction>(U)))
3538 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003539}
3540
Chandler Carruth70b44c52012-09-15 11:43:14 +00003541/// \brief Promote the allocas, using the best available technique.
3542///
3543/// This attempts to promote whatever allocas have been identified as viable in
3544/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3545/// If there is a domtree available, we attempt to promote using the full power
3546/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3547/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003548/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003549bool SROA::promoteAllocas(Function &F) {
3550 if (PromotableAllocas.empty())
3551 return false;
3552
3553 NumPromoted += PromotableAllocas.size();
3554
3555 if (DT && !ForceSSAUpdater) {
3556 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Hal Finkel60db0582014-09-07 18:57:58 +00003557 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003558 PromotableAllocas.clear();
3559 return true;
3560 }
3561
3562 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3563 SSAUpdater SSA;
3564 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003565 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003566
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003567 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003568 SmallVector<Instruction *, 8> Worklist;
3569 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003570 SmallVector<Instruction *, 32> DeadInsts;
3571
Chandler Carruth70b44c52012-09-15 11:43:14 +00003572 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3573 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003574 Insts.clear();
3575 Worklist.clear();
3576 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003577
Chandler Carruth45b136f2013-08-11 01:03:18 +00003578 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003579
Chandler Carruth45b136f2013-08-11 01:03:18 +00003580 while (!Worklist.empty()) {
3581 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003582
Chandler Carruth70b44c52012-09-15 11:43:14 +00003583 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3584 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3585 // leading to them) here. Eventually it should use them to optimize the
3586 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003587 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003588 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3589 II->getIntrinsicID() == Intrinsic::lifetime_end);
3590 II->eraseFromParent();
3591 continue;
3592 }
3593
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003594 // Push the loads and stores we find onto the list. SROA will already
3595 // have validated that all loads and stores are viable candidates for
3596 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003597 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003598 assert(LI->getType() == AI->getAllocatedType());
3599 Insts.push_back(LI);
3600 continue;
3601 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003602 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003603 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3604 Insts.push_back(SI);
3605 continue;
3606 }
3607
3608 // For everything else, we know that only no-op bitcasts and GEPs will
3609 // make it this far, just recurse through them and recall them for later
3610 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003611 DeadInsts.push_back(I);
3612 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003613 }
3614 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003615 while (!DeadInsts.empty())
3616 DeadInsts.pop_back_val()->eraseFromParent();
3617 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003618 }
3619
3620 PromotableAllocas.clear();
3621 return true;
3622}
3623
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003624bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003625 if (skipOptnoneFunction(F))
3626 return false;
3627
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003628 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3629 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003630 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3631 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003632 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3633 return false;
3634 }
Rafael Espindola93512512014-02-25 17:30:31 +00003635 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003636 DominatorTreeWrapperPass *DTWP =
3637 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003638 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +00003639 AT = &getAnalysis<AssumptionTracker>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003640
3641 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003642 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003643 I != E; ++I)
3644 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3645 Worklist.insert(AI);
3646
3647 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003648 // A set of deleted alloca instruction pointers which should be removed from
3649 // the list of promotable allocas.
3650 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3651
Chandler Carruthac8317f2012-10-04 12:33:50 +00003652 do {
3653 while (!Worklist.empty()) {
3654 Changed |= runOnAlloca(*Worklist.pop_back_val());
3655 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003656
Chandler Carruthac8317f2012-10-04 12:33:50 +00003657 // Remove the deleted allocas from various lists so that we don't try to
3658 // continue processing them.
3659 if (!DeletedAllocas.empty()) {
Chandler Carruthd031fe92014-03-03 19:28:52 +00003660 auto IsInSet = [&](AllocaInst *AI) {
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003661 return DeletedAllocas.count(AI);
3662 };
3663 Worklist.remove_if(IsInSet);
3664 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003665 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3666 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003667 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00003668 PromotableAllocas.end());
3669 DeletedAllocas.clear();
3670 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003671 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003672
Chandler Carruthac8317f2012-10-04 12:33:50 +00003673 Changed |= promoteAllocas(F);
3674
3675 Worklist = PostPromotionWorklist;
3676 PostPromotionWorklist.clear();
3677 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003678
3679 return Changed;
3680}
3681
3682void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel60db0582014-09-07 18:57:58 +00003683 AU.addRequired<AssumptionTracker>();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003684 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003685 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003686 AU.setPreservesCFG();
3687}