blob: f9ebd75ec7177b3f35df3671a0d07183e8e984dc [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.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000810 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000811 for (User *U : DebugNode->users())
812 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000813 DDIs.push_back(DDI);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000814 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000815 DVIs.push_back(DVI);
816 }
817
818 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +0000819
820 // While we have the debug information, clear it off of the alloca. The
821 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +0000822 while (!DDIs.empty())
823 DDIs.pop_back_val()->eraseFromParent();
824 while (!DVIs.empty())
825 DVIs.pop_back_val()->eraseFromParent();
826 }
827
Craig Topper3e4c6972014-03-05 09:10:37 +0000828 bool isInstInList(Instruction *I,
829 const SmallVectorImpl<Instruction*> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +0000830 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000831 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +0000832 Ptr = LI->getOperand(0);
833 else
834 Ptr = cast<StoreInst>(I)->getPointerOperand();
835
836 // Only used to detect cycles, which will be rare and quickly found as
837 // we're walking up a chain of defs rather than down through uses.
838 SmallPtrSet<Value *, 4> Visited;
839
840 do {
841 if (Ptr == &AI)
842 return true;
843
844 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
845 Ptr = BCI->getOperand(0);
846 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
847 Ptr = GEPI->getPointerOperand();
848 else
849 return false;
850
David Blaikie70573dc2014-11-19 07:49:26 +0000851 } while (Visited.insert(Ptr).second);
Chandler Carruthc17283b2013-08-11 01:56:15 +0000852
853 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000854 }
855
Craig Topper3e4c6972014-03-05 09:10:37 +0000856 void updateDebugInfo(Instruction *Inst) const override {
Chandler Carruth61747042014-10-16 21:05:14 +0000857 for (DbgDeclareInst *DDI : DDIs)
Chandler Carruth70b44c52012-09-15 11:43:14 +0000858 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
859 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
860 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
861 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Chandler Carruth61747042014-10-16 21:05:14 +0000862 for (DbgValueInst *DVI : DVIs) {
Craig Topperf40110f2014-04-25 05:29:35 +0000863 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +0000864 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
865 // If an argument is zero extended then use argument directly. The ZExt
866 // may be zapped by an optimization pass in future.
867 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
868 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000869 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +0000870 Arg = dyn_cast<Argument>(SExt->getOperand(0));
871 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000872 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000873 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000874 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +0000875 } else {
876 continue;
877 }
878 Instruction *DbgVal =
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000879 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
880 DIExpression(DVI->getExpression()), Inst);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000881 DbgVal->setDebugLoc(DVI->getDebugLoc());
882 }
883 }
884};
885} // end anon namespace
886
887
888namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000889/// \brief An optimization pass providing Scalar Replacement of Aggregates.
890///
891/// This pass takes allocations which can be completely analyzed (that is, they
892/// don't escape) and tries to turn them into scalar SSA values. There are
893/// a few steps to this process.
894///
895/// 1) It takes allocations of aggregates and analyzes the ways in which they
896/// are used to try to split them into smaller allocations, ideally of
897/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000898/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000899/// 2) It will transform accesses into forms which are suitable for SSA value
900/// promotion. This can be replacing a memset with a scalar store of an
901/// integer value, or it can involve speculating operations on a PHI or
902/// select to be a PHI or select of the results.
903/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
904/// onto insert and extract operations on a vector value, and convert them to
905/// this form. By doing so, it will enable promotion of vector aggregates to
906/// SSA vector values.
907class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +0000908 const bool RequiresDomTree;
909
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000910 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +0000911 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000912 DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +0000913 AssumptionTracker *AT;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000914
915 /// \brief Worklist of alloca instructions to simplify.
916 ///
917 /// Each alloca in the function is added to this. Each new alloca formed gets
918 /// added to it as well to recursively simplify unless that alloca can be
919 /// directly promoted. Finally, each time we rewrite a use of an alloca other
920 /// the one being actively rewritten, we add it back onto the list if not
921 /// already present to ensure it is re-visited.
922 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
923
924 /// \brief A collection of instructions to delete.
925 /// We try to batch deletions to simplify code and make things a bit more
926 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +0000927 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000928
Chandler Carruthac8317f2012-10-04 12:33:50 +0000929 /// \brief Post-promotion worklist.
930 ///
931 /// Sometimes we discover an alloca which has a high probability of becoming
932 /// viable for SROA after a round of promotion takes place. In those cases,
933 /// the alloca is enqueued here for re-processing.
934 ///
935 /// Note that we have to be very careful to clear allocas out of this list in
936 /// the event they are deleted.
937 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
938
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000939 /// \brief A collection of alloca instructions we can directly promote.
940 std::vector<AllocaInst *> PromotableAllocas;
941
Chandler Carruthf0546402013-07-18 07:15:00 +0000942 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
943 ///
944 /// All of these PHIs have been checked for the safety of speculation and by
945 /// being speculated will allow promoting allocas currently in the promotable
946 /// queue.
947 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
948
949 /// \brief A worklist of select instructions to speculate prior to promoting
950 /// allocas.
951 ///
952 /// All of these select instructions have been checked for the safety of
953 /// speculation and by being speculated will allow promoting allocas
954 /// currently in the promotable queue.
955 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
956
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000957public:
Chandler Carruth70b44c52012-09-15 11:43:14 +0000958 SROA(bool RequiresDomTree = true)
959 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
Craig Topperf40110f2014-04-25 05:29:35 +0000960 C(nullptr), DL(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000961 initializeSROAPass(*PassRegistry::getPassRegistry());
962 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000963 bool runOnFunction(Function &F) override;
964 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000965
Craig Topper3e4c6972014-03-05 09:10:37 +0000966 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000967 static char ID;
968
969private:
Chandler Carruth82a57542012-10-01 10:54:05 +0000970 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000971 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000972
Chandler Carruth83934062014-10-16 21:11:55 +0000973 bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000974 AllocaSlices::iterator B, AllocaSlices::iterator E,
975 int64_t BeginOffset, int64_t EndOffset,
976 ArrayRef<AllocaSlices::iterator> SplitUses);
Chandler Carruth83934062014-10-16 21:11:55 +0000977 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000978 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000979 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +0000980 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +0000981 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000982};
983}
984
985char SROA::ID = 0;
986
Chandler Carruth70b44c52012-09-15 11:43:14 +0000987FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
988 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000989}
990
991INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
992 false, false)
Hal Finkel60db0582014-09-07 18:57:58 +0000993INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000994INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000995INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
996 false, false)
997
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000998/// Walk the range of a partitioning looking for a common type to cover this
999/// sequence of slices.
1000static Type *findCommonType(AllocaSlices::const_iterator B,
1001 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001002 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001003 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001004 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001005 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001006
1007 // Note that we need to look at *every* alloca slice's Use to ensure we
1008 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001009 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001010 Use *U = I->getUse();
1011 if (isa<IntrinsicInst>(*U->getUser()))
1012 continue;
1013 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1014 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001015
Craig Topperf40110f2014-04-25 05:29:35 +00001016 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001017 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001018 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001019 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001020 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001021 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001022
Chandler Carruth4de31542014-01-21 23:16:05 +00001023 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001024 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001025 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001026 // entity causing the split. Also skip if the type is not a byte width
1027 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001028 if (UserITy->getBitWidth() % 8 != 0 ||
1029 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001030 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001031
Chandler Carruth4de31542014-01-21 23:16:05 +00001032 // Track the largest bitwidth integer type used in this way in case there
1033 // is no common type.
1034 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1035 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001036 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001037
1038 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1039 // depend on types skipped above.
1040 if (!UserTy || (Ty && Ty != UserTy))
1041 TyIsCommon = false; // Give up on anything but an iN type.
1042 else
1043 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001044 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001045
1046 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001047}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001048
Chandler Carruthf0546402013-07-18 07:15:00 +00001049/// PHI instructions that use an alloca and are subsequently loaded can be
1050/// rewritten to load both input pointers in the pred blocks and then PHI the
1051/// results, allowing the load of the alloca to be promoted.
1052/// From this:
1053/// %P2 = phi [i32* %Alloca, i32* %Other]
1054/// %V = load i32* %P2
1055/// to:
1056/// %V1 = load i32* %Alloca -> will be mem2reg'd
1057/// ...
1058/// %V2 = load i32* %Other
1059/// ...
1060/// %V = phi [i32 %V1, i32 %V2]
1061///
1062/// We can do this to a select if its only uses are loads and if the operands
1063/// to the select can be loaded unconditionally.
1064///
1065/// FIXME: This should be hoisted into a generic utility, likely in
1066/// Transforms/Util/Local.h
1067static bool isSafePHIToSpeculate(PHINode &PN,
Craig Topperf40110f2014-04-25 05:29:35 +00001068 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001069 // For now, we can only do this promotion if the load is in the same block
1070 // as the PHI, and if there are no stores between the phi and load.
1071 // TODO: Allow recursive phi users.
1072 // TODO: Allow stores.
1073 BasicBlock *BB = PN.getParent();
1074 unsigned MaxAlign = 0;
1075 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001076 for (User *U : PN.users()) {
1077 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001078 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001079 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001080
Chandler Carruthf0546402013-07-18 07:15:00 +00001081 // For now we only allow loads in the same block as the PHI. This is
1082 // a common case that happens when instcombine merges two loads through
1083 // a PHI.
1084 if (LI->getParent() != BB)
1085 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001086
Chandler Carruthf0546402013-07-18 07:15:00 +00001087 // Ensure that there are no instructions between the PHI and the load that
1088 // could store.
1089 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1090 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001091 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001092
Chandler Carruthf0546402013-07-18 07:15:00 +00001093 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1094 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001095 }
1096
Chandler Carruthf0546402013-07-18 07:15:00 +00001097 if (!HaveLoad)
1098 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001099
Chandler Carruthf0546402013-07-18 07:15:00 +00001100 // We can only transform this if it is safe to push the loads into the
1101 // predecessor blocks. The only thing to watch out for is that we can't put
1102 // a possibly trapping load in the predecessor if it is a critical edge.
1103 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1104 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1105 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001106
Chandler Carruthf0546402013-07-18 07:15:00 +00001107 // If the value is produced by the terminator of the predecessor (an
1108 // invoke) or it has side-effects, there is no valid place to put a load
1109 // in the predecessor.
1110 if (TI == InVal || TI->mayHaveSideEffects())
1111 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001112
Chandler Carruthf0546402013-07-18 07:15:00 +00001113 // If the predecessor has a single successor, then the edge isn't
1114 // critical.
1115 if (TI->getNumSuccessors() == 1)
1116 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001117
Chandler Carruthf0546402013-07-18 07:15:00 +00001118 // If this pointer is always safe to load, or if we can prove that there
1119 // is already a load in the block, then we can move the load to the pred
1120 // block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001121 if (InVal->isDereferenceablePointer(DL) ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001122 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001123 continue;
1124
1125 return false;
1126 }
1127
1128 return true;
1129}
1130
1131static void speculatePHINodeLoads(PHINode &PN) {
1132 DEBUG(dbgs() << " original: " << PN << "\n");
1133
1134 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1135 IRBuilderTy PHIBuilder(&PN);
1136 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1137 PN.getName() + ".sroa.speculated");
1138
Hal Finkelcc39b672014-07-24 12:16:19 +00001139 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001140 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001141 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001142
1143 AAMDNodes AATags;
1144 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001145 unsigned Align = SomeLoad->getAlignment();
1146
1147 // Rewrite all loads of the PN to use the new PHI.
1148 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001149 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001150 LI->replaceAllUsesWith(NewPN);
1151 LI->eraseFromParent();
1152 }
1153
1154 // Inject loads into all of the pred blocks.
1155 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1156 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1157 TerminatorInst *TI = Pred->getTerminator();
1158 Value *InVal = PN.getIncomingValue(Idx);
1159 IRBuilderTy PredBuilder(TI);
1160
1161 LoadInst *Load = PredBuilder.CreateLoad(
1162 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1163 ++NumLoadsSpeculated;
1164 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001165 if (AATags)
1166 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001167 NewPN->addIncoming(Load, Pred);
1168 }
1169
1170 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1171 PN.eraseFromParent();
1172}
1173
1174/// Select instructions that use an alloca and are subsequently loaded can be
1175/// rewritten to load both input pointers and then select between the result,
1176/// allowing the load of the alloca to be promoted.
1177/// From this:
1178/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1179/// %V = load i32* %P2
1180/// to:
1181/// %V1 = load i32* %Alloca -> will be mem2reg'd
1182/// %V2 = load i32* %Other
1183/// %V = select i1 %cond, i32 %V1, i32 %V2
1184///
1185/// We can do this to a select if its only uses are loads and if the operand
1186/// to the select can be loaded unconditionally.
Craig Topperf40110f2014-04-25 05:29:35 +00001187static bool isSafeSelectToSpeculate(SelectInst &SI,
1188 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001189 Value *TValue = SI.getTrueValue();
1190 Value *FValue = SI.getFalseValue();
Hal Finkel2e42c342014-07-10 05:27:53 +00001191 bool TDerefable = TValue->isDereferenceablePointer(DL);
1192 bool FDerefable = FValue->isDereferenceablePointer(DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001193
Chandler Carruthcdf47882014-03-09 03:16:01 +00001194 for (User *U : SI.users()) {
1195 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001196 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001197 return false;
1198
1199 // Both operands to the select need to be dereferencable, either
1200 // absolutely (e.g. allocas) or at this point because we can see other
1201 // accesses to it.
1202 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001203 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001204 return false;
1205 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001206 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001207 return false;
1208 }
1209
1210 return true;
1211}
1212
1213static void speculateSelectInstLoads(SelectInst &SI) {
1214 DEBUG(dbgs() << " original: " << SI << "\n");
1215
1216 IRBuilderTy IRB(&SI);
1217 Value *TV = SI.getTrueValue();
1218 Value *FV = SI.getFalseValue();
1219 // Replace the loads of the select with a select of two loads.
1220 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001221 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001222 assert(LI->isSimple() && "We only speculate simple loads");
1223
1224 IRB.SetInsertPoint(LI);
1225 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001226 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001227 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001228 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001229 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001230
Hal Finkelcc39b672014-07-24 12:16:19 +00001231 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001232 TL->setAlignment(LI->getAlignment());
1233 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001234
1235 AAMDNodes Tags;
1236 LI->getAAMetadata(Tags);
1237 if (Tags) {
1238 TL->setAAMetadata(Tags);
1239 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001240 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001241
1242 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1243 LI->getName() + ".sroa.speculated");
1244
1245 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1246 LI->replaceAllUsesWith(V);
1247 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001248 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001249 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001250}
1251
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001252/// \brief Build a GEP out of a base pointer and indices.
1253///
1254/// This will return the BasePtr if that is valid, or build a new GEP
1255/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001256static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001257 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001258 if (Indices.empty())
1259 return BasePtr;
1260
1261 // A single zero index is a no-op, so check for this and avoid building a GEP
1262 // in that case.
1263 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1264 return BasePtr;
1265
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001266 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001267}
1268
1269/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1270/// TargetTy without changing the offset of the pointer.
1271///
1272/// This routine assumes we've already established a properly offset GEP with
1273/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1274/// zero-indices down through type layers until we find one the same as
1275/// TargetTy. If we can't find one with the same type, we at least try to use
1276/// one with the same size. If none of that works, we just produce the GEP as
1277/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001278static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001279 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001280 SmallVectorImpl<Value *> &Indices,
1281 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001282 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001283 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001284
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001285 // Pointer size to use for the indices.
1286 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1287
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001288 // See if we can descend into a struct and locate a field with the correct
1289 // type.
1290 unsigned NumLayers = 0;
1291 Type *ElementTy = Ty;
1292 do {
1293 if (ElementTy->isPointerTy())
1294 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001295
1296 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1297 ElementTy = ArrayTy->getElementType();
1298 Indices.push_back(IRB.getIntN(PtrSize, 0));
1299 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1300 ElementTy = VectorTy->getElementType();
1301 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001302 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001303 if (STy->element_begin() == STy->element_end())
1304 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001305 ElementTy = *STy->element_begin();
1306 Indices.push_back(IRB.getInt32(0));
1307 } else {
1308 break;
1309 }
1310 ++NumLayers;
1311 } while (ElementTy != TargetTy);
1312 if (ElementTy != TargetTy)
1313 Indices.erase(Indices.end() - NumLayers, Indices.end());
1314
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001315 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001316}
1317
1318/// \brief Recursively compute indices for a natural GEP.
1319///
1320/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1321/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001322static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001323 Value *Ptr, Type *Ty, APInt &Offset,
1324 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001325 SmallVectorImpl<Value *> &Indices,
1326 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001327 if (Offset == 0)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001328 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001329
1330 // We can't recurse through pointer types.
1331 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001332 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001333
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001334 // We try to analyze GEPs over vectors here, but note that these GEPs are
1335 // extremely poorly defined currently. The long-term goal is to remove GEPing
1336 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001337 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001338 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001339 if (ElementSizeInBits % 8 != 0) {
1340 // GEPs over non-multiple of 8 size vector elements are invalid.
1341 return nullptr;
1342 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001343 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001344 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001345 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001346 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001347 Offset -= NumSkippedElements * ElementSize;
1348 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001349 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001350 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001351 }
1352
1353 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1354 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001355 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001356 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001357 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001358 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001359
1360 Offset -= NumSkippedElements * ElementSize;
1361 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001362 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001363 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001364 }
1365
1366 StructType *STy = dyn_cast<StructType>(Ty);
1367 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001368 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001369
Chandler Carruth90a735d2013-07-19 07:21:28 +00001370 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001371 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001372 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001373 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001374 unsigned Index = SL->getElementContainingOffset(StructOffset);
1375 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1376 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001377 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001378 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001379
1380 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001381 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001382 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001383}
1384
1385/// \brief Get a natural GEP from a base pointer to a particular offset and
1386/// resulting in a particular type.
1387///
1388/// The goal is to produce a "natural" looking GEP that works with the existing
1389/// composite types to arrive at the appropriate offset and element type for
1390/// a pointer. TargetTy is the element type the returned GEP should point-to if
1391/// possible. We recurse by decreasing Offset, adding the appropriate index to
1392/// Indices, and setting Ty to the result subtype.
1393///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001394/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001395static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001396 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001397 SmallVectorImpl<Value *> &Indices,
1398 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001399 PointerType *Ty = cast<PointerType>(Ptr->getType());
1400
1401 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1402 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001403 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001404 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001405
1406 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001407 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001408 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001409 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001410 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001411 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001412 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001413
1414 Offset -= NumSkippedElements * ElementSize;
1415 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001416 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001417 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001418}
1419
1420/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1421/// resulting pointer has PointerTy.
1422///
1423/// This tries very hard to compute a "natural" GEP which arrives at the offset
1424/// and produces the pointer type desired. Where it cannot, it will try to use
1425/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1426/// fails, it will try to use an existing i8* and GEP to the byte offset and
1427/// bitcast to the type.
1428///
1429/// The strategy for finding the more natural GEPs is to peel off layers of the
1430/// pointer, walking back through bit casts and GEPs, searching for a base
1431/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001432/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001433/// a single GEP as possible, thus making each GEP more independent of the
1434/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001435static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1436 APInt Offset, Type *PointerTy,
1437 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001438 // Even though we don't look through PHI nodes, we could be called on an
1439 // instruction in an unreachable block, which may be on a cycle.
1440 SmallPtrSet<Value *, 4> Visited;
1441 Visited.insert(Ptr);
1442 SmallVector<Value *, 4> Indices;
1443
1444 // We may end up computing an offset pointer that has the wrong type. If we
1445 // never are able to compute one directly that has the correct type, we'll
1446 // fall back to it, so keep it around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001447 Value *OffsetPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001448
1449 // Remember any i8 pointer we come across to re-use if we need to do a raw
1450 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001451 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001452 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1453
1454 Type *TargetTy = PointerTy->getPointerElementType();
1455
1456 do {
1457 // First fold any existing GEPs into the offset.
1458 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1459 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001460 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001461 break;
1462 Offset += GEPOffset;
1463 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001464 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001465 break;
1466 }
1467
1468 // See if we can perform a natural GEP here.
1469 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001470 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001471 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001472 if (P->getType() == PointerTy) {
1473 // Zap any offset pointer that we ended up computing in previous rounds.
1474 if (OffsetPtr && OffsetPtr->use_empty())
1475 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1476 I->eraseFromParent();
1477 return P;
1478 }
1479 if (!OffsetPtr) {
1480 OffsetPtr = P;
1481 }
1482 }
1483
1484 // Stash this pointer if we've found an i8*.
1485 if (Ptr->getType()->isIntegerTy(8)) {
1486 Int8Ptr = Ptr;
1487 Int8PtrOffset = Offset;
1488 }
1489
1490 // Peel off a layer of the pointer and update the offset appropriately.
1491 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1492 Ptr = cast<Operator>(Ptr)->getOperand(0);
1493 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1494 if (GA->mayBeOverridden())
1495 break;
1496 Ptr = GA->getAliasee();
1497 } else {
1498 break;
1499 }
1500 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001501 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001502
1503 if (!OffsetPtr) {
1504 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001505 Int8Ptr = IRB.CreateBitCast(
1506 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1507 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001508 Int8PtrOffset = Offset;
1509 }
1510
1511 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1512 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001513 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001514 }
1515 Ptr = OffsetPtr;
1516
1517 // On the off chance we were targeting i8*, guard the bitcast here.
1518 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001519 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001520
1521 return Ptr;
1522}
1523
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001524/// \brief Test whether we can convert a value from the old to the new type.
1525///
1526/// This predicate should be used to guard calls to convertValue in order to
1527/// ensure that we only try to convert viable values. The strategy is that we
1528/// will peel off single element struct and array wrappings to get to an
1529/// underlying value, and convert that value.
1530static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1531 if (OldTy == NewTy)
1532 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001533 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1534 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1535 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1536 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001537 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1538 return false;
1539 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1540 return false;
1541
Benjamin Kramer56262592013-09-22 11:24:58 +00001542 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001543 // of pointers and integers.
1544 OldTy = OldTy->getScalarType();
1545 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001546 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1547 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1548 return true;
1549 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1550 return true;
1551 return false;
1552 }
1553
1554 return true;
1555}
1556
1557/// \brief Generic routine to convert an SSA value to a value of a different
1558/// type.
1559///
1560/// This will try various different casting techniques, such as bitcasts,
1561/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1562/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001563static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001564 Type *NewTy) {
1565 Type *OldTy = V->getType();
1566 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1567
1568 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001569 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001570
1571 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1572 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001573 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1574 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001575
Benjamin Kramer90901a32013-09-21 20:36:04 +00001576 // See if we need inttoptr for this type pair. A cast involving both scalars
1577 // and vectors requires and additional bitcast.
1578 if (OldTy->getScalarType()->isIntegerTy() &&
1579 NewTy->getScalarType()->isPointerTy()) {
1580 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1581 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1582 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1583 NewTy);
1584
1585 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1586 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1587 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1588 NewTy);
1589
1590 return IRB.CreateIntToPtr(V, NewTy);
1591 }
1592
1593 // See if we need ptrtoint for this type pair. A cast involving both scalars
1594 // and vectors requires and additional bitcast.
1595 if (OldTy->getScalarType()->isPointerTy() &&
1596 NewTy->getScalarType()->isIntegerTy()) {
1597 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1598 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1599 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1600 NewTy);
1601
1602 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1603 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1604 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1605 NewTy);
1606
1607 return IRB.CreatePtrToInt(V, NewTy);
1608 }
1609
1610 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001611}
1612
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001613/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001614///
1615/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001616/// for a single slice.
Chandler Carruthc659df92014-10-16 20:24:07 +00001617static bool
1618isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
1619 uint64_t SliceEndOffset, VectorType *Ty,
1620 uint64_t ElementSize, const Slice &S) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001621 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001622 uint64_t BeginOffset =
Chandler Carruthc659df92014-10-16 20:24:07 +00001623 std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001624 uint64_t BeginIndex = BeginOffset / ElementSize;
1625 if (BeginIndex * ElementSize != BeginOffset ||
1626 BeginIndex >= Ty->getNumElements())
1627 return false;
1628 uint64_t EndOffset =
Chandler Carruthc659df92014-10-16 20:24:07 +00001629 std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001630 uint64_t EndIndex = EndOffset / ElementSize;
1631 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1632 return false;
1633
1634 assert(EndIndex > BeginIndex && "Empty vector!");
1635 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001636 Type *SliceTy = (NumElements == 1)
1637 ? Ty->getElementType()
1638 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001639
1640 Type *SplitIntTy =
1641 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1642
Chandler Carruthc659df92014-10-16 20:24:07 +00001643 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001644
1645 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1646 if (MI->isVolatile())
1647 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001648 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001649 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001650 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1651 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1652 II->getIntrinsicID() != Intrinsic::lifetime_end)
1653 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001654 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1655 // Disable vector promotion when there are loads or stores of an FCA.
1656 return false;
1657 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1658 if (LI->isVolatile())
1659 return false;
1660 Type *LTy = LI->getType();
Chandler Carruthc659df92014-10-16 20:24:07 +00001661 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001662 assert(LTy->isIntegerTy());
1663 LTy = SplitIntTy;
1664 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001665 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001666 return false;
1667 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1668 if (SI->isVolatile())
1669 return false;
1670 Type *STy = SI->getValueOperand()->getType();
Chandler Carruthc659df92014-10-16 20:24:07 +00001671 if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001672 assert(STy->isIntegerTy());
1673 STy = SplitIntTy;
1674 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001675 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001676 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001677 } else {
1678 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001679 }
1680
1681 return true;
1682}
1683
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001684/// \brief Test whether the given alloca partitioning and range of slices can be
1685/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001686///
1687/// This is a quick test to check whether we can rewrite a particular alloca
1688/// partition (and its newly formed alloca) into a vector alloca with only
1689/// whole-vector loads and stores such that it could be promoted to a vector
1690/// SSA value. We only can ensure this for a limited set of operations, and we
1691/// don't want to do the rewrites unless we are confident that the result will
1692/// be promotable, so we have an early test here.
Chandler Carruth2dc96822014-10-18 00:44:02 +00001693static VectorType *
David Majnemerc0a313b2014-11-21 02:34:55 +00001694isVectorPromotionViable(const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001695 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
Chandler Carruthc659df92014-10-16 20:24:07 +00001696 AllocaSlices::const_range Slices,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001697 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001698 // Collect the candidate types for vector-based promotion. Also track whether
1699 // we have different element types.
1700 SmallVector<VectorType *, 4> CandidateTys;
1701 Type *CommonEltTy = nullptr;
1702 bool HaveCommonEltTy = true;
1703 auto CheckCandidateType = [&](Type *Ty) {
1704 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1705 CandidateTys.push_back(VTy);
1706 if (!CommonEltTy)
1707 CommonEltTy = VTy->getElementType();
1708 else if (CommonEltTy != VTy->getElementType())
1709 HaveCommonEltTy = false;
1710 }
1711 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001712 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruthc659df92014-10-16 20:24:07 +00001713 for (const auto &S : Slices)
Chandler Carruth2dc96822014-10-18 00:44:02 +00001714 if (S.beginOffset() == SliceBeginOffset &&
1715 S.endOffset() == SliceEndOffset) {
1716 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1717 CheckCandidateType(LI->getType());
1718 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1719 CheckCandidateType(SI->getValueOperand()->getType());
1720 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001721
Chandler Carruth2dc96822014-10-18 00:44:02 +00001722 // If we didn't find a vector type, nothing to do here.
1723 if (CandidateTys.empty())
1724 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001725
Chandler Carruth2dc96822014-10-18 00:44:02 +00001726 // Remove non-integer vector types if we had multiple common element types.
1727 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1728 // do that until all the backends are known to produce good code for all
1729 // integer vector types.
1730 if (!HaveCommonEltTy) {
1731 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1732 [](VectorType *VTy) {
1733 return !VTy->getElementType()->isIntegerTy();
1734 }),
1735 CandidateTys.end());
1736
1737 // If there were no integer vector types, give up.
1738 if (CandidateTys.empty())
1739 return nullptr;
1740
1741 // Rank the remaining candidate vector types. This is easy because we know
1742 // they're all integer vectors. We sort by ascending number of elements.
1743 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1744 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1745 "Cannot have vector types of different sizes!");
1746 assert(RHSTy->getElementType()->isIntegerTy() &&
1747 "All non-integer types eliminated!");
1748 assert(LHSTy->getElementType()->isIntegerTy() &&
1749 "All non-integer types eliminated!");
1750 return RHSTy->getNumElements() < LHSTy->getNumElements();
1751 };
1752 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1753 CandidateTys.erase(
1754 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1755 CandidateTys.end());
1756 } else {
1757// The only way to have the same element type in every vector type is to
1758// have the same vector type. Check that and remove all but one.
1759#ifndef NDEBUG
1760 for (VectorType *VTy : CandidateTys) {
1761 assert(VTy->getElementType() == CommonEltTy &&
1762 "Unaccounted for element type!");
1763 assert(VTy == CandidateTys[0] &&
1764 "Different vector types with the same element type!");
1765 }
1766#endif
1767 CandidateTys.resize(1);
1768 }
1769
1770 // Try each vector type, and return the one which works.
1771 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1772 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1773
1774 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1775 // that aren't byte sized.
1776 if (ElementSize % 8)
1777 return false;
1778 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1779 "vector size not a multiple of element size?");
1780 ElementSize /= 8;
1781
1782 for (const auto &S : Slices)
1783 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1784 VTy, ElementSize, S))
1785 return false;
1786
1787 for (const auto &SI : SplitUses)
1788 if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1789 VTy, ElementSize, *SI))
1790 return false;
1791
1792 return true;
1793 };
1794 for (VectorType *VTy : CandidateTys)
1795 if (CheckVectorTypeForPromotion(VTy))
1796 return VTy;
1797
1798 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001799}
1800
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001801/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001802///
1803/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001804/// test below on a single slice of the alloca.
1805static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1806 Type *AllocaTy,
1807 uint64_t AllocBeginOffset,
Chandler Carruthc659df92014-10-16 20:24:07 +00001808 uint64_t Size,
1809 const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001810 bool &WholeAllocaOp) {
Chandler Carruthc659df92014-10-16 20:24:07 +00001811 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1812 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001813
1814 // We can't reasonably handle cases where the load or store extends past
1815 // the end of the aloca's type and into its padding.
1816 if (RelEnd > Size)
1817 return false;
1818
Chandler Carruthc659df92014-10-16 20:24:07 +00001819 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001820
1821 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1822 if (LI->isVolatile())
1823 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001824 // Note that we don't count vector loads or stores as whole-alloca
1825 // operations which enable integer widening because we would prefer to use
1826 // vector widening instead.
1827 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001828 WholeAllocaOp = true;
1829 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001830 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001831 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001832 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001833 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001834 // Non-integer loads need to be convertible from the alloca type so that
1835 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001836 return false;
1837 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001838 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1839 Type *ValueTy = SI->getValueOperand()->getType();
1840 if (SI->isVolatile())
1841 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001842 // Note that we don't count vector loads or stores as whole-alloca
1843 // operations which enable integer widening because we would prefer to use
1844 // vector widening instead.
1845 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001846 WholeAllocaOp = true;
1847 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001848 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001849 return false;
1850 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001851 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001852 // Non-integer stores need to be convertible to the alloca type so that
1853 // they are promotable.
1854 return false;
1855 }
1856 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1857 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1858 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001859 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001860 return false; // Skip any unsplittable intrinsics.
1861 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1862 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1863 II->getIntrinsicID() != Intrinsic::lifetime_end)
1864 return false;
1865 } else {
1866 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001867 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001868
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001869 return true;
1870}
1871
Chandler Carruth435c4e02012-10-15 08:40:30 +00001872/// \brief Test whether the given alloca partition's integer operations can be
1873/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00001874///
Chandler Carruth435c4e02012-10-15 08:40:30 +00001875/// This is a quick test to check whether we can rewrite the integer loads and
1876/// stores to a particular alloca into wider loads and stores and be able to
1877/// promote the resulting alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +00001878static bool
Chandler Carruth90a735d2013-07-19 07:21:28 +00001879isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
Chandler Carruthc659df92014-10-16 20:24:07 +00001880 uint64_t AllocBeginOffset,
1881 AllocaSlices::const_range Slices,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001882 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001883 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00001884 // Don't create integer types larger than the maximum bitwidth.
1885 if (SizeInBits > IntegerType::MAX_INT_BITS)
1886 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00001887
1888 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001889 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001890 return false;
1891
Chandler Carruth58d05562012-10-25 04:37:07 +00001892 // We need to ensure that an integer type with the appropriate bitwidth can
1893 // be converted to the alloca type, whatever that is. We don't want to force
1894 // the alloca itself to have an integer type if there is a more suitable one.
1895 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001896 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1897 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00001898 return false;
1899
Chandler Carruth90a735d2013-07-19 07:21:28 +00001900 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
Chandler Carruth435c4e02012-10-15 08:40:30 +00001901
Chandler Carruthf0546402013-07-18 07:15:00 +00001902 // While examining uses, we ensure that the alloca has a covering load or
1903 // store. We don't want to widen the integer operations only to fail to
1904 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00001905 // later). However, if there are only splittable uses, go ahead and assume
1906 // that we cover the alloca.
Chandler Carruthc659df92014-10-16 20:24:07 +00001907 bool WholeAllocaOp =
1908 Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00001909
Chandler Carruthc659df92014-10-16 20:24:07 +00001910 for (const auto &S : Slices)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001911 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
Chandler Carruthc659df92014-10-16 20:24:07 +00001912 S, WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00001913 return false;
1914
Chandler Carruthc659df92014-10-16 20:24:07 +00001915 for (const auto &SI : SplitUses)
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001916 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
Chandler Carruthc659df92014-10-16 20:24:07 +00001917 *SI, WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00001918 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001919
Chandler Carruth92924fd2012-09-24 00:34:20 +00001920 return WholeAllocaOp;
1921}
1922
Chandler Carruthd177f862013-03-20 07:30:36 +00001923static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001924 IntegerType *Ty, uint64_t Offset,
1925 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00001926 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001927 IntegerType *IntTy = cast<IntegerType>(V->getType());
1928 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1929 "Element extends past full value");
1930 uint64_t ShAmt = 8*Offset;
1931 if (DL.isBigEndian())
1932 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001933 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001934 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001935 DEBUG(dbgs() << " shifted: " << *V << "\n");
1936 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001937 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1938 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001939 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001940 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00001941 DEBUG(dbgs() << " trunced: " << *V << "\n");
1942 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001943 return V;
1944}
1945
Chandler Carruthd177f862013-03-20 07:30:36 +00001946static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001947 Value *V, uint64_t Offset, const Twine &Name) {
1948 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1949 IntegerType *Ty = cast<IntegerType>(V->getType());
1950 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1951 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00001952 DEBUG(dbgs() << " start: " << *V << "\n");
1953 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001954 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00001955 DEBUG(dbgs() << " extended: " << *V << "\n");
1956 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001957 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1958 "Element store outside of alloca store");
1959 uint64_t ShAmt = 8*Offset;
1960 if (DL.isBigEndian())
1961 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00001962 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001963 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00001964 DEBUG(dbgs() << " shifted: " << *V << "\n");
1965 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001966
1967 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1968 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1969 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00001970 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001971 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00001972 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00001973 }
1974 return V;
1975}
1976
Chandler Carruthd177f862013-03-20 07:30:36 +00001977static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00001978 unsigned BeginIndex, unsigned EndIndex,
1979 const Twine &Name) {
1980 VectorType *VecTy = cast<VectorType>(V->getType());
1981 unsigned NumElements = EndIndex - BeginIndex;
1982 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1983
1984 if (NumElements == VecTy->getNumElements())
1985 return V;
1986
1987 if (NumElements == 1) {
1988 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1989 Name + ".extract");
1990 DEBUG(dbgs() << " extract: " << *V << "\n");
1991 return V;
1992 }
1993
1994 SmallVector<Constant*, 8> Mask;
1995 Mask.reserve(NumElements);
1996 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1997 Mask.push_back(IRB.getInt32(i));
1998 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1999 ConstantVector::get(Mask),
2000 Name + ".extract");
2001 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2002 return V;
2003}
2004
Chandler Carruthd177f862013-03-20 07:30:36 +00002005static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002006 unsigned BeginIndex, const Twine &Name) {
2007 VectorType *VecTy = cast<VectorType>(Old->getType());
2008 assert(VecTy && "Can only insert a vector into a vector");
2009
2010 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2011 if (!Ty) {
2012 // Single element to insert.
2013 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2014 Name + ".insert");
2015 DEBUG(dbgs() << " insert: " << *V << "\n");
2016 return V;
2017 }
2018
2019 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2020 "Too many elements!");
2021 if (Ty->getNumElements() == VecTy->getNumElements()) {
2022 assert(V->getType() == VecTy && "Vector type mismatch");
2023 return V;
2024 }
2025 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2026
2027 // When inserting a smaller vector into the larger to store, we first
2028 // use a shuffle vector to widen it with undef elements, and then
2029 // a second shuffle vector to select between the loaded vector and the
2030 // incoming vector.
2031 SmallVector<Constant*, 8> Mask;
2032 Mask.reserve(VecTy->getNumElements());
2033 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2034 if (i >= BeginIndex && i < EndIndex)
2035 Mask.push_back(IRB.getInt32(i - BeginIndex));
2036 else
2037 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2038 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2039 ConstantVector::get(Mask),
2040 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002041 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002042
2043 Mask.clear();
2044 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002045 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2046
2047 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2048
2049 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002050 return V;
2051}
2052
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002053namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002054/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2055/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002056///
2057/// Also implements the rewriting to vector-based accesses when the partition
2058/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2059/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002060class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002061 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002062 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2063 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002064
Chandler Carruth90a735d2013-07-19 07:21:28 +00002065 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002066 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002067 SROA &Pass;
2068 AllocaInst &OldAI, &NewAI;
2069 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002070 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002071
Chandler Carruth2dc96822014-10-18 00:44:02 +00002072 // This is a convenience and flag variable that will be null unless the new
2073 // alloca's integer operations should be widened to this integer type due to
2074 // passing isIntegerWideningViable above. If it is non-null, the desired
2075 // integer type will be stored here for easy access during rewriting.
2076 IntegerType *IntTy;
2077
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002078 // If we are rewriting an alloca partition which can be written as pure
2079 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002080 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002081 // - The new alloca is exactly the size of the vector type here.
2082 // - The accesses all either map to the entire vector or to a single
2083 // element.
2084 // - The set of accessing instructions is only one of those handled above
2085 // in isVectorPromotionViable. Generally these are the same access kinds
2086 // which are promotable via mem2reg.
2087 VectorType *VecTy;
2088 Type *ElementTy;
2089 uint64_t ElementSize;
2090
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002091 // The original offset of the slice currently being rewritten relative to
2092 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002093 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002094 // The new offsets of the slice currently being rewritten relative to the
2095 // original alloca.
2096 uint64_t NewBeginOffset, NewEndOffset;
2097
2098 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002099 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002100 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002101 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002102 Instruction *OldPtr;
2103
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002104 // Track post-rewrite users which are PHI nodes and Selects.
2105 SmallPtrSetImpl<PHINode *> &PHIUsers;
2106 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002107
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002108 // Utility IR builder, whose name prefix is setup for each visited use, and
2109 // the insertion point is set to point to the user.
2110 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002111
2112public:
Chandler Carruth83934062014-10-16 21:11:55 +00002113 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002114 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002115 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002116 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2117 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002118 SmallPtrSetImpl<PHINode *> &PHIUsers,
2119 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002120 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002121 NewAllocaBeginOffset(NewAllocaBeginOffset),
2122 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002123 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002124 IntTy(IsIntegerPromotable
2125 ? Type::getIntNTy(
2126 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002127 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002128 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002129 VecTy(PromotableVecTy),
2130 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2131 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002132 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002133 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002134 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002135 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002136 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002137 "Only multiple-of-8 sized vector elements are viable");
2138 ++NumVectorized;
2139 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002140 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002141 }
2142
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002143 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002144 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002145 BeginOffset = I->beginOffset();
2146 EndOffset = I->endOffset();
2147 IsSplittable = I->isSplittable();
2148 IsSplit =
2149 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002150
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002151 // Compute the intersecting offset range.
2152 assert(BeginOffset < NewAllocaEndOffset);
2153 assert(EndOffset > NewAllocaBeginOffset);
2154 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2155 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2156
2157 SliceSize = NewEndOffset - NewBeginOffset;
2158
Chandler Carruthf0546402013-07-18 07:15:00 +00002159 OldUse = I->getUse();
2160 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002161
Chandler Carruthf0546402013-07-18 07:15:00 +00002162 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2163 IRB.SetInsertPoint(OldUserI);
2164 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2165 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2166
2167 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2168 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002169 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002170 return CanSROA;
2171 }
2172
2173private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002174 // Make sure the other visit overloads are visible.
2175 using Base::visit;
2176
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002177 // Every instruction which can end up as a user must have a rewrite rule.
2178 bool visitInstruction(Instruction &I) {
2179 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2180 llvm_unreachable("No rewrite rule for this instruction!");
2181 }
2182
Chandler Carruth47954c82014-02-26 05:12:43 +00002183 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2184 // Note that the offset computation can use BeginOffset or NewBeginOffset
2185 // interchangeably for unsplit slices.
2186 assert(IsSplit || BeginOffset == NewBeginOffset);
2187 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2188
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002189#ifndef NDEBUG
2190 StringRef OldName = OldPtr->getName();
2191 // Skip through the last '.sroa.' component of the name.
2192 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2193 if (LastSROAPrefix != StringRef::npos) {
2194 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2195 // Look for an SROA slice index.
2196 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2197 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2198 // Strip the index and look for the offset.
2199 OldName = OldName.substr(IndexEnd + 1);
2200 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2201 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2202 // Strip the offset.
2203 OldName = OldName.substr(OffsetEnd + 1);
2204 }
2205 }
2206 // Strip any SROA suffixes as well.
2207 OldName = OldName.substr(0, OldName.find(".sroa_"));
2208#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002209
2210 return getAdjustedPtr(IRB, DL, &NewAI,
2211 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002212#ifndef NDEBUG
2213 Twine(OldName) + "."
2214#else
2215 Twine()
2216#endif
2217 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002218 }
2219
Chandler Carruth2659e502014-02-26 05:02:19 +00002220 /// \brief Compute suitable alignment to access this slice of the *new* alloca.
2221 ///
2222 /// You can optionally pass a type to this routine and if that type's ABI
2223 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002224 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002225 unsigned NewAIAlign = NewAI.getAlignment();
2226 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002227 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth2659e502014-02-26 05:02:19 +00002228 unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2229 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002230 }
2231
Chandler Carruth845b73c2012-11-21 08:16:30 +00002232 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002233 assert(VecTy && "Can only call getIndex when rewriting a vector");
2234 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2235 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2236 uint32_t Index = RelOffset / ElementSize;
2237 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002238 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002239 }
2240
2241 void deleteIfTriviallyDead(Value *V) {
2242 Instruction *I = cast<Instruction>(V);
2243 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002244 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002245 }
2246
Chandler Carruthea27cf02014-02-26 04:25:04 +00002247 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002248 unsigned BeginIndex = getIndex(NewBeginOffset);
2249 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002250 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002251
2252 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002253 "load");
2254 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002255 }
2256
Chandler Carruthea27cf02014-02-26 04:25:04 +00002257 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002258 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002259 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002260 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002261 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002262 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002263 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2264 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2265 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002266 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002267 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002268 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002269 }
2270
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002271 bool visitLoadInst(LoadInst &LI) {
2272 DEBUG(dbgs() << " original: " << LI << "\n");
2273 Value *OldOp = LI.getOperand(0);
2274 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002275
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002276 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002277 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002278 bool IsPtrAdjusted = false;
2279 Value *V;
2280 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002281 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002282 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002283 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002284 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002285 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002286 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth25adb7b02014-02-25 11:21:48 +00002287 LI.isVolatile(), LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002288 } else {
2289 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002290 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002291 getSliceAlign(TargetTy), LI.isVolatile(),
2292 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002293 IsPtrAdjusted = true;
2294 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002295 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002296
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002297 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002298 assert(!LI.isVolatile());
2299 assert(LI.getType()->isIntegerTy() &&
2300 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002301 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002302 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002303 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002304 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002305 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002306 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002307 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002308 // Create a placeholder value with the same type as LI to use as the
2309 // basis for the new value. This allows us to replace the uses of LI with
2310 // the computed value, and then replace the placeholder with LI, leaving
2311 // LI only used for this computation.
2312 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002313 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth90a735d2013-07-19 07:21:28 +00002314 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002315 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002316 LI.replaceAllUsesWith(V);
2317 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002318 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002319 } else {
2320 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002321 }
2322
Chandler Carruth18db7952012-11-20 01:12:50 +00002323 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002324 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002325 DEBUG(dbgs() << " to: " << *V << "\n");
2326 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002327 }
2328
Chandler Carruthea27cf02014-02-26 04:25:04 +00002329 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002330 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002331 unsigned BeginIndex = getIndex(NewBeginOffset);
2332 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002333 assert(EndIndex > BeginIndex && "Empty vector!");
2334 unsigned NumElements = EndIndex - BeginIndex;
2335 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002336 Type *SliceTy =
2337 (NumElements == 1) ? ElementTy
2338 : VectorType::get(ElementTy, NumElements);
2339 if (V->getType() != SliceTy)
2340 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002341
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002342 // Mix in the existing elements.
2343 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2344 "load");
2345 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2346 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002347 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002348 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002349
2350 (void)Store;
2351 DEBUG(dbgs() << " to: " << *Store << "\n");
2352 return true;
2353 }
2354
Chandler Carruthea27cf02014-02-26 04:25:04 +00002355 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002356 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002357 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002358 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002359 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002360 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002361 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002362 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2363 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002364 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002365 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002366 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002367 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002368 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002369 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002370 (void)Store;
2371 DEBUG(dbgs() << " to: " << *Store << "\n");
2372 return true;
2373 }
2374
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002375 bool visitStoreInst(StoreInst &SI) {
2376 DEBUG(dbgs() << " original: " << SI << "\n");
2377 Value *OldOp = SI.getOperand(1);
2378 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002379
Chandler Carruth18db7952012-11-20 01:12:50 +00002380 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002381
Chandler Carruthac8317f2012-10-04 12:33:50 +00002382 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2383 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002384 if (V->getType()->isPointerTy())
2385 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002386 Pass.PostPromotionWorklist.insert(AI);
2387
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002388 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002389 assert(!SI.isVolatile());
2390 assert(V->getType()->isIntegerTy() &&
2391 "Only integer type loads and stores are split");
2392 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth90a735d2013-07-19 07:21:28 +00002393 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002394 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002395 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002396 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002397 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002398 }
2399
Chandler Carruth18db7952012-11-20 01:12:50 +00002400 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002401 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002402 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002403 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002404
Chandler Carruth18db7952012-11-20 01:12:50 +00002405 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002406 if (NewBeginOffset == NewAllocaBeginOffset &&
2407 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002408 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2409 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002410 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2411 SI.isVolatile());
2412 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002413 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002414 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2415 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002416 }
2417 (void)NewSI;
2418 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002419 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002420
2421 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2422 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002423 }
2424
Chandler Carruth514f34f2012-12-17 04:07:30 +00002425 /// \brief Compute an integer value from splatting an i8 across the given
2426 /// number of bytes.
2427 ///
2428 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2429 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002430 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002431 ///
2432 /// \param V The i8 value to splat.
2433 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002434 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002435 assert(Size > 0 && "Expected a positive number of bytes.");
2436 IntegerType *VTy = cast<IntegerType>(V->getType());
2437 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2438 if (Size == 1)
2439 return V;
2440
2441 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002442 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002443 ConstantExpr::getUDiv(
2444 Constant::getAllOnesValue(SplatIntTy),
2445 ConstantExpr::getZExt(
2446 Constant::getAllOnesValue(V->getType()),
2447 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002448 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002449 return V;
2450 }
2451
Chandler Carruthccca5042012-12-17 04:07:37 +00002452 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002453 Value *getVectorSplat(Value *V, unsigned NumElements) {
2454 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002455 DEBUG(dbgs() << " splat: " << *V << "\n");
2456 return V;
2457 }
2458
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002459 bool visitMemSetInst(MemSetInst &II) {
2460 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002461 assert(II.getRawDest() == OldPtr);
2462
2463 // If the memset has a variable size, it cannot be split, just adjust the
2464 // pointer to the new alloca.
2465 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002466 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002467 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002468 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002469 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002470 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002471
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002472 deleteIfTriviallyDead(OldPtr);
2473 return false;
2474 }
2475
2476 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002477 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002478
2479 Type *AllocaTy = NewAI.getAllocatedType();
2480 Type *ScalarTy = AllocaTy->getScalarType();
2481
2482 // If this doesn't map cleanly onto the alloca type, and that type isn't
2483 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002484 if (!VecTy && !IntTy &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002485 (BeginOffset > NewAllocaBeginOffset ||
2486 EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002487 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002488 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002489 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2490 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002491 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002492 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2493 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002494 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2495 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002496 (void)New;
2497 DEBUG(dbgs() << " to: " << *New << "\n");
2498 return false;
2499 }
2500
2501 // If we can represent this as a simple value, we have to build the actual
2502 // value to store, which requires expanding the byte present in memset to
2503 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002504 // splatting the byte to a sufficiently wide integer, splatting it across
2505 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002506 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002507
Chandler Carruthccca5042012-12-17 04:07:37 +00002508 if (VecTy) {
2509 // If this is a memset of a vectorized alloca, insert it.
2510 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002511
Chandler Carruthf0546402013-07-18 07:15:00 +00002512 unsigned BeginIndex = getIndex(NewBeginOffset);
2513 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002514 assert(EndIndex > BeginIndex && "Empty vector!");
2515 unsigned NumElements = EndIndex - BeginIndex;
2516 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2517
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002518 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002519 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2520 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002521 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002522 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002523
Chandler Carruthce4562b2012-12-17 13:41:21 +00002524 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002525 "oldload");
2526 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002527 } else if (IntTy) {
2528 // If this is a memset on an alloca where we can widen stores, insert the
2529 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002530 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002531
Chandler Carruthf0546402013-07-18 07:15:00 +00002532 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002533 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002534
2535 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2536 EndOffset != NewAllocaBeginOffset)) {
2537 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002538 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002539 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002540 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002541 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002542 } else {
2543 assert(V->getType() == IntTy &&
2544 "Wrong type for an alloca wide integer!");
2545 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002546 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002547 } else {
2548 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002549 assert(NewBeginOffset == NewAllocaBeginOffset);
2550 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002551
Chandler Carruth90a735d2013-07-19 07:21:28 +00002552 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002553 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002554 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002555
Chandler Carruth90a735d2013-07-19 07:21:28 +00002556 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002557 }
2558
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002559 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002560 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002561 (void)New;
2562 DEBUG(dbgs() << " to: " << *New << "\n");
2563 return !II.isVolatile();
2564 }
2565
2566 bool visitMemTransferInst(MemTransferInst &II) {
2567 // Rewriting of memory transfer instructions can be a bit tricky. We break
2568 // them into two categories: split intrinsics and unsplit intrinsics.
2569
2570 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002571
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002572 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002573 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002574 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002575
Chandler Carruthaa72b932014-02-26 07:29:54 +00002576 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002577
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002578 // For unsplit intrinsics, we simply modify the source and destination
2579 // pointers in place. This isn't just an optimization, it is a matter of
2580 // correctness. With unsplit intrinsics we may be dealing with transfers
2581 // within a single alloca before SROA ran, or with transfers that have
2582 // a variable length. We may also be dealing with memmove instead of
2583 // memcpy, and so simply updating the pointers is the necessary for us to
2584 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002585 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002586 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002587 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002588 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002589 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002590 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002591
Chandler Carruthaa72b932014-02-26 07:29:54 +00002592 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002593 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002594 II.setAlignment(
2595 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002596 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002597
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002598 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002599 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002600 return false;
2601 }
2602 // For split transfer intrinsics we have an incredibly useful assurance:
2603 // the source and destination do not reside within the same alloca, and at
2604 // least one of them does not escape. This means that we can replace
2605 // memmove with memcpy, and we don't need to worry about all manner of
2606 // downsides to splitting and transforming the operations.
2607
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002608 // If this doesn't map cleanly onto the alloca type, and that type isn't
2609 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002610 bool EmitMemCpy =
2611 !VecTy && !IntTy &&
2612 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2613 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2614 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002615
2616 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2617 // size hasn't been shrunk based on analysis of the viable range, this is
2618 // a no-op.
2619 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002620 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002621 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002622
2623 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002624 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002625 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002626 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002627 return false;
2628 }
2629 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002630 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002631
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002632 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2633 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002634 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002635 if (AllocaInst *AI
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002636 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2637 assert(AI != &OldAI && AI != &NewAI &&
2638 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002639 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002640 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002641
Chandler Carruth286d87e2014-02-26 08:25:02 +00002642 Type *OtherPtrTy = OtherPtr->getType();
2643 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2644
Chandler Carruth181ed052014-02-26 05:33:36 +00002645 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002646 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002647 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002648 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2649 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002650
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002651 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002652 // Compute the other pointer, folding as much as possible to produce
2653 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002654 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002655 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002656
Chandler Carruth47954c82014-02-26 05:12:43 +00002657 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002658 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002659 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002660
Chandler Carruthaa72b932014-02-26 07:29:54 +00002661 CallInst *New = IRB.CreateMemCpy(
2662 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2663 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002664 (void)New;
2665 DEBUG(dbgs() << " to: " << *New << "\n");
2666 return false;
2667 }
2668
Chandler Carruthf0546402013-07-18 07:15:00 +00002669 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2670 NewEndOffset == NewAllocaEndOffset;
2671 uint64_t Size = NewEndOffset - NewBeginOffset;
2672 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2673 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002674 unsigned NumElements = EndIndex - BeginIndex;
2675 IntegerType *SubIntTy
Craig Topperf40110f2014-04-25 05:29:35 +00002676 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002677
Chandler Carruth286d87e2014-02-26 08:25:02 +00002678 // Reset the other pointer type to match the register type we're going to
2679 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002680 if (VecTy && !IsWholeAlloca) {
2681 if (NumElements == 1)
2682 OtherPtrTy = VecTy->getElementType();
2683 else
2684 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2685
Chandler Carruth286d87e2014-02-26 08:25:02 +00002686 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002687 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002688 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2689 } else {
2690 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002691 }
2692
Chandler Carruth181ed052014-02-26 05:33:36 +00002693 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002694 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002695 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002696 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002697 unsigned DstAlign = SliceAlign;
2698 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002699 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002700 std::swap(SrcAlign, DstAlign);
2701 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002702
2703 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002704 if (VecTy && !IsWholeAlloca && !IsDest) {
2705 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002706 "load");
2707 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002708 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002709 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002710 "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002711 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002712 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002713 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002714 } else {
Chandler Carruthaa72b932014-02-26 07:29:54 +00002715 Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002716 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717 }
2718
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002719 if (VecTy && !IsWholeAlloca && IsDest) {
2720 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002721 "oldload");
2722 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002723 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002724 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002725 "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002726 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002727 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002728 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2729 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002730 }
2731
Chandler Carruth871ba722012-09-26 10:27:46 +00002732 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002733 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002734 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002735 DEBUG(dbgs() << " to: " << *Store << "\n");
2736 return !II.isVolatile();
2737 }
2738
2739 bool visitIntrinsicInst(IntrinsicInst &II) {
2740 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2741 II.getIntrinsicID() == Intrinsic::lifetime_end);
2742 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002743 assert(II.getArgOperand(1) == OldPtr);
2744
2745 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002746 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002747
2748 ConstantInt *Size
2749 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002750 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002751 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002752 Value *New;
2753 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2754 New = IRB.CreateLifetimeStart(Ptr, Size);
2755 else
2756 New = IRB.CreateLifetimeEnd(Ptr, Size);
2757
Edwin Vane82f80d42013-01-29 17:42:24 +00002758 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002759 DEBUG(dbgs() << " to: " << *New << "\n");
2760 return true;
2761 }
2762
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002763 bool visitPHINode(PHINode &PN) {
2764 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00002765 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2766 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002767
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002768 // We would like to compute a new pointer in only one place, but have it be
2769 // as local as possible to the PHI. To do that, we re-use the location of
2770 // the old pointer, which necessarily must be in the right position to
2771 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00002772 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00002773 if (isa<PHINode>(OldPtr))
2774 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
2775 else
2776 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00002777 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002778
Chandler Carruth47954c82014-02-26 05:12:43 +00002779 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002780 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002781 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002782
Chandler Carruth82a57542012-10-01 10:54:05 +00002783 DEBUG(dbgs() << " to: " << PN << "\n");
2784 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002785
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002786 // PHIs can't be promoted on their own, but often can be speculated. We
2787 // check the speculation outside of the rewriter so that we see the
2788 // fully-rewritten alloca.
2789 PHIUsers.insert(&PN);
2790 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002791 }
2792
2793 bool visitSelectInst(SelectInst &SI) {
2794 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002795 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2796 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00002797 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2798 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00002799
Chandler Carruth47954c82014-02-26 05:12:43 +00002800 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00002801 // Replace the operands which were using the old pointer.
2802 if (SI.getOperand(1) == OldPtr)
2803 SI.setOperand(1, NewPtr);
2804 if (SI.getOperand(2) == OldPtr)
2805 SI.setOperand(2, NewPtr);
2806
Chandler Carruth82a57542012-10-01 10:54:05 +00002807 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002808 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00002809
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002810 // Selects can't be promoted on their own, but often can be speculated. We
2811 // check the speculation outside of the rewriter so that we see the
2812 // fully-rewritten alloca.
2813 SelectUsers.insert(&SI);
2814 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002815 }
2816
2817};
2818}
2819
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002820namespace {
2821/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2822///
2823/// This pass aggressively rewrites all aggregate loads and stores on
2824/// a particular pointer (or any pointer derived from it which we can identify)
2825/// with scalar loads and stores.
2826class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2827 // Befriend the base class so it can delegate to private visit methods.
2828 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2829
Chandler Carruth90a735d2013-07-19 07:21:28 +00002830 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002831
2832 /// Queue of pointer uses to analyze and potentially rewrite.
2833 SmallVector<Use *, 8> Queue;
2834
2835 /// Set to prevent us from cycling with phi nodes and loops.
2836 SmallPtrSet<User *, 8> Visited;
2837
2838 /// The current pointer use being rewritten. This is used to dig up the used
2839 /// value (as opposed to the user).
2840 Use *U;
2841
2842public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00002843 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002844
2845 /// Rewrite loads and stores through a pointer and all pointers derived from
2846 /// it.
2847 bool rewrite(Instruction &I) {
2848 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2849 enqueueUsers(I);
2850 bool Changed = false;
2851 while (!Queue.empty()) {
2852 U = Queue.pop_back_val();
2853 Changed |= visit(cast<Instruction>(U->getUser()));
2854 }
2855 return Changed;
2856 }
2857
2858private:
2859 /// Enqueue all the users of the given instruction for further processing.
2860 /// This uses a set to de-duplicate users.
2861 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002862 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00002863 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00002864 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002865 }
2866
2867 // Conservative default is to not rewrite anything.
2868 bool visitInstruction(Instruction &I) { return false; }
2869
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002870 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002871 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002872 class OpSplitter {
2873 protected:
2874 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00002875 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002876 /// The indices which to be used with insert- or extractvalue to select the
2877 /// appropriate value within the aggregate.
2878 SmallVector<unsigned, 4> Indices;
2879 /// The indices to a GEP instruction which will move Ptr to the correct slot
2880 /// within the aggregate.
2881 SmallVector<Value *, 4> GEPIndices;
2882 /// The base pointer of the original op, used as a base for GEPing the
2883 /// split operations.
2884 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002885
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002886 /// Initialize the splitter with an insertion point, Ptr and start with a
2887 /// single zero GEP index.
2888 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002889 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002890
2891 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002892 /// \brief Generic recursive split emission routine.
2893 ///
2894 /// This method recursively splits an aggregate op (load or store) into
2895 /// scalar or vector ops. It splits recursively until it hits a single value
2896 /// and emits that single value operation via the template argument.
2897 ///
2898 /// The logic of this routine relies on GEPs and insertvalue and
2899 /// extractvalue all operating with the same fundamental index list, merely
2900 /// formatted differently (GEPs need actual values).
2901 ///
2902 /// \param Ty The type being split recursively into smaller ops.
2903 /// \param Agg The aggregate value being built up or stored, depending on
2904 /// whether this is splitting a load or a store respectively.
2905 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2906 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002907 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002908
2909 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2910 unsigned OldSize = Indices.size();
2911 (void)OldSize;
2912 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2913 ++Idx) {
2914 assert(Indices.size() == OldSize && "Did not return to the old size");
2915 Indices.push_back(Idx);
2916 GEPIndices.push_back(IRB.getInt32(Idx));
2917 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2918 GEPIndices.pop_back();
2919 Indices.pop_back();
2920 }
2921 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002922 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002923
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002924 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2925 unsigned OldSize = Indices.size();
2926 (void)OldSize;
2927 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2928 ++Idx) {
2929 assert(Indices.size() == OldSize && "Did not return to the old size");
2930 Indices.push_back(Idx);
2931 GEPIndices.push_back(IRB.getInt32(Idx));
2932 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2933 GEPIndices.pop_back();
2934 Indices.pop_back();
2935 }
2936 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002937 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002938
2939 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002940 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002941 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002942
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002943 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002944 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002945 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002946
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002947 /// Emit a leaf load of a single value. This is called at the leaves of the
2948 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002949 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002950 assert(Ty->isSingleValueType());
2951 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00002952 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2953 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002954 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2955 DEBUG(dbgs() << " to: " << *Load << "\n");
2956 }
2957 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002958
2959 bool visitLoadInst(LoadInst &LI) {
2960 assert(LI.getPointerOperand() == *U);
2961 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2962 return false;
2963
2964 // We have an aggregate being loaded, split it apart.
2965 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002966 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002967 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002968 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002969 LI.replaceAllUsesWith(V);
2970 LI.eraseFromParent();
2971 return true;
2972 }
2973
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002974 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002975 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00002976 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002977
2978 /// Emit a leaf store of a single value. This is called at the leaves of the
2979 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00002980 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00002981 assert(Ty->isSingleValueType());
2982 // Extract the single value and store it using the indices.
2983 Value *Store = IRB.CreateStore(
2984 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2985 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2986 (void)Store;
2987 DEBUG(dbgs() << " to: " << *Store << "\n");
2988 }
2989 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00002990
2991 bool visitStoreInst(StoreInst &SI) {
2992 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2993 return false;
2994 Value *V = SI.getValueOperand();
2995 if (V->getType()->isSingleValueType())
2996 return false;
2997
2998 // We have an aggregate being stored, split it apart.
2999 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003000 StoreOpSplitter Splitter(&SI, *U);
3001 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003002 SI.eraseFromParent();
3003 return true;
3004 }
3005
3006 bool visitBitCastInst(BitCastInst &BC) {
3007 enqueueUsers(BC);
3008 return false;
3009 }
3010
3011 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3012 enqueueUsers(GEPI);
3013 return false;
3014 }
3015
3016 bool visitPHINode(PHINode &PN) {
3017 enqueueUsers(PN);
3018 return false;
3019 }
3020
3021 bool visitSelectInst(SelectInst &SI) {
3022 enqueueUsers(SI);
3023 return false;
3024 }
3025};
3026}
3027
Chandler Carruthba931992012-10-13 10:49:33 +00003028/// \brief Strip aggregate type wrapping.
3029///
3030/// This removes no-op aggregate types wrapping an underlying type. It will
3031/// strip as many layers of types as it can without changing either the type
3032/// size or the allocated size.
3033static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3034 if (Ty->isSingleValueType())
3035 return Ty;
3036
3037 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3038 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3039
3040 Type *InnerTy;
3041 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3042 InnerTy = ArrTy->getElementType();
3043 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3044 const StructLayout *SL = DL.getStructLayout(STy);
3045 unsigned Index = SL->getElementContainingOffset(0);
3046 InnerTy = STy->getElementType(Index);
3047 } else {
3048 return Ty;
3049 }
3050
3051 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3052 TypeSize > DL.getTypeSizeInBits(InnerTy))
3053 return Ty;
3054
3055 return stripAggregateTypeWrapping(DL, InnerTy);
3056}
3057
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003058/// \brief Try to find a partition of the aggregate type passed in for a given
3059/// offset and size.
3060///
3061/// This recurses through the aggregate type and tries to compute a subtype
3062/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003063/// of an array, it will even compute a new array type for that sub-section,
3064/// and the same for structs.
3065///
3066/// Note that this routine is very strict and tries to find a partition of the
3067/// type which produces the *exact* right offset and size. It is not forgiving
3068/// when the size or offset cause either end of type-based partition to be off.
3069/// Also, this is a best-effort routine. It is reasonable to give up and not
3070/// return a type if necessary.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003071static Type *getTypePartition(const DataLayout &DL, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003072 uint64_t Offset, uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003073 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3074 return stripAggregateTypeWrapping(DL, Ty);
3075 if (Offset > DL.getTypeAllocSize(Ty) ||
3076 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003077 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003078
3079 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3080 // We can't partition pointers...
3081 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003082 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003083
3084 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003085 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003086 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003087 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003088 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003089 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003090 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003091 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003092 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003093 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003094 Offset -= NumSkippedElements * ElementSize;
3095
3096 // First check if we need to recurse.
3097 if (Offset > 0 || Size < ElementSize) {
3098 // Bail if the partition ends in a different array element.
3099 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003100 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003101 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003102 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003103 }
3104 assert(Offset == 0);
3105
3106 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003107 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003108 assert(Size > ElementSize);
3109 uint64_t NumElements = Size / ElementSize;
3110 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003111 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003112 return ArrayType::get(ElementTy, NumElements);
3113 }
3114
3115 StructType *STy = dyn_cast<StructType>(Ty);
3116 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003117 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003118
Chandler Carruth90a735d2013-07-19 07:21:28 +00003119 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003120 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003121 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003122 uint64_t EndOffset = Offset + Size;
3123 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003124 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003125
3126 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003127 Offset -= SL->getElementOffset(Index);
3128
3129 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003130 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003131 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003132 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003133
3134 // See if any partition must be contained by the element.
3135 if (Offset > 0 || Size < ElementSize) {
3136 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003137 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003138 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003139 }
3140 assert(Offset == 0);
3141
3142 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003143 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003144
3145 StructType::element_iterator EI = STy->element_begin() + Index,
3146 EE = STy->element_end();
3147 if (EndOffset < SL->getSizeInBytes()) {
3148 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3149 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003150 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003151
3152 // Don't try to form "natural" types if the elements don't line up with the
3153 // expected size.
3154 // FIXME: We could potentially recurse down through the last element in the
3155 // sub-struct to find a natural end point.
3156 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003157 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003158
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003159 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003160 EE = STy->element_begin() + EndIndex;
3161 }
3162
3163 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003164 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003165 STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003166 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003167 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003168 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003169
Chandler Carruth054a40a2012-09-14 11:08:31 +00003170 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003171}
3172
3173/// \brief Rewrite an alloca partition's users.
3174///
3175/// This routine drives both of the rewriting goals of the SROA pass. It tries
3176/// to rewrite uses of an alloca partition to be conducive for SSA value
3177/// promotion. If the partition needs a new, more refined alloca, this will
3178/// build that new alloca, preserving as much type information as possible, and
3179/// rewrite the uses of the old alloca to point at the new one and have the
3180/// appropriate new offsets. It also evaluates how successful the rewrite was
3181/// at enabling promotion and if it was successful queues the alloca to be
3182/// promoted.
Chandler Carruth83934062014-10-16 21:11:55 +00003183bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003184 AllocaSlices::iterator B, AllocaSlices::iterator E,
3185 int64_t BeginOffset, int64_t EndOffset,
3186 ArrayRef<AllocaSlices::iterator> SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003187 assert(BeginOffset < EndOffset);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003188 uint64_t SliceSize = EndOffset - BeginOffset;
Chandler Carruth82a57542012-10-01 10:54:05 +00003189
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003190 // Try to compute a friendly type for this partition of the alloca. This
3191 // won't always succeed, in which case we fall back to a legal integer type
3192 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003193 Type *SliceTy = nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00003194 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003195 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3196 SliceTy = CommonUseTy;
3197 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003198 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003199 BeginOffset, SliceSize))
3200 SliceTy = TypePartitionTy;
3201 if ((!SliceTy || (SliceTy->isArrayTy() &&
3202 SliceTy->getArrayElementType()->isIntegerTy())) &&
3203 DL->isLegalInteger(SliceSize * 8))
3204 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3205 if (!SliceTy)
3206 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3207 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
Chandler Carruthf0546402013-07-18 07:15:00 +00003208
Chandler Carruth2dc96822014-10-18 00:44:02 +00003209 bool IsIntegerPromotable = isIntegerWideningViable(
3210 *DL, SliceTy, BeginOffset, AllocaSlices::const_range(B, E), SplitUses);
Chandler Carruthf0546402013-07-18 07:15:00 +00003211
Chandler Carruth2dc96822014-10-18 00:44:02 +00003212 VectorType *VecTy =
3213 IsIntegerPromotable
3214 ? nullptr
David Majnemerc0a313b2014-11-21 02:34:55 +00003215 : isVectorPromotionViable(*DL, BeginOffset, EndOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00003216 AllocaSlices::const_range(B, E), SplitUses);
3217 if (VecTy)
3218 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003219
3220 // Check for the case where we're going to rewrite to a new alloca of the
3221 // exact same type as the original, and with the same access offsets. In that
3222 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003223 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003224 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003225 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003226 assert(BeginOffset == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003227 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003228 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003229 // FIXME: We should be able to bail at this point with "nothing changed".
3230 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003231 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003232 unsigned Alignment = AI.getAlignment();
3233 if (!Alignment) {
3234 // The minimum alignment which users can rely on when the explicit
3235 // alignment is omitted or zero is that required by the ABI for this
3236 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003237 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003238 }
Chandler Carruthf0546402013-07-18 07:15:00 +00003239 Alignment = MinAlign(Alignment, BeginOffset);
Chandler Carruth903790e2012-09-29 10:41:21 +00003240 // If we will get at least this much alignment from the type alone, leave
3241 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003242 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003243 Alignment = 0;
Chandler Carruth83934062014-10-16 21:11:55 +00003244 NewAI =
3245 new AllocaInst(SliceTy, nullptr, Alignment,
3246 AI.getName() + ".sroa." + Twine(B - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003247 ++NumNewAllocas;
3248 }
3249
3250 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthf0546402013-07-18 07:15:00 +00003251 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3252 << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003253
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003254 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003255 // promoted allocas. We will reset it to this point if the alloca is not in
3256 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003257 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003258 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003259 SmallPtrSet<PHINode *, 8> PHIUsers;
3260 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003261
Chandler Carruth83934062014-10-16 21:11:55 +00003262 AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, BeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00003263 EndOffset, IsIntegerPromotable, VecTy, PHIUsers,
3264 SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003265 bool Promotable = true;
Chandler Carruth61747042014-10-16 21:05:14 +00003266 for (auto & SplitUse : SplitUses) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003267 DEBUG(dbgs() << " rewriting split ");
Chandler Carruth83934062014-10-16 21:11:55 +00003268 DEBUG(AS.printSlice(dbgs(), SplitUse, ""));
Chandler Carruth61747042014-10-16 21:05:14 +00003269 Promotable &= Rewriter.visit(SplitUse);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003270 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003271 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003272 for (AllocaSlices::iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003273 DEBUG(dbgs() << " rewriting ");
Chandler Carruth83934062014-10-16 21:11:55 +00003274 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruthf0546402013-07-18 07:15:00 +00003275 Promotable &= Rewriter.visit(I);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003276 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003277 }
3278
Chandler Carruth6c321c12013-07-19 10:57:36 +00003279 NumAllocaPartitionUses += NumUses;
3280 MaxUsesPerAllocaPartition =
3281 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003282
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003283 // Now that we've processed all the slices in the new partition, check if any
3284 // PHIs or Selects would block promotion.
3285 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3286 E = PHIUsers.end();
3287 I != E; ++I)
3288 if (!isSafePHIToSpeculate(**I, DL)) {
3289 Promotable = false;
3290 PHIUsers.clear();
3291 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003292 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003293 }
3294 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3295 E = SelectUsers.end();
3296 I != E; ++I)
3297 if (!isSafeSelectToSpeculate(**I, DL)) {
3298 Promotable = false;
3299 PHIUsers.clear();
3300 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003301 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003302 }
3303
3304 if (Promotable) {
3305 if (PHIUsers.empty() && SelectUsers.empty()) {
3306 // Promote the alloca.
3307 PromotableAllocas.push_back(NewAI);
3308 } else {
3309 // If we have either PHIs or Selects to speculate, add them to those
3310 // worklists and re-queue the new alloca so that we promote in on the
3311 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003312 for (PHINode *PHIUser : PHIUsers)
3313 SpeculatablePHIs.insert(PHIUser);
3314 for (SelectInst *SelectUser : SelectUsers)
3315 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003316 Worklist.insert(NewAI);
3317 }
3318 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003319 // If we can't promote the alloca, iterate on it to check for new
3320 // refinements exposed by splitting the current alloca. Don't iterate on an
3321 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003322 if (NewAI != &AI)
3323 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003324
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003325 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003326 while (PostPromotionWorklist.size() > PPWOldSize)
3327 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003328 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003329
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003330 return true;
3331}
3332
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003333static void
3334removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3335 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003336 if (Offset >= MaxSplitUseEndOffset) {
3337 SplitUses.clear();
3338 MaxSplitUseEndOffset = 0;
3339 return;
3340 }
3341
3342 size_t SplitUsesOldSize = SplitUses.size();
3343 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003344 [Offset](const AllocaSlices::iterator &I) {
3345 return I->endOffset() <= Offset;
3346 }),
Chandler Carruthf0546402013-07-18 07:15:00 +00003347 SplitUses.end());
3348 if (SplitUsesOldSize == SplitUses.size())
3349 return;
3350
3351 // Recompute the max. While this is linear, so is remove_if.
3352 MaxSplitUseEndOffset = 0;
Chandler Carruth61747042014-10-16 21:05:14 +00003353 for (AllocaSlices::iterator SplitUse : SplitUses)
3354 MaxSplitUseEndOffset =
3355 std::max(SplitUse->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003356}
3357
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003358/// \brief Walks the slices of an alloca and form partitions based on them,
3359/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003360bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3361 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003362 return false;
3363
Chandler Carruth6c321c12013-07-19 10:57:36 +00003364 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003365 bool Changed = false;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003366 SmallVector<AllocaSlices::iterator, 4> SplitUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003367 uint64_t MaxSplitUseEndOffset = 0;
3368
Chandler Carruth83934062014-10-16 21:11:55 +00003369 uint64_t BeginOffset = AS.begin()->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003370
Chandler Carruth83934062014-10-16 21:11:55 +00003371 for (AllocaSlices::iterator SI = AS.begin(), SJ = std::next(SI),
3372 SE = AS.end();
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003373 SI != SE; SI = SJ) {
3374 uint64_t MaxEndOffset = SI->endOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003375
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003376 if (!SI->isSplittable()) {
3377 // When we're forming an unsplittable region, it must always start at the
3378 // first slice and will extend through its end.
3379 assert(BeginOffset == SI->beginOffset());
Chandler Carruthf0546402013-07-18 07:15:00 +00003380
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003381 // Form a partition including all of the overlapping slices with this
3382 // unsplittable slice.
3383 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3384 if (!SJ->isSplittable())
3385 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3386 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003387 }
3388 } else {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003389 assert(SI->isSplittable()); // Established above.
Chandler Carruthf0546402013-07-18 07:15:00 +00003390
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003391 // Collect all of the overlapping splittable slices.
3392 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3393 SJ->isSplittable()) {
3394 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3395 ++SJ;
Chandler Carruthf0546402013-07-18 07:15:00 +00003396 }
3397
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003398 // Back up MaxEndOffset and SJ if we ended the span early when
3399 // encountering an unsplittable slice.
3400 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3401 assert(!SJ->isSplittable());
3402 MaxEndOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003403 }
3404 }
3405
3406 // Check if we have managed to move the end offset forward yet. If so,
3407 // we'll have to rewrite uses and erase old split uses.
3408 if (BeginOffset < MaxEndOffset) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003409 // Rewrite a sequence of overlapping slices.
Chandler Carruth83934062014-10-16 21:11:55 +00003410 Changed |= rewritePartition(AI, AS, SI, SJ, BeginOffset, MaxEndOffset,
3411 SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003412 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003413
3414 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3415 }
3416
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003417 // Accumulate all the splittable slices from the [SI,SJ) region which
Chandler Carruthf0546402013-07-18 07:15:00 +00003418 // overlap going forward.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003419 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3420 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3421 SplitUses.push_back(SK);
3422 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
Chandler Carruthf0546402013-07-18 07:15:00 +00003423 }
3424
3425 // If we're already at the end and we have no split uses, we're done.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003426 if (SJ == SE && SplitUses.empty())
Chandler Carruthf0546402013-07-18 07:15:00 +00003427 break;
3428
3429 // If we have no split uses or no gap in offsets, we're ready to move to
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003430 // the next slice.
3431 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3432 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003433 continue;
3434 }
3435
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003436 // Even if we have split slices, if the next slice is splittable and the
3437 // split slices reach it, we can simply set up the beginning offset of the
3438 // next iteration to bridge between them.
3439 if (SJ != SE && SJ->isSplittable() &&
3440 MaxSplitUseEndOffset > SJ->beginOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00003441 BeginOffset = MaxEndOffset;
3442 continue;
3443 }
3444
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003445 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3446 // range of slices.
Chandler Carruthf0546402013-07-18 07:15:00 +00003447 uint64_t PostSplitEndOffset =
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003448 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003449
Chandler Carruth83934062014-10-16 21:11:55 +00003450 Changed |= rewritePartition(AI, AS, SJ, SJ, MaxEndOffset,
3451 PostSplitEndOffset, SplitUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003452 ++NumPartitions;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003453
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003454 if (SJ == SE)
Chandler Carruthf0546402013-07-18 07:15:00 +00003455 break; // Skip the rest, we don't need to do any cleanup.
3456
3457 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3458 PostSplitEndOffset);
3459
3460 // Now just reset the begin offset for the next iteration.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003461 BeginOffset = SJ->beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00003462 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003463
Chandler Carruth6c321c12013-07-19 10:57:36 +00003464 NumAllocaPartitions += NumPartitions;
3465 MaxPartitionsPerAlloca =
3466 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003467
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003468 return Changed;
3469}
3470
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003471/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3472void SROA::clobberUse(Use &U) {
3473 Value *OldV = U;
3474 // Replace the use with an undef value.
3475 U = UndefValue::get(OldV->getType());
3476
3477 // Check for this making an instruction dead. We have to garbage collect
3478 // all the dead instructions to ensure the uses of any alloca end up being
3479 // minimal.
3480 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3481 if (isInstructionTriviallyDead(OldI)) {
3482 DeadInsts.insert(OldI);
3483 }
3484}
3485
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003486/// \brief Analyze an alloca for SROA.
3487///
3488/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003489/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003490/// rewritten as needed.
3491bool SROA::runOnAlloca(AllocaInst &AI) {
3492 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3493 ++NumAllocasAnalyzed;
3494
3495 // Special case dead allocas, as they're trivial.
3496 if (AI.use_empty()) {
3497 AI.eraseFromParent();
3498 return true;
3499 }
3500
3501 // Skip alloca forms that this analysis can't handle.
3502 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003503 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003504 return false;
3505
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003506 bool Changed = false;
3507
3508 // First, split any FCA loads and stores touching this alloca to promote
3509 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003510 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003511 Changed |= AggRewriter.rewrite(AI);
3512
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003513 // Build the slices using a recursive instruction-visiting builder.
Chandler Carruth83934062014-10-16 21:11:55 +00003514 AllocaSlices AS(*DL, AI);
3515 DEBUG(AS.print(dbgs()));
3516 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003517 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003518
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003519 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00003520 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003521 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003522 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00003523 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003524
3525 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003526 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003527
3528 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003529 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003530 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003531 }
Chandler Carruth83934062014-10-16 21:11:55 +00003532 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003533 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003534 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003535 }
3536
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003537 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00003538 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003539 return Changed;
3540
Chandler Carruth83934062014-10-16 21:11:55 +00003541 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00003542
3543 DEBUG(dbgs() << " Speculating PHIs\n");
3544 while (!SpeculatablePHIs.empty())
3545 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3546
3547 DEBUG(dbgs() << " Speculating Selects\n");
3548 while (!SpeculatableSelects.empty())
3549 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3550
3551 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003552}
3553
Chandler Carruth19450da2012-09-14 10:26:38 +00003554/// \brief Delete the dead instructions accumulated in this run.
3555///
3556/// Recursively deletes the dead instructions we've accumulated. This is done
3557/// at the very end to maximize locality of the recursive delete and to
3558/// minimize the problems of invalidated instruction pointers as such pointers
3559/// are used heavily in the intermediate stages of the algorithm.
3560///
3561/// We also record the alloca instructions deleted here so that they aren't
3562/// subsequently handed to mem2reg to promote.
Craig Topper71b7b682014-08-21 05:55:13 +00003563void SROA::deleteDeadInstructions(SmallPtrSetImpl<AllocaInst*> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003564 while (!DeadInsts.empty()) {
3565 Instruction *I = DeadInsts.pop_back_val();
3566 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3567
Chandler Carruth58d05562012-10-25 04:37:07 +00003568 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3569
Chandler Carruth1583e992014-03-03 10:42:58 +00003570 for (Use &Operand : I->operands())
3571 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003572 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00003573 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003574 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003575 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003576 }
3577
3578 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3579 DeletedAllocas.insert(AI);
3580
3581 ++NumDeleted;
3582 I->eraseFromParent();
3583 }
3584}
3585
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003586static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003587 SmallVectorImpl<Instruction *> &Worklist,
Craig Topper71b7b682014-08-21 05:55:13 +00003588 SmallPtrSetImpl<Instruction *> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003589 for (User *U : I.users())
David Blaikie70573dc2014-11-19 07:49:26 +00003590 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003591 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003592}
3593
Chandler Carruth70b44c52012-09-15 11:43:14 +00003594/// \brief Promote the allocas, using the best available technique.
3595///
3596/// This attempts to promote whatever allocas have been identified as viable in
3597/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3598/// If there is a domtree available, we attempt to promote using the full power
3599/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3600/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003601/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003602bool SROA::promoteAllocas(Function &F) {
3603 if (PromotableAllocas.empty())
3604 return false;
3605
3606 NumPromoted += PromotableAllocas.size();
3607
3608 if (DT && !ForceSSAUpdater) {
3609 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Hal Finkel60db0582014-09-07 18:57:58 +00003610 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003611 PromotableAllocas.clear();
3612 return true;
3613 }
3614
3615 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3616 SSAUpdater SSA;
3617 DIBuilder DIB(*F.getParent());
Chandler Carruth45b136f2013-08-11 01:03:18 +00003618 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003619
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003620 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003621 SmallVector<Instruction *, 8> Worklist;
3622 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003623 SmallVector<Instruction *, 32> DeadInsts;
3624
Chandler Carruth70b44c52012-09-15 11:43:14 +00003625 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3626 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003627 Insts.clear();
3628 Worklist.clear();
3629 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003630
Chandler Carruth45b136f2013-08-11 01:03:18 +00003631 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003632
Chandler Carruth45b136f2013-08-11 01:03:18 +00003633 while (!Worklist.empty()) {
3634 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003635
Chandler Carruth70b44c52012-09-15 11:43:14 +00003636 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3637 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3638 // leading to them) here. Eventually it should use them to optimize the
3639 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003640 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003641 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3642 II->getIntrinsicID() == Intrinsic::lifetime_end);
3643 II->eraseFromParent();
3644 continue;
3645 }
3646
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003647 // Push the loads and stores we find onto the list. SROA will already
3648 // have validated that all loads and stores are viable candidates for
3649 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003650 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003651 assert(LI->getType() == AI->getAllocatedType());
3652 Insts.push_back(LI);
3653 continue;
3654 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003655 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003656 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3657 Insts.push_back(SI);
3658 continue;
3659 }
3660
3661 // For everything else, we know that only no-op bitcasts and GEPs will
3662 // make it this far, just recurse through them and recall them for later
3663 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003664 DeadInsts.push_back(I);
3665 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003666 }
3667 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003668 while (!DeadInsts.empty())
3669 DeadInsts.pop_back_val()->eraseFromParent();
3670 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003671 }
3672
3673 PromotableAllocas.clear();
3674 return true;
3675}
3676
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003677bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003678 if (skipOptnoneFunction(F))
3679 return false;
3680
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003681 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3682 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003683 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3684 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003685 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3686 return false;
3687 }
Rafael Espindola93512512014-02-25 17:30:31 +00003688 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003689 DominatorTreeWrapperPass *DTWP =
3690 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003691 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +00003692 AT = &getAnalysis<AssumptionTracker>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003693
3694 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003695 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003696 I != E; ++I)
3697 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3698 Worklist.insert(AI);
3699
3700 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003701 // A set of deleted alloca instruction pointers which should be removed from
3702 // the list of promotable allocas.
3703 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3704
Chandler Carruthac8317f2012-10-04 12:33:50 +00003705 do {
3706 while (!Worklist.empty()) {
3707 Changed |= runOnAlloca(*Worklist.pop_back_val());
3708 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003709
Chandler Carruthac8317f2012-10-04 12:33:50 +00003710 // Remove the deleted allocas from various lists so that we don't try to
3711 // continue processing them.
3712 if (!DeletedAllocas.empty()) {
Chandler Carruthd031fe92014-03-03 19:28:52 +00003713 auto IsInSet = [&](AllocaInst *AI) {
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003714 return DeletedAllocas.count(AI);
3715 };
3716 Worklist.remove_if(IsInSet);
3717 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003718 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3719 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003720 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00003721 PromotableAllocas.end());
3722 DeletedAllocas.clear();
3723 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003724 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003725
Chandler Carruthac8317f2012-10-04 12:33:50 +00003726 Changed |= promoteAllocas(F);
3727
3728 Worklist = PostPromotionWorklist;
3729 PostPromotionWorklist.clear();
3730 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003731
3732 return Changed;
3733}
3734
3735void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel60db0582014-09-07 18:57:58 +00003736 AU.addRequired<AssumptionTracker>();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003737 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003738 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003739 AU.setPreservesCFG();
3740}