blob: 45b66674bc95fa44e79e852f143f25a98d4f710e [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth1b398ae2012-09-14 09:22:59 +000026#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Hal Finkel60db0582014-09-07 18:57:58 +000031#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000036#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000043#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000054#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include "llvm/Transforms/Utils/SSAUpdater.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000059
60#if __cplusplus >= 201103L && !defined(NDEBUG)
61// We only use this for a debug check in C++11
62#include <random>
63#endif
64
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065using namespace llvm;
66
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "sroa"
68
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000070STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000071STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000074STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000077STATISTIC(NumDeleted, "Number of instructions deleted");
78STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079
Chandler Carruth70b44c52012-09-15 11:43:14 +000080/// Hidden option to force the pass to not use DomTree and mem2reg, instead
81/// forming SSA values through the SSAUpdater infrastructure.
82static cl::opt<bool>
83ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
84
Chandler Carruth83cee772014-02-25 03:59:29 +000085/// Hidden option to enable randomly shuffling the slices to help uncover
86/// instability in their order.
87static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88 cl::init(false), cl::Hidden);
89
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000090/// Hidden option to experiment with completely strict handling of inbounds
91/// GEPs.
92static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
93 cl::init(false), cl::Hidden);
94
Chandler Carruth1b398ae2012-09-14 09:22:59 +000095namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000096/// \brief A custom IRBuilder inserter which prefixes all names if they are
97/// preserved.
98template <bool preserveNames = true>
99class IRBuilderPrefixedInserter :
100 public IRBuilderDefaultInserter<preserveNames> {
101 std::string Prefix;
102
103public:
104 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
105
106protected:
107 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108 BasicBlock::iterator InsertPt) const {
109 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
111 }
112};
113
114// Specialization for not preserving the name is trivial.
115template <>
116class IRBuilderPrefixedInserter<false> :
117 public IRBuilderDefaultInserter<false> {
118public:
119 void SetNamePrefix(const Twine &P) {}
120};
121
Chandler Carruthd177f862013-03-20 07:30:36 +0000122/// \brief Provide a typedef for IRBuilder that drops names in release builds.
123#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000124typedef llvm::IRBuilder<true, ConstantFolder,
125 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000126#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000127typedef llvm::IRBuilder<false, ConstantFolder,
128 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000129#endif
130}
131
132namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000133/// \brief A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000134///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000135/// This structure represents a slice of an alloca used by some instruction. It
136/// stores both the begin and end offsets of this use, a pointer to the use
137/// itself, and a flag indicating whether we can classify the use as splittable
138/// or not when forming partitions of the alloca.
139class Slice {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000140 /// \brief The beginning offset of the range.
141 uint64_t BeginOffset;
142
143 /// \brief The ending offset, not included in the range.
144 uint64_t EndOffset;
145
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000146 /// \brief Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000147 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000148 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000149
150public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000151 Slice() : BeginOffset(), EndOffset() {}
152 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000153 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000155
156 uint64_t beginOffset() const { return BeginOffset; }
157 uint64_t endOffset() const { return EndOffset; }
158
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000159 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000161
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000162 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000163
Craig Topperf40110f2014-04-25 05:29:35 +0000164 bool isDead() const { return getUse() == nullptr; }
165 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000166
167 /// \brief Support for ordering ranges.
168 ///
169 /// This provides an ordering over ranges such that start offsets are
170 /// always increasing, and within equal start offsets, the end offsets are
171 /// decreasing. Thus the spanning range comes first in a cluster with the
172 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 bool operator<(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000174 if (beginOffset() < RHS.beginOffset()) return true;
175 if (beginOffset() > RHS.beginOffset()) return false;
176 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
177 if (endOffset() > RHS.endOffset()) return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000178 return false;
179 }
180
181 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000183 uint64_t RHSOffset) {
184 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000185 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000187 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000188 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000190
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000191 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000192 return isSplittable() == RHS.isSplittable() &&
193 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000194 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000195 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000196};
Chandler Carruthf0546402013-07-18 07:15:00 +0000197} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000198
199namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000200template <typename T> struct isPodLike;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000201template <> struct isPodLike<Slice> {
Chandler Carruthf0546402013-07-18 07:15:00 +0000202 static const bool value = true;
203};
Chandler Carruthf74654d2013-03-18 08:36:46 +0000204}
205
206namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000207/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000208///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000209/// This class represents the slices of an alloca which are formed by its
210/// various uses. If a pointer escapes, we can't fully build a representation
211/// for the slices used and we reflect that in this structure. The uses are
212/// stored, sorted by increasing beginning offset and with unsplittable slices
213/// starting at a particular offset before splittable slices.
214class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000215public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000216 /// \brief Construct the slices of a particular alloca.
217 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000218
219 /// \brief Test whether a pointer to the allocation escapes our analysis.
220 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000221 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000222 /// ignored.
223 bool isEscaped() const { return PointerEscapingInstr; }
224
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000225 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000226 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000227 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000228 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000229 iterator begin() { return Slices.begin(); }
230 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000231
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000232 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000233 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000234 const_iterator begin() const { return Slices.begin(); }
235 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000236 /// @}
237
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000238 /// \brief Access the dead users for this alloca.
239 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000240
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000241 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000242 ///
243 /// These are operands which have cannot actually be used to refer to the
244 /// alloca as they are outside its range and the user doesn't correct for
245 /// that. These mostly consist of PHI node inputs and the like which we just
246 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000247 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000248
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000249#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000250 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000251 void printSlice(raw_ostream &OS, const_iterator I,
252 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000253 void printUse(raw_ostream &OS, const_iterator I,
254 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000256 void dump(const_iterator I) const;
257 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000258#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000259
260private:
261 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000262 class SliceBuilder;
263 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000264
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000265#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000266 /// \brief Handle to alloca instruction to simplify method interfaces.
267 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000268#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000269
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000270 /// \brief The instruction responsible for this alloca not having a known set
271 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000272 ///
273 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000274 /// store a pointer to that here and abort trying to form slices of the
275 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000276 Instruction *PointerEscapingInstr;
277
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000278 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000279 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000280 /// We store a vector of the slices formed by uses of the alloca here. This
281 /// vector is sorted by increasing begin offset, and then the unsplittable
282 /// slices before the splittable ones. See the Slice inner class for more
283 /// details.
284 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000285
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000286 /// \brief Instructions which will become dead if we rewrite the alloca.
287 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000288 /// Note that these are not separated by slice. This is because we expect an
289 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
290 /// all these instructions can simply be removed and replaced with undef as
291 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000292 SmallVector<Instruction *, 8> DeadUsers;
293
294 /// \brief Operands which will become dead if we rewrite the alloca.
295 ///
296 /// These are operands that in their particular use can be replaced with
297 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
298 /// to PHI nodes and the like. They aren't entirely dead (there might be
299 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
300 /// want to swap this particular input for undef to simplify the use lists of
301 /// the alloca.
302 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000303};
304}
305
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000306static Value *foldSelectInst(SelectInst &SI) {
307 // If the condition being selected on is a constant or the same value is
308 // being selected between, fold the select. Yes this does (rarely) happen
309 // early on.
310 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
311 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000312 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000313 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000314
Craig Topperf40110f2014-04-25 05:29:35 +0000315 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000316}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000317
Jingyue Wuec33fa92014-08-22 22:45:57 +0000318/// \brief A helper that folds a PHI node or a select.
319static Value *foldPHINodeOrSelectInst(Instruction &I) {
320 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
321 // If PN merges together the same value, return that value.
322 return PN->hasConstantValue();
323 }
324 return foldSelectInst(cast<SelectInst>(I));
325}
326
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 Carruth83934062014-10-16 21:11:55 +0000337 AllocaSlices &AS;
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:
Chandler Carruth83934062014-10-16 21:11:55 +0000346 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000347 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000348 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000349
350private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000351 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000352 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000353 AS.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 Carruth83934062014-10-16 21:11:55 +0000364 << " alloca: " << AS.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 Carruth83934062014-10-16 21:11:55 +0000382 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000383 << " use: " << I << "\n");
384 EndOffset = AllocSize;
385 }
386
Chandler Carruth83934062014-10-16 21:11:55 +0000387 AS.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 Carruth83934062014-10-16 21:11:55 +0000488 << " alloca: " << AS.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())
Chandler Carruth83934062014-10-16 21:11:55 +0000538 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000539 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 Carruth83934062014-10-16 21:11:55 +0000561 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000562 unsigned PrevIdx = MTPI->second;
563 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000564 Slice &PrevP = AS.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 Carruth83934062014-10-16 21:11:55 +0000582 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000583 "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())
David Blaikie70573dc2014-11-19 07:49:26 +0000642 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000643 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
Jingyue Wuec33fa92014-08-22 22:45:57 +0000649 void visitPHINodeOrSelectInst(Instruction &I) {
650 assert(isa<PHINode>(I) || isa<SelectInst>(I));
651 if (I.use_empty())
652 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000653
Jingyue Wuec33fa92014-08-22 22:45:57 +0000654 // TODO: We could use SimplifyInstruction here to fold PHINodes and
655 // SelectInsts. However, doing so requires to change the current
656 // dead-operand-tracking mechanism. For instance, suppose neither loading
657 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
658 // trap either. However, if we simply replace %U with undef using the
659 // current dead-operand-tracking mechanism, "load (select undef, undef,
660 // %other)" may trap because the select may return the first operand
661 // "undef".
662 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000663 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000664 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000665 // through the PHI/select as if we had RAUW'ed it.
666 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000667 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000668 // Otherwise the operand to the PHI/select is dead, and we can replace
669 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000670 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000671
672 return;
673 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000674
Chandler Carruthf0546402013-07-18 07:15:00 +0000675 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000676 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000677
Chandler Carruthf0546402013-07-18 07:15:00 +0000678 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000679 uint64_t &Size = PHIOrSelectSizes[&I];
680 if (!Size) {
681 // This is a new PHI/Select, check for an unsafe use of it.
682 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000683 return PI.setAborted(UnsafeI);
684 }
685
686 // For PHI and select operands outside the alloca, we can't nuke the entire
687 // phi or select -- the other side might still be relevant, so we special
688 // case them here and use a separate structure to track the operands
689 // themselves which should be replaced with undef.
690 // FIXME: This should instead be escaped in the event we're instrumenting
691 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000692 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000693 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000694 return;
695 }
696
Jingyue Wuec33fa92014-08-22 22:45:57 +0000697 insertUse(I, Offset, Size);
698 }
699
700 void visitPHINode(PHINode &PN) {
701 visitPHINodeOrSelectInst(PN);
702 }
703
704 void visitSelectInst(SelectInst &SI) {
705 visitPHINodeOrSelectInst(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000706 }
707
Chandler Carruthf0546402013-07-18 07:15:00 +0000708 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000709 void visitInstruction(Instruction &I) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000710 PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000711 }
712};
713
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000714AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000715 :
716#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
717 AI(AI),
718#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000719 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000720 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000721 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000722 if (PtrI.isEscaped() || PtrI.isAborted()) {
723 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000724 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000725 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
726 : PtrI.getAbortingInst();
727 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000728 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000729 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000730
Benjamin Kramer08e50702013-07-20 08:38:34 +0000731 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
732 std::mem_fun_ref(&Slice::isDead)),
733 Slices.end());
734
Chandler Carruth83cee772014-02-25 03:59:29 +0000735#if __cplusplus >= 201103L && !defined(NDEBUG)
736 if (SROARandomShuffleSlices) {
737 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
738 std::shuffle(Slices.begin(), Slices.end(), MT);
739 }
740#endif
741
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000742 // Sort the uses. This arranges for the offsets to be in ascending order,
743 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000744 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000745}
746
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000747#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
748
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000749void AllocaSlices::print(raw_ostream &OS, const_iterator I,
750 StringRef Indent) const {
751 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +0000752 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000753}
754
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000755void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
756 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000757 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000758 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +0000759 << (I->isSplittable() ? " (splittable)" : "") << "\n";
760}
761
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000762void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
763 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000764 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000765}
766
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000767void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000768 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000769 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000770 << " A pointer to this alloca escaped by:\n"
771 << " " << *PointerEscapingInstr << "\n";
772 return;
773 }
774
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000775 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +0000776 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000778}
779
Alp Tokerf929e092014-01-04 22:47:48 +0000780LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
781 print(dbgs(), I);
782}
783LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000784
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000785#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
786
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000787namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000788/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
789///
790/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
791/// the loads and stores of an alloca instruction, as well as updating its
792/// debug information. This is used when a domtree is unavailable and thus
793/// mem2reg in its full form can't be used to handle promotion of allocas to
794/// scalar values.
795class AllocaPromoter : public LoadAndStorePromoter {
796 AllocaInst &AI;
797 DIBuilder &DIB;
798
799 SmallVector<DbgDeclareInst *, 4> DDIs;
800 SmallVector<DbgValueInst *, 4> DVIs;
801
802public:
Chandler Carruth45b136f2013-08-11 01:03:18 +0000803 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +0000804 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +0000805 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +0000806
807 void run(const SmallVectorImpl<Instruction*> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000808 // Retain the debug information attached to the alloca for use when
809 // rewriting loads and stores.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000810 if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
811 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
812 for (User *U : DebugNode->users())
813 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
814 DDIs.push_back(DDI);
815 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
816 DVIs.push_back(DVI);
817 }
Chandler Carruth70b44c52012-09-15 11:43:14 +0000818 }
819
820 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000821
822 // While we have the debug information, clear it off of the alloca. The
823 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000824 while (!DDIs.empty())
825 DDIs.pop_back_val()->eraseFromParent();
826 while (!DVIs.empty())
827 DVIs.pop_back_val()->eraseFromParent();
828 }
829
Craig Topper3e4c6972014-03-05 09:10:37 +0000830 bool isInstInList(Instruction *I,
831 const SmallVectorImpl<Instruction*> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000832 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000833 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000834 Ptr = LI->getOperand(0);
835 else
836 Ptr = cast<StoreInst>(I)->getPointerOperand();
837
838 // Only used to detect cycles, which will be rare and quickly found as
839 // we're walking up a chain of defs rather than down through uses.
840 SmallPtrSet<Value *, 4> Visited;
841
842 do {
843 if (Ptr == &AI)
844 return true;
845
846 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
847 Ptr = BCI->getOperand(0);
848 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
849 Ptr = GEPI->getPointerOperand();
850 else
851 return false;
852
David Blaikie70573dc2014-11-19 07:49:26 +0000853 } while (Visited.insert(Ptr).second);
Chandler Carruthc17283b2013-08-11 01:56:15 +0000854
855 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000856 }
857
Craig Topper3e4c6972014-03-05 09:10:37 +0000858 void updateDebugInfo(Instruction *Inst) const override {
Chandler Carruth61747042014-10-16 21:05:14 +0000859 for (DbgDeclareInst *DDI : DDIs)
Chandler Carruth70b44c52012-09-15 11:43:14 +0000860 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
861 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
862 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
863 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Chandler Carruth61747042014-10-16 21:05:14 +0000864 for (DbgValueInst *DVI : DVIs) {
Craig Topperf40110f2014-04-25 05:29:35 +0000865 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000866 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
867 // If an argument is zero extended then use argument directly. The ZExt
868 // may be zapped by an optimization pass in future.
869 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
870 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000871 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000872 Arg = dyn_cast<Argument>(SExt->getOperand(0));
873 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000874 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000875 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000876 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000877 } else {
878 continue;
879 }
880 Instruction *DbgVal =
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000881 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
882 DIExpression(DVI->getExpression()), Inst);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000883 DbgVal->setDebugLoc(DVI->getDebugLoc());
884 }
885 }
886};
887} // end anon namespace
888
889
890namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000891/// \brief An optimization pass providing Scalar Replacement of Aggregates.
892///
893/// This pass takes allocations which can be completely analyzed (that is, they
894/// don't escape) and tries to turn them into scalar SSA values. There are
895/// a few steps to this process.
896///
897/// 1) It takes allocations of aggregates and analyzes the ways in which they
898/// are used to try to split them into smaller allocations, ideally of
899/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000900/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000901/// 2) It will transform accesses into forms which are suitable for SSA value
902/// promotion. This can be replacing a memset with a scalar store of an
903/// integer value, or it can involve speculating operations on a PHI or
904/// select to be a PHI or select of the results.
905/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
906/// onto insert and extract operations on a vector value, and convert them to
907/// this form. By doing so, it will enable promotion of vector aggregates to
908/// SSA vector values.
909class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000910 const bool RequiresDomTree;
911
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000912 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000913 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000914 DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +0000915 AssumptionTracker *AT;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000916
917 /// \brief Worklist of alloca instructions to simplify.
918 ///
919 /// Each alloca in the function is added to this. Each new alloca formed gets
920 /// added to it as well to recursively simplify unless that alloca can be
921 /// directly promoted. Finally, each time we rewrite a use of an alloca other
922 /// the one being actively rewritten, we add it back onto the list if not
923 /// already present to ensure it is re-visited.
924 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
925
926 /// \brief A collection of instructions to delete.
927 /// We try to batch deletions to simplify code and make things a bit more
928 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000929 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000930
Chandler Carruthac8317f2012-10-04 12:33:50 +0000931 /// \brief Post-promotion worklist.
932 ///
933 /// Sometimes we discover an alloca which has a high probability of becoming
934 /// viable for SROA after a round of promotion takes place. In those cases,
935 /// the alloca is enqueued here for re-processing.
936 ///
937 /// Note that we have to be very careful to clear allocas out of this list in
938 /// the event they are deleted.
939 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
940
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000941 /// \brief A collection of alloca instructions we can directly promote.
942 std::vector<AllocaInst *> PromotableAllocas;
943
Chandler Carruthf0546402013-07-18 07:15:00 +0000944 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
945 ///
946 /// All of these PHIs have been checked for the safety of speculation and by
947 /// being speculated will allow promoting allocas currently in the promotable
948 /// queue.
949 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
950
951 /// \brief A worklist of select instructions to speculate prior to promoting
952 /// allocas.
953 ///
954 /// All of these select instructions have been checked for the safety of
955 /// speculation and by being speculated will allow promoting allocas
956 /// currently in the promotable queue.
957 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
958
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000959public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000960 SROA(bool RequiresDomTree = true)
961 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Craig Topperf40110f2014-04-25 05:29:35 +0000962 C(nullptr), DL(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000963 initializeSROAPass(*PassRegistry::getPassRegistry());
964 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000965 bool runOnFunction(Function &F) override;
966 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000967
Craig Topper3e4c6972014-03-05 09:10:37 +0000968 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000969 static char ID;
970
971private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000972 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000973 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000974
Chandler Carruth83934062014-10-16 21:11:55 +0000975 bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000976 AllocaSlices::iterator B, AllocaSlices::iterator E,
977 int64_t BeginOffset, int64_t EndOffset,
978 ArrayRef<AllocaSlices::iterator> SplitUses);
Chandler Carruth83934062014-10-16 21:11:55 +0000979 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000980 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000981 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +0000982 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000983 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000984};
985}
986
987char SROA::ID = 0;
988
Chandler Carruth70b44c52012-09-15 11:43:14 +0000989FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
990 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000991}
992
993INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
994 false, false)
Hal Finkel60db0582014-09-07 18:57:58 +0000995INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000996INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000997INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
998 false, false)
999
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001000/// Walk the range of a partitioning looking for a common type to cover this
1001/// sequence of slices.
1002static Type *findCommonType(AllocaSlices::const_iterator B,
1003 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001004 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001005 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001006 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001007 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001008
1009 // Note that we need to look at *every* alloca slice's Use to ensure we
1010 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001011 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001012 Use *U = I->getUse();
1013 if (isa<IntrinsicInst>(*U->getUser()))
1014 continue;
1015 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1016 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001017
Craig Topperf40110f2014-04-25 05:29:35 +00001018 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001019 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001020 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001021 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001022 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001023 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001024
Chandler Carruth4de31542014-01-21 23:16:05 +00001025 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001026 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001027 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001028 // entity causing the split. Also skip if the type is not a byte width
1029 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001030 if (UserITy->getBitWidth() % 8 != 0 ||
1031 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001033
Chandler Carruth4de31542014-01-21 23:16:05 +00001034 // Track the largest bitwidth integer type used in this way in case there
1035 // is no common type.
1036 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1037 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001038 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001039
1040 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1041 // depend on types skipped above.
1042 if (!UserTy || (Ty && Ty != UserTy))
1043 TyIsCommon = false; // Give up on anything but an iN type.
1044 else
1045 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001046 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001047
1048 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001049}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001050
Chandler Carruthf0546402013-07-18 07:15:00 +00001051/// PHI instructions that use an alloca and are subsequently loaded can be
1052/// rewritten to load both input pointers in the pred blocks and then PHI the
1053/// results, allowing the load of the alloca to be promoted.
1054/// From this:
1055/// %P2 = phi [i32* %Alloca, i32* %Other]
1056/// %V = load i32* %P2
1057/// to:
1058/// %V1 = load i32* %Alloca -> will be mem2reg'd
1059/// ...
1060/// %V2 = load i32* %Other
1061/// ...
1062/// %V = phi [i32 %V1, i32 %V2]
1063///
1064/// We can do this to a select if its only uses are loads and if the operands
1065/// to the select can be loaded unconditionally.
1066///
1067/// FIXME: This should be hoisted into a generic utility, likely in
1068/// Transforms/Util/Local.h
1069static bool isSafePHIToSpeculate(PHINode &PN,
Craig Topperf40110f2014-04-25 05:29:35 +00001070 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001071 // For now, we can only do this promotion if the load is in the same block
1072 // as the PHI, and if there are no stores between the phi and load.
1073 // TODO: Allow recursive phi users.
1074 // TODO: Allow stores.
1075 BasicBlock *BB = PN.getParent();
1076 unsigned MaxAlign = 0;
1077 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001078 for (User *U : PN.users()) {
1079 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001080 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001081 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001082
Chandler Carruthf0546402013-07-18 07:15:00 +00001083 // For now we only allow loads in the same block as the PHI. This is
1084 // a common case that happens when instcombine merges two loads through
1085 // a PHI.
1086 if (LI->getParent() != BB)
1087 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001088
Chandler Carruthf0546402013-07-18 07:15:00 +00001089 // Ensure that there are no instructions between the PHI and the load that
1090 // could store.
1091 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1092 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001093 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001094
Chandler Carruthf0546402013-07-18 07:15:00 +00001095 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1096 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001097 }
1098
Chandler Carruthf0546402013-07-18 07:15:00 +00001099 if (!HaveLoad)
1100 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001101
Chandler Carruthf0546402013-07-18 07:15:00 +00001102 // We can only transform this if it is safe to push the loads into the
1103 // predecessor blocks. The only thing to watch out for is that we can't put
1104 // a possibly trapping load in the predecessor if it is a critical edge.
1105 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1106 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1107 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001108
Chandler Carruthf0546402013-07-18 07:15:00 +00001109 // If the value is produced by the terminator of the predecessor (an
1110 // invoke) or it has side-effects, there is no valid place to put a load
1111 // in the predecessor.
1112 if (TI == InVal || TI->mayHaveSideEffects())
1113 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001114
Chandler Carruthf0546402013-07-18 07:15:00 +00001115 // If the predecessor has a single successor, then the edge isn't
1116 // critical.
1117 if (TI->getNumSuccessors() == 1)
1118 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001119
Chandler Carruthf0546402013-07-18 07:15:00 +00001120 // If this pointer is always safe to load, or if we can prove that there
1121 // is already a load in the block, then we can move the load to the pred
1122 // block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001123 if (InVal->isDereferenceablePointer(DL) ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001124 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001125 continue;
1126
1127 return false;
1128 }
1129
1130 return true;
1131}
1132
1133static void speculatePHINodeLoads(PHINode &PN) {
1134 DEBUG(dbgs() << " original: " << PN << "\n");
1135
1136 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1137 IRBuilderTy PHIBuilder(&PN);
1138 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1139 PN.getName() + ".sroa.speculated");
1140
Hal Finkelcc39b672014-07-24 12:16:19 +00001141 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001142 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001143 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001144
1145 AAMDNodes AATags;
1146 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001147 unsigned Align = SomeLoad->getAlignment();
1148
1149 // Rewrite all loads of the PN to use the new PHI.
1150 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001151 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001152 LI->replaceAllUsesWith(NewPN);
1153 LI->eraseFromParent();
1154 }
1155
1156 // Inject loads into all of the pred blocks.
1157 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1158 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1159 TerminatorInst *TI = Pred->getTerminator();
1160 Value *InVal = PN.getIncomingValue(Idx);
1161 IRBuilderTy PredBuilder(TI);
1162
1163 LoadInst *Load = PredBuilder.CreateLoad(
1164 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1165 ++NumLoadsSpeculated;
1166 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001167 if (AATags)
1168 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001169 NewPN->addIncoming(Load, Pred);
1170 }
1171
1172 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1173 PN.eraseFromParent();
1174}
1175
1176/// Select instructions that use an alloca and are subsequently loaded can be
1177/// rewritten to load both input pointers and then select between the result,
1178/// allowing the load of the alloca to be promoted.
1179/// From this:
1180/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1181/// %V = load i32* %P2
1182/// to:
1183/// %V1 = load i32* %Alloca -> will be mem2reg'd
1184/// %V2 = load i32* %Other
1185/// %V = select i1 %cond, i32 %V1, i32 %V2
1186///
1187/// We can do this to a select if its only uses are loads and if the operand
1188/// to the select can be loaded unconditionally.
Craig Topperf40110f2014-04-25 05:29:35 +00001189static bool isSafeSelectToSpeculate(SelectInst &SI,
1190 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001191 Value *TValue = SI.getTrueValue();
1192 Value *FValue = SI.getFalseValue();
Hal Finkel2e42c342014-07-10 05:27:53 +00001193 bool TDerefable = TValue->isDereferenceablePointer(DL);
1194 bool FDerefable = FValue->isDereferenceablePointer(DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001195
Chandler Carruthcdf47882014-03-09 03:16:01 +00001196 for (User *U : SI.users()) {
1197 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001198 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001199 return false;
1200
1201 // Both operands to the select need to be dereferencable, either
1202 // absolutely (e.g. allocas) or at this point because we can see other
1203 // accesses to it.
1204 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001205 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001206 return false;
1207 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001208 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001209 return false;
1210 }
1211
1212 return true;
1213}
1214
1215static void speculateSelectInstLoads(SelectInst &SI) {
1216 DEBUG(dbgs() << " original: " << SI << "\n");
1217
1218 IRBuilderTy IRB(&SI);
1219 Value *TV = SI.getTrueValue();
1220 Value *FV = SI.getFalseValue();
1221 // Replace the loads of the select with a select of two loads.
1222 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001223 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001224 assert(LI->isSimple() && "We only speculate simple loads");
1225
1226 IRB.SetInsertPoint(LI);
1227 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001228 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001229 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001230 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001231 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001232
Hal Finkelcc39b672014-07-24 12:16:19 +00001233 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001234 TL->setAlignment(LI->getAlignment());
1235 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001236
1237 AAMDNodes Tags;
1238 LI->getAAMetadata(Tags);
1239 if (Tags) {
1240 TL->setAAMetadata(Tags);
1241 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001242 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001243
1244 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1245 LI->getName() + ".sroa.speculated");
1246
1247 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1248 LI->replaceAllUsesWith(V);
1249 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001250 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001251 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001252}
1253
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001254/// \brief Build a GEP out of a base pointer and indices.
1255///
1256/// This will return the BasePtr if that is valid, or build a new GEP
1257/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001258static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001259 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001260 if (Indices.empty())
1261 return BasePtr;
1262
1263 // A single zero index is a no-op, so check for this and avoid building a GEP
1264 // in that case.
1265 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1266 return BasePtr;
1267
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001268 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001269}
1270
1271/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1272/// TargetTy without changing the offset of the pointer.
1273///
1274/// This routine assumes we've already established a properly offset GEP with
1275/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1276/// zero-indices down through type layers until we find one the same as
1277/// TargetTy. If we can't find one with the same type, we at least try to use
1278/// one with the same size. If none of that works, we just produce the GEP as
1279/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001280static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001281 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001282 SmallVectorImpl<Value *> &Indices,
1283 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001284 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001285 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001286
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001287 // Pointer size to use for the indices.
1288 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1289
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001290 // See if we can descend into a struct and locate a field with the correct
1291 // type.
1292 unsigned NumLayers = 0;
1293 Type *ElementTy = Ty;
1294 do {
1295 if (ElementTy->isPointerTy())
1296 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001297
1298 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1299 ElementTy = ArrayTy->getElementType();
1300 Indices.push_back(IRB.getIntN(PtrSize, 0));
1301 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1302 ElementTy = VectorTy->getElementType();
1303 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001304 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001305 if (STy->element_begin() == STy->element_end())
1306 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001307 ElementTy = *STy->element_begin();
1308 Indices.push_back(IRB.getInt32(0));
1309 } else {
1310 break;
1311 }
1312 ++NumLayers;
1313 } while (ElementTy != TargetTy);
1314 if (ElementTy != TargetTy)
1315 Indices.erase(Indices.end() - NumLayers, Indices.end());
1316
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001317 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001318}
1319
1320/// \brief Recursively compute indices for a natural GEP.
1321///
1322/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1323/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001324static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001325 Value *Ptr, Type *Ty, APInt &Offset,
1326 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001327 SmallVectorImpl<Value *> &Indices,
1328 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001329 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001330 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001331
1332 // We can't recurse through pointer types.
1333 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001334 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001335
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001336 // We try to analyze GEPs over vectors here, but note that these GEPs are
1337 // extremely poorly defined currently. The long-term goal is to remove GEPing
1338 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001339 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001340 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001341 if (ElementSizeInBits % 8 != 0) {
1342 // GEPs over non-multiple of 8 size vector elements are invalid.
1343 return nullptr;
1344 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001345 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001346 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001347 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001348 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001349 Offset -= NumSkippedElements * ElementSize;
1350 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001351 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001352 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001353 }
1354
1355 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1356 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001357 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001358 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001359 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001360 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001361
1362 Offset -= NumSkippedElements * ElementSize;
1363 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001364 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001365 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001366 }
1367
1368 StructType *STy = dyn_cast<StructType>(Ty);
1369 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001370 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001371
Chandler Carruth90a735d2013-07-19 07:21:28 +00001372 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001373 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001374 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001375 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001376 unsigned Index = SL->getElementContainingOffset(StructOffset);
1377 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1378 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001379 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001380 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001381
1382 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001383 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001384 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001385}
1386
1387/// \brief Get a natural GEP from a base pointer to a particular offset and
1388/// resulting in a particular type.
1389///
1390/// The goal is to produce a "natural" looking GEP that works with the existing
1391/// composite types to arrive at the appropriate offset and element type for
1392/// a pointer. TargetTy is the element type the returned GEP should point-to if
1393/// possible. We recurse by decreasing Offset, adding the appropriate index to
1394/// Indices, and setting Ty to the result subtype.
1395///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001396/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001397static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001398 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001399 SmallVectorImpl<Value *> &Indices,
1400 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001401 PointerType *Ty = cast<PointerType>(Ptr->getType());
1402
1403 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1404 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001405 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001406 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001407
1408 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001409 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001410 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001411 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001412 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001414 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001415
1416 Offset -= NumSkippedElements * ElementSize;
1417 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001418 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001419 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001420}
1421
1422/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1423/// resulting pointer has PointerTy.
1424///
1425/// This tries very hard to compute a "natural" GEP which arrives at the offset
1426/// and produces the pointer type desired. Where it cannot, it will try to use
1427/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1428/// fails, it will try to use an existing i8* and GEP to the byte offset and
1429/// bitcast to the type.
1430///
1431/// The strategy for finding the more natural GEPs is to peel off layers of the
1432/// pointer, walking back through bit casts and GEPs, searching for a base
1433/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001434/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001435/// a single GEP as possible, thus making each GEP more independent of the
1436/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001437static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1438 APInt Offset, Type *PointerTy,
1439 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001440 // Even though we don't look through PHI nodes, we could be called on an
1441 // instruction in an unreachable block, which may be on a cycle.
1442 SmallPtrSet<Value *, 4> Visited;
1443 Visited.insert(Ptr);
1444 SmallVector<Value *, 4> Indices;
1445
1446 // We may end up computing an offset pointer that has the wrong type. If we
1447 // never are able to compute one directly that has the correct type, we'll
1448 // fall back to it, so keep it around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001449 Value *OffsetPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001450
1451 // Remember any i8 pointer we come across to re-use if we need to do a raw
1452 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001453 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001454 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1455
1456 Type *TargetTy = PointerTy->getPointerElementType();
1457
1458 do {
1459 // First fold any existing GEPs into the offset.
1460 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1461 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001462 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001463 break;
1464 Offset += GEPOffset;
1465 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001466 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001467 break;
1468 }
1469
1470 // See if we can perform a natural GEP here.
1471 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001472 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001473 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001474 if (P->getType() == PointerTy) {
1475 // Zap any offset pointer that we ended up computing in previous rounds.
1476 if (OffsetPtr && OffsetPtr->use_empty())
1477 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1478 I->eraseFromParent();
1479 return P;
1480 }
1481 if (!OffsetPtr) {
1482 OffsetPtr = P;
1483 }
1484 }
1485
1486 // Stash this pointer if we've found an i8*.
1487 if (Ptr->getType()->isIntegerTy(8)) {
1488 Int8Ptr = Ptr;
1489 Int8PtrOffset = Offset;
1490 }
1491
1492 // Peel off a layer of the pointer and update the offset appropriately.
1493 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1494 Ptr = cast<Operator>(Ptr)->getOperand(0);
1495 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1496 if (GA->mayBeOverridden())
1497 break;
1498 Ptr = GA->getAliasee();
1499 } else {
1500 break;
1501 }
1502 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001503 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001504
1505 if (!OffsetPtr) {
1506 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001507 Int8Ptr = IRB.CreateBitCast(
1508 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1509 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001510 Int8PtrOffset = Offset;
1511 }
1512
1513 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1514 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001515 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001516 }
1517 Ptr = OffsetPtr;
1518
1519 // On the off chance we were targeting i8*, guard the bitcast here.
1520 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001521 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001522
1523 return Ptr;
1524}
1525
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001526/// \brief Test whether we can convert a value from the old to the new type.
1527///
1528/// This predicate should be used to guard calls to convertValue in order to
1529/// ensure that we only try to convert viable values. The strategy is that we
1530/// will peel off single element struct and array wrappings to get to an
1531/// underlying value, and convert that value.
1532static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1533 if (OldTy == NewTy)
1534 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001535 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1536 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1537 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1538 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001539 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1540 return false;
1541 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1542 return false;
1543
Benjamin Kramer56262592013-09-22 11:24:58 +00001544 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001545 // of pointers and integers.
1546 OldTy = OldTy->getScalarType();
1547 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001548 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1549 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1550 return true;
1551 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1552 return true;
1553 return false;
1554 }
1555
1556 return true;
1557}
1558
1559/// \brief Generic routine to convert an SSA value to a value of a different
1560/// type.
1561///
1562/// This will try various different casting techniques, such as bitcasts,
1563/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1564/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001565static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001566 Type *NewTy) {
1567 Type *OldTy = V->getType();
1568 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1569
1570 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001571 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001572
1573 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1574 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001575 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1576 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001577
Benjamin Kramer90901a32013-09-21 20:36:04 +00001578 // See if we need inttoptr for this type pair. A cast involving both scalars
1579 // and vectors requires and additional bitcast.
1580 if (OldTy->getScalarType()->isIntegerTy() &&
1581 NewTy->getScalarType()->isPointerTy()) {
1582 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1583 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1584 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1585 NewTy);
1586
1587 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1588 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1589 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1590 NewTy);
1591
1592 return IRB.CreateIntToPtr(V, NewTy);
1593 }
1594
1595 // See if we need ptrtoint for this type pair. A cast involving both scalars
1596 // and vectors requires and additional bitcast.
1597 if (OldTy->getScalarType()->isPointerTy() &&
1598 NewTy->getScalarType()->isIntegerTy()) {
1599 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1600 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1601 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1602 NewTy);
1603
1604 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1605 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1606 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1607 NewTy);
1608
1609 return IRB.CreatePtrToInt(V, NewTy);
1610 }
1611
1612 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001613}
1614
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001615/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001616///
1617/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001618/// for a single slice.
Chandler Carruthc659df92014-10-16 20:24:07 +00001619static bool
1620isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
1621 uint64_t SliceEndOffset, VectorType *Ty,
1622 uint64_t ElementSize, const Slice &S) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001623 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001624 uint64_t BeginOffset =
Chandler Carruthc659df92014-10-16 20:24:07 +00001625 std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001626 uint64_t BeginIndex = BeginOffset / ElementSize;
1627 if (BeginIndex * ElementSize != BeginOffset ||
1628 BeginIndex >= Ty->getNumElements())
1629 return false;
1630 uint64_t EndOffset =
Chandler Carruthc659df92014-10-16 20:24:07 +00001631 std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001632 uint64_t EndIndex = EndOffset / ElementSize;
1633 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1634 return false;
1635
1636 assert(EndIndex > BeginIndex && "Empty vector!");
1637 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001638 Type *SliceTy = (NumElements == 1)
1639 ? Ty->getElementType()
1640 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001641
1642 Type *SplitIntTy =
1643 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1644
Chandler Carruthc659df92014-10-16 20:24:07 +00001645 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001646
1647 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1648 if (MI->isVolatile())
1649 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001650 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001651 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001652 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1653 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1654 II->getIntrinsicID() != Intrinsic::lifetime_end)
1655 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001656 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1657 // Disable vector promotion when there are loads or stores of an FCA.
1658 return false;
1659 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1660 if (LI->isVolatile())
1661 return false;
1662 Type *LTy = LI->getType();
Chandler Carruthc659df92014-10-16 20:24:07 +00001663 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.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 Carruthc659df92014-10-16 20:24:07 +00001673 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001674 assert(STy->isIntegerTy());
1675 STy = SplitIntTy;
1676 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001677 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001678 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001679 } else {
1680 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001681 }
1682
1683 return true;
1684}
1685
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001686/// \brief Test whether the given alloca partitioning and range of slices can be
1687/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001688///
1689/// This is a quick test to check whether we can rewrite a particular alloca
1690/// partition (and its newly formed alloca) into a vector alloca with only
1691/// whole-vector loads and stores such that it could be promoted to a vector
1692/// SSA value. We only can ensure this for a limited set of operations, and we
1693/// don't want to do the rewrites unless we are confident that the result will
1694/// be promotable, so we have an early test here.
Chandler Carruth2dc96822014-10-18 00:44:02 +00001695static VectorType *
David Majnemerc0a313b2014-11-21 02:34:55 +00001696isVectorPromotionViable(const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001697 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
Chandler Carruthc659df92014-10-16 20:24:07 +00001698 AllocaSlices::const_range Slices,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001699 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001700 // Collect the candidate types for vector-based promotion. Also track whether
1701 // we have different element types.
1702 SmallVector<VectorType *, 4> CandidateTys;
1703 Type *CommonEltTy = nullptr;
1704 bool HaveCommonEltTy = true;
1705 auto CheckCandidateType = [&](Type *Ty) {
1706 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1707 CandidateTys.push_back(VTy);
1708 if (!CommonEltTy)
1709 CommonEltTy = VTy->getElementType();
1710 else if (CommonEltTy != VTy->getElementType())
1711 HaveCommonEltTy = false;
1712 }
1713 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001714 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruthc659df92014-10-16 20:24:07 +00001715 for (const auto &S : Slices)
Chandler Carruth2dc96822014-10-18 00:44:02 +00001716 if (S.beginOffset() == SliceBeginOffset &&
1717 S.endOffset() == SliceEndOffset) {
1718 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1719 CheckCandidateType(LI->getType());
1720 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1721 CheckCandidateType(SI->getValueOperand()->getType());
1722 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001723
Chandler Carruth2dc96822014-10-18 00:44:02 +00001724 // If we didn't find a vector type, nothing to do here.
1725 if (CandidateTys.empty())
1726 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001727
Chandler Carruth2dc96822014-10-18 00:44:02 +00001728 // Remove non-integer vector types if we had multiple common element types.
1729 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1730 // do that until all the backends are known to produce good code for all
1731 // integer vector types.
1732 if (!HaveCommonEltTy) {
1733 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1734 [](VectorType *VTy) {
1735 return !VTy->getElementType()->isIntegerTy();
1736 }),
1737 CandidateTys.end());
1738
1739 // If there were no integer vector types, give up.
1740 if (CandidateTys.empty())
1741 return nullptr;
1742
1743 // Rank the remaining candidate vector types. This is easy because we know
1744 // they're all integer vectors. We sort by ascending number of elements.
1745 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1746 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1747 "Cannot have vector types of different sizes!");
1748 assert(RHSTy->getElementType()->isIntegerTy() &&
1749 "All non-integer types eliminated!");
1750 assert(LHSTy->getElementType()->isIntegerTy() &&
1751 "All non-integer types eliminated!");
1752 return RHSTy->getNumElements() < LHSTy->getNumElements();
1753 };
1754 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1755 CandidateTys.erase(
1756 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1757 CandidateTys.end());
1758 } else {
1759// The only way to have the same element type in every vector type is to
1760// have the same vector type. Check that and remove all but one.
1761#ifndef NDEBUG
1762 for (VectorType *VTy : CandidateTys) {
1763 assert(VTy->getElementType() == CommonEltTy &&
1764 "Unaccounted for element type!");
1765 assert(VTy == CandidateTys[0] &&
1766 "Different vector types with the same element type!");
1767 }
1768#endif
1769 CandidateTys.resize(1);
1770 }
1771
1772 // Try each vector type, and return the one which works.
1773 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1774 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1775
1776 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1777 // that aren't byte sized.
1778 if (ElementSize % 8)
1779 return false;
1780 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1781 "vector size not a multiple of element size?");
1782 ElementSize /= 8;
1783
1784 for (const auto &S : Slices)
1785 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1786 VTy, ElementSize, S))
1787 return false;
1788
1789 for (const auto &SI : SplitUses)
1790 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1791 VTy, ElementSize, *SI))
1792 return false;
1793
1794 return true;
1795 };
1796 for (VectorType *VTy : CandidateTys)
1797 if (CheckVectorTypeForPromotion(VTy))
1798 return VTy;
1799
1800 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001801}
1802
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001803/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001804///
1805/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001806/// test below on a single slice of the alloca.
1807static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1808 Type *AllocaTy,
1809 uint64_t AllocBeginOffset,
Chandler Carruthc659df92014-10-16 20:24:07 +00001810 uint64_t Size,
1811 const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001812 bool &WholeAllocaOp) {
Chandler Carruthc659df92014-10-16 20:24:07 +00001813 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1814 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001815
1816 // We can't reasonably handle cases where the load or store extends past
1817 // the end of the aloca's type and into its padding.
1818 if (RelEnd > Size)
1819 return false;
1820
Chandler Carruthc659df92014-10-16 20:24:07 +00001821 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001822
1823 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1824 if (LI->isVolatile())
1825 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001826 // Note that we don't count vector loads or stores as whole-alloca
1827 // operations which enable integer widening because we would prefer to use
1828 // vector widening instead.
1829 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001830 WholeAllocaOp = true;
1831 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001832 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001833 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001834 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001835 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001836 // Non-integer loads need to be convertible from the alloca type so that
1837 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001838 return false;
1839 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001840 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1841 Type *ValueTy = SI->getValueOperand()->getType();
1842 if (SI->isVolatile())
1843 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001844 // Note that we don't count vector loads or stores as whole-alloca
1845 // operations which enable integer widening because we would prefer to use
1846 // vector widening instead.
1847 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001848 WholeAllocaOp = true;
1849 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001850 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001851 return false;
1852 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001853 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001854 // Non-integer stores need to be convertible to the alloca type so that
1855 // they are promotable.
1856 return false;
1857 }
1858 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1859 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1860 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001861 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001862 return false; // Skip any unsplittable intrinsics.
1863 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1864 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1865 II->getIntrinsicID() != Intrinsic::lifetime_end)
1866 return false;
1867 } else {
1868 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001869 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001870
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001871 return true;
1872}
1873
Chandler Carruth435c4e02012-10-15 08:40:30 +00001874/// \brief Test whether the given alloca partition's integer operations can be
1875/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001876///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001877/// This is a quick test to check whether we can rewrite the integer loads and
1878/// stores to a particular alloca into wider loads and stores and be able to
1879/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001880static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001881isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruthc659df92014-10-16 20:24:07 +00001882 uint64_t AllocBeginOffset,
1883 AllocaSlices::const_range Slices,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001884 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001885 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001886 // Don't create integer types larger than the maximum bitwidth.
1887 if (SizeInBits > IntegerType::MAX_INT_BITS)
1888 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001889
1890 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001891 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001892 return false;
1893
Chandler Carruth58d05562012-10-25 04:37:07 +00001894 // We need to ensure that an integer type with the appropriate bitwidth can
1895 // be converted to the alloca type, whatever that is. We don't want to force
1896 // the alloca itself to have an integer type if there is a more suitable one.
1897 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001898 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1899 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001900 return false;
1901
Chandler Carruth90a735d2013-07-19 07:21:28 +00001902 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001903
Chandler Carruthf0546402013-07-18 07:15:00 +00001904 // While examining uses, we ensure that the alloca has a covering load or
1905 // store. We don't want to widen the integer operations only to fail to
1906 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001907 // later). However, if there are only splittable uses, go ahead and assume
1908 // that we cover the alloca.
Chandler Carruthc659df92014-10-16 20:24:07 +00001909 bool WholeAllocaOp =
1910 Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001911
Chandler Carruthc659df92014-10-16 20:24:07 +00001912 for (const auto &S : Slices)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001913 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
Chandler Carruthc659df92014-10-16 20:24:07 +00001914 S, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001915 return false;
1916
Chandler Carruthc659df92014-10-16 20:24:07 +00001917 for (const auto &SI : SplitUses)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001918 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
Chandler Carruthc659df92014-10-16 20:24:07 +00001919 *SI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001920 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001921
Chandler Carruth92924fd2012-09-24 00:34:20 +00001922 return WholeAllocaOp;
1923}
1924
Chandler Carruthd177f862013-03-20 07:30:36 +00001925static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001926 IntegerType *Ty, uint64_t Offset,
1927 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001928 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001929 IntegerType *IntTy = cast<IntegerType>(V->getType());
1930 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1931 "Element extends past full value");
1932 uint64_t ShAmt = 8*Offset;
1933 if (DL.isBigEndian())
1934 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001935 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001936 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001937 DEBUG(dbgs() << " shifted: " << *V << "\n");
1938 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001939 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1940 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001941 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001942 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001943 DEBUG(dbgs() << " trunced: " << *V << "\n");
1944 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001945 return V;
1946}
1947
Chandler Carruthd177f862013-03-20 07:30:36 +00001948static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001949 Value *V, uint64_t Offset, const Twine &Name) {
1950 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1951 IntegerType *Ty = cast<IntegerType>(V->getType());
1952 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1953 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001954 DEBUG(dbgs() << " start: " << *V << "\n");
1955 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001956 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001957 DEBUG(dbgs() << " extended: " << *V << "\n");
1958 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001959 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1960 "Element store outside of alloca store");
1961 uint64_t ShAmt = 8*Offset;
1962 if (DL.isBigEndian())
1963 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001964 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001965 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001966 DEBUG(dbgs() << " shifted: " << *V << "\n");
1967 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001968
1969 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1970 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1971 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001972 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001973 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001974 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001975 }
1976 return V;
1977}
1978
Chandler Carruthd177f862013-03-20 07:30:36 +00001979static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001980 unsigned BeginIndex, unsigned EndIndex,
1981 const Twine &Name) {
1982 VectorType *VecTy = cast<VectorType>(V->getType());
1983 unsigned NumElements = EndIndex - BeginIndex;
1984 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1985
1986 if (NumElements == VecTy->getNumElements())
1987 return V;
1988
1989 if (NumElements == 1) {
1990 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1991 Name + ".extract");
1992 DEBUG(dbgs() << " extract: " << *V << "\n");
1993 return V;
1994 }
1995
1996 SmallVector<Constant*, 8> Mask;
1997 Mask.reserve(NumElements);
1998 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1999 Mask.push_back(IRB.getInt32(i));
2000 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2001 ConstantVector::get(Mask),
2002 Name + ".extract");
2003 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2004 return V;
2005}
2006
Chandler Carruthd177f862013-03-20 07:30:36 +00002007static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002008 unsigned BeginIndex, const Twine &Name) {
2009 VectorType *VecTy = cast<VectorType>(Old->getType());
2010 assert(VecTy && "Can only insert a vector into a vector");
2011
2012 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2013 if (!Ty) {
2014 // Single element to insert.
2015 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2016 Name + ".insert");
2017 DEBUG(dbgs() << " insert: " << *V << "\n");
2018 return V;
2019 }
2020
2021 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2022 "Too many elements!");
2023 if (Ty->getNumElements() == VecTy->getNumElements()) {
2024 assert(V->getType() == VecTy && "Vector type mismatch");
2025 return V;
2026 }
2027 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2028
2029 // When inserting a smaller vector into the larger to store, we first
2030 // use a shuffle vector to widen it with undef elements, and then
2031 // a second shuffle vector to select between the loaded vector and the
2032 // incoming vector.
2033 SmallVector<Constant*, 8> Mask;
2034 Mask.reserve(VecTy->getNumElements());
2035 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2036 if (i >= BeginIndex && i < EndIndex)
2037 Mask.push_back(IRB.getInt32(i - BeginIndex));
2038 else
2039 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2040 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2041 ConstantVector::get(Mask),
2042 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002043 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002044
2045 Mask.clear();
2046 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002047 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2048
2049 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2050
2051 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002052 return V;
2053}
2054
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002055namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002056/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2057/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002058///
2059/// Also implements the rewriting to vector-based accesses when the partition
2060/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2061/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002062class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002063 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002064 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2065 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002066
Chandler Carruth90a735d2013-07-19 07:21:28 +00002067 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002068 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002069 SROA &Pass;
2070 AllocaInst &OldAI, &NewAI;
2071 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002072 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002073
Chandler Carruth2dc96822014-10-18 00:44:02 +00002074 // This is a convenience and flag variable that will be null unless the new
2075 // alloca's integer operations should be widened to this integer type due to
2076 // passing isIntegerWideningViable above. If it is non-null, the desired
2077 // integer type will be stored here for easy access during rewriting.
2078 IntegerType *IntTy;
2079
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002080 // If we are rewriting an alloca partition which can be written as pure
2081 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002082 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002083 // - The new alloca is exactly the size of the vector type here.
2084 // - The accesses all either map to the entire vector or to a single
2085 // element.
2086 // - The set of accessing instructions is only one of those handled above
2087 // in isVectorPromotionViable. Generally these are the same access kinds
2088 // which are promotable via mem2reg.
2089 VectorType *VecTy;
2090 Type *ElementTy;
2091 uint64_t ElementSize;
2092
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002093 // The original offset of the slice currently being rewritten relative to
2094 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002095 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002096 // The new offsets of the slice currently being rewritten relative to the
2097 // original alloca.
2098 uint64_t NewBeginOffset, NewEndOffset;
2099
2100 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002101 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002102 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002103 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002104 Instruction *OldPtr;
2105
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002106 // Track post-rewrite users which are PHI nodes and Selects.
2107 SmallPtrSetImpl<PHINode *> &PHIUsers;
2108 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002109
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002110 // Utility IR builder, whose name prefix is setup for each visited use, and
2111 // the insertion point is set to point to the user.
2112 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002113
2114public:
Chandler Carruth83934062014-10-16 21:11:55 +00002115 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002116 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002117 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002118 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2119 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002120 SmallPtrSetImpl<PHINode *> &PHIUsers,
2121 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002122 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002123 NewAllocaBeginOffset(NewAllocaBeginOffset),
2124 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002125 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002126 IntTy(IsIntegerPromotable
2127 ? Type::getIntNTy(
2128 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002129 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002130 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002131 VecTy(PromotableVecTy),
2132 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2133 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002134 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002135 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002136 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002137 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002138 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002139 "Only multiple-of-8 sized vector elements are viable");
2140 ++NumVectorized;
2141 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002142 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002143 }
2144
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002145 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002146 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002147 BeginOffset = I->beginOffset();
2148 EndOffset = I->endOffset();
2149 IsSplittable = I->isSplittable();
2150 IsSplit =
2151 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002152
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002153 // Compute the intersecting offset range.
2154 assert(BeginOffset < NewAllocaEndOffset);
2155 assert(EndOffset > NewAllocaBeginOffset);
2156 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2157 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2158
2159 SliceSize = NewEndOffset - NewBeginOffset;
2160
Chandler Carruthf0546402013-07-18 07:15:00 +00002161 OldUse = I->getUse();
2162 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002163
Chandler Carruthf0546402013-07-18 07:15:00 +00002164 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2165 IRB.SetInsertPoint(OldUserI);
2166 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2167 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2168
2169 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2170 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002171 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002172 return CanSROA;
2173 }
2174
2175private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002176 // Make sure the other visit overloads are visible.
2177 using Base::visit;
2178
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002179 // Every instruction which can end up as a user must have a rewrite rule.
2180 bool visitInstruction(Instruction &I) {
2181 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2182 llvm_unreachable("No rewrite rule for this instruction!");
2183 }
2184
Chandler Carruth47954c82014-02-26 05:12:43 +00002185 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2186 // Note that the offset computation can use BeginOffset or NewBeginOffset
2187 // interchangeably for unsplit slices.
2188 assert(IsSplit || BeginOffset == NewBeginOffset);
2189 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2190
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002191#ifndef NDEBUG
2192 StringRef OldName = OldPtr->getName();
2193 // Skip through the last '.sroa.' component of the name.
2194 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2195 if (LastSROAPrefix != StringRef::npos) {
2196 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2197 // Look for an SROA slice index.
2198 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2199 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2200 // Strip the index and look for the offset.
2201 OldName = OldName.substr(IndexEnd + 1);
2202 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2203 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2204 // Strip the offset.
2205 OldName = OldName.substr(OffsetEnd + 1);
2206 }
2207 }
2208 // Strip any SROA suffixes as well.
2209 OldName = OldName.substr(0, OldName.find(".sroa_"));
2210#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002211
2212 return getAdjustedPtr(IRB, DL, &NewAI,
2213 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002214#ifndef NDEBUG
2215 Twine(OldName) + "."
2216#else
2217 Twine()
2218#endif
2219 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002220 }
2221
Chandler Carruth2659e502014-02-26 05:02:19 +00002222 /// \brief Compute suitable alignment to access this slice of the *new* alloca.
2223 ///
2224 /// You can optionally pass a type to this routine and if that type's ABI
2225 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002226 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002227 unsigned NewAIAlign = NewAI.getAlignment();
2228 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002229 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth2659e502014-02-26 05:02:19 +00002230 unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2231 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002232 }
2233
Chandler Carruth845b73c2012-11-21 08:16:30 +00002234 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002235 assert(VecTy && "Can only call getIndex when rewriting a vector");
2236 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2237 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2238 uint32_t Index = RelOffset / ElementSize;
2239 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002240 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002241 }
2242
2243 void deleteIfTriviallyDead(Value *V) {
2244 Instruction *I = cast<Instruction>(V);
2245 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002246 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002247 }
2248
Chandler Carruthea27cf02014-02-26 04:25:04 +00002249 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002250 unsigned BeginIndex = getIndex(NewBeginOffset);
2251 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002252 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002253
2254 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002255 "load");
2256 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002257 }
2258
Chandler Carruthea27cf02014-02-26 04:25:04 +00002259 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002260 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002261 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002262 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002263 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002264 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002265 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2266 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2267 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002268 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002269 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002270 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002271 }
2272
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002273 bool visitLoadInst(LoadInst &LI) {
2274 DEBUG(dbgs() << " original: " << LI << "\n");
2275 Value *OldOp = LI.getOperand(0);
2276 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002277
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002278 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002279 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002280 bool IsPtrAdjusted = false;
2281 Value *V;
2282 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002283 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002284 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002285 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002286 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002287 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002288 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002289 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002290 } else {
2291 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002292 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002293 getSliceAlign(TargetTy), LI.isVolatile(),
2294 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002295 IsPtrAdjusted = true;
2296 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002297 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002298
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002299 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002300 assert(!LI.isVolatile());
2301 assert(LI.getType()->isIntegerTy() &&
2302 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002303 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002304 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002305 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002306 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002307 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002308 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002309 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002310 // Create a placeholder value with the same type as LI to use as the
2311 // basis for the new value. This allows us to replace the uses of LI with
2312 // the computed value, and then replace the placeholder with LI, leaving
2313 // LI only used for this computation.
2314 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002315 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002316 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002317 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002318 LI.replaceAllUsesWith(V);
2319 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002320 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002321 } else {
2322 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002323 }
2324
Chandler Carruth18db7952012-11-20 01:12:50 +00002325 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002326 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002327 DEBUG(dbgs() << " to: " << *V << "\n");
2328 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002329 }
2330
Chandler Carruthea27cf02014-02-26 04:25:04 +00002331 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002332 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002333 unsigned BeginIndex = getIndex(NewBeginOffset);
2334 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002335 assert(EndIndex > BeginIndex && "Empty vector!");
2336 unsigned NumElements = EndIndex - BeginIndex;
2337 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002338 Type *SliceTy =
2339 (NumElements == 1) ? ElementTy
2340 : VectorType::get(ElementTy, NumElements);
2341 if (V->getType() != SliceTy)
2342 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002343
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002344 // Mix in the existing elements.
2345 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2346 "load");
2347 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2348 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002349 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002350 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002351
2352 (void)Store;
2353 DEBUG(dbgs() << " to: " << *Store << "\n");
2354 return true;
2355 }
2356
Chandler Carruthea27cf02014-02-26 04:25:04 +00002357 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002358 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002359 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002360 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002361 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002362 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002363 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002364 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2365 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002366 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002367 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002368 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002369 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002370 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002371 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002372 (void)Store;
2373 DEBUG(dbgs() << " to: " << *Store << "\n");
2374 return true;
2375 }
2376
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002377 bool visitStoreInst(StoreInst &SI) {
2378 DEBUG(dbgs() << " original: " << SI << "\n");
2379 Value *OldOp = SI.getOperand(1);
2380 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002381
Chandler Carruth18db7952012-11-20 01:12:50 +00002382 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002383
Chandler Carruthac8317f2012-10-04 12:33:50 +00002384 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2385 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002386 if (V->getType()->isPointerTy())
2387 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002388 Pass.PostPromotionWorklist.insert(AI);
2389
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002390 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002391 assert(!SI.isVolatile());
2392 assert(V->getType()->isIntegerTy() &&
2393 "Only integer type loads and stores are split");
2394 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002395 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002396 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002397 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002398 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002399 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002400 }
2401
Chandler Carruth18db7952012-11-20 01:12:50 +00002402 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002403 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002404 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002405 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002406
Chandler Carruth18db7952012-11-20 01:12:50 +00002407 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002408 if (NewBeginOffset == NewAllocaBeginOffset &&
2409 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002410 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2411 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002412 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2413 SI.isVolatile());
2414 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002415 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002416 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2417 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002418 }
2419 (void)NewSI;
2420 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002421 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002422
2423 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2424 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002425 }
2426
Chandler Carruth514f34f2012-12-17 04:07:30 +00002427 /// \brief Compute an integer value from splatting an i8 across the given
2428 /// number of bytes.
2429 ///
2430 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2431 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002432 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002433 ///
2434 /// \param V The i8 value to splat.
2435 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002436 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002437 assert(Size > 0 && "Expected a positive number of bytes.");
2438 IntegerType *VTy = cast<IntegerType>(V->getType());
2439 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2440 if (Size == 1)
2441 return V;
2442
2443 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002444 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002445 ConstantExpr::getUDiv(
2446 Constant::getAllOnesValue(SplatIntTy),
2447 ConstantExpr::getZExt(
2448 Constant::getAllOnesValue(V->getType()),
2449 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002450 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002451 return V;
2452 }
2453
Chandler Carruthccca5042012-12-17 04:07:37 +00002454 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002455 Value *getVectorSplat(Value *V, unsigned NumElements) {
2456 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002457 DEBUG(dbgs() << " splat: " << *V << "\n");
2458 return V;
2459 }
2460
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002461 bool visitMemSetInst(MemSetInst &II) {
2462 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002463 assert(II.getRawDest() == OldPtr);
2464
2465 // If the memset has a variable size, it cannot be split, just adjust the
2466 // pointer to the new alloca.
2467 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002468 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002469 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002470 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002471 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002472 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002473
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002474 deleteIfTriviallyDead(OldPtr);
2475 return false;
2476 }
2477
2478 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002479 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002480
2481 Type *AllocaTy = NewAI.getAllocatedType();
2482 Type *ScalarTy = AllocaTy->getScalarType();
2483
2484 // If this doesn't map cleanly onto the alloca type, and that type isn't
2485 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002486 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002487 (BeginOffset > NewAllocaBeginOffset ||
2488 EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002489 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002490 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002491 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2492 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002493 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002494 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2495 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002496 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2497 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002498 (void)New;
2499 DEBUG(dbgs() << " to: " << *New << "\n");
2500 return false;
2501 }
2502
2503 // If we can represent this as a simple value, we have to build the actual
2504 // value to store, which requires expanding the byte present in memset to
2505 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002506 // splatting the byte to a sufficiently wide integer, splatting it across
2507 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002508 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002509
Chandler Carruthccca5042012-12-17 04:07:37 +00002510 if (VecTy) {
2511 // If this is a memset of a vectorized alloca, insert it.
2512 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002513
Chandler Carruthf0546402013-07-18 07:15:00 +00002514 unsigned BeginIndex = getIndex(NewBeginOffset);
2515 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002516 assert(EndIndex > BeginIndex && "Empty vector!");
2517 unsigned NumElements = EndIndex - BeginIndex;
2518 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2519
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002520 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002521 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2522 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002523 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002524 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002525
Chandler Carruthce4562b2012-12-17 13:41:21 +00002526 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002527 "oldload");
2528 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002529 } else if (IntTy) {
2530 // If this is a memset on an alloca where we can widen stores, insert the
2531 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002532 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002533
Chandler Carruthf0546402013-07-18 07:15:00 +00002534 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002535 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002536
2537 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2538 EndOffset != NewAllocaBeginOffset)) {
2539 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002540 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002541 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002542 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002543 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002544 } else {
2545 assert(V->getType() == IntTy &&
2546 "Wrong type for an alloca wide integer!");
2547 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002548 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002549 } else {
2550 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002551 assert(NewBeginOffset == NewAllocaBeginOffset);
2552 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002553
Chandler Carruth90a735d2013-07-19 07:21:28 +00002554 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002555 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002556 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002557
Chandler Carruth90a735d2013-07-19 07:21:28 +00002558 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002559 }
2560
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002561 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002562 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002563 (void)New;
2564 DEBUG(dbgs() << " to: " << *New << "\n");
2565 return !II.isVolatile();
2566 }
2567
2568 bool visitMemTransferInst(MemTransferInst &II) {
2569 // Rewriting of memory transfer instructions can be a bit tricky. We break
2570 // them into two categories: split intrinsics and unsplit intrinsics.
2571
2572 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002573
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002574 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002575 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002576 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002577
Chandler Carruthaa72b932014-02-26 07:29:54 +00002578 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002579
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002580 // For unsplit intrinsics, we simply modify the source and destination
2581 // pointers in place. This isn't just an optimization, it is a matter of
2582 // correctness. With unsplit intrinsics we may be dealing with transfers
2583 // within a single alloca before SROA ran, or with transfers that have
2584 // a variable length. We may also be dealing with memmove instead of
2585 // memcpy, and so simply updating the pointers is the necessary for us to
2586 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002587 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002588 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002589 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002590 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002591 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002592 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002593
Chandler Carruthaa72b932014-02-26 07:29:54 +00002594 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002595 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002596 II.setAlignment(
2597 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002598 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002599
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002600 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002601 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002602 return false;
2603 }
2604 // For split transfer intrinsics we have an incredibly useful assurance:
2605 // the source and destination do not reside within the same alloca, and at
2606 // least one of them does not escape. This means that we can replace
2607 // memmove with memcpy, and we don't need to worry about all manner of
2608 // downsides to splitting and transforming the operations.
2609
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002610 // If this doesn't map cleanly onto the alloca type, and that type isn't
2611 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002612 bool EmitMemCpy =
2613 !VecTy && !IntTy &&
2614 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2615 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2616 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002617
2618 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2619 // size hasn't been shrunk based on analysis of the viable range, this is
2620 // a no-op.
2621 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002622 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002623 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002624
2625 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002626 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002627 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002628 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002629 return false;
2630 }
2631 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002632 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002633
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002634 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2635 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002636 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002637 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002638 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2639 assert(AI != &OldAI && AI != &NewAI &&
2640 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002641 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002642 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002643
Chandler Carruth286d87e2014-02-26 08:25:02 +00002644 Type *OtherPtrTy = OtherPtr->getType();
2645 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2646
Chandler Carruth181ed052014-02-26 05:33:36 +00002647 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002648 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002649 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002650 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2651 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002652
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002653 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002654 // Compute the other pointer, folding as much as possible to produce
2655 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002656 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002657 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002658
Chandler Carruth47954c82014-02-26 05:12:43 +00002659 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002660 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002661 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002662
Chandler Carruthaa72b932014-02-26 07:29:54 +00002663 CallInst *New = IRB.CreateMemCpy(
2664 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2665 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002666 (void)New;
2667 DEBUG(dbgs() << " to: " << *New << "\n");
2668 return false;
2669 }
2670
Chandler Carruthf0546402013-07-18 07:15:00 +00002671 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2672 NewEndOffset == NewAllocaEndOffset;
2673 uint64_t Size = NewEndOffset - NewBeginOffset;
2674 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2675 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002676 unsigned NumElements = EndIndex - BeginIndex;
2677 IntegerType *SubIntTy
Craig Topperf40110f2014-04-25 05:29:35 +00002678 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002679
Chandler Carruth286d87e2014-02-26 08:25:02 +00002680 // Reset the other pointer type to match the register type we're going to
2681 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002682 if (VecTy && !IsWholeAlloca) {
2683 if (NumElements == 1)
2684 OtherPtrTy = VecTy->getElementType();
2685 else
2686 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2687
Chandler Carruth286d87e2014-02-26 08:25:02 +00002688 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002689 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002690 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2691 } else {
2692 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002693 }
2694
Chandler Carruth181ed052014-02-26 05:33:36 +00002695 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002696 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002697 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002698 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002699 unsigned DstAlign = SliceAlign;
2700 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002701 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002702 std::swap(SrcAlign, DstAlign);
2703 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002704
2705 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002706 if (VecTy && !IsWholeAlloca && !IsDest) {
2707 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002708 "load");
2709 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002710 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002711 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002712 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002713 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002714 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002715 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002716 } else {
Chandler Carruthaa72b932014-02-26 07:29:54 +00002717 Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002718 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002719 }
2720
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002721 if (VecTy && !IsWholeAlloca && IsDest) {
2722 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002723 "oldload");
2724 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002725 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002726 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002727 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002728 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002729 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002730 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2731 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002732 }
2733
Chandler Carruth871ba722012-09-26 10:27:46 +00002734 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002735 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002736 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002737 DEBUG(dbgs() << " to: " << *Store << "\n");
2738 return !II.isVolatile();
2739 }
2740
2741 bool visitIntrinsicInst(IntrinsicInst &II) {
2742 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2743 II.getIntrinsicID() == Intrinsic::lifetime_end);
2744 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002745 assert(II.getArgOperand(1) == OldPtr);
2746
2747 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002748 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002749
2750 ConstantInt *Size
2751 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002752 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002753 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002754 Value *New;
2755 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2756 New = IRB.CreateLifetimeStart(Ptr, Size);
2757 else
2758 New = IRB.CreateLifetimeEnd(Ptr, Size);
2759
Edwin Vane82f80d42013-01-29 17:42:24 +00002760 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002761 DEBUG(dbgs() << " to: " << *New << "\n");
2762 return true;
2763 }
2764
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002765 bool visitPHINode(PHINode &PN) {
2766 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002767 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2768 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002769
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002770 // We would like to compute a new pointer in only one place, but have it be
2771 // as local as possible to the PHI. To do that, we re-use the location of
2772 // the old pointer, which necessarily must be in the right position to
2773 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002774 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002775 if (isa<PHINode>(OldPtr))
2776 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
2777 else
2778 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002779 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002780
Chandler Carruth47954c82014-02-26 05:12:43 +00002781 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002782 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002783 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002784
Chandler Carruth82a57542012-10-01 10:54:05 +00002785 DEBUG(dbgs() << " to: " << PN << "\n");
2786 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002787
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002788 // PHIs can't be promoted on their own, but often can be speculated. We
2789 // check the speculation outside of the rewriter so that we see the
2790 // fully-rewritten alloca.
2791 PHIUsers.insert(&PN);
2792 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002793 }
2794
2795 bool visitSelectInst(SelectInst &SI) {
2796 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002797 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2798 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002799 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2800 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002801
Chandler Carruth47954c82014-02-26 05:12:43 +00002802 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002803 // Replace the operands which were using the old pointer.
2804 if (SI.getOperand(1) == OldPtr)
2805 SI.setOperand(1, NewPtr);
2806 if (SI.getOperand(2) == OldPtr)
2807 SI.setOperand(2, NewPtr);
2808
Chandler Carruth82a57542012-10-01 10:54:05 +00002809 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002810 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002811
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002812 // Selects can't be promoted on their own, but often can be speculated. We
2813 // check the speculation outside of the rewriter so that we see the
2814 // fully-rewritten alloca.
2815 SelectUsers.insert(&SI);
2816 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002817 }
2818
2819};
2820}
2821
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002822namespace {
2823/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2824///
2825/// This pass aggressively rewrites all aggregate loads and stores on
2826/// a particular pointer (or any pointer derived from it which we can identify)
2827/// with scalar loads and stores.
2828class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2829 // Befriend the base class so it can delegate to private visit methods.
2830 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2831
Chandler Carruth90a735d2013-07-19 07:21:28 +00002832 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002833
2834 /// Queue of pointer uses to analyze and potentially rewrite.
2835 SmallVector<Use *, 8> Queue;
2836
2837 /// Set to prevent us from cycling with phi nodes and loops.
2838 SmallPtrSet<User *, 8> Visited;
2839
2840 /// The current pointer use being rewritten. This is used to dig up the used
2841 /// value (as opposed to the user).
2842 Use *U;
2843
2844public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002845 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002846
2847 /// Rewrite loads and stores through a pointer and all pointers derived from
2848 /// it.
2849 bool rewrite(Instruction &I) {
2850 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2851 enqueueUsers(I);
2852 bool Changed = false;
2853 while (!Queue.empty()) {
2854 U = Queue.pop_back_val();
2855 Changed |= visit(cast<Instruction>(U->getUser()));
2856 }
2857 return Changed;
2858 }
2859
2860private:
2861 /// Enqueue all the users of the given instruction for further processing.
2862 /// This uses a set to de-duplicate users.
2863 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002864 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00002865 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00002866 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002867 }
2868
2869 // Conservative default is to not rewrite anything.
2870 bool visitInstruction(Instruction &I) { return false; }
2871
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002872 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002873 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002874 class OpSplitter {
2875 protected:
2876 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002877 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002878 /// The indices which to be used with insert- or extractvalue to select the
2879 /// appropriate value within the aggregate.
2880 SmallVector<unsigned, 4> Indices;
2881 /// The indices to a GEP instruction which will move Ptr to the correct slot
2882 /// within the aggregate.
2883 SmallVector<Value *, 4> GEPIndices;
2884 /// The base pointer of the original op, used as a base for GEPing the
2885 /// split operations.
2886 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002887
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002888 /// Initialize the splitter with an insertion point, Ptr and start with a
2889 /// single zero GEP index.
2890 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002891 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002892
2893 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002894 /// \brief Generic recursive split emission routine.
2895 ///
2896 /// This method recursively splits an aggregate op (load or store) into
2897 /// scalar or vector ops. It splits recursively until it hits a single value
2898 /// and emits that single value operation via the template argument.
2899 ///
2900 /// The logic of this routine relies on GEPs and insertvalue and
2901 /// extractvalue all operating with the same fundamental index list, merely
2902 /// formatted differently (GEPs need actual values).
2903 ///
2904 /// \param Ty The type being split recursively into smaller ops.
2905 /// \param Agg The aggregate value being built up or stored, depending on
2906 /// whether this is splitting a load or a store respectively.
2907 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2908 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002909 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002910
2911 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2912 unsigned OldSize = Indices.size();
2913 (void)OldSize;
2914 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2915 ++Idx) {
2916 assert(Indices.size() == OldSize && "Did not return to the old size");
2917 Indices.push_back(Idx);
2918 GEPIndices.push_back(IRB.getInt32(Idx));
2919 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2920 GEPIndices.pop_back();
2921 Indices.pop_back();
2922 }
2923 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002924 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002925
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002926 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2927 unsigned OldSize = Indices.size();
2928 (void)OldSize;
2929 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2930 ++Idx) {
2931 assert(Indices.size() == OldSize && "Did not return to the old size");
2932 Indices.push_back(Idx);
2933 GEPIndices.push_back(IRB.getInt32(Idx));
2934 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2935 GEPIndices.pop_back();
2936 Indices.pop_back();
2937 }
2938 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002939 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002940
2941 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002942 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002943 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002944
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002945 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002946 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002947 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002948
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002949 /// Emit a leaf load of a single value. This is called at the leaves of the
2950 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002951 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002952 assert(Ty->isSingleValueType());
2953 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002954 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2955 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002956 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2957 DEBUG(dbgs() << " to: " << *Load << "\n");
2958 }
2959 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002960
2961 bool visitLoadInst(LoadInst &LI) {
2962 assert(LI.getPointerOperand() == *U);
2963 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2964 return false;
2965
2966 // We have an aggregate being loaded, split it apart.
2967 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002968 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002969 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002970 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002971 LI.replaceAllUsesWith(V);
2972 LI.eraseFromParent();
2973 return true;
2974 }
2975
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002976 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002977 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002978 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002979
2980 /// Emit a leaf store of a single value. This is called at the leaves of the
2981 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002982 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002983 assert(Ty->isSingleValueType());
2984 // Extract the single value and store it using the indices.
2985 Value *Store = IRB.CreateStore(
2986 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2987 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2988 (void)Store;
2989 DEBUG(dbgs() << " to: " << *Store << "\n");
2990 }
2991 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002992
2993 bool visitStoreInst(StoreInst &SI) {
2994 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2995 return false;
2996 Value *V = SI.getValueOperand();
2997 if (V->getType()->isSingleValueType())
2998 return false;
2999
3000 // We have an aggregate being stored, split it apart.
3001 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003002 StoreOpSplitter Splitter(&SI, *U);
3003 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003004 SI.eraseFromParent();
3005 return true;
3006 }
3007
3008 bool visitBitCastInst(BitCastInst &BC) {
3009 enqueueUsers(BC);
3010 return false;
3011 }
3012
3013 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3014 enqueueUsers(GEPI);
3015 return false;
3016 }
3017
3018 bool visitPHINode(PHINode &PN) {
3019 enqueueUsers(PN);
3020 return false;
3021 }
3022
3023 bool visitSelectInst(SelectInst &SI) {
3024 enqueueUsers(SI);
3025 return false;
3026 }
3027};
3028}
3029
Chandler Carruthba931992012-10-13 10:49:33 +00003030/// \brief Strip aggregate type wrapping.
3031///
3032/// This removes no-op aggregate types wrapping an underlying type. It will
3033/// strip as many layers of types as it can without changing either the type
3034/// size or the allocated size.
3035static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3036 if (Ty->isSingleValueType())
3037 return Ty;
3038
3039 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3040 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3041
3042 Type *InnerTy;
3043 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3044 InnerTy = ArrTy->getElementType();
3045 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3046 const StructLayout *SL = DL.getStructLayout(STy);
3047 unsigned Index = SL->getElementContainingOffset(0);
3048 InnerTy = STy->getElementType(Index);
3049 } else {
3050 return Ty;
3051 }
3052
3053 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3054 TypeSize > DL.getTypeSizeInBits(InnerTy))
3055 return Ty;
3056
3057 return stripAggregateTypeWrapping(DL, InnerTy);
3058}
3059
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003060/// \brief Try to find a partition of the aggregate type passed in for a given
3061/// offset and size.
3062///
3063/// This recurses through the aggregate type and tries to compute a subtype
3064/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003065/// of an array, it will even compute a new array type for that sub-section,
3066/// and the same for structs.
3067///
3068/// Note that this routine is very strict and tries to find a partition of the
3069/// type which produces the *exact* right offset and size. It is not forgiving
3070/// when the size or offset cause either end of type-based partition to be off.
3071/// Also, this is a best-effort routine. It is reasonable to give up and not
3072/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003073static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003074 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003075 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3076 return stripAggregateTypeWrapping(DL, Ty);
3077 if (Offset > DL.getTypeAllocSize(Ty) ||
3078 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003079 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003080
3081 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3082 // We can't partition pointers...
3083 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003084 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003085
3086 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003087 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003088 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003089 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003090 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003091 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003092 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003093 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003094 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003095 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003096 Offset -= NumSkippedElements * ElementSize;
3097
3098 // First check if we need to recurse.
3099 if (Offset > 0 || Size < ElementSize) {
3100 // Bail if the partition ends in a different array element.
3101 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003102 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003103 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003104 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003105 }
3106 assert(Offset == 0);
3107
3108 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003109 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003110 assert(Size > ElementSize);
3111 uint64_t NumElements = Size / ElementSize;
3112 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003113 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003114 return ArrayType::get(ElementTy, NumElements);
3115 }
3116
3117 StructType *STy = dyn_cast<StructType>(Ty);
3118 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003119 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003120
Chandler Carruth90a735d2013-07-19 07:21:28 +00003121 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003122 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003123 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003124 uint64_t EndOffset = Offset + Size;
3125 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003126 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003127
3128 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003129 Offset -= SL->getElementOffset(Index);
3130
3131 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003132 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003133 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003134 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003135
3136 // See if any partition must be contained by the element.
3137 if (Offset > 0 || Size < ElementSize) {
3138 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003139 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003140 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003141 }
3142 assert(Offset == 0);
3143
3144 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003145 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003146
3147 StructType::element_iterator EI = STy->element_begin() + Index,
3148 EE = STy->element_end();
3149 if (EndOffset < SL->getSizeInBytes()) {
3150 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3151 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003152 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003153
3154 // Don't try to form "natural" types if the elements don't line up with the
3155 // expected size.
3156 // FIXME: We could potentially recurse down through the last element in the
3157 // sub-struct to find a natural end point.
3158 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003159 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003160
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003161 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003162 EE = STy->element_begin() + EndIndex;
3163 }
3164
3165 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003166 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003167 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003168 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003169 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003170 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003171
Chandler Carruth054a40a2012-09-14 11:08:31 +00003172 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003173}
3174
3175/// \brief Rewrite an alloca partition's users.
3176///
3177/// This routine drives both of the rewriting goals of the SROA pass. It tries
3178/// to rewrite uses of an alloca partition to be conducive for SSA value
3179/// promotion. If the partition needs a new, more refined alloca, this will
3180/// build that new alloca, preserving as much type information as possible, and
3181/// rewrite the uses of the old alloca to point at the new one and have the
3182/// appropriate new offsets. It also evaluates how successful the rewrite was
3183/// at enabling promotion and if it was successful queues the alloca to be
3184/// promoted.
Chandler Carruth83934062014-10-16 21:11:55 +00003185bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003186 AllocaSlices::iterator B, AllocaSlices::iterator E,
3187 int64_t BeginOffset, int64_t EndOffset,
3188 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003189 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003190 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003191
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003192 // Try to compute a friendly type for this partition of the alloca. This
3193 // won't always succeed, in which case we fall back to a legal integer type
3194 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003195 Type *SliceTy = nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00003196 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003197 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3198 SliceTy = CommonUseTy;
3199 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003200 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003201 BeginOffset, SliceSize))
3202 SliceTy = TypePartitionTy;
3203 if ((!SliceTy || (SliceTy->isArrayTy() &&
3204 SliceTy->getArrayElementType()->isIntegerTy())) &&
3205 DL->isLegalInteger(SliceSize * 8))
3206 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3207 if (!SliceTy)
3208 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3209 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003210
Chandler Carruth2dc96822014-10-18 00:44:02 +00003211 bool IsIntegerPromotable = isIntegerWideningViable(
3212 *DL, SliceTy, BeginOffset, AllocaSlices::const_range(B, E), SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003213
Chandler Carruth2dc96822014-10-18 00:44:02 +00003214 VectorType *VecTy =
3215 IsIntegerPromotable
3216 ? nullptr
David Majnemerc0a313b2014-11-21 02:34:55 +00003217 : isVectorPromotionViable(*DL, BeginOffset, EndOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00003218 AllocaSlices::const_range(B, E), SplitUses);
3219 if (VecTy)
3220 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003221
3222 // Check for the case where we're going to rewrite to a new alloca of the
3223 // exact same type as the original, and with the same access offsets. In that
3224 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003225 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003226 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003227 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003228 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003229 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003230 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003231 // FIXME: We should be able to bail at this point with "nothing changed".
3232 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003233 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003234 unsigned Alignment = AI.getAlignment();
3235 if (!Alignment) {
3236 // The minimum alignment which users can rely on when the explicit
3237 // alignment is omitted or zero is that required by the ABI for this
3238 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003239 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003240 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003241 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003242 // If we will get at least this much alignment from the type alone, leave
3243 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003244 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003245 Alignment = 0;
Chandler Carruth83934062014-10-16 21:11:55 +00003246 NewAI =
3247 new AllocaInst(SliceTy, nullptr, Alignment,
3248 AI.getName() + ".sroa." + Twine(B - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003249 ++NumNewAllocas;
3250 }
3251
3252 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003253 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3254 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003255
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003256 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003257 // promoted allocas. We will reset it to this point if the alloca is not in
3258 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003259 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003260 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003261 SmallPtrSet<PHINode *, 8> PHIUsers;
3262 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003263
Chandler Carruth83934062014-10-16 21:11:55 +00003264 AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, BeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00003265 EndOffset, IsIntegerPromotable, VecTy, PHIUsers,
3266 SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003267 bool Promotable = true;
Chandler Carruth61747042014-10-16 21:05:14 +00003268 for (auto & SplitUse : SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003269 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth83934062014-10-16 21:11:55 +00003270 DEBUG(AS.printSlice(dbgs(), SplitUse, ""));
Chandler Carruth61747042014-10-16 21:05:14 +00003271 Promotable &= Rewriter.visit(SplitUse);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003272 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003273 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003274 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003275 DEBUG(dbgs() << " rewriting ");
Chandler Carruth83934062014-10-16 21:11:55 +00003276 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003277 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003278 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003279 }
3280
Chandler Carruth6c321c12013-07-19 10:57:36 +00003281 NumAllocaPartitionUses += NumUses;
3282 MaxUsesPerAllocaPartition =
3283 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003284
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003285 // Now that we've processed all the slices in the new partition, check if any
3286 // PHIs or Selects would block promotion.
3287 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3288 E = PHIUsers.end();
3289 I != E; ++I)
3290 if (!isSafePHIToSpeculate(**I, DL)) {
3291 Promotable = false;
3292 PHIUsers.clear();
3293 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003294 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003295 }
3296 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3297 E = SelectUsers.end();
3298 I != E; ++I)
3299 if (!isSafeSelectToSpeculate(**I, DL)) {
3300 Promotable = false;
3301 PHIUsers.clear();
3302 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003303 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003304 }
3305
3306 if (Promotable) {
3307 if (PHIUsers.empty() && SelectUsers.empty()) {
3308 // Promote the alloca.
3309 PromotableAllocas.push_back(NewAI);
3310 } else {
3311 // If we have either PHIs or Selects to speculate, add them to those
3312 // worklists and re-queue the new alloca so that we promote in on the
3313 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003314 for (PHINode *PHIUser : PHIUsers)
3315 SpeculatablePHIs.insert(PHIUser);
3316 for (SelectInst *SelectUser : SelectUsers)
3317 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003318 Worklist.insert(NewAI);
3319 }
3320 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003321 // If we can't promote the alloca, iterate on it to check for new
3322 // refinements exposed by splitting the current alloca. Don't iterate on an
3323 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003324 if (NewAI != &AI)
3325 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003326
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003327 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003328 while (PostPromotionWorklist.size() > PPWOldSize)
3329 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003330 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003331
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003332 return true;
3333}
3334
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003335static void
3336removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3337 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003338 if (Offset >= MaxSplitUseEndOffset) {
3339 SplitUses.clear();
3340 MaxSplitUseEndOffset = 0;
3341 return;
3342 }
3343
3344 size_t SplitUsesOldSize = SplitUses.size();
3345 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003346 [Offset](const AllocaSlices::iterator &I) {
3347 return I->endOffset() <= Offset;
3348 }),
Chandler Carruthf0546402013-07-18 07:15:00 +00003349 SplitUses.end());
3350 if (SplitUsesOldSize == SplitUses.size())
3351 return;
3352
3353 // Recompute the max. While this is linear, so is remove_if.
3354 MaxSplitUseEndOffset = 0;
Chandler Carruth61747042014-10-16 21:05:14 +00003355 for (AllocaSlices::iterator SplitUse : SplitUses)
3356 MaxSplitUseEndOffset =
3357 std::max(SplitUse->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003358}
3359
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003360/// \brief Walks the slices of an alloca and form partitions based on them,
3361/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003362bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3363 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003364 return false;
3365
Chandler Carruth6c321c12013-07-19 10:57:36 +00003366 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003367 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003368 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003369 uint64_t MaxSplitUseEndOffset = 0;
3370
Chandler Carruth83934062014-10-16 21:11:55 +00003371 uint64_t BeginOffset = AS.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003372
Chandler Carruth83934062014-10-16 21:11:55 +00003373 for (AllocaSlices::iterator SI = AS.begin(), SJ = std::next(SI),
3374 SE = AS.end();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003375 SI != SE; SI = SJ) {
3376 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003377
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003378 if (!SI->isSplittable()) {
3379 // When we're forming an unsplittable region, it must always start at the
3380 // first slice and will extend through its end.
3381 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003382
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003383 // Form a partition including all of the overlapping slices with this
3384 // unsplittable slice.
3385 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3386 if (!SJ->isSplittable())
3387 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3388 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003389 }
3390 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003391 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003392
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003393 // Collect all of the overlapping splittable slices.
3394 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3395 SJ->isSplittable()) {
3396 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3397 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003398 }
3399
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003400 // Back up MaxEndOffset and SJ if we ended the span early when
3401 // encountering an unsplittable slice.
3402 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3403 assert(!SJ->isSplittable());
3404 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003405 }
3406 }
3407
3408 // Check if we have managed to move the end offset forward yet. If so,
3409 // we'll have to rewrite uses and erase old split uses.
3410 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003411 // Rewrite a sequence of overlapping slices.
Chandler Carruth83934062014-10-16 21:11:55 +00003412 Changed |= rewritePartition(AI, AS, SI, SJ, BeginOffset, MaxEndOffset,
3413 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003414 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003415
3416 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3417 }
3418
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003419 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003420 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003421 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3422 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3423 SplitUses.push_back(SK);
3424 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003425 }
3426
3427 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003428 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003429 break;
3430
3431 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003432 // the next slice.
3433 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3434 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003435 continue;
3436 }
3437
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003438 // Even if we have split slices, if the next slice is splittable and the
3439 // split slices reach it, we can simply set up the beginning offset of the
3440 // next iteration to bridge between them.
3441 if (SJ != SE && SJ->isSplittable() &&
3442 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003443 BeginOffset = MaxEndOffset;
3444 continue;
3445 }
3446
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003447 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3448 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003449 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003450 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003451
Chandler Carruth83934062014-10-16 21:11:55 +00003452 Changed |= rewritePartition(AI, AS, SJ, SJ, MaxEndOffset,
3453 PostSplitEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003454 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003455
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003456 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003457 break; // Skip the rest, we don't need to do any cleanup.
3458
3459 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3460 PostSplitEndOffset);
3461
3462 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003463 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003464 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003465
Chandler Carruth6c321c12013-07-19 10:57:36 +00003466 NumAllocaPartitions += NumPartitions;
3467 MaxPartitionsPerAlloca =
3468 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003469
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003470 return Changed;
3471}
3472
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003473/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3474void SROA::clobberUse(Use &U) {
3475 Value *OldV = U;
3476 // Replace the use with an undef value.
3477 U = UndefValue::get(OldV->getType());
3478
3479 // Check for this making an instruction dead. We have to garbage collect
3480 // all the dead instructions to ensure the uses of any alloca end up being
3481 // minimal.
3482 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3483 if (isInstructionTriviallyDead(OldI)) {
3484 DeadInsts.insert(OldI);
3485 }
3486}
3487
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003488/// \brief Analyze an alloca for SROA.
3489///
3490/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003491/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003492/// rewritten as needed.
3493bool SROA::runOnAlloca(AllocaInst &AI) {
3494 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3495 ++NumAllocasAnalyzed;
3496
3497 // Special case dead allocas, as they're trivial.
3498 if (AI.use_empty()) {
3499 AI.eraseFromParent();
3500 return true;
3501 }
3502
3503 // Skip alloca forms that this analysis can't handle.
3504 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003505 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003506 return false;
3507
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003508 bool Changed = false;
3509
3510 // First, split any FCA loads and stores touching this alloca to promote
3511 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003512 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003513 Changed |= AggRewriter.rewrite(AI);
3514
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003515 // Build the slices using a recursive instruction-visiting builder.
Chandler Carruth83934062014-10-16 21:11:55 +00003516 AllocaSlices AS(*DL, AI);
3517 DEBUG(AS.print(dbgs()));
3518 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003519 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003520
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003521 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00003522 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003523 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003524 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00003525 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003526
3527 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003528 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003529
3530 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003531 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003532 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003533 }
Chandler Carruth83934062014-10-16 21:11:55 +00003534 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003535 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003536 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003537 }
3538
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003539 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00003540 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003541 return Changed;
3542
Chandler Carruth83934062014-10-16 21:11:55 +00003543 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00003544
3545 DEBUG(dbgs() << " Speculating PHIs\n");
3546 while (!SpeculatablePHIs.empty())
3547 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3548
3549 DEBUG(dbgs() << " Speculating Selects\n");
3550 while (!SpeculatableSelects.empty())
3551 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3552
3553 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003554}
3555
Chandler Carruth19450da2012-09-14 10:26:38 +00003556/// \brief Delete the dead instructions accumulated in this run.
3557///
3558/// Recursively deletes the dead instructions we've accumulated. This is done
3559/// at the very end to maximize locality of the recursive delete and to
3560/// minimize the problems of invalidated instruction pointers as such pointers
3561/// are used heavily in the intermediate stages of the algorithm.
3562///
3563/// We also record the alloca instructions deleted here so that they aren't
3564/// subsequently handed to mem2reg to promote.
Craig Topper71b7b682014-08-21 05:55:13 +00003565void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003566 while (!DeadInsts.empty()) {
3567 Instruction *I = DeadInsts.pop_back_val();
3568 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3569
Chandler Carruth58d05562012-10-25 04:37:07 +00003570 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3571
Chandler Carruth1583e992014-03-03 10:42:58 +00003572 for (Use &Operand : I->operands())
3573 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003574 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00003575 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003576 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003577 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003578 }
3579
3580 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3581 DeletedAllocas.insert(AI);
3582
3583 ++NumDeleted;
3584 I->eraseFromParent();
3585 }
3586}
3587
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003588static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003589 SmallVectorImpl<Instruction *> &Worklist,
Craig Topper71b7b682014-08-21 05:55:13 +00003590 SmallPtrSetImpl<Instruction *> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003591 for (User *U : I.users())
David Blaikie70573dc2014-11-19 07:49:26 +00003592 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003593 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003594}
3595
Chandler Carruth70b44c52012-09-15 11:43:14 +00003596/// \brief Promote the allocas, using the best available technique.
3597///
3598/// This attempts to promote whatever allocas have been identified as viable in
3599/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3600/// If there is a domtree available, we attempt to promote using the full power
3601/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3602/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003603/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003604bool SROA::promoteAllocas(Function &F) {
3605 if (PromotableAllocas.empty())
3606 return false;
3607
3608 NumPromoted += PromotableAllocas.size();
3609
3610 if (DT && !ForceSSAUpdater) {
3611 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Hal Finkel60db0582014-09-07 18:57:58 +00003612 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003613 PromotableAllocas.clear();
3614 return true;
3615 }
3616
3617 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3618 SSAUpdater SSA;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003619 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Chandler Carruth45b136f2013-08-11 01:03:18 +00003620 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003621
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003622 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003623 SmallVector<Instruction *, 8> Worklist;
3624 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003625 SmallVector<Instruction *, 32> DeadInsts;
3626
Chandler Carruth70b44c52012-09-15 11:43:14 +00003627 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3628 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003629 Insts.clear();
3630 Worklist.clear();
3631 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003632
Chandler Carruth45b136f2013-08-11 01:03:18 +00003633 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003634
Chandler Carruth45b136f2013-08-11 01:03:18 +00003635 while (!Worklist.empty()) {
3636 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003637
Chandler Carruth70b44c52012-09-15 11:43:14 +00003638 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3639 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3640 // leading to them) here. Eventually it should use them to optimize the
3641 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003642 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003643 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3644 II->getIntrinsicID() == Intrinsic::lifetime_end);
3645 II->eraseFromParent();
3646 continue;
3647 }
3648
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003649 // Push the loads and stores we find onto the list. SROA will already
3650 // have validated that all loads and stores are viable candidates for
3651 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003652 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003653 assert(LI->getType() == AI->getAllocatedType());
3654 Insts.push_back(LI);
3655 continue;
3656 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003657 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003658 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3659 Insts.push_back(SI);
3660 continue;
3661 }
3662
3663 // For everything else, we know that only no-op bitcasts and GEPs will
3664 // make it this far, just recurse through them and recall them for later
3665 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003666 DeadInsts.push_back(I);
3667 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003668 }
3669 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003670 while (!DeadInsts.empty())
3671 DeadInsts.pop_back_val()->eraseFromParent();
3672 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003673 }
3674
3675 PromotableAllocas.clear();
3676 return true;
3677}
3678
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003679bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003680 if (skipOptnoneFunction(F))
3681 return false;
3682
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003683 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3684 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003685 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3686 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003687 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3688 return false;
3689 }
Rafael Espindola93512512014-02-25 17:30:31 +00003690 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003691 DominatorTreeWrapperPass *DTWP =
3692 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003693 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +00003694 AT = &getAnalysis<AssumptionTracker>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003695
3696 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003697 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003698 I != E; ++I)
3699 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3700 Worklist.insert(AI);
3701
3702 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003703 // A set of deleted alloca instruction pointers which should be removed from
3704 // the list of promotable allocas.
3705 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3706
Chandler Carruthac8317f2012-10-04 12:33:50 +00003707 do {
3708 while (!Worklist.empty()) {
3709 Changed |= runOnAlloca(*Worklist.pop_back_val());
3710 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003711
Chandler Carruthac8317f2012-10-04 12:33:50 +00003712 // Remove the deleted allocas from various lists so that we don't try to
3713 // continue processing them.
3714 if (!DeletedAllocas.empty()) {
Chandler Carruthd031fe92014-03-03 19:28:52 +00003715 auto IsInSet = [&](AllocaInst *AI) {
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003716 return DeletedAllocas.count(AI);
3717 };
3718 Worklist.remove_if(IsInSet);
3719 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003720 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3721 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003722 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00003723 PromotableAllocas.end());
3724 DeletedAllocas.clear();
3725 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003726 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003727
Chandler Carruthac8317f2012-10-04 12:33:50 +00003728 Changed |= promoteAllocas(F);
3729
3730 Worklist = PostPromotionWorklist;
3731 PostPromotionWorklist.clear();
3732 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003733
3734 return Changed;
3735}
3736
3737void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel60db0582014-09-07 18:57:58 +00003738 AU.addRequired<AssumptionTracker>();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003739 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003740 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003741 AU.setPreservesCFG();
3742}