blob: 04bf4f8dfc3ad37f658fb102f02efee623063293 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000032#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000035#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000037#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000039#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Function.h"
41#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000042#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000047#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000048#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000049#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000053#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000058
59#if __cplusplus >= 201103L && !defined(NDEBUG)
60// We only use this for a debug check in C++11
61#include <random>
62#endif
63
Chandler Carruth1b398ae2012-09-14 09:22:59 +000064using namespace llvm;
65
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "sroa"
67
Chandler Carruth1b398ae2012-09-14 09:22:59 +000068STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000069STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000070STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
71STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
72STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000073STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
74STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000076STATISTIC(NumDeleted, "Number of instructions deleted");
77STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078
Chandler Carruth70b44c52012-09-15 11:43:14 +000079/// Hidden option to force the pass to not use DomTree and mem2reg, instead
80/// forming SSA values through the SSAUpdater infrastructure.
81static cl::opt<bool>
82ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
83
Chandler Carruth83cee772014-02-25 03:59:29 +000084/// Hidden option to enable randomly shuffling the slices to help uncover
85/// instability in their order.
86static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
87 cl::init(false), cl::Hidden);
88
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000089/// Hidden option to experiment with completely strict handling of inbounds
90/// GEPs.
91static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
92 cl::init(false), cl::Hidden);
93
Chandler Carruth1b398ae2012-09-14 09:22:59 +000094namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000095/// \brief A custom IRBuilder inserter which prefixes all names if they are
96/// preserved.
97template <bool preserveNames = true>
98class IRBuilderPrefixedInserter :
99 public IRBuilderDefaultInserter<preserveNames> {
100 std::string Prefix;
101
102public:
103 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
104
105protected:
106 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
107 BasicBlock::iterator InsertPt) const {
108 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
109 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
110 }
111};
112
113// Specialization for not preserving the name is trivial.
114template <>
115class IRBuilderPrefixedInserter<false> :
116 public IRBuilderDefaultInserter<false> {
117public:
118 void SetNamePrefix(const Twine &P) {}
119};
120
Chandler Carruthd177f862013-03-20 07:30:36 +0000121/// \brief Provide a typedef for IRBuilder that drops names in release builds.
122#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000123typedef llvm::IRBuilder<true, ConstantFolder,
124 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000125#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000126typedef llvm::IRBuilder<false, ConstantFolder,
127 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000128#endif
129}
130
131namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000132/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000133///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000134/// This structure represents a slice of an alloca used by some instruction. It
135/// stores both the begin and end offsets of this use, a pointer to the use
136/// itself, and a flag indicating whether we can classify the use as splittable
137/// or not when forming partitions of the alloca.
138class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000139 /// \brief The beginning offset of the range.
140 uint64_t BeginOffset;
141
142 /// \brief The ending offset, not included in the range.
143 uint64_t EndOffset;
144
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000145 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000146 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000147 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000148
149public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000150 Slice() : BeginOffset(), EndOffset() {}
151 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000152 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000153 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000154
155 uint64_t beginOffset() const { return BeginOffset; }
156 uint64_t endOffset() const { return EndOffset; }
157
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000158 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
159 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000160
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000161 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000162
Craig Topperf40110f2014-04-25 05:29:35 +0000163 bool isDead() const { return getUse() == nullptr; }
164 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000165
166 /// \brief Support for ordering ranges.
167 ///
168 /// This provides an ordering over ranges such that start offsets are
169 /// always increasing, and within equal start offsets, the end offsets are
170 /// decreasing. Thus the spanning range comes first in a cluster with the
171 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 if (beginOffset() < RHS.beginOffset()) return true;
174 if (beginOffset() > RHS.beginOffset()) return false;
175 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
176 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000177 return false;
178 }
179
180 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000181 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000182 uint64_t RHSOffset) {
183 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000184 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000185 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000186 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000187 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000188 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000189
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000190 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000191 return isSplittable() == RHS.isSplittable() &&
192 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000193 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000194 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000195};
Chandler Carruthf0546402013-07-18 07:15:00 +0000196} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000197
198namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000199template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000200template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000201 static const bool value = true;
202};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000203}
204
205namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000207///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000208/// This class represents the slices of an alloca which are formed by its
209/// various uses. If a pointer escapes, we can't fully build a representation
210/// for the slices used and we reflect that in this structure. The uses are
211/// stored, sorted by increasing beginning offset and with unsplittable slices
212/// starting at a particular offset before splittable slices.
213class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000214public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000215 /// \brief Construct the slices of a particular alloca.
216 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217
218 /// \brief Test whether a pointer to the allocation escapes our analysis.
219 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000220 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000221 /// ignored.
222 bool isEscaped() const { return PointerEscapingInstr; }
223
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000224 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000225 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000226 typedef SmallVectorImpl<Slice>::iterator iterator;
227 iterator begin() { return Slices.begin(); }
228 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000229
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000230 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
231 const_iterator begin() const { return Slices.begin(); }
232 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000233 /// @}
234
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000235 /// \brief Allow iterating the dead users for this alloca.
236 ///
237 /// These are instructions which will never actually use the alloca as they
238 /// are outside the allocated range. They are safe to replace with undef and
239 /// delete.
240 /// @{
241 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
242 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
243 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
244 /// @}
245
Chandler Carruth93a21e72012-09-14 10:18:49 +0000246 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000247 ///
248 /// These are operands which have cannot actually be used to refer to the
249 /// alloca as they are outside its range and the user doesn't correct for
250 /// that. These mostly consist of PHI node inputs and the like which we just
251 /// need to replace with undef.
252 /// @{
253 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
254 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
255 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
256 /// @}
257
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000258#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000259 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000260 void printSlice(raw_ostream &OS, const_iterator I,
261 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000262 void printUse(raw_ostream &OS, const_iterator I,
263 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000264 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000265 void dump(const_iterator I) const;
266 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000267#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000268
269private:
270 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000271 class SliceBuilder;
272 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000273
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000274#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000275 /// \brief Handle to alloca instruction to simplify method interfaces.
276 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000277#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000278
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000279 /// \brief The instruction responsible for this alloca not having a known set
280 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000281 ///
282 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000283 /// store a pointer to that here and abort trying to form slices of the
284 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000285 Instruction *PointerEscapingInstr;
286
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000287 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000289 /// We store a vector of the slices formed by uses of the alloca here. This
290 /// vector is sorted by increasing begin offset, and then the unsplittable
291 /// slices before the splittable ones. See the Slice inner class for more
292 /// details.
293 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000294
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 /// \brief Instructions which will become dead if we rewrite the alloca.
296 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000297 /// Note that these are not separated by slice. This is because we expect an
298 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
299 /// all these instructions can simply be removed and replaced with undef as
300 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000301 SmallVector<Instruction *, 8> DeadUsers;
302
303 /// \brief Operands which will become dead if we rewrite the alloca.
304 ///
305 /// These are operands that in their particular use can be replaced with
306 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
307 /// to PHI nodes and the like. They aren't entirely dead (there might be
308 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
309 /// want to swap this particular input for undef to simplify the use lists of
310 /// the alloca.
311 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000312};
313}
314
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000315static Value *foldSelectInst(SelectInst &SI) {
316 // If the condition being selected on is a constant or the same value is
317 // being selected between, fold the select. Yes this does (rarely) happen
318 // early on.
319 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
320 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000321 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000322 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000323
Craig Topperf40110f2014-04-25 05:29:35 +0000324 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000325}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000327/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000328///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329/// This class builds a set of alloca slices by recursively visiting the uses
330/// of an alloca and making a slice for each load and store at each offset.
331class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
332 friend class PtrUseVisitor<SliceBuilder>;
333 friend class InstVisitor<SliceBuilder>;
334 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000335
336 const uint64_t AllocSize;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000337 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000338
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000339 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000340 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
341
342 /// \brief Set to de-duplicate dead instructions found in the use walk.
343 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000344
345public:
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000346 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000347 : PtrUseVisitor<SliceBuilder>(DL),
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000348 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000349
350private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000351 void markAsDead(Instruction &I) {
352 if (VisitedDeadInsts.insert(&I))
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000353 S.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000354 }
355
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000356 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000357 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000358 // Completely skip uses which have a zero size or start either before or
359 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000360 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000361 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000362 << " which has zero size or starts outside of the "
363 << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000364 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000365 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000366 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000367 }
368
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000369 uint64_t BeginOffset = Offset.getZExtValue();
370 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000371
372 // Clamp the end offset to the end of the allocation. Note that this is
373 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000374 // This may appear superficially to be something we could ignore entirely,
375 // but that is not so! There may be widened loads or PHI-node uses where
376 // some instructions are dead but not others. We can't completely ignore
377 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000378 assert(AllocSize >= BeginOffset); // Established above.
379 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000380 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
381 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000382 << " alloca: " << S.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000383 << " use: " << I << "\n");
384 EndOffset = AllocSize;
385 }
386
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000387 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000388 }
389
390 void visitBitCastInst(BitCastInst &BC) {
391 if (BC.use_empty())
392 return markAsDead(BC);
393
394 return Base::visitBitCastInst(BC);
395 }
396
397 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
398 if (GEPI.use_empty())
399 return markAsDead(GEPI);
400
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000401 if (SROAStrictInbounds && GEPI.isInBounds()) {
402 // FIXME: This is a manually un-factored variant of the basic code inside
403 // of GEPs with checking of the inbounds invariant specified in the
404 // langref in a very strict sense. If we ever want to enable
405 // SROAStrictInbounds, this code should be factored cleanly into
406 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
407 // by writing out the code here where we have tho underlying allocation
408 // size readily available.
409 APInt GEPOffset = Offset;
410 for (gep_type_iterator GTI = gep_type_begin(GEPI),
411 GTE = gep_type_end(GEPI);
412 GTI != GTE; ++GTI) {
413 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
414 if (!OpC)
415 break;
416
417 // Handle a struct index, which adds its field offset to the pointer.
418 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
419 unsigned ElementIdx = OpC->getZExtValue();
420 const StructLayout *SL = DL.getStructLayout(STy);
421 GEPOffset +=
422 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
423 } else {
424 // For array or vector indices, scale the index by the size of the type.
425 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
426 GEPOffset += Index * APInt(Offset.getBitWidth(),
427 DL.getTypeAllocSize(GTI.getIndexedType()));
428 }
429
430 // If this index has computed an intermediate pointer which is not
431 // inbounds, then the result of the GEP is a poison value and we can
432 // delete it and all uses.
433 if (GEPOffset.ugt(AllocSize))
434 return markAsDead(GEPI);
435 }
436 }
437
Chandler Carruthf0546402013-07-18 07:15:00 +0000438 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000439 }
440
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000441 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000442 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000443 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000444 // and cover the entire alloca. This prevents us from splitting over
445 // eagerly.
446 // FIXME: In the great blue eventually, we should eagerly split all integer
447 // loads and stores, and then have a separate step that merges adjacent
448 // alloca partitions into a single partition suitable for integer widening.
449 // Or we should skip the merge step and rely on GVN and other passes to
450 // merge adjacent loads and stores that survive mem2reg.
451 bool IsSplittable =
452 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000453
454 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000455 }
456
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000457 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000458 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
459 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000460
461 if (!IsOffsetKnown)
462 return PI.setAborted(&LI);
463
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000464 uint64_t Size = DL.getTypeStoreSize(LI.getType());
465 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000466 }
467
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000468 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000469 Value *ValOp = SI.getValueOperand();
470 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000471 return PI.setEscapedAndAborted(&SI);
472 if (!IsOffsetKnown)
473 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000474
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000475 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
476
477 // If this memory access can be shown to *statically* extend outside the
478 // bounds of of the allocation, it's behavior is undefined, so simply
479 // ignore it. Note that this is more strict than the generic clamping
480 // behavior of insertUse. We also try to handle cases which might run the
481 // risk of overflow.
482 // FIXME: We should instead consider the pointer to have escaped if this
483 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000484 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000485 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
486 << " which extends past the end of the " << AllocSize
487 << " byte alloca:\n"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000488 << " alloca: " << S.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000489 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000490 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000491 }
492
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000493 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
494 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000495 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000496 }
497
498
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000499 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000500 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000501 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000502 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000503 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000504 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000505 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000506
507 if (!IsOffsetKnown)
508 return PI.setAborted(&II);
509
510 insertUse(II, Offset,
511 Length ? Length->getLimitedValue()
512 : AllocSize - Offset.getLimitedValue(),
513 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000514 }
515
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000516 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000517 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000518 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000519 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000520 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000521
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000522 // Because we can visit these intrinsics twice, also check to see if the
523 // first time marked this instruction as dead. If so, skip it.
524 if (VisitedDeadInsts.count(&II))
525 return;
526
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000527 if (!IsOffsetKnown)
528 return PI.setAborted(&II);
529
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000530 // This side of the transfer is completely out-of-bounds, and so we can
531 // nuke the entire transfer. However, we also need to nuke the other side
532 // if already added to our partitions.
533 // FIXME: Yet another place we really should bypass this when
534 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000535 if (Offset.uge(AllocSize)) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000536 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
537 if (MTPI != MemTransferSliceMap.end())
538 S.Slices[MTPI->second].kill();
539 return markAsDead(II);
540 }
541
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000542 uint64_t RawOffset = Offset.getLimitedValue();
543 uint64_t Size = Length ? Length->getLimitedValue()
544 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000545
Chandler Carruthf0546402013-07-18 07:15:00 +0000546 // Check for the special case where the same exact value is used for both
547 // source and dest.
548 if (*U == II.getRawDest() && *U == II.getRawSource()) {
549 // For non-volatile transfers this is a no-op.
550 if (!II.isVolatile())
551 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000552
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000553 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000554 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000555
Chandler Carruthf0546402013-07-18 07:15:00 +0000556 // If we have seen both source and destination for a mem transfer, then
557 // they both point to the same alloca.
558 bool Inserted;
559 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000560 std::tie(MTPI, Inserted) =
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000561 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000562 unsigned PrevIdx = MTPI->second;
563 if (!Inserted) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000564 Slice &PrevP = S.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000565
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000566 // Check if the begin offsets match and this is a non-volatile transfer.
567 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000568 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
569 PrevP.kill();
570 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000571 }
572
573 // Otherwise we have an offset transfer within the same alloca. We can't
574 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000575 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000576 }
577
Chandler Carruthe3899f22013-07-15 17:36:21 +0000578 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000579 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000580
Chandler Carruthf0546402013-07-18 07:15:00 +0000581 // Check that we ended up with a valid index in the map.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000582 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
583 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000584 }
585
586 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000587 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000588 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000589 void visitIntrinsicInst(IntrinsicInst &II) {
590 if (!IsOffsetKnown)
591 return PI.setAborted(&II);
592
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000593 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
594 II.getIntrinsicID() == Intrinsic::lifetime_end) {
595 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000596 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
597 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000598 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000599 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000600 }
601
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000602 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603 }
604
605 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
606 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000607 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000608 // are considered unsplittable and the size is the maximum loaded or stored
609 // size.
610 SmallPtrSet<Instruction *, 4> Visited;
611 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
612 Visited.insert(Root);
613 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000614 // If there are no loads or stores, the access is dead. We mark that as
615 // a size zero access.
616 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000617 do {
618 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000619 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000620
621 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000622 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000623 continue;
624 }
625 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
626 Value *Op = SI->getOperand(0);
627 if (Op == UsedI)
628 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000630 continue;
631 }
632
633 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
634 if (!GEP->hasAllZeroIndices())
635 return GEP;
636 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
637 !isa<SelectInst>(I)) {
638 return I;
639 }
640
Chandler Carruthcdf47882014-03-09 03:16:01 +0000641 for (User *U : I->users())
642 if (Visited.insert(cast<Instruction>(U)))
643 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000644 } while (!Uses.empty());
645
Craig Topperf40110f2014-04-25 05:29:35 +0000646 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000647 }
648
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000649 void visitPHINode(PHINode &PN) {
650 if (PN.use_empty())
Chandler Carruthf0546402013-07-18 07:15:00 +0000651 return markAsDead(PN);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000652 if (!IsOffsetKnown)
653 return PI.setAborted(&PN);
654
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000655 // See if we already have computed info on this node.
Chandler Carruthf0546402013-07-18 07:15:00 +0000656 uint64_t &PHISize = PHIOrSelectSizes[&PN];
657 if (!PHISize) {
658 // This is a new PHI node, check for an unsafe use of the PHI node.
659 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
660 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661 }
662
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000663 // For PHI and select operands outside the alloca, we can't nuke the entire
664 // phi or select -- the other side might still be relevant, so we special
665 // case them here and use a separate structure to track the operands
666 // themselves which should be replaced with undef.
Chandler Carruthf0546402013-07-18 07:15:00 +0000667 // FIXME: This should instead be escaped in the event we're instrumenting
668 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000669 if (Offset.uge(AllocSize)) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000670 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000671 return;
672 }
673
Chandler Carruthf0546402013-07-18 07:15:00 +0000674 insertUse(PN, Offset, PHISize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000675 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000676
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000677 void visitSelectInst(SelectInst &SI) {
678 if (SI.use_empty())
679 return markAsDead(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000680 if (Value *Result = foldSelectInst(SI)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000681 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000682 // If the result of the constant fold will be the pointer, recurse
683 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000684 enqueueUsers(SI);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000685 else
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000686 // Otherwise the operand to the select is dead, and we can replace it
687 // with undef.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000688 S.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000689
690 return;
691 }
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 if (!IsOffsetKnown)
693 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000694
Chandler Carruthf0546402013-07-18 07:15:00 +0000695 // See if we already have computed info on this node.
696 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
697 if (!SelectSize) {
698 // This is a new Select, check for an unsafe use of it.
699 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
700 return PI.setAborted(UnsafeI);
701 }
702
703 // For PHI and select operands outside the alloca, we can't nuke the entire
704 // phi or select -- the other side might still be relevant, so we special
705 // case them here and use a separate structure to track the operands
706 // themselves which should be replaced with undef.
707 // FIXME: This should instead be escaped in the event we're instrumenting
708 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000709 if (Offset.uge(AllocSize)) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000710 S.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000711 return;
712 }
713
714 insertUse(SI, Offset, SelectSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000715 }
716
Chandler Carruthf0546402013-07-18 07:15:00 +0000717 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000718 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000719 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000720 }
721};
722
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000723AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000724 :
725#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
726 AI(AI),
727#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000728 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000729 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000730 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000731 if (PtrI.isEscaped() || PtrI.isAborted()) {
732 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000733 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000734 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
735 : PtrI.getAbortingInst();
736 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000737 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000738 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000739
Benjamin Kramer08e50702013-07-20 08:38:34 +0000740 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
741 std::mem_fun_ref(&Slice::isDead)),
742 Slices.end());
743
Chandler Carruth83cee772014-02-25 03:59:29 +0000744#if __cplusplus >= 201103L && !defined(NDEBUG)
745 if (SROARandomShuffleSlices) {
746 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
747 std::shuffle(Slices.begin(), Slices.end(), MT);
748 }
749#endif
750
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000751 // Sort the uses. This arranges for the offsets to be in ascending order,
752 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000753 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000754}
755
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000756#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
757
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000758void AllocaSlices::print(raw_ostream &OS, const_iterator I,
759 StringRef Indent) const {
760 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000761 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000762}
763
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000764void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
765 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000766 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000767 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000768 << (I->isSplittable() ? " (splittable)" : "") << "\n";
769}
770
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000771void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
772 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000773 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000774}
775
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000776void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000778 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000779 << " A pointer to this alloca escaped by:\n"
780 << " " << *PointerEscapingInstr << "\n";
781 return;
782 }
783
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000784 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000785 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000786 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787}
788
Alp Tokerf929e092014-01-04 22:47:48 +0000789LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
790 print(dbgs(), I);
791}
792LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000793
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000794#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
795
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000796namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000797/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
798///
799/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
800/// the loads and stores of an alloca instruction, as well as updating its
801/// debug information. This is used when a domtree is unavailable and thus
802/// mem2reg in its full form can't be used to handle promotion of allocas to
803/// scalar values.
804class AllocaPromoter : public LoadAndStorePromoter {
805 AllocaInst &AI;
806 DIBuilder &DIB;
807
808 SmallVector<DbgDeclareInst *, 4> DDIs;
809 SmallVector<DbgValueInst *, 4> DVIs;
810
811public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000812 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000813 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000814 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000815
816 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000817 // Retain the debug information attached to the alloca for use when
818 // rewriting loads and stores.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000819 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000820 for (User *U : DebugNode->users())
821 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000822 DDIs.push_back(DDI);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000823 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000824 DVIs.push_back(DVI);
825 }
826
827 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000828
829 // While we have the debug information, clear it off of the alloca. The
830 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000831 while (!DDIs.empty())
832 DDIs.pop_back_val()->eraseFromParent();
833 while (!DVIs.empty())
834 DVIs.pop_back_val()->eraseFromParent();
835 }
836
Craig Topper3e4c6972014-03-05 09:10:37 +0000837 bool isInstInList(Instruction *I,
838 const SmallVectorImpl<Instruction*> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000839 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000840 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000841 Ptr = LI->getOperand(0);
842 else
843 Ptr = cast<StoreInst>(I)->getPointerOperand();
844
845 // Only used to detect cycles, which will be rare and quickly found as
846 // we're walking up a chain of defs rather than down through uses.
847 SmallPtrSet<Value *, 4> Visited;
848
849 do {
850 if (Ptr == &AI)
851 return true;
852
853 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
854 Ptr = BCI->getOperand(0);
855 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
856 Ptr = GEPI->getPointerOperand();
857 else
858 return false;
859
860 } while (Visited.insert(Ptr));
861
862 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000863 }
864
Craig Topper3e4c6972014-03-05 09:10:37 +0000865 void updateDebugInfo(Instruction *Inst) const override {
Craig Topper31ee5862013-07-03 15:07:05 +0000866 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000867 E = DDIs.end(); I != E; ++I) {
868 DbgDeclareInst *DDI = *I;
869 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
870 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
871 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
872 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
873 }
Craig Topper31ee5862013-07-03 15:07:05 +0000874 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +0000875 E = DVIs.end(); I != E; ++I) {
876 DbgValueInst *DVI = *I;
Craig Topperf40110f2014-04-25 05:29:35 +0000877 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000878 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
879 // If an argument is zero extended then use argument directly. The ZExt
880 // may be zapped by an optimization pass in future.
881 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
882 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000883 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000884 Arg = dyn_cast<Argument>(SExt->getOperand(0));
885 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000886 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000887 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000888 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000889 } else {
890 continue;
891 }
892 Instruction *DbgVal =
893 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
894 Inst);
895 DbgVal->setDebugLoc(DVI->getDebugLoc());
896 }
897 }
898};
899} // end anon namespace
900
901
902namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000903/// \brief An optimization pass providing Scalar Replacement of Aggregates.
904///
905/// This pass takes allocations which can be completely analyzed (that is, they
906/// don't escape) and tries to turn them into scalar SSA values. There are
907/// a few steps to this process.
908///
909/// 1) It takes allocations of aggregates and analyzes the ways in which they
910/// are used to try to split them into smaller allocations, ideally of
911/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000912/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000913/// 2) It will transform accesses into forms which are suitable for SSA value
914/// promotion. This can be replacing a memset with a scalar store of an
915/// integer value, or it can involve speculating operations on a PHI or
916/// select to be a PHI or select of the results.
917/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
918/// onto insert and extract operations on a vector value, and convert them to
919/// this form. By doing so, it will enable promotion of vector aggregates to
920/// SSA vector values.
921class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000922 const bool RequiresDomTree;
923
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000924 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000925 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000926 DominatorTree *DT;
927
928 /// \brief Worklist of alloca instructions to simplify.
929 ///
930 /// Each alloca in the function is added to this. Each new alloca formed gets
931 /// added to it as well to recursively simplify unless that alloca can be
932 /// directly promoted. Finally, each time we rewrite a use of an alloca other
933 /// the one being actively rewritten, we add it back onto the list if not
934 /// already present to ensure it is re-visited.
935 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
936
937 /// \brief A collection of instructions to delete.
938 /// We try to batch deletions to simplify code and make things a bit more
939 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000940 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000941
Chandler Carruthac8317f2012-10-04 12:33:50 +0000942 /// \brief Post-promotion worklist.
943 ///
944 /// Sometimes we discover an alloca which has a high probability of becoming
945 /// viable for SROA after a round of promotion takes place. In those cases,
946 /// the alloca is enqueued here for re-processing.
947 ///
948 /// Note that we have to be very careful to clear allocas out of this list in
949 /// the event they are deleted.
950 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
951
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000952 /// \brief A collection of alloca instructions we can directly promote.
953 std::vector<AllocaInst *> PromotableAllocas;
954
Chandler Carruthf0546402013-07-18 07:15:00 +0000955 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
956 ///
957 /// All of these PHIs have been checked for the safety of speculation and by
958 /// being speculated will allow promoting allocas currently in the promotable
959 /// queue.
960 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
961
962 /// \brief A worklist of select instructions to speculate prior to promoting
963 /// allocas.
964 ///
965 /// All of these select instructions have been checked for the safety of
966 /// speculation and by being speculated will allow promoting allocas
967 /// currently in the promotable queue.
968 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
969
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000970public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000971 SROA(bool RequiresDomTree = true)
972 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Craig Topperf40110f2014-04-25 05:29:35 +0000973 C(nullptr), DL(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000974 initializeSROAPass(*PassRegistry::getPassRegistry());
975 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000976 bool runOnFunction(Function &F) override;
977 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000978
Craig Topper3e4c6972014-03-05 09:10:37 +0000979 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000980 static char ID;
981
982private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000983 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000984 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000985
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000986 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
987 AllocaSlices::iterator B, AllocaSlices::iterator E,
988 int64_t BeginOffset, int64_t EndOffset,
989 ArrayRef<AllocaSlices::iterator> SplitUses);
990 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000991 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000992 void clobberUse(Use &U);
Chandler Carruth19450da2012-09-14 10:26:38 +0000993 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000994 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000995};
996}
997
998char SROA::ID = 0;
999
Chandler Carruth70b44c52012-09-15 11:43:14 +00001000FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1001 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001002}
1003
1004INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1005 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +00001006INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001007INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1008 false, false)
1009
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001010/// Walk the range of a partitioning looking for a common type to cover this
1011/// sequence of slices.
1012static Type *findCommonType(AllocaSlices::const_iterator B,
1013 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001014 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001015 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001016 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001017 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001018
1019 // Note that we need to look at *every* alloca slice's Use to ensure we
1020 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001021 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001022 Use *U = I->getUse();
1023 if (isa<IntrinsicInst>(*U->getUser()))
1024 continue;
1025 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1026 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001027
Craig Topperf40110f2014-04-25 05:29:35 +00001028 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001029 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001030 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001031 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001033 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001034
Chandler Carruth4de31542014-01-21 23:16:05 +00001035 if (!UserTy || (Ty && Ty != UserTy))
1036 TyIsCommon = false; // Give up on anything but an iN type.
1037 else
1038 Ty = UserTy;
1039
1040 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001041 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001042 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001043 // entity causing the split. Also skip if the type is not a byte width
1044 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001045 if (UserITy->getBitWidth() % 8 != 0 ||
1046 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001047 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001048
Chandler Carruth4de31542014-01-21 23:16:05 +00001049 // Track the largest bitwidth integer type used in this way in case there
1050 // is no common type.
1051 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1052 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001053 }
1054 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001055
1056 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001057}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001058
Chandler Carruthf0546402013-07-18 07:15:00 +00001059/// PHI instructions that use an alloca and are subsequently loaded can be
1060/// rewritten to load both input pointers in the pred blocks and then PHI the
1061/// results, allowing the load of the alloca to be promoted.
1062/// From this:
1063/// %P2 = phi [i32* %Alloca, i32* %Other]
1064/// %V = load i32* %P2
1065/// to:
1066/// %V1 = load i32* %Alloca -> will be mem2reg'd
1067/// ...
1068/// %V2 = load i32* %Other
1069/// ...
1070/// %V = phi [i32 %V1, i32 %V2]
1071///
1072/// We can do this to a select if its only uses are loads and if the operands
1073/// to the select can be loaded unconditionally.
1074///
1075/// FIXME: This should be hoisted into a generic utility, likely in
1076/// Transforms/Util/Local.h
1077static bool isSafePHIToSpeculate(PHINode &PN,
Craig Topperf40110f2014-04-25 05:29:35 +00001078 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001079 // For now, we can only do this promotion if the load is in the same block
1080 // as the PHI, and if there are no stores between the phi and load.
1081 // TODO: Allow recursive phi users.
1082 // TODO: Allow stores.
1083 BasicBlock *BB = PN.getParent();
1084 unsigned MaxAlign = 0;
1085 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001086 for (User *U : PN.users()) {
1087 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001088 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001089 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001090
Chandler Carruthf0546402013-07-18 07:15:00 +00001091 // For now we only allow loads in the same block as the PHI. This is
1092 // a common case that happens when instcombine merges two loads through
1093 // a PHI.
1094 if (LI->getParent() != BB)
1095 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001096
Chandler Carruthf0546402013-07-18 07:15:00 +00001097 // Ensure that there are no instructions between the PHI and the load that
1098 // could store.
1099 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1100 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001101 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001102
Chandler Carruthf0546402013-07-18 07:15:00 +00001103 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1104 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001105 }
1106
Chandler Carruthf0546402013-07-18 07:15:00 +00001107 if (!HaveLoad)
1108 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001109
Chandler Carruthf0546402013-07-18 07:15:00 +00001110 // We can only transform this if it is safe to push the loads into the
1111 // predecessor blocks. The only thing to watch out for is that we can't put
1112 // a possibly trapping load in the predecessor if it is a critical edge.
1113 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1114 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1115 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001116
Chandler Carruthf0546402013-07-18 07:15:00 +00001117 // If the value is produced by the terminator of the predecessor (an
1118 // invoke) or it has side-effects, there is no valid place to put a load
1119 // in the predecessor.
1120 if (TI == InVal || TI->mayHaveSideEffects())
1121 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001122
Chandler Carruthf0546402013-07-18 07:15:00 +00001123 // If the predecessor has a single successor, then the edge isn't
1124 // critical.
1125 if (TI->getNumSuccessors() == 1)
1126 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001127
Chandler Carruthf0546402013-07-18 07:15:00 +00001128 // If this pointer is always safe to load, or if we can prove that there
1129 // is already a load in the block, then we can move the load to the pred
1130 // block.
1131 if (InVal->isDereferenceablePointer() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001132 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001133 continue;
1134
1135 return false;
1136 }
1137
1138 return true;
1139}
1140
1141static void speculatePHINodeLoads(PHINode &PN) {
1142 DEBUG(dbgs() << " original: " << PN << "\n");
1143
1144 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1145 IRBuilderTy PHIBuilder(&PN);
1146 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1147 PN.getName() + ".sroa.speculated");
1148
1149 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1150 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001151 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001152 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1153 unsigned Align = SomeLoad->getAlignment();
1154
1155 // Rewrite all loads of the PN to use the new PHI.
1156 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001157 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001158 LI->replaceAllUsesWith(NewPN);
1159 LI->eraseFromParent();
1160 }
1161
1162 // Inject loads into all of the pred blocks.
1163 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1164 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1165 TerminatorInst *TI = Pred->getTerminator();
1166 Value *InVal = PN.getIncomingValue(Idx);
1167 IRBuilderTy PredBuilder(TI);
1168
1169 LoadInst *Load = PredBuilder.CreateLoad(
1170 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1171 ++NumLoadsSpeculated;
1172 Load->setAlignment(Align);
1173 if (TBAATag)
1174 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1175 NewPN->addIncoming(Load, Pred);
1176 }
1177
1178 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1179 PN.eraseFromParent();
1180}
1181
1182/// Select instructions that use an alloca and are subsequently loaded can be
1183/// rewritten to load both input pointers and then select between the result,
1184/// allowing the load of the alloca to be promoted.
1185/// From this:
1186/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1187/// %V = load i32* %P2
1188/// to:
1189/// %V1 = load i32* %Alloca -> will be mem2reg'd
1190/// %V2 = load i32* %Other
1191/// %V = select i1 %cond, i32 %V1, i32 %V2
1192///
1193/// We can do this to a select if its only uses are loads and if the operand
1194/// to the select can be loaded unconditionally.
Craig Topperf40110f2014-04-25 05:29:35 +00001195static bool isSafeSelectToSpeculate(SelectInst &SI,
1196 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001197 Value *TValue = SI.getTrueValue();
1198 Value *FValue = SI.getFalseValue();
1199 bool TDerefable = TValue->isDereferenceablePointer();
1200 bool FDerefable = FValue->isDereferenceablePointer();
1201
Chandler Carruthcdf47882014-03-09 03:16:01 +00001202 for (User *U : SI.users()) {
1203 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001204 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001205 return false;
1206
1207 // Both operands to the select need to be dereferencable, either
1208 // absolutely (e.g. allocas) or at this point because we can see other
1209 // accesses to it.
1210 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001211 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001212 return false;
1213 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001214 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001215 return false;
1216 }
1217
1218 return true;
1219}
1220
1221static void speculateSelectInstLoads(SelectInst &SI) {
1222 DEBUG(dbgs() << " original: " << SI << "\n");
1223
1224 IRBuilderTy IRB(&SI);
1225 Value *TV = SI.getTrueValue();
1226 Value *FV = SI.getFalseValue();
1227 // Replace the loads of the select with a select of two loads.
1228 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001229 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001230 assert(LI->isSimple() && "We only speculate simple loads");
1231
1232 IRB.SetInsertPoint(LI);
1233 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001234 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001235 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001236 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001237 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001238
Chandler Carruthf0546402013-07-18 07:15:00 +00001239 // Transfer alignment and TBAA info if present.
1240 TL->setAlignment(LI->getAlignment());
1241 FL->setAlignment(LI->getAlignment());
1242 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1243 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1244 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001245 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001246
1247 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1248 LI->getName() + ".sroa.speculated");
1249
1250 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1251 LI->replaceAllUsesWith(V);
1252 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001253 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001254 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001255}
1256
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001257/// \brief Build a GEP out of a base pointer and indices.
1258///
1259/// This will return the BasePtr if that is valid, or build a new GEP
1260/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001261static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001262 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001263 if (Indices.empty())
1264 return BasePtr;
1265
1266 // A single zero index is a no-op, so check for this and avoid building a GEP
1267 // in that case.
1268 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1269 return BasePtr;
1270
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001271 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001272}
1273
1274/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1275/// TargetTy without changing the offset of the pointer.
1276///
1277/// This routine assumes we've already established a properly offset GEP with
1278/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1279/// zero-indices down through type layers until we find one the same as
1280/// TargetTy. If we can't find one with the same type, we at least try to use
1281/// one with the same size. If none of that works, we just produce the GEP as
1282/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001283static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001284 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001285 SmallVectorImpl<Value *> &Indices,
1286 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001287 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001288 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001289
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001290 // Pointer size to use for the indices.
1291 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1292
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001293 // See if we can descend into a struct and locate a field with the correct
1294 // type.
1295 unsigned NumLayers = 0;
1296 Type *ElementTy = Ty;
1297 do {
1298 if (ElementTy->isPointerTy())
1299 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001300
1301 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1302 ElementTy = ArrayTy->getElementType();
1303 Indices.push_back(IRB.getIntN(PtrSize, 0));
1304 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1305 ElementTy = VectorTy->getElementType();
1306 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001307 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001308 if (STy->element_begin() == STy->element_end())
1309 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001310 ElementTy = *STy->element_begin();
1311 Indices.push_back(IRB.getInt32(0));
1312 } else {
1313 break;
1314 }
1315 ++NumLayers;
1316 } while (ElementTy != TargetTy);
1317 if (ElementTy != TargetTy)
1318 Indices.erase(Indices.end() - NumLayers, Indices.end());
1319
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001320 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001321}
1322
1323/// \brief Recursively compute indices for a natural GEP.
1324///
1325/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1326/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001327static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001328 Value *Ptr, Type *Ty, APInt &Offset,
1329 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001330 SmallVectorImpl<Value *> &Indices,
1331 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001332 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001333 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001334
1335 // We can't recurse through pointer types.
1336 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001337 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001338
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001339 // We try to analyze GEPs over vectors here, but note that these GEPs are
1340 // extremely poorly defined currently. The long-term goal is to remove GEPing
1341 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001342 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001343 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001344 if (ElementSizeInBits % 8 != 0) {
1345 // GEPs over non-multiple of 8 size vector elements are invalid.
1346 return nullptr;
1347 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001348 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001349 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001350 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001351 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001352 Offset -= NumSkippedElements * ElementSize;
1353 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001354 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001355 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001356 }
1357
1358 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1359 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001360 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001361 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001362 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001363 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001364
1365 Offset -= NumSkippedElements * ElementSize;
1366 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001367 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001368 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001369 }
1370
1371 StructType *STy = dyn_cast<StructType>(Ty);
1372 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001373 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001374
Chandler Carruth90a735d2013-07-19 07:21:28 +00001375 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001376 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001377 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001378 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001379 unsigned Index = SL->getElementContainingOffset(StructOffset);
1380 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1381 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001382 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001383 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001384
1385 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001386 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001387 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001388}
1389
1390/// \brief Get a natural GEP from a base pointer to a particular offset and
1391/// resulting in a particular type.
1392///
1393/// The goal is to produce a "natural" looking GEP that works with the existing
1394/// composite types to arrive at the appropriate offset and element type for
1395/// a pointer. TargetTy is the element type the returned GEP should point-to if
1396/// possible. We recurse by decreasing Offset, adding the appropriate index to
1397/// Indices, and setting Ty to the result subtype.
1398///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001399/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001400static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001401 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001402 SmallVectorImpl<Value *> &Indices,
1403 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001404 PointerType *Ty = cast<PointerType>(Ptr->getType());
1405
1406 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1407 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001408 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001409 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001410
1411 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001412 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001414 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001415 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001416 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001417 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001418
1419 Offset -= NumSkippedElements * ElementSize;
1420 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001421 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001422 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001423}
1424
1425/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1426/// resulting pointer has PointerTy.
1427///
1428/// This tries very hard to compute a "natural" GEP which arrives at the offset
1429/// and produces the pointer type desired. Where it cannot, it will try to use
1430/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1431/// fails, it will try to use an existing i8* and GEP to the byte offset and
1432/// bitcast to the type.
1433///
1434/// The strategy for finding the more natural GEPs is to peel off layers of the
1435/// pointer, walking back through bit casts and GEPs, searching for a base
1436/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001437/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001438/// a single GEP as possible, thus making each GEP more independent of the
1439/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001440static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1441 APInt Offset, Type *PointerTy,
1442 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001443 // Even though we don't look through PHI nodes, we could be called on an
1444 // instruction in an unreachable block, which may be on a cycle.
1445 SmallPtrSet<Value *, 4> Visited;
1446 Visited.insert(Ptr);
1447 SmallVector<Value *, 4> Indices;
1448
1449 // We may end up computing an offset pointer that has the wrong type. If we
1450 // never are able to compute one directly that has the correct type, we'll
1451 // fall back to it, so keep it around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001452 Value *OffsetPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001453
1454 // Remember any i8 pointer we come across to re-use if we need to do a raw
1455 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001456 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001457 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1458
1459 Type *TargetTy = PointerTy->getPointerElementType();
1460
1461 do {
1462 // First fold any existing GEPs into the offset.
1463 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1464 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001465 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001466 break;
1467 Offset += GEPOffset;
1468 Ptr = GEP->getPointerOperand();
1469 if (!Visited.insert(Ptr))
1470 break;
1471 }
1472
1473 // See if we can perform a natural GEP here.
1474 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001475 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001476 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001477 if (P->getType() == PointerTy) {
1478 // Zap any offset pointer that we ended up computing in previous rounds.
1479 if (OffsetPtr && OffsetPtr->use_empty())
1480 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1481 I->eraseFromParent();
1482 return P;
1483 }
1484 if (!OffsetPtr) {
1485 OffsetPtr = P;
1486 }
1487 }
1488
1489 // Stash this pointer if we've found an i8*.
1490 if (Ptr->getType()->isIntegerTy(8)) {
1491 Int8Ptr = Ptr;
1492 Int8PtrOffset = Offset;
1493 }
1494
1495 // Peel off a layer of the pointer and update the offset appropriately.
1496 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1497 Ptr = cast<Operator>(Ptr)->getOperand(0);
1498 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1499 if (GA->mayBeOverridden())
1500 break;
1501 Ptr = GA->getAliasee();
1502 } else {
1503 break;
1504 }
1505 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1506 } while (Visited.insert(Ptr));
1507
1508 if (!OffsetPtr) {
1509 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001510 Int8Ptr = IRB.CreateBitCast(
1511 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1512 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001513 Int8PtrOffset = Offset;
1514 }
1515
1516 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1517 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001518 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001519 }
1520 Ptr = OffsetPtr;
1521
1522 // On the off chance we were targeting i8*, guard the bitcast here.
1523 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001524 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001525
1526 return Ptr;
1527}
1528
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001529/// \brief Test whether we can convert a value from the old to the new type.
1530///
1531/// This predicate should be used to guard calls to convertValue in order to
1532/// ensure that we only try to convert viable values. The strategy is that we
1533/// will peel off single element struct and array wrappings to get to an
1534/// underlying value, and convert that value.
1535static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1536 if (OldTy == NewTy)
1537 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001538 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1539 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1540 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1541 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001542 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1543 return false;
1544 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1545 return false;
1546
Benjamin Kramer56262592013-09-22 11:24:58 +00001547 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001548 // of pointers and integers.
1549 OldTy = OldTy->getScalarType();
1550 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001551 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1552 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1553 return true;
1554 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1555 return true;
1556 return false;
1557 }
1558
1559 return true;
1560}
1561
1562/// \brief Generic routine to convert an SSA value to a value of a different
1563/// type.
1564///
1565/// This will try various different casting techniques, such as bitcasts,
1566/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1567/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001568static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001569 Type *NewTy) {
1570 Type *OldTy = V->getType();
1571 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1572
1573 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001574 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001575
1576 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1577 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001578 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1579 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001580
Benjamin Kramer90901a32013-09-21 20:36:04 +00001581 // See if we need inttoptr for this type pair. A cast involving both scalars
1582 // and vectors requires and additional bitcast.
1583 if (OldTy->getScalarType()->isIntegerTy() &&
1584 NewTy->getScalarType()->isPointerTy()) {
1585 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1586 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1587 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1588 NewTy);
1589
1590 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1591 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1592 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1593 NewTy);
1594
1595 return IRB.CreateIntToPtr(V, NewTy);
1596 }
1597
1598 // See if we need ptrtoint for this type pair. A cast involving both scalars
1599 // and vectors requires and additional bitcast.
1600 if (OldTy->getScalarType()->isPointerTy() &&
1601 NewTy->getScalarType()->isIntegerTy()) {
1602 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1603 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1604 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1605 NewTy);
1606
1607 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1608 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1609 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1610 NewTy);
1611
1612 return IRB.CreatePtrToInt(V, NewTy);
1613 }
1614
1615 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001616}
1617
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001618/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001619///
1620/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001621/// for a single slice.
1622static bool isVectorPromotionViableForSlice(
1623 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1624 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1625 AllocaSlices::const_iterator I) {
1626 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001627 uint64_t BeginOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001628 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001629 uint64_t BeginIndex = BeginOffset / ElementSize;
1630 if (BeginIndex * ElementSize != BeginOffset ||
1631 BeginIndex >= Ty->getNumElements())
1632 return false;
1633 uint64_t EndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001634 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001635 uint64_t EndIndex = EndOffset / ElementSize;
1636 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1637 return false;
1638
1639 assert(EndIndex > BeginIndex && "Empty vector!");
1640 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001641 Type *SliceTy =
Chandler Carruthf0546402013-07-18 07:15:00 +00001642 (NumElements == 1) ? Ty->getElementType()
1643 : VectorType::get(Ty->getElementType(), NumElements);
1644
1645 Type *SplitIntTy =
1646 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1647
1648 Use *U = I->getUse();
1649
1650 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1651 if (MI->isVolatile())
1652 return false;
1653 if (!I->isSplittable())
1654 return false; // Skip any unsplittable intrinsics.
1655 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1656 // Disable vector promotion when there are loads or stores of an FCA.
1657 return false;
1658 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1659 if (LI->isVolatile())
1660 return false;
1661 Type *LTy = LI->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001662 if (SliceBeginOffset > I->beginOffset() ||
1663 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001664 assert(LTy->isIntegerTy());
1665 LTy = SplitIntTy;
1666 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001667 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001668 return false;
1669 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1670 if (SI->isVolatile())
1671 return false;
1672 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001673 if (SliceBeginOffset > I->beginOffset() ||
1674 SliceEndOffset < I->endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001675 assert(STy->isIntegerTy());
1676 STy = SplitIntTy;
1677 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001678 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001679 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001680 } else {
1681 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001682 }
1683
1684 return true;
1685}
1686
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001687/// \brief Test whether the given alloca partitioning and range of slices can be
1688/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001689///
1690/// This is a quick test to check whether we can rewrite a particular alloca
1691/// partition (and its newly formed alloca) into a vector alloca with only
1692/// whole-vector loads and stores such that it could be promoted to a vector
1693/// SSA value. We only can ensure this for a limited set of operations, and we
1694/// don't want to do the rewrites unless we are confident that the result will
1695/// be promotable, so we have an early test here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001696static bool
1697isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1698 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1699 AllocaSlices::const_iterator I,
1700 AllocaSlices::const_iterator E,
1701 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001702 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1703 if (!Ty)
1704 return false;
1705
Chandler Carruth90a735d2013-07-19 07:21:28 +00001706 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001707
1708 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1709 // that aren't byte sized.
1710 if (ElementSize % 8)
1711 return false;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001712 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
Benjamin Kramerc003a452013-01-01 16:13:35 +00001713 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001714 ElementSize /= 8;
1715
Chandler Carruthf0546402013-07-18 07:15:00 +00001716 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001717 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1718 SliceEndOffset, Ty, ElementSize, I))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001719 return false;
1720
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001721 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1722 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001723 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001724 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1725 SliceEndOffset, Ty, ElementSize, *SUI))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001726 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001727
1728 return true;
1729}
1730
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001731/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001732///
1733/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001734/// test below on a single slice of the alloca.
1735static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1736 Type *AllocaTy,
1737 uint64_t AllocBeginOffset,
1738 uint64_t Size, AllocaSlices &S,
1739 AllocaSlices::const_iterator I,
1740 bool &WholeAllocaOp) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001741 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1742 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1743
1744 // We can't reasonably handle cases where the load or store extends past
1745 // the end of the aloca's type and into its padding.
1746 if (RelEnd > Size)
1747 return false;
1748
1749 Use *U = I->getUse();
1750
1751 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1752 if (LI->isVolatile())
1753 return false;
1754 if (RelBegin == 0 && RelEnd == Size)
1755 WholeAllocaOp = true;
1756 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001757 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001758 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001759 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001760 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001761 // Non-integer loads need to be convertible from the alloca type so that
1762 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001763 return false;
1764 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001765 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1766 Type *ValueTy = SI->getValueOperand()->getType();
1767 if (SI->isVolatile())
1768 return false;
1769 if (RelBegin == 0 && RelEnd == Size)
1770 WholeAllocaOp = true;
1771 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001772 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001773 return false;
1774 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001775 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001776 // Non-integer stores need to be convertible to the alloca type so that
1777 // they are promotable.
1778 return false;
1779 }
1780 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1781 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1782 return false;
1783 if (!I->isSplittable())
1784 return false; // Skip any unsplittable intrinsics.
1785 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1786 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1787 II->getIntrinsicID() != Intrinsic::lifetime_end)
1788 return false;
1789 } else {
1790 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001791 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001792
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001793 return true;
1794}
1795
Chandler Carruth435c4e02012-10-15 08:40:30 +00001796/// \brief Test whether the given alloca partition's integer operations can be
1797/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001798///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001799/// This is a quick test to check whether we can rewrite the integer loads and
1800/// stores to a particular alloca into wider loads and stores and be able to
1801/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001802static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001803isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001804 uint64_t AllocBeginOffset, AllocaSlices &S,
1805 AllocaSlices::const_iterator I,
1806 AllocaSlices::const_iterator E,
1807 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001808 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001809 // Don't create integer types larger than the maximum bitwidth.
1810 if (SizeInBits > IntegerType::MAX_INT_BITS)
1811 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001812
1813 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001814 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001815 return false;
1816
Chandler Carruth58d05562012-10-25 04:37:07 +00001817 // We need to ensure that an integer type with the appropriate bitwidth can
1818 // be converted to the alloca type, whatever that is. We don't want to force
1819 // the alloca itself to have an integer type if there is a more suitable one.
1820 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001821 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1822 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001823 return false;
1824
Chandler Carruth90a735d2013-07-19 07:21:28 +00001825 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001826
Chandler Carruthf0546402013-07-18 07:15:00 +00001827 // While examining uses, we ensure that the alloca has a covering load or
1828 // store. We don't want to widen the integer operations only to fail to
1829 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001830 // later). However, if there are only splittable uses, go ahead and assume
1831 // that we cover the alloca.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001832 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001833
Chandler Carruthf0546402013-07-18 07:15:00 +00001834 for (; I != E; ++I)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001835 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1836 S, I, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001837 return false;
1838
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001839 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1840 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00001841 SUI != SUE; ++SUI)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001842 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1843 S, *SUI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001844 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001845
Chandler Carruth92924fd2012-09-24 00:34:20 +00001846 return WholeAllocaOp;
1847}
1848
Chandler Carruthd177f862013-03-20 07:30:36 +00001849static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001850 IntegerType *Ty, uint64_t Offset,
1851 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001852 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001853 IntegerType *IntTy = cast<IntegerType>(V->getType());
1854 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1855 "Element extends past full value");
1856 uint64_t ShAmt = 8*Offset;
1857 if (DL.isBigEndian())
1858 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001859 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001860 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001861 DEBUG(dbgs() << " shifted: " << *V << "\n");
1862 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001863 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1864 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001865 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001866 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001867 DEBUG(dbgs() << " trunced: " << *V << "\n");
1868 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001869 return V;
1870}
1871
Chandler Carruthd177f862013-03-20 07:30:36 +00001872static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001873 Value *V, uint64_t Offset, const Twine &Name) {
1874 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1875 IntegerType *Ty = cast<IntegerType>(V->getType());
1876 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1877 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001878 DEBUG(dbgs() << " start: " << *V << "\n");
1879 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001880 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001881 DEBUG(dbgs() << " extended: " << *V << "\n");
1882 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001883 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1884 "Element store outside of alloca store");
1885 uint64_t ShAmt = 8*Offset;
1886 if (DL.isBigEndian())
1887 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001888 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001889 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001890 DEBUG(dbgs() << " shifted: " << *V << "\n");
1891 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001892
1893 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1894 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1895 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001896 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001897 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001898 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001899 }
1900 return V;
1901}
1902
Chandler Carruthd177f862013-03-20 07:30:36 +00001903static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001904 unsigned BeginIndex, unsigned EndIndex,
1905 const Twine &Name) {
1906 VectorType *VecTy = cast<VectorType>(V->getType());
1907 unsigned NumElements = EndIndex - BeginIndex;
1908 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1909
1910 if (NumElements == VecTy->getNumElements())
1911 return V;
1912
1913 if (NumElements == 1) {
1914 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1915 Name + ".extract");
1916 DEBUG(dbgs() << " extract: " << *V << "\n");
1917 return V;
1918 }
1919
1920 SmallVector<Constant*, 8> Mask;
1921 Mask.reserve(NumElements);
1922 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1923 Mask.push_back(IRB.getInt32(i));
1924 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1925 ConstantVector::get(Mask),
1926 Name + ".extract");
1927 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1928 return V;
1929}
1930
Chandler Carruthd177f862013-03-20 07:30:36 +00001931static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00001932 unsigned BeginIndex, const Twine &Name) {
1933 VectorType *VecTy = cast<VectorType>(Old->getType());
1934 assert(VecTy && "Can only insert a vector into a vector");
1935
1936 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1937 if (!Ty) {
1938 // Single element to insert.
1939 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1940 Name + ".insert");
1941 DEBUG(dbgs() << " insert: " << *V << "\n");
1942 return V;
1943 }
1944
1945 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1946 "Too many elements!");
1947 if (Ty->getNumElements() == VecTy->getNumElements()) {
1948 assert(V->getType() == VecTy && "Vector type mismatch");
1949 return V;
1950 }
1951 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1952
1953 // When inserting a smaller vector into the larger to store, we first
1954 // use a shuffle vector to widen it with undef elements, and then
1955 // a second shuffle vector to select between the loaded vector and the
1956 // incoming vector.
1957 SmallVector<Constant*, 8> Mask;
1958 Mask.reserve(VecTy->getNumElements());
1959 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1960 if (i >= BeginIndex && i < EndIndex)
1961 Mask.push_back(IRB.getInt32(i - BeginIndex));
1962 else
1963 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1964 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1965 ConstantVector::get(Mask),
1966 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00001967 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001968
1969 Mask.clear();
1970 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00001971 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1972
1973 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1974
1975 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00001976 return V;
1977}
1978
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001979namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001980/// \brief Visitor to rewrite instructions using p particular slice of an alloca
1981/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001982///
1983/// Also implements the rewriting to vector-based accesses when the partition
1984/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1985/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001986class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001987 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001988 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1989 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001990
Chandler Carruth90a735d2013-07-19 07:21:28 +00001991 const DataLayout &DL;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001992 AllocaSlices &S;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001993 SROA &Pass;
1994 AllocaInst &OldAI, &NewAI;
1995 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00001996 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001997
1998 // If we are rewriting an alloca partition which can be written as pure
1999 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002000 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002001 // - The new alloca is exactly the size of the vector type here.
2002 // - The accesses all either map to the entire vector or to a single
2003 // element.
2004 // - The set of accessing instructions is only one of those handled above
2005 // in isVectorPromotionViable. Generally these are the same access kinds
2006 // which are promotable via mem2reg.
2007 VectorType *VecTy;
2008 Type *ElementTy;
2009 uint64_t ElementSize;
2010
Chandler Carruth92924fd2012-09-24 00:34:20 +00002011 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002012 // alloca's integer operations should be widened to this integer type due to
2013 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002014 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002015 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002016
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002017 // The original offset of the slice currently being rewritten relative to
2018 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002019 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002020 // The new offsets of the slice currently being rewritten relative to the
2021 // original alloca.
2022 uint64_t NewBeginOffset, NewEndOffset;
2023
2024 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002025 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002026 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002027 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002028 Instruction *OldPtr;
2029
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002030 // Track post-rewrite users which are PHI nodes and Selects.
2031 SmallPtrSetImpl<PHINode *> &PHIUsers;
2032 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002033
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002034 // Utility IR builder, whose name prefix is setup for each visited use, and
2035 // the insertion point is set to point to the user.
2036 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002037
2038public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002039 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
2040 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002041 uint64_t NewAllocaBeginOffset,
2042 uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
2043 bool IsIntegerPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002044 SmallPtrSetImpl<PHINode *> &PHIUsers,
2045 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002046 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002047 NewAllocaBeginOffset(NewAllocaBeginOffset),
2048 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002049 NewAllocaTy(NewAI.getAllocatedType()),
Craig Topperf40110f2014-04-25 05:29:35 +00002050 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : nullptr),
2051 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002052 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002053 IntTy(IsIntegerPromotable
2054 ? Type::getIntNTy(
2055 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002056 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002057 : nullptr),
Chandler Carruthf0546402013-07-18 07:15:00 +00002058 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002059 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002060 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002061 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002062 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002063 "Only multiple-of-8 sized vector elements are viable");
2064 ++NumVectorized;
2065 }
2066 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
2067 IsVectorPromotable != IsIntegerPromotable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002068 }
2069
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002070 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002071 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002072 BeginOffset = I->beginOffset();
2073 EndOffset = I->endOffset();
2074 IsSplittable = I->isSplittable();
2075 IsSplit =
2076 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002077
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002078 // Compute the intersecting offset range.
2079 assert(BeginOffset < NewAllocaEndOffset);
2080 assert(EndOffset > NewAllocaBeginOffset);
2081 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2082 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2083
2084 SliceSize = NewEndOffset - NewBeginOffset;
2085
Chandler Carruthf0546402013-07-18 07:15:00 +00002086 OldUse = I->getUse();
2087 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002088
Chandler Carruthf0546402013-07-18 07:15:00 +00002089 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2090 IRB.SetInsertPoint(OldUserI);
2091 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2092 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2093
2094 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2095 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002096 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002097 return CanSROA;
2098 }
2099
2100private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002101 // Make sure the other visit overloads are visible.
2102 using Base::visit;
2103
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002104 // Every instruction which can end up as a user must have a rewrite rule.
2105 bool visitInstruction(Instruction &I) {
2106 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2107 llvm_unreachable("No rewrite rule for this instruction!");
2108 }
2109
Chandler Carruth47954c82014-02-26 05:12:43 +00002110 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2111 // Note that the offset computation can use BeginOffset or NewBeginOffset
2112 // interchangeably for unsplit slices.
2113 assert(IsSplit || BeginOffset == NewBeginOffset);
2114 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2115
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002116#ifndef NDEBUG
2117 StringRef OldName = OldPtr->getName();
2118 // Skip through the last '.sroa.' component of the name.
2119 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2120 if (LastSROAPrefix != StringRef::npos) {
2121 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2122 // Look for an SROA slice index.
2123 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2124 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2125 // Strip the index and look for the offset.
2126 OldName = OldName.substr(IndexEnd + 1);
2127 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2128 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2129 // Strip the offset.
2130 OldName = OldName.substr(OffsetEnd + 1);
2131 }
2132 }
2133 // Strip any SROA suffixes as well.
2134 OldName = OldName.substr(0, OldName.find(".sroa_"));
2135#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002136
2137 return getAdjustedPtr(IRB, DL, &NewAI,
2138 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002139#ifndef NDEBUG
2140 Twine(OldName) + "."
2141#else
2142 Twine()
2143#endif
2144 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002145 }
2146
Chandler Carruth2659e502014-02-26 05:02:19 +00002147 /// \brief Compute suitable alignment to access this slice of the *new* alloca.
2148 ///
2149 /// You can optionally pass a type to this routine and if that type's ABI
2150 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002151 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002152 unsigned NewAIAlign = NewAI.getAlignment();
2153 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002154 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth2659e502014-02-26 05:02:19 +00002155 unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2156 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002157 }
2158
Chandler Carruth845b73c2012-11-21 08:16:30 +00002159 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002160 assert(VecTy && "Can only call getIndex when rewriting a vector");
2161 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2162 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2163 uint32_t Index = RelOffset / ElementSize;
2164 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002165 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002166 }
2167
2168 void deleteIfTriviallyDead(Value *V) {
2169 Instruction *I = cast<Instruction>(V);
2170 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002171 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002172 }
2173
Chandler Carruthea27cf02014-02-26 04:25:04 +00002174 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002175 unsigned BeginIndex = getIndex(NewBeginOffset);
2176 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002177 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002178
2179 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002180 "load");
2181 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002182 }
2183
Chandler Carruthea27cf02014-02-26 04:25:04 +00002184 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002185 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002186 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002187 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002188 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002189 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002190 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2191 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2192 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002193 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002194 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002195 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002196 }
2197
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002198 bool visitLoadInst(LoadInst &LI) {
2199 DEBUG(dbgs() << " original: " << LI << "\n");
2200 Value *OldOp = LI.getOperand(0);
2201 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002202
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002203 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002204 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002205 bool IsPtrAdjusted = false;
2206 Value *V;
2207 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002208 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002209 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002210 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002211 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002212 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002213 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002214 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002215 } else {
2216 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002217 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002218 getSliceAlign(TargetTy), LI.isVolatile(),
2219 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002220 IsPtrAdjusted = true;
2221 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002222 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002223
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002224 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002225 assert(!LI.isVolatile());
2226 assert(LI.getType()->isIntegerTy() &&
2227 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002228 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002229 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002230 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002231 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002232 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002233 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002234 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002235 // Create a placeholder value with the same type as LI to use as the
2236 // basis for the new value. This allows us to replace the uses of LI with
2237 // the computed value, and then replace the placeholder with LI, leaving
2238 // LI only used for this computation.
2239 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002240 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002241 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002242 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002243 LI.replaceAllUsesWith(V);
2244 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002245 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002246 } else {
2247 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002248 }
2249
Chandler Carruth18db7952012-11-20 01:12:50 +00002250 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002251 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002252 DEBUG(dbgs() << " to: " << *V << "\n");
2253 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002254 }
2255
Chandler Carruthea27cf02014-02-26 04:25:04 +00002256 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002257 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002258 unsigned BeginIndex = getIndex(NewBeginOffset);
2259 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002260 assert(EndIndex > BeginIndex && "Empty vector!");
2261 unsigned NumElements = EndIndex - BeginIndex;
2262 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002263 Type *SliceTy =
2264 (NumElements == 1) ? ElementTy
2265 : VectorType::get(ElementTy, NumElements);
2266 if (V->getType() != SliceTy)
2267 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002268
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002269 // Mix in the existing elements.
2270 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2271 "load");
2272 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2273 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002274 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002275 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002276
2277 (void)Store;
2278 DEBUG(dbgs() << " to: " << *Store << "\n");
2279 return true;
2280 }
2281
Chandler Carruthea27cf02014-02-26 04:25:04 +00002282 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002283 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002284 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002285 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002286 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002287 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002288 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002289 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2290 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002291 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002292 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002293 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002294 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002295 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002296 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002297 (void)Store;
2298 DEBUG(dbgs() << " to: " << *Store << "\n");
2299 return true;
2300 }
2301
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002302 bool visitStoreInst(StoreInst &SI) {
2303 DEBUG(dbgs() << " original: " << SI << "\n");
2304 Value *OldOp = SI.getOperand(1);
2305 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002306
Chandler Carruth18db7952012-11-20 01:12:50 +00002307 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002308
Chandler Carruthac8317f2012-10-04 12:33:50 +00002309 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2310 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002311 if (V->getType()->isPointerTy())
2312 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002313 Pass.PostPromotionWorklist.insert(AI);
2314
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002315 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002316 assert(!SI.isVolatile());
2317 assert(V->getType()->isIntegerTy() &&
2318 "Only integer type loads and stores are split");
2319 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002320 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002321 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002322 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002323 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002324 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002325 }
2326
Chandler Carruth18db7952012-11-20 01:12:50 +00002327 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002328 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002329 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002330 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002331
Chandler Carruth18db7952012-11-20 01:12:50 +00002332 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002333 if (NewBeginOffset == NewAllocaBeginOffset &&
2334 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002335 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2336 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002337 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2338 SI.isVolatile());
2339 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002340 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002341 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2342 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002343 }
2344 (void)NewSI;
2345 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002346 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002347
2348 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2349 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002350 }
2351
Chandler Carruth514f34f2012-12-17 04:07:30 +00002352 /// \brief Compute an integer value from splatting an i8 across the given
2353 /// number of bytes.
2354 ///
2355 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2356 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002357 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002358 ///
2359 /// \param V The i8 value to splat.
2360 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002361 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002362 assert(Size > 0 && "Expected a positive number of bytes.");
2363 IntegerType *VTy = cast<IntegerType>(V->getType());
2364 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2365 if (Size == 1)
2366 return V;
2367
2368 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002369 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002370 ConstantExpr::getUDiv(
2371 Constant::getAllOnesValue(SplatIntTy),
2372 ConstantExpr::getZExt(
2373 Constant::getAllOnesValue(V->getType()),
2374 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002375 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002376 return V;
2377 }
2378
Chandler Carruthccca5042012-12-17 04:07:37 +00002379 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002380 Value *getVectorSplat(Value *V, unsigned NumElements) {
2381 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002382 DEBUG(dbgs() << " splat: " << *V << "\n");
2383 return V;
2384 }
2385
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002386 bool visitMemSetInst(MemSetInst &II) {
2387 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388 assert(II.getRawDest() == OldPtr);
2389
2390 // If the memset has a variable size, it cannot be split, just adjust the
2391 // pointer to the new alloca.
2392 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002393 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002394 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002395 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002396 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002397 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002398
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002399 deleteIfTriviallyDead(OldPtr);
2400 return false;
2401 }
2402
2403 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002404 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002405
2406 Type *AllocaTy = NewAI.getAllocatedType();
2407 Type *ScalarTy = AllocaTy->getScalarType();
2408
2409 // If this doesn't map cleanly onto the alloca type, and that type isn't
2410 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002411 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002412 (BeginOffset > NewAllocaBeginOffset ||
2413 EndOffset < NewAllocaEndOffset ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002414 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002415 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2416 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002417 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002418 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2419 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002420 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2421 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002422 (void)New;
2423 DEBUG(dbgs() << " to: " << *New << "\n");
2424 return false;
2425 }
2426
2427 // If we can represent this as a simple value, we have to build the actual
2428 // value to store, which requires expanding the byte present in memset to
2429 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002430 // splatting the byte to a sufficiently wide integer, splatting it across
2431 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002432 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002433
Chandler Carruthccca5042012-12-17 04:07:37 +00002434 if (VecTy) {
2435 // If this is a memset of a vectorized alloca, insert it.
2436 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002437
Chandler Carruthf0546402013-07-18 07:15:00 +00002438 unsigned BeginIndex = getIndex(NewBeginOffset);
2439 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002440 assert(EndIndex > BeginIndex && "Empty vector!");
2441 unsigned NumElements = EndIndex - BeginIndex;
2442 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2443
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002444 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002445 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2446 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002447 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002448 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002449
Chandler Carruthce4562b2012-12-17 13:41:21 +00002450 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002451 "oldload");
2452 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002453 } else if (IntTy) {
2454 // If this is a memset on an alloca where we can widen stores, insert the
2455 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002456 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002457
Chandler Carruthf0546402013-07-18 07:15:00 +00002458 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002459 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002460
2461 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2462 EndOffset != NewAllocaBeginOffset)) {
2463 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002464 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002465 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002466 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002467 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002468 } else {
2469 assert(V->getType() == IntTy &&
2470 "Wrong type for an alloca wide integer!");
2471 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002472 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002473 } else {
2474 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002475 assert(NewBeginOffset == NewAllocaBeginOffset);
2476 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002477
Chandler Carruth90a735d2013-07-19 07:21:28 +00002478 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002479 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002480 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002481
Chandler Carruth90a735d2013-07-19 07:21:28 +00002482 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002483 }
2484
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002485 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002486 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002487 (void)New;
2488 DEBUG(dbgs() << " to: " << *New << "\n");
2489 return !II.isVolatile();
2490 }
2491
2492 bool visitMemTransferInst(MemTransferInst &II) {
2493 // Rewriting of memory transfer instructions can be a bit tricky. We break
2494 // them into two categories: split intrinsics and unsplit intrinsics.
2495
2496 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002497
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002498 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002499 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002500 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002501
Chandler Carruthaa72b932014-02-26 07:29:54 +00002502 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002503
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002504 // For unsplit intrinsics, we simply modify the source and destination
2505 // pointers in place. This isn't just an optimization, it is a matter of
2506 // correctness. With unsplit intrinsics we may be dealing with transfers
2507 // within a single alloca before SROA ran, or with transfers that have
2508 // a variable length. We may also be dealing with memmove instead of
2509 // memcpy, and so simply updating the pointers is the necessary for us to
2510 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002511 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002512 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002513 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002514 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002515 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002516 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002517
Chandler Carruthaa72b932014-02-26 07:29:54 +00002518 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002519 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002520 II.setAlignment(
2521 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002522 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002523
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002524 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002525 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002526 return false;
2527 }
2528 // For split transfer intrinsics we have an incredibly useful assurance:
2529 // the source and destination do not reside within the same alloca, and at
2530 // least one of them does not escape. This means that we can replace
2531 // memmove with memcpy, and we don't need to worry about all manner of
2532 // downsides to splitting and transforming the operations.
2533
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002534 // If this doesn't map cleanly onto the alloca type, and that type isn't
2535 // a single value type, just emit a memcpy.
2536 bool EmitMemCpy
Chandler Carruthf0546402013-07-18 07:15:00 +00002537 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2538 EndOffset < NewAllocaEndOffset ||
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002539 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002540
2541 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2542 // size hasn't been shrunk based on analysis of the viable range, this is
2543 // a no-op.
2544 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002545 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002546 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002547
2548 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002549 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002550 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002551 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002552 return false;
2553 }
2554 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002555 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002556
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002557 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2558 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002559 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002560 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002561 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2562 assert(AI != &OldAI && AI != &NewAI &&
2563 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002564 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002565 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002566
Chandler Carruth286d87e2014-02-26 08:25:02 +00002567 Type *OtherPtrTy = OtherPtr->getType();
2568 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2569
Chandler Carruth181ed052014-02-26 05:33:36 +00002570 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002571 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002572 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002573 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2574 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002575
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002576 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002577 // Compute the other pointer, folding as much as possible to produce
2578 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002579 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002580 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002581
Chandler Carruth47954c82014-02-26 05:12:43 +00002582 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002583 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002584 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002585
Chandler Carruthaa72b932014-02-26 07:29:54 +00002586 CallInst *New = IRB.CreateMemCpy(
2587 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2588 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002589 (void)New;
2590 DEBUG(dbgs() << " to: " << *New << "\n");
2591 return false;
2592 }
2593
Chandler Carruthf0546402013-07-18 07:15:00 +00002594 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2595 NewEndOffset == NewAllocaEndOffset;
2596 uint64_t Size = NewEndOffset - NewBeginOffset;
2597 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2598 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002599 unsigned NumElements = EndIndex - BeginIndex;
2600 IntegerType *SubIntTy
Craig Topperf40110f2014-04-25 05:29:35 +00002601 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002602
Chandler Carruth286d87e2014-02-26 08:25:02 +00002603 // Reset the other pointer type to match the register type we're going to
2604 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002605 if (VecTy && !IsWholeAlloca) {
2606 if (NumElements == 1)
2607 OtherPtrTy = VecTy->getElementType();
2608 else
2609 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2610
Chandler Carruth286d87e2014-02-26 08:25:02 +00002611 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002612 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002613 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2614 } else {
2615 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002616 }
2617
Chandler Carruth181ed052014-02-26 05:33:36 +00002618 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002619 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002620 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002621 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002622 unsigned DstAlign = SliceAlign;
2623 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002624 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002625 std::swap(SrcAlign, DstAlign);
2626 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002627
2628 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002629 if (VecTy && !IsWholeAlloca && !IsDest) {
2630 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002631 "load");
2632 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002633 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002634 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002635 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002636 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002637 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002638 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002639 } else {
Chandler Carruthaa72b932014-02-26 07:29:54 +00002640 Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002641 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002642 }
2643
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002644 if (VecTy && !IsWholeAlloca && IsDest) {
2645 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002646 "oldload");
2647 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002648 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002649 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002650 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002651 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002652 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002653 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2654 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002655 }
2656
Chandler Carruth871ba722012-09-26 10:27:46 +00002657 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002658 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002659 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002660 DEBUG(dbgs() << " to: " << *Store << "\n");
2661 return !II.isVolatile();
2662 }
2663
2664 bool visitIntrinsicInst(IntrinsicInst &II) {
2665 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2666 II.getIntrinsicID() == Intrinsic::lifetime_end);
2667 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002668 assert(II.getArgOperand(1) == OldPtr);
2669
2670 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002671 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002672
2673 ConstantInt *Size
2674 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002675 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002676 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002677 Value *New;
2678 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2679 New = IRB.CreateLifetimeStart(Ptr, Size);
2680 else
2681 New = IRB.CreateLifetimeEnd(Ptr, Size);
2682
Edwin Vane82f80d42013-01-29 17:42:24 +00002683 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002684 DEBUG(dbgs() << " to: " << *New << "\n");
2685 return true;
2686 }
2687
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002688 bool visitPHINode(PHINode &PN) {
2689 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002690 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2691 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002692
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002693 // We would like to compute a new pointer in only one place, but have it be
2694 // as local as possible to the PHI. To do that, we re-use the location of
2695 // the old pointer, which necessarily must be in the right position to
2696 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002697 IRBuilderTy PtrBuilder(IRB);
2698 PtrBuilder.SetInsertPoint(OldPtr);
2699 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002700
Chandler Carruth47954c82014-02-26 05:12:43 +00002701 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002702 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002703 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002704
Chandler Carruth82a57542012-10-01 10:54:05 +00002705 DEBUG(dbgs() << " to: " << PN << "\n");
2706 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002707
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002708 // PHIs can't be promoted on their own, but often can be speculated. We
2709 // check the speculation outside of the rewriter so that we see the
2710 // fully-rewritten alloca.
2711 PHIUsers.insert(&PN);
2712 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002713 }
2714
2715 bool visitSelectInst(SelectInst &SI) {
2716 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002717 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2718 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002719 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2720 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002721
Chandler Carruth47954c82014-02-26 05:12:43 +00002722 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002723 // Replace the operands which were using the old pointer.
2724 if (SI.getOperand(1) == OldPtr)
2725 SI.setOperand(1, NewPtr);
2726 if (SI.getOperand(2) == OldPtr)
2727 SI.setOperand(2, NewPtr);
2728
Chandler Carruth82a57542012-10-01 10:54:05 +00002729 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002730 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002731
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002732 // Selects can't be promoted on their own, but often can be speculated. We
2733 // check the speculation outside of the rewriter so that we see the
2734 // fully-rewritten alloca.
2735 SelectUsers.insert(&SI);
2736 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002737 }
2738
2739};
2740}
2741
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002742namespace {
2743/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2744///
2745/// This pass aggressively rewrites all aggregate loads and stores on
2746/// a particular pointer (or any pointer derived from it which we can identify)
2747/// with scalar loads and stores.
2748class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2749 // Befriend the base class so it can delegate to private visit methods.
2750 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2751
Chandler Carruth90a735d2013-07-19 07:21:28 +00002752 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002753
2754 /// Queue of pointer uses to analyze and potentially rewrite.
2755 SmallVector<Use *, 8> Queue;
2756
2757 /// Set to prevent us from cycling with phi nodes and loops.
2758 SmallPtrSet<User *, 8> Visited;
2759
2760 /// The current pointer use being rewritten. This is used to dig up the used
2761 /// value (as opposed to the user).
2762 Use *U;
2763
2764public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002765 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002766
2767 /// Rewrite loads and stores through a pointer and all pointers derived from
2768 /// it.
2769 bool rewrite(Instruction &I) {
2770 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2771 enqueueUsers(I);
2772 bool Changed = false;
2773 while (!Queue.empty()) {
2774 U = Queue.pop_back_val();
2775 Changed |= visit(cast<Instruction>(U->getUser()));
2776 }
2777 return Changed;
2778 }
2779
2780private:
2781 /// Enqueue all the users of the given instruction for further processing.
2782 /// This uses a set to de-duplicate users.
2783 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002784 for (Use &U : I.uses())
2785 if (Visited.insert(U.getUser()))
2786 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002787 }
2788
2789 // Conservative default is to not rewrite anything.
2790 bool visitInstruction(Instruction &I) { return false; }
2791
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002792 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002793 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002794 class OpSplitter {
2795 protected:
2796 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002797 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002798 /// The indices which to be used with insert- or extractvalue to select the
2799 /// appropriate value within the aggregate.
2800 SmallVector<unsigned, 4> Indices;
2801 /// The indices to a GEP instruction which will move Ptr to the correct slot
2802 /// within the aggregate.
2803 SmallVector<Value *, 4> GEPIndices;
2804 /// The base pointer of the original op, used as a base for GEPing the
2805 /// split operations.
2806 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002807
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002808 /// Initialize the splitter with an insertion point, Ptr and start with a
2809 /// single zero GEP index.
2810 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002811 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002812
2813 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002814 /// \brief Generic recursive split emission routine.
2815 ///
2816 /// This method recursively splits an aggregate op (load or store) into
2817 /// scalar or vector ops. It splits recursively until it hits a single value
2818 /// and emits that single value operation via the template argument.
2819 ///
2820 /// The logic of this routine relies on GEPs and insertvalue and
2821 /// extractvalue all operating with the same fundamental index list, merely
2822 /// formatted differently (GEPs need actual values).
2823 ///
2824 /// \param Ty The type being split recursively into smaller ops.
2825 /// \param Agg The aggregate value being built up or stored, depending on
2826 /// whether this is splitting a load or a store respectively.
2827 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2828 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002829 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002830
2831 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2832 unsigned OldSize = Indices.size();
2833 (void)OldSize;
2834 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2835 ++Idx) {
2836 assert(Indices.size() == OldSize && "Did not return to the old size");
2837 Indices.push_back(Idx);
2838 GEPIndices.push_back(IRB.getInt32(Idx));
2839 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2840 GEPIndices.pop_back();
2841 Indices.pop_back();
2842 }
2843 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002844 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002845
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002846 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2847 unsigned OldSize = Indices.size();
2848 (void)OldSize;
2849 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2850 ++Idx) {
2851 assert(Indices.size() == OldSize && "Did not return to the old size");
2852 Indices.push_back(Idx);
2853 GEPIndices.push_back(IRB.getInt32(Idx));
2854 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2855 GEPIndices.pop_back();
2856 Indices.pop_back();
2857 }
2858 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002859 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002860
2861 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002862 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002863 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002864
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002865 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002866 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002867 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002868
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002869 /// Emit a leaf load of a single value. This is called at the leaves of the
2870 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002871 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002872 assert(Ty->isSingleValueType());
2873 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002874 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2875 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002876 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2877 DEBUG(dbgs() << " to: " << *Load << "\n");
2878 }
2879 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002880
2881 bool visitLoadInst(LoadInst &LI) {
2882 assert(LI.getPointerOperand() == *U);
2883 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2884 return false;
2885
2886 // We have an aggregate being loaded, split it apart.
2887 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002888 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002889 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002890 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002891 LI.replaceAllUsesWith(V);
2892 LI.eraseFromParent();
2893 return true;
2894 }
2895
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002896 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002897 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002898 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002899
2900 /// Emit a leaf store of a single value. This is called at the leaves of the
2901 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002902 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002903 assert(Ty->isSingleValueType());
2904 // Extract the single value and store it using the indices.
2905 Value *Store = IRB.CreateStore(
2906 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2907 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2908 (void)Store;
2909 DEBUG(dbgs() << " to: " << *Store << "\n");
2910 }
2911 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002912
2913 bool visitStoreInst(StoreInst &SI) {
2914 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2915 return false;
2916 Value *V = SI.getValueOperand();
2917 if (V->getType()->isSingleValueType())
2918 return false;
2919
2920 // We have an aggregate being stored, split it apart.
2921 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002922 StoreOpSplitter Splitter(&SI, *U);
2923 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002924 SI.eraseFromParent();
2925 return true;
2926 }
2927
2928 bool visitBitCastInst(BitCastInst &BC) {
2929 enqueueUsers(BC);
2930 return false;
2931 }
2932
2933 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2934 enqueueUsers(GEPI);
2935 return false;
2936 }
2937
2938 bool visitPHINode(PHINode &PN) {
2939 enqueueUsers(PN);
2940 return false;
2941 }
2942
2943 bool visitSelectInst(SelectInst &SI) {
2944 enqueueUsers(SI);
2945 return false;
2946 }
2947};
2948}
2949
Chandler Carruthba931992012-10-13 10:49:33 +00002950/// \brief Strip aggregate type wrapping.
2951///
2952/// This removes no-op aggregate types wrapping an underlying type. It will
2953/// strip as many layers of types as it can without changing either the type
2954/// size or the allocated size.
2955static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2956 if (Ty->isSingleValueType())
2957 return Ty;
2958
2959 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2960 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2961
2962 Type *InnerTy;
2963 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2964 InnerTy = ArrTy->getElementType();
2965 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2966 const StructLayout *SL = DL.getStructLayout(STy);
2967 unsigned Index = SL->getElementContainingOffset(0);
2968 InnerTy = STy->getElementType(Index);
2969 } else {
2970 return Ty;
2971 }
2972
2973 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2974 TypeSize > DL.getTypeSizeInBits(InnerTy))
2975 return Ty;
2976
2977 return stripAggregateTypeWrapping(DL, InnerTy);
2978}
2979
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002980/// \brief Try to find a partition of the aggregate type passed in for a given
2981/// offset and size.
2982///
2983/// This recurses through the aggregate type and tries to compute a subtype
2984/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00002985/// of an array, it will even compute a new array type for that sub-section,
2986/// and the same for structs.
2987///
2988/// Note that this routine is very strict and tries to find a partition of the
2989/// type which produces the *exact* right offset and size. It is not forgiving
2990/// when the size or offset cause either end of type-based partition to be off.
2991/// Also, this is a best-effort routine. It is reasonable to give up and not
2992/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002993static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002994 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002995 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2996 return stripAggregateTypeWrapping(DL, Ty);
2997 if (Offset > DL.getTypeAllocSize(Ty) ||
2998 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00002999 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003000
3001 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3002 // We can't partition pointers...
3003 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003004 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003005
3006 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003007 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003008 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003009 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003010 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003011 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003012 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003013 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003014 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003015 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003016 Offset -= NumSkippedElements * ElementSize;
3017
3018 // First check if we need to recurse.
3019 if (Offset > 0 || Size < ElementSize) {
3020 // Bail if the partition ends in a different array element.
3021 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003022 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003023 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003024 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003025 }
3026 assert(Offset == 0);
3027
3028 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003029 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003030 assert(Size > ElementSize);
3031 uint64_t NumElements = Size / ElementSize;
3032 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003033 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003034 return ArrayType::get(ElementTy, NumElements);
3035 }
3036
3037 StructType *STy = dyn_cast<StructType>(Ty);
3038 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003039 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003040
Chandler Carruth90a735d2013-07-19 07:21:28 +00003041 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003042 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003043 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003044 uint64_t EndOffset = Offset + Size;
3045 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003046 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003047
3048 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003049 Offset -= SL->getElementOffset(Index);
3050
3051 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003052 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003053 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003054 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003055
3056 // See if any partition must be contained by the element.
3057 if (Offset > 0 || Size < ElementSize) {
3058 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003059 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003060 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003061 }
3062 assert(Offset == 0);
3063
3064 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003065 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003066
3067 StructType::element_iterator EI = STy->element_begin() + Index,
3068 EE = STy->element_end();
3069 if (EndOffset < SL->getSizeInBytes()) {
3070 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3071 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003072 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003073
3074 // Don't try to form "natural" types if the elements don't line up with the
3075 // expected size.
3076 // FIXME: We could potentially recurse down through the last element in the
3077 // sub-struct to find a natural end point.
3078 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003079 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003080
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003081 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003082 EE = STy->element_begin() + EndIndex;
3083 }
3084
3085 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003086 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003087 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003088 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003089 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003090 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003091
Chandler Carruth054a40a2012-09-14 11:08:31 +00003092 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003093}
3094
3095/// \brief Rewrite an alloca partition's users.
3096///
3097/// This routine drives both of the rewriting goals of the SROA pass. It tries
3098/// to rewrite uses of an alloca partition to be conducive for SSA value
3099/// promotion. If the partition needs a new, more refined alloca, this will
3100/// build that new alloca, preserving as much type information as possible, and
3101/// rewrite the uses of the old alloca to point at the new one and have the
3102/// appropriate new offsets. It also evaluates how successful the rewrite was
3103/// at enabling promotion and if it was successful queues the alloca to be
3104/// promoted.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003105bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3106 AllocaSlices::iterator B, AllocaSlices::iterator E,
3107 int64_t BeginOffset, int64_t EndOffset,
3108 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003109 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003110 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003111
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003112 // Try to compute a friendly type for this partition of the alloca. This
3113 // won't always succeed, in which case we fall back to a legal integer type
3114 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003115 Type *SliceTy = nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00003116 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003117 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3118 SliceTy = CommonUseTy;
3119 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003120 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003121 BeginOffset, SliceSize))
3122 SliceTy = TypePartitionTy;
3123 if ((!SliceTy || (SliceTy->isArrayTy() &&
3124 SliceTy->getArrayElementType()->isIntegerTy())) &&
3125 DL->isLegalInteger(SliceSize * 8))
3126 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3127 if (!SliceTy)
3128 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3129 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003130
3131 bool IsVectorPromotable = isVectorPromotionViable(
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003132 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003133
3134 bool IsIntegerPromotable =
3135 !IsVectorPromotable &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003136 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003137
3138 // Check for the case where we're going to rewrite to a new alloca of the
3139 // exact same type as the original, and with the same access offsets. In that
3140 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003141 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003142 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003143 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003144 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003145 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003146 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003147 // FIXME: We should be able to bail at this point with "nothing changed".
3148 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003149 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003150 unsigned Alignment = AI.getAlignment();
3151 if (!Alignment) {
3152 // The minimum alignment which users can rely on when the explicit
3153 // alignment is omitted or zero is that required by the ABI for this
3154 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003155 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003156 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003157 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003158 // If we will get at least this much alignment from the type alone, leave
3159 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003160 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003161 Alignment = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003162 NewAI = new AllocaInst(SliceTy, nullptr, Alignment,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003163 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003164 ++NumNewAllocas;
3165 }
3166
3167 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003168 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3169 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003170
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003171 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003172 // promoted allocas. We will reset it to this point if the alloca is not in
3173 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003174 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003175 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003176 SmallPtrSet<PHINode *, 8> PHIUsers;
3177 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003178
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003179 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3180 EndOffset, IsVectorPromotable,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003181 IsIntegerPromotable, PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003182 bool Promotable = true;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003183 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3184 SUE = SplitUses.end();
Chandler Carruthf0546402013-07-18 07:15:00 +00003185 SUI != SUE; ++SUI) {
3186 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003187 DEBUG(S.printSlice(dbgs(), *SUI, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003188 Promotable &= Rewriter.visit(*SUI);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003189 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003190 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003191 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003192 DEBUG(dbgs() << " rewriting ");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003193 DEBUG(S.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003194 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003195 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003196 }
3197
Chandler Carruth6c321c12013-07-19 10:57:36 +00003198 NumAllocaPartitionUses += NumUses;
3199 MaxUsesPerAllocaPartition =
3200 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003201
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003202 // Now that we've processed all the slices in the new partition, check if any
3203 // PHIs or Selects would block promotion.
3204 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3205 E = PHIUsers.end();
3206 I != E; ++I)
3207 if (!isSafePHIToSpeculate(**I, DL)) {
3208 Promotable = false;
3209 PHIUsers.clear();
3210 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003211 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003212 }
3213 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3214 E = SelectUsers.end();
3215 I != E; ++I)
3216 if (!isSafeSelectToSpeculate(**I, DL)) {
3217 Promotable = false;
3218 PHIUsers.clear();
3219 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003220 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003221 }
3222
3223 if (Promotable) {
3224 if (PHIUsers.empty() && SelectUsers.empty()) {
3225 // Promote the alloca.
3226 PromotableAllocas.push_back(NewAI);
3227 } else {
3228 // If we have either PHIs or Selects to speculate, add them to those
3229 // worklists and re-queue the new alloca so that we promote in on the
3230 // next iteration.
3231 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3232 E = PHIUsers.end();
3233 I != E; ++I)
3234 SpeculatablePHIs.insert(*I);
3235 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3236 E = SelectUsers.end();
3237 I != E; ++I)
3238 SpeculatableSelects.insert(*I);
3239 Worklist.insert(NewAI);
3240 }
3241 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003242 // If we can't promote the alloca, iterate on it to check for new
3243 // refinements exposed by splitting the current alloca. Don't iterate on an
3244 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003245 if (NewAI != &AI)
3246 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003247
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003248 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003249 while (PostPromotionWorklist.size() > PPWOldSize)
3250 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003251 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003252
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003253 return true;
3254}
3255
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003256static void
3257removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3258 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003259 if (Offset >= MaxSplitUseEndOffset) {
3260 SplitUses.clear();
3261 MaxSplitUseEndOffset = 0;
3262 return;
3263 }
3264
3265 size_t SplitUsesOldSize = SplitUses.size();
3266 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003267 [Offset](const AllocaSlices::iterator &I) {
3268 return I->endOffset() <= Offset;
3269 }),
Chandler Carruthf0546402013-07-18 07:15:00 +00003270 SplitUses.end());
3271 if (SplitUsesOldSize == SplitUses.size())
3272 return;
3273
3274 // Recompute the max. While this is linear, so is remove_if.
3275 MaxSplitUseEndOffset = 0;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003276 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
Chandler Carruthf0546402013-07-18 07:15:00 +00003277 SUI = SplitUses.begin(),
3278 SUE = SplitUses.end();
3279 SUI != SUE; ++SUI)
3280 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3281}
3282
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003283/// \brief Walks the slices of an alloca and form partitions based on them,
3284/// rewriting each of their uses.
3285bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3286 if (S.begin() == S.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003287 return false;
3288
Chandler Carruth6c321c12013-07-19 10:57:36 +00003289 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003290 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003291 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003292 uint64_t MaxSplitUseEndOffset = 0;
3293
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003294 uint64_t BeginOffset = S.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003295
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003296 for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003297 SI != SE; SI = SJ) {
3298 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003299
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003300 if (!SI->isSplittable()) {
3301 // When we're forming an unsplittable region, it must always start at the
3302 // first slice and will extend through its end.
3303 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003304
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003305 // Form a partition including all of the overlapping slices with this
3306 // unsplittable slice.
3307 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3308 if (!SJ->isSplittable())
3309 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3310 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003311 }
3312 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003313 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003314
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003315 // Collect all of the overlapping splittable slices.
3316 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3317 SJ->isSplittable()) {
3318 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3319 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003320 }
3321
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003322 // Back up MaxEndOffset and SJ if we ended the span early when
3323 // encountering an unsplittable slice.
3324 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3325 assert(!SJ->isSplittable());
3326 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003327 }
3328 }
3329
3330 // Check if we have managed to move the end offset forward yet. If so,
3331 // we'll have to rewrite uses and erase old split uses.
3332 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003333 // Rewrite a sequence of overlapping slices.
3334 Changed |=
3335 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003336 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003337
3338 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3339 }
3340
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003341 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003342 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003343 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3344 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3345 SplitUses.push_back(SK);
3346 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003347 }
3348
3349 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003350 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003351 break;
3352
3353 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003354 // the next slice.
3355 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3356 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003357 continue;
3358 }
3359
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003360 // Even if we have split slices, if the next slice is splittable and the
3361 // split slices reach it, we can simply set up the beginning offset of the
3362 // next iteration to bridge between them.
3363 if (SJ != SE && SJ->isSplittable() &&
3364 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003365 BeginOffset = MaxEndOffset;
3366 continue;
3367 }
3368
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003369 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3370 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003371 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003372 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003373
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003374 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3375 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003376 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003377
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003378 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003379 break; // Skip the rest, we don't need to do any cleanup.
3380
3381 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3382 PostSplitEndOffset);
3383
3384 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003385 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003386 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003387
Chandler Carruth6c321c12013-07-19 10:57:36 +00003388 NumAllocaPartitions += NumPartitions;
3389 MaxPartitionsPerAlloca =
3390 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003391
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003392 return Changed;
3393}
3394
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003395/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3396void SROA::clobberUse(Use &U) {
3397 Value *OldV = U;
3398 // Replace the use with an undef value.
3399 U = UndefValue::get(OldV->getType());
3400
3401 // Check for this making an instruction dead. We have to garbage collect
3402 // all the dead instructions to ensure the uses of any alloca end up being
3403 // minimal.
3404 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3405 if (isInstructionTriviallyDead(OldI)) {
3406 DeadInsts.insert(OldI);
3407 }
3408}
3409
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003410/// \brief Analyze an alloca for SROA.
3411///
3412/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003413/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003414/// rewritten as needed.
3415bool SROA::runOnAlloca(AllocaInst &AI) {
3416 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3417 ++NumAllocasAnalyzed;
3418
3419 // Special case dead allocas, as they're trivial.
3420 if (AI.use_empty()) {
3421 AI.eraseFromParent();
3422 return true;
3423 }
3424
3425 // Skip alloca forms that this analysis can't handle.
3426 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003427 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003428 return false;
3429
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003430 bool Changed = false;
3431
3432 // First, split any FCA loads and stores touching this alloca to promote
3433 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003434 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003435 Changed |= AggRewriter.rewrite(AI);
3436
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003437 // Build the slices using a recursive instruction-visiting builder.
3438 AllocaSlices S(*DL, AI);
3439 DEBUG(S.print(dbgs()));
3440 if (S.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003441 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003442
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003443 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003444 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3445 DE = S.dead_user_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003446 DI != DE; ++DI) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003447 // Free up everything used by this instruction.
Chandler Carruth1583e992014-03-03 10:42:58 +00003448 for (Use &DeadOp : (*DI)->operands())
3449 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003450
3451 // Now replace the uses of this instruction.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003452 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003453
3454 // And mark it for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003455 DeadInsts.insert(*DI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003456 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003457 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003458 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3459 DE = S.dead_op_end();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003460 DO != DE; ++DO) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003461 clobberUse(**DO);
3462 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003463 }
3464
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003465 // No slices to split. Leave the dead alloca for a later pass to clean up.
3466 if (S.begin() == S.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003467 return Changed;
3468
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003469 Changed |= splitAlloca(AI, S);
Chandler Carruthf0546402013-07-18 07:15:00 +00003470
3471 DEBUG(dbgs() << " Speculating PHIs\n");
3472 while (!SpeculatablePHIs.empty())
3473 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3474
3475 DEBUG(dbgs() << " Speculating Selects\n");
3476 while (!SpeculatableSelects.empty())
3477 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3478
3479 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003480}
3481
Chandler Carruth19450da2012-09-14 10:26:38 +00003482/// \brief Delete the dead instructions accumulated in this run.
3483///
3484/// Recursively deletes the dead instructions we've accumulated. This is done
3485/// at the very end to maximize locality of the recursive delete and to
3486/// minimize the problems of invalidated instruction pointers as such pointers
3487/// are used heavily in the intermediate stages of the algorithm.
3488///
3489/// We also record the alloca instructions deleted here so that they aren't
3490/// subsequently handed to mem2reg to promote.
3491void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003492 while (!DeadInsts.empty()) {
3493 Instruction *I = DeadInsts.pop_back_val();
3494 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3495
Chandler Carruth58d05562012-10-25 04:37:07 +00003496 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3497
Chandler Carruth1583e992014-03-03 10:42:58 +00003498 for (Use &Operand : I->operands())
3499 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003500 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00003501 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003502 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003503 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003504 }
3505
3506 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3507 DeletedAllocas.insert(AI);
3508
3509 ++NumDeleted;
3510 I->eraseFromParent();
3511 }
3512}
3513
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003514static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003515 SmallVectorImpl<Instruction *> &Worklist,
3516 SmallPtrSet<Instruction *, 8> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003517 for (User *U : I.users())
3518 if (Visited.insert(cast<Instruction>(U)))
3519 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003520}
3521
Chandler Carruth70b44c52012-09-15 11:43:14 +00003522/// \brief Promote the allocas, using the best available technique.
3523///
3524/// This attempts to promote whatever allocas have been identified as viable in
3525/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3526/// If there is a domtree available, we attempt to promote using the full power
3527/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3528/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003529/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003530bool SROA::promoteAllocas(Function &F) {
3531 if (PromotableAllocas.empty())
3532 return false;
3533
3534 NumPromoted += PromotableAllocas.size();
3535
3536 if (DT && !ForceSSAUpdater) {
3537 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Nick Lewyckyc7776f72013-08-13 22:51:58 +00003538 PromoteMemToReg(PromotableAllocas, *DT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003539 PromotableAllocas.clear();
3540 return true;
3541 }
3542
3543 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3544 SSAUpdater SSA;
3545 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003546 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003547
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003548 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003549 SmallVector<Instruction *, 8> Worklist;
3550 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003551 SmallVector<Instruction *, 32> DeadInsts;
3552
Chandler Carruth70b44c52012-09-15 11:43:14 +00003553 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3554 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003555 Insts.clear();
3556 Worklist.clear();
3557 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003558
Chandler Carruth45b136f2013-08-11 01:03:18 +00003559 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003560
Chandler Carruth45b136f2013-08-11 01:03:18 +00003561 while (!Worklist.empty()) {
3562 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003563
Chandler Carruth70b44c52012-09-15 11:43:14 +00003564 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3565 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3566 // leading to them) here. Eventually it should use them to optimize the
3567 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003568 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003569 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3570 II->getIntrinsicID() == Intrinsic::lifetime_end);
3571 II->eraseFromParent();
3572 continue;
3573 }
3574
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003575 // Push the loads and stores we find onto the list. SROA will already
3576 // have validated that all loads and stores are viable candidates for
3577 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003578 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003579 assert(LI->getType() == AI->getAllocatedType());
3580 Insts.push_back(LI);
3581 continue;
3582 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003583 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003584 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3585 Insts.push_back(SI);
3586 continue;
3587 }
3588
3589 // For everything else, we know that only no-op bitcasts and GEPs will
3590 // make it this far, just recurse through them and recall them for later
3591 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003592 DeadInsts.push_back(I);
3593 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003594 }
3595 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003596 while (!DeadInsts.empty())
3597 DeadInsts.pop_back_val()->eraseFromParent();
3598 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003599 }
3600
3601 PromotableAllocas.clear();
3602 return true;
3603}
3604
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003605bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003606 if (skipOptnoneFunction(F))
3607 return false;
3608
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003609 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3610 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003611 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3612 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003613 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3614 return false;
3615 }
Rafael Espindola93512512014-02-25 17:30:31 +00003616 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003617 DominatorTreeWrapperPass *DTWP =
3618 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003619 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003620
3621 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003622 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003623 I != E; ++I)
3624 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3625 Worklist.insert(AI);
3626
3627 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003628 // A set of deleted alloca instruction pointers which should be removed from
3629 // the list of promotable allocas.
3630 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3631
Chandler Carruthac8317f2012-10-04 12:33:50 +00003632 do {
3633 while (!Worklist.empty()) {
3634 Changed |= runOnAlloca(*Worklist.pop_back_val());
3635 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003636
Chandler Carruthac8317f2012-10-04 12:33:50 +00003637 // Remove the deleted allocas from various lists so that we don't try to
3638 // continue processing them.
3639 if (!DeletedAllocas.empty()) {
Chandler Carruthd031fe92014-03-03 19:28:52 +00003640 auto IsInSet = [&](AllocaInst *AI) {
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003641 return DeletedAllocas.count(AI);
3642 };
3643 Worklist.remove_if(IsInSet);
3644 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003645 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3646 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003647 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00003648 PromotableAllocas.end());
3649 DeletedAllocas.clear();
3650 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003651 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003652
Chandler Carruthac8317f2012-10-04 12:33:50 +00003653 Changed |= promoteAllocas(F);
3654
3655 Worklist = PostPromotionWorklist;
3656 PostPromotionWorklist.clear();
3657 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003658
3659 return Changed;
3660}
3661
3662void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003663 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003664 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003665 AU.setPreservesCFG();
3666}