blob: cecd29b13410f2c1f8974a7bdf876f163f3f68a9 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth1b398ae2012-09-14 09:22:59 +000026#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000031#include "llvm/Analysis/AssumptionCache.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.
Chandler Carruth113dc642014-12-20 02:39:18 +000082static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
83 cl::Hidden);
Chandler Carruth70b44c52012-09-15 11:43:14 +000084
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.
Chandler Carruth113dc642014-12-20 02:39:18 +000092static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
93 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +000094
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>
Chandler Carruth113dc642014-12-20 02:39:18 +000099class IRBuilderPrefixedInserter
100 : public IRBuilderDefaultInserter<preserveNames> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000101 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 <>
Chandler Carruth113dc642014-12-20 02:39:18 +0000116class IRBuilderPrefixedInserter<false>
117 : public IRBuilderDefaultInserter<false> {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000118public:
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 Carruth113dc642014-12-20 02:39:18 +0000124typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
125 IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000126#else
Chandler Carruth113dc642014-12-20 02:39:18 +0000127typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
128 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 Carruth113dc642014-12-20 02:39:18 +0000174 if (beginOffset() < RHS.beginOffset())
175 return true;
176 if (beginOffset() > RHS.beginOffset())
177 return false;
178 if (isSplittable() != RHS.isSplittable())
179 return !isSplittable();
180 if (endOffset() > RHS.endOffset())
181 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000182 return false;
183 }
184
185 /// \brief Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000186 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000187 uint64_t RHSOffset) {
188 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000190 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000191 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000192 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000193 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000194
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000195 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000196 return isSplittable() == RHS.isSplittable() &&
197 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000198 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000199 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000200};
Chandler Carruthf0546402013-07-18 07:15:00 +0000201} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000202
203namespace llvm {
Chandler Carruthf0546402013-07-18 07:15:00 +0000204template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000205template <> struct isPodLike<Slice> { static const bool value = true; };
Chandler Carruthf74654d2013-03-18 08:36:46 +0000206}
207
208namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000209/// \brief Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000210///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211/// This class represents the slices of an alloca which are formed by its
212/// various uses. If a pointer escapes, we can't fully build a representation
213/// for the slices used and we reflect that in this structure. The uses are
214/// stored, sorted by increasing beginning offset and with unsplittable slices
215/// starting at a particular offset before splittable slices.
216class AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000217public:
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000218 /// \brief Construct the slices of a particular alloca.
219 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000220
221 /// \brief Test whether a pointer to the allocation escapes our analysis.
222 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000223 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000224 /// ignored.
225 bool isEscaped() const { return PointerEscapingInstr; }
226
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000227 /// \brief Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000228 /// @{
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000229 typedef SmallVectorImpl<Slice>::iterator iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000230 typedef iterator_range<iterator> range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000231 iterator begin() { return Slices.begin(); }
232 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000233
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000234 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
Chandler Carruthc659df92014-10-16 20:24:07 +0000235 typedef iterator_range<const_iterator> const_range;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000236 const_iterator begin() const { return Slices.begin(); }
237 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000238 /// @}
239
Chandler Carruth0715cba2015-01-01 11:54:38 +0000240 /// \brief Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000241 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000242
243 /// \brief Insert new slices for this alloca.
244 ///
245 /// This moves the slices into the alloca's slices collection, and re-sorts
246 /// everything so that the usual ordering properties of the alloca's slices
247 /// hold.
248 void insert(ArrayRef<Slice> NewSlices) {
249 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000250 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000251 auto SliceI = Slices.begin() + OldSize;
252 std::sort(SliceI, Slices.end());
253 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
254 }
255
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000256 // Forward declare an iterator to befriend it.
257 class partition_iterator;
258
259 /// \brief A partition of the slices.
260 ///
261 /// An ephemeral representation for a range of slices which can be viewed as
262 /// a partition of the alloca. This range represents a span of the alloca's
263 /// memory which cannot be split, and provides access to all of the slices
264 /// overlapping some part of the partition.
265 ///
266 /// Objects of this type are produced by traversing the alloca's slices, but
267 /// are only ephemeral and not persistent.
268 class Partition {
269 private:
270 friend class AllocaSlices;
271 friend class AllocaSlices::partition_iterator;
272
273 /// \brief The begining and ending offsets of the alloca for this partition.
274 uint64_t BeginOffset, EndOffset;
275
276 /// \brief The start end end iterators of this partition.
277 iterator SI, SJ;
278
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000279 /// \brief A collection of split slice tails overlapping the partition.
280 SmallVector<Slice *, 4> SplitTails;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000281
282 /// \brief Raw constructor builds an empty partition starting and ending at
283 /// the given iterator.
284 Partition(iterator SI) : SI(SI), SJ(SI) {}
285
286 public:
287 /// \brief The start offset of this partition.
288 ///
289 /// All of the contained slices start at or after this offset.
290 uint64_t beginOffset() const { return BeginOffset; }
291
292 /// \brief The end offset of this partition.
293 ///
294 /// All of the contained slices end at or before this offset.
295 uint64_t endOffset() const { return EndOffset; }
296
297 /// \brief The size of the partition.
298 ///
299 /// Note that this can never be zero.
300 uint64_t size() const {
301 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
302 return EndOffset - BeginOffset;
303 }
304
305 /// \brief Test whether this partition contains no slices, and merely spans
306 /// a region occupied by split slices.
307 bool empty() const { return SI == SJ; }
308
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000309 /// \name Iterate slices that start within the partition.
310 /// These may be splittable or unsplittable. They have a begin offset >= the
311 /// partition begin offset.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000312 /// @{
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000313 // FIXME: We should probably define a "concat_iterator" helper and use that
314 // to stitch together pointee_iterators over the split tails and the
315 // contiguous iterators of the partition. That would give a much nicer
316 // interface here. We could then additionally expose filtered iterators for
317 // split, unsplit, and unsplittable splices based on the usage patterns.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000318 iterator begin() const { return SI; }
319 iterator end() const { return SJ; }
320 /// @}
321
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000322 /// \brief Get the sequence of split slice tails.
323 ///
324 /// These tails are of slices which start before this partition but are
325 /// split and overlap into the partition. We accumulate these while forming
326 /// partitions.
327 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000328 };
329
330 /// \brief An iterator over partitions of the alloca's slices.
331 ///
332 /// This iterator implements the core algorithm for partitioning the alloca's
333 /// slices. It is a forward iterator as we don't support backtracking for
334 /// efficiency reasons, and re-use a single storage area to maintain the
335 /// current set of split slices.
336 ///
337 /// It is templated on the slice iterator type to use so that it can operate
338 /// with either const or non-const slice iterators.
339 class partition_iterator
340 : public iterator_facade_base<partition_iterator,
341 std::forward_iterator_tag, Partition> {
342 friend class AllocaSlices;
343
344 /// \brief Most of the state for walking the partitions is held in a class
345 /// with a nice interface for examining them.
346 Partition P;
347
348 /// \brief We need to keep the end of the slices to know when to stop.
349 AllocaSlices::iterator SE;
350
351 /// \brief We also need to keep track of the maximum split end offset seen.
352 /// FIXME: Do we really?
353 uint64_t MaxSplitSliceEndOffset;
354
355 /// \brief Sets the partition to be empty at given iterator, and sets the
356 /// end iterator.
357 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
358 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
359 // If not already at the end, advance our state to form the initial
360 // partition.
361 if (SI != SE)
362 advance();
363 }
364
365 /// \brief Advance the iterator to the next partition.
366 ///
367 /// Requires that the iterator not be at the end of the slices.
368 void advance() {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000369 assert((P.SI != SE || !P.SplitTails.empty()) &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000370 "Cannot advance past the end of the slices!");
371
372 // Clear out any split uses which have ended.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000373 if (!P.SplitTails.empty()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000374 if (P.EndOffset >= MaxSplitSliceEndOffset) {
375 // If we've finished all splits, this is easy.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000376 P.SplitTails.clear();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000377 MaxSplitSliceEndOffset = 0;
378 } else {
379 // Remove the uses which have ended in the prior partition. This
380 // cannot change the max split slice end because we just checked that
381 // the prior partition ended prior to that max.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000382 P.SplitTails.erase(
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000383 std::remove_if(
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000384 P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000385 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000386 P.SplitTails.end());
387 assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000388 [&](Slice *S) {
389 return S->endOffset() == MaxSplitSliceEndOffset;
390 }) &&
391 "Could not find the current max split slice offset!");
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000392 assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000393 [&](Slice *S) {
394 return S->endOffset() <= MaxSplitSliceEndOffset;
395 }) &&
396 "Max split slice end offset is not actually the max!");
397 }
398 }
399
400 // If P.SI is already at the end, then we've cleared the split tail and
401 // now have an end iterator.
402 if (P.SI == SE) {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000403 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000404 return;
405 }
406
407 // If we had a non-empty partition previously, set up the state for
408 // subsequent partitions.
409 if (P.SI != P.SJ) {
410 // Accumulate all the splittable slices which started in the old
411 // partition into the split list.
412 for (Slice &S : P)
413 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000414 P.SplitTails.push_back(&S);
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000415 MaxSplitSliceEndOffset =
416 std::max(S.endOffset(), MaxSplitSliceEndOffset);
417 }
418
419 // Start from the end of the previous partition.
420 P.SI = P.SJ;
421
422 // If P.SI is now at the end, we at most have a tail of split slices.
423 if (P.SI == SE) {
424 P.BeginOffset = P.EndOffset;
425 P.EndOffset = MaxSplitSliceEndOffset;
426 return;
427 }
428
429 // If the we have split slices and the next slice is after a gap and is
430 // not splittable immediately form an empty partition for the split
431 // slices up until the next slice begins.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000432 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000433 !P.SI->isSplittable()) {
434 P.BeginOffset = P.EndOffset;
435 P.EndOffset = P.SI->beginOffset();
436 return;
437 }
438 }
439
440 // OK, we need to consume new slices. Set the end offset based on the
441 // current slice, and step SJ past it. The beginning offset of the
442 // parttion is the beginning offset of the next slice unless we have
443 // pre-existing split slices that are continuing, in which case we begin
444 // at the prior end offset.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000445 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000446 P.EndOffset = P.SI->endOffset();
447 ++P.SJ;
448
449 // There are two strategies to form a partition based on whether the
450 // partition starts with an unsplittable slice or a splittable slice.
451 if (!P.SI->isSplittable()) {
452 // When we're forming an unsplittable region, it must always start at
453 // the first slice and will extend through its end.
454 assert(P.BeginOffset == P.SI->beginOffset());
455
456 // Form a partition including all of the overlapping slices with this
457 // unsplittable slice.
458 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
459 if (!P.SJ->isSplittable())
460 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
461 ++P.SJ;
462 }
463
464 // We have a partition across a set of overlapping unsplittable
465 // partitions.
466 return;
467 }
468
469 // If we're starting with a splittable slice, then we need to form
470 // a synthetic partition spanning it and any other overlapping splittable
471 // splices.
472 assert(P.SI->isSplittable() && "Forming a splittable partition!");
473
474 // Collect all of the overlapping splittable slices.
475 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
476 P.SJ->isSplittable()) {
477 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
478 ++P.SJ;
479 }
480
481 // Back upiP.EndOffset if we ended the span early when encountering an
482 // unsplittable slice. This synthesizes the early end offset of
483 // a partition spanning only splittable slices.
484 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
485 assert(!P.SJ->isSplittable());
486 P.EndOffset = P.SJ->beginOffset();
487 }
488 }
489
490 public:
491 bool operator==(const partition_iterator &RHS) const {
492 assert(SE == RHS.SE &&
493 "End iterators don't match between compared partition iterators!");
494
495 // The observed positions of partitions is marked by the P.SI iterator and
496 // the emptyness of the split slices. The latter is only relevant when
497 // P.SI == SE, as the end iterator will additionally have an empty split
498 // slices list, but the prior may have the same P.SI and a tail of split
499 // slices.
500 if (P.SI == RHS.P.SI &&
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000501 P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000502 assert(P.SJ == RHS.P.SJ &&
503 "Same set of slices formed two different sized partitions!");
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000504 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000505 "Same slice position with differently sized non-empty split "
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000506 "slice tails!");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000507 return true;
508 }
509 return false;
510 }
511
512 partition_iterator &operator++() {
513 advance();
514 return *this;
515 }
516
517 Partition &operator*() { return P; }
518 };
519
520 /// \brief A forward range over the partitions of the alloca's slices.
521 ///
522 /// This accesses an iterator range over the partitions of the alloca's
523 /// slices. It computes these partitions on the fly based on the overlapping
524 /// offsets of the slices and the ability to split them. It will visit "empty"
525 /// partitions to cover regions of the alloca only accessed via split
526 /// slices.
527 iterator_range<partition_iterator> partitions() {
528 return make_range(partition_iterator(begin(), end()),
529 partition_iterator(end(), end()));
530 }
531
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000532 /// \brief Access the dead users for this alloca.
533 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000534
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000535 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000536 ///
537 /// These are operands which have cannot actually be used to refer to the
538 /// alloca as they are outside its range and the user doesn't correct for
539 /// that. These mostly consist of PHI node inputs and the like which we just
540 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000541 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000542
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000543#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000544 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000545 void printSlice(raw_ostream &OS, const_iterator I,
546 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000547 void printUse(raw_ostream &OS, const_iterator I,
548 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000549 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000550 void dump(const_iterator I) const;
551 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000552#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000553
554private:
555 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000556 class SliceBuilder;
557 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000558
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000559#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000560 /// \brief Handle to alloca instruction to simplify method interfaces.
561 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000562#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000563
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000564 /// \brief The instruction responsible for this alloca not having a known set
565 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000566 ///
567 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000568 /// store a pointer to that here and abort trying to form slices of the
569 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000570 Instruction *PointerEscapingInstr;
571
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000572 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000573 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000574 /// We store a vector of the slices formed by uses of the alloca here. This
575 /// vector is sorted by increasing begin offset, and then the unsplittable
576 /// slices before the splittable ones. See the Slice inner class for more
577 /// details.
578 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000579
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000580 /// \brief Instructions which will become dead if we rewrite the alloca.
581 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000582 /// Note that these are not separated by slice. This is because we expect an
583 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
584 /// all these instructions can simply be removed and replaced with undef as
585 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000586 SmallVector<Instruction *, 8> DeadUsers;
587
588 /// \brief Operands which will become dead if we rewrite the alloca.
589 ///
590 /// These are operands that in their particular use can be replaced with
591 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
592 /// to PHI nodes and the like. They aren't entirely dead (there might be
593 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
594 /// want to swap this particular input for undef to simplify the use lists of
595 /// the alloca.
596 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000597};
598}
599
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000600static Value *foldSelectInst(SelectInst &SI) {
601 // If the condition being selected on is a constant or the same value is
602 // being selected between, fold the select. Yes this does (rarely) happen
603 // early on.
604 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000605 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000606 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000607 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000608
Craig Topperf40110f2014-04-25 05:29:35 +0000609 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000610}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000611
Jingyue Wuec33fa92014-08-22 22:45:57 +0000612/// \brief A helper that folds a PHI node or a select.
613static Value *foldPHINodeOrSelectInst(Instruction &I) {
614 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
615 // If PN merges together the same value, return that value.
616 return PN->hasConstantValue();
617 }
618 return foldSelectInst(cast<SelectInst>(I));
619}
620
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000621/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000622///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000623/// This class builds a set of alloca slices by recursively visiting the uses
624/// of an alloca and making a slice for each load and store at each offset.
625class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
626 friend class PtrUseVisitor<SliceBuilder>;
627 friend class InstVisitor<SliceBuilder>;
628 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629
630 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000631 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000632
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000633 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000634 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
635
636 /// \brief Set to de-duplicate dead instructions found in the use walk.
637 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000638
639public:
Chandler Carruth83934062014-10-16 21:11:55 +0000640 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000641 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000642 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000643
644private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000645 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000646 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000647 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000648 }
649
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000650 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000651 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000652 // Completely skip uses which have a zero size or start either before or
653 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000654 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000655 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000656 << " which has zero size or starts outside of the "
657 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000658 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000659 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000660 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661 }
662
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000663 uint64_t BeginOffset = Offset.getZExtValue();
664 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000665
666 // Clamp the end offset to the end of the allocation. Note that this is
667 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000668 // This may appear superficially to be something we could ignore entirely,
669 // but that is not so! There may be widened loads or PHI-node uses where
670 // some instructions are dead but not others. We can't completely ignore
671 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000672 assert(AllocSize >= BeginOffset); // Established above.
673 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000674 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
675 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000676 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000677 << " use: " << I << "\n");
678 EndOffset = AllocSize;
679 }
680
Chandler Carruth83934062014-10-16 21:11:55 +0000681 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000682 }
683
684 void visitBitCastInst(BitCastInst &BC) {
685 if (BC.use_empty())
686 return markAsDead(BC);
687
688 return Base::visitBitCastInst(BC);
689 }
690
691 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
692 if (GEPI.use_empty())
693 return markAsDead(GEPI);
694
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000695 if (SROAStrictInbounds && GEPI.isInBounds()) {
696 // FIXME: This is a manually un-factored variant of the basic code inside
697 // of GEPs with checking of the inbounds invariant specified in the
698 // langref in a very strict sense. If we ever want to enable
699 // SROAStrictInbounds, this code should be factored cleanly into
700 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
701 // by writing out the code here where we have tho underlying allocation
702 // size readily available.
703 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000705 for (gep_type_iterator GTI = gep_type_begin(GEPI),
706 GTE = gep_type_end(GEPI);
707 GTI != GTE; ++GTI) {
708 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
709 if (!OpC)
710 break;
711
712 // Handle a struct index, which adds its field offset to the pointer.
713 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
714 unsigned ElementIdx = OpC->getZExtValue();
715 const StructLayout *SL = DL.getStructLayout(STy);
716 GEPOffset +=
717 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
718 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000719 // For array or vector indices, scale the index by the size of the
720 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000721 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
722 GEPOffset += Index * APInt(Offset.getBitWidth(),
723 DL.getTypeAllocSize(GTI.getIndexedType()));
724 }
725
726 // If this index has computed an intermediate pointer which is not
727 // inbounds, then the result of the GEP is a poison value and we can
728 // delete it and all uses.
729 if (GEPOffset.ugt(AllocSize))
730 return markAsDead(GEPI);
731 }
732 }
733
Chandler Carruthf0546402013-07-18 07:15:00 +0000734 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000735 }
736
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000737 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000738 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000739 // We allow splitting of non-volatile loads and stores where the type is an
740 // integer type. These may be used to implement 'memcpy' or other "transfer
741 // of bits" patterns.
742 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000743
744 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000745 }
746
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000747 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000748 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
749 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000750
751 if (!IsOffsetKnown)
752 return PI.setAborted(&LI);
753
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000754 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000755 uint64_t Size = DL.getTypeStoreSize(LI.getType());
756 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000757 }
758
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000759 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000760 Value *ValOp = SI.getValueOperand();
761 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000762 return PI.setEscapedAndAborted(&SI);
763 if (!IsOffsetKnown)
764 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000765
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000766 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000767 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
768
769 // If this memory access can be shown to *statically* extend outside the
770 // bounds of of the allocation, it's behavior is undefined, so simply
771 // ignore it. Note that this is more strict than the generic clamping
772 // behavior of insertUse. We also try to handle cases which might run the
773 // risk of overflow.
774 // FIXME: We should instead consider the pointer to have escaped if this
775 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000776 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000777 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
778 << " which extends past the end of the " << AllocSize
779 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000780 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000781 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000782 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000783 }
784
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000785 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
786 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000787 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000788 }
789
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000790 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000791 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000792 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000793 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000794 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000795 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000796 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000797
798 if (!IsOffsetKnown)
799 return PI.setAborted(&II);
800
Chandler Carruth113dc642014-12-20 02:39:18 +0000801 insertUse(II, Offset, Length ? Length->getLimitedValue()
802 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000803 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000804 }
805
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000806 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000807 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000808 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000809 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000810 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000811
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000812 // Because we can visit these intrinsics twice, also check to see if the
813 // first time marked this instruction as dead. If so, skip it.
814 if (VisitedDeadInsts.count(&II))
815 return;
816
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000817 if (!IsOffsetKnown)
818 return PI.setAborted(&II);
819
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000820 // This side of the transfer is completely out-of-bounds, and so we can
821 // nuke the entire transfer. However, we also need to nuke the other side
822 // if already added to our partitions.
823 // FIXME: Yet another place we really should bypass this when
824 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000825 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000826 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
827 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000828 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000829 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000830 return markAsDead(II);
831 }
832
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000833 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000834 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000835
Chandler Carruthf0546402013-07-18 07:15:00 +0000836 // Check for the special case where the same exact value is used for both
837 // source and dest.
838 if (*U == II.getRawDest() && *U == II.getRawSource()) {
839 // For non-volatile transfers this is a no-op.
840 if (!II.isVolatile())
841 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000842
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000843 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000844 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000845
Chandler Carruthf0546402013-07-18 07:15:00 +0000846 // If we have seen both source and destination for a mem transfer, then
847 // they both point to the same alloca.
848 bool Inserted;
849 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000850 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000851 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000852 unsigned PrevIdx = MTPI->second;
853 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000854 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000855
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000856 // Check if the begin offsets match and this is a non-volatile transfer.
857 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000858 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
859 PrevP.kill();
860 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000861 }
862
863 // Otherwise we have an offset transfer within the same alloca. We can't
864 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000865 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000866 }
867
Chandler Carruthe3899f22013-07-15 17:36:21 +0000868 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000869 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000870
Chandler Carruthf0546402013-07-18 07:15:00 +0000871 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000872 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000873 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000874 }
875
876 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000877 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000878 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000879 void visitIntrinsicInst(IntrinsicInst &II) {
880 if (!IsOffsetKnown)
881 return PI.setAborted(&II);
882
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000883 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
884 II.getIntrinsicID() == Intrinsic::lifetime_end) {
885 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000886 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
887 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000888 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000889 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000890 }
891
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000892 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000893 }
894
895 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
896 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000897 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000898 // are considered unsplittable and the size is the maximum loaded or stored
899 // size.
900 SmallPtrSet<Instruction *, 4> Visited;
901 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
902 Visited.insert(Root);
903 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000904 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000905 // If there are no loads or stores, the access is dead. We mark that as
906 // a size zero access.
907 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000908 do {
909 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000910 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000911
912 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000913 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000914 continue;
915 }
916 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
917 Value *Op = SI->getOperand(0);
918 if (Op == UsedI)
919 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000920 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000921 continue;
922 }
923
924 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
925 if (!GEP->hasAllZeroIndices())
926 return GEP;
927 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
928 !isa<SelectInst>(I)) {
929 return I;
930 }
931
Chandler Carruthcdf47882014-03-09 03:16:01 +0000932 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000933 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000934 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000935 } while (!Uses.empty());
936
Craig Topperf40110f2014-04-25 05:29:35 +0000937 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000938 }
939
Jingyue Wuec33fa92014-08-22 22:45:57 +0000940 void visitPHINodeOrSelectInst(Instruction &I) {
941 assert(isa<PHINode>(I) || isa<SelectInst>(I));
942 if (I.use_empty())
943 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000944
Jingyue Wuec33fa92014-08-22 22:45:57 +0000945 // TODO: We could use SimplifyInstruction here to fold PHINodes and
946 // SelectInsts. However, doing so requires to change the current
947 // dead-operand-tracking mechanism. For instance, suppose neither loading
948 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
949 // trap either. However, if we simply replace %U with undef using the
950 // current dead-operand-tracking mechanism, "load (select undef, undef,
951 // %other)" may trap because the select may return the first operand
952 // "undef".
953 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000954 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000955 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000956 // through the PHI/select as if we had RAUW'ed it.
957 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000958 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000959 // Otherwise the operand to the PHI/select is dead, and we can replace
960 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000961 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000962
963 return;
964 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000965
Chandler Carruthf0546402013-07-18 07:15:00 +0000966 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000967 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000968
Chandler Carruthf0546402013-07-18 07:15:00 +0000969 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000970 uint64_t &Size = PHIOrSelectSizes[&I];
971 if (!Size) {
972 // This is a new PHI/Select, check for an unsafe use of it.
973 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000974 return PI.setAborted(UnsafeI);
975 }
976
977 // For PHI and select operands outside the alloca, we can't nuke the entire
978 // phi or select -- the other side might still be relevant, so we special
979 // case them here and use a separate structure to track the operands
980 // themselves which should be replaced with undef.
981 // FIXME: This should instead be escaped in the event we're instrumenting
982 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000983 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000984 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000985 return;
986 }
987
Jingyue Wuec33fa92014-08-22 22:45:57 +0000988 insertUse(I, Offset, Size);
989 }
990
Chandler Carruth113dc642014-12-20 02:39:18 +0000991 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000992
Chandler Carruth113dc642014-12-20 02:39:18 +0000993 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000994
Chandler Carruthf0546402013-07-18 07:15:00 +0000995 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000996 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000997};
998
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000999AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001000 :
1001#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1002 AI(AI),
1003#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001004 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001005 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001006 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001007 if (PtrI.isEscaped() || PtrI.isAborted()) {
1008 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001009 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001010 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1011 : PtrI.getAbortingInst();
1012 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001013 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001014 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001015
Benjamin Kramer08e50702013-07-20 08:38:34 +00001016 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
Chandler Carruth68ea4152014-12-18 05:19:47 +00001017 [](const Slice &S) {
1018 return S.isDead();
1019 }),
Benjamin Kramer08e50702013-07-20 08:38:34 +00001020 Slices.end());
1021
Chandler Carruth83cee772014-02-25 03:59:29 +00001022#if __cplusplus >= 201103L && !defined(NDEBUG)
1023 if (SROARandomShuffleSlices) {
1024 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1025 std::shuffle(Slices.begin(), Slices.end(), MT);
1026 }
1027#endif
1028
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001029 // Sort the uses. This arranges for the offsets to be in ascending order,
1030 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001031 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001032}
1033
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001034#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1035
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001036void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1037 StringRef Indent) const {
1038 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001039 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001040 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001041}
1042
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001043void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1044 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001045 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001046 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001047 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001048}
1049
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001050void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1051 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001052 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001053}
1054
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001055void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001056 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001057 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001058 << " A pointer to this alloca escaped by:\n"
1059 << " " << *PointerEscapingInstr << "\n";
1060 return;
1061 }
1062
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001063 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001064 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001065 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001066}
1067
Alp Tokerf929e092014-01-04 22:47:48 +00001068LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1069 print(dbgs(), I);
1070}
1071LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001072
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001073#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1074
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001075namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001076/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1077///
1078/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1079/// the loads and stores of an alloca instruction, as well as updating its
1080/// debug information. This is used when a domtree is unavailable and thus
1081/// mem2reg in its full form can't be used to handle promotion of allocas to
1082/// scalar values.
1083class AllocaPromoter : public LoadAndStorePromoter {
1084 AllocaInst &AI;
1085 DIBuilder &DIB;
1086
1087 SmallVector<DbgDeclareInst *, 4> DDIs;
1088 SmallVector<DbgValueInst *, 4> DVIs;
1089
1090public:
Chandler Carruth45b136f2013-08-11 01:03:18 +00001091 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +00001092 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +00001093 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +00001094
Chandler Carruth113dc642014-12-20 02:39:18 +00001095 void run(const SmallVectorImpl<Instruction *> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00001096 // Retain the debug information attached to the alloca for use when
1097 // rewriting loads and stores.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001098 if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
1099 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
1100 for (User *U : DebugNode->users())
1101 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1102 DDIs.push_back(DDI);
1103 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1104 DVIs.push_back(DVI);
1105 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00001106 }
1107
1108 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00001109
1110 // While we have the debug information, clear it off of the alloca. The
1111 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +00001112 while (!DDIs.empty())
1113 DDIs.pop_back_val()->eraseFromParent();
1114 while (!DVIs.empty())
1115 DVIs.pop_back_val()->eraseFromParent();
1116 }
1117
Chandler Carruth113dc642014-12-20 02:39:18 +00001118 bool
1119 isInstInList(Instruction *I,
1120 const SmallVectorImpl<Instruction *> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +00001121 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001122 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +00001123 Ptr = LI->getOperand(0);
1124 else
1125 Ptr = cast<StoreInst>(I)->getPointerOperand();
1126
1127 // Only used to detect cycles, which will be rare and quickly found as
1128 // we're walking up a chain of defs rather than down through uses.
1129 SmallPtrSet<Value *, 4> Visited;
1130
1131 do {
1132 if (Ptr == &AI)
1133 return true;
1134
1135 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
1136 Ptr = BCI->getOperand(0);
1137 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1138 Ptr = GEPI->getPointerOperand();
1139 else
1140 return false;
1141
David Blaikie70573dc2014-11-19 07:49:26 +00001142 } while (Visited.insert(Ptr).second);
Chandler Carruthc17283b2013-08-11 01:56:15 +00001143
1144 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001145 }
1146
Craig Topper3e4c6972014-03-05 09:10:37 +00001147 void updateDebugInfo(Instruction *Inst) const override {
Chandler Carruth61747042014-10-16 21:05:14 +00001148 for (DbgDeclareInst *DDI : DDIs)
Chandler Carruth70b44c52012-09-15 11:43:14 +00001149 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1150 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1151 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1152 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Chandler Carruth61747042014-10-16 21:05:14 +00001153 for (DbgValueInst *DVI : DVIs) {
Craig Topperf40110f2014-04-25 05:29:35 +00001154 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001155 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1156 // If an argument is zero extended then use argument directly. The ZExt
1157 // may be zapped by an optimization pass in future.
1158 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1159 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001160 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +00001161 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1162 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001163 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001164 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001165 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001166 } else {
1167 continue;
1168 }
1169 Instruction *DbgVal =
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001170 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1171 DIExpression(DVI->getExpression()), Inst);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001172 DbgVal->setDebugLoc(DVI->getDebugLoc());
1173 }
1174 }
1175};
1176} // end anon namespace
1177
Chandler Carruth70b44c52012-09-15 11:43:14 +00001178namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001179/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1180///
1181/// This pass takes allocations which can be completely analyzed (that is, they
1182/// don't escape) and tries to turn them into scalar SSA values. There are
1183/// a few steps to this process.
1184///
1185/// 1) It takes allocations of aggregates and analyzes the ways in which they
1186/// are used to try to split them into smaller allocations, ideally of
1187/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001188/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001189/// 2) It will transform accesses into forms which are suitable for SSA value
1190/// promotion. This can be replacing a memset with a scalar store of an
1191/// integer value, or it can involve speculating operations on a PHI or
1192/// select to be a PHI or select of the results.
1193/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1194/// onto insert and extract operations on a vector value, and convert them to
1195/// this form. By doing so, it will enable promotion of vector aggregates to
1196/// SSA vector values.
1197class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001198 const bool RequiresDomTree;
1199
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001200 LLVMContext *C;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001201 DominatorTree *DT;
Chandler Carruth66b31302015-01-04 12:03:27 +00001202 AssumptionCache *AC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001203
1204 /// \brief Worklist of alloca instructions to simplify.
1205 ///
1206 /// Each alloca in the function is added to this. Each new alloca formed gets
1207 /// added to it as well to recursively simplify unless that alloca can be
1208 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1209 /// the one being actively rewritten, we add it back onto the list if not
1210 /// already present to ensure it is re-visited.
Chandler Carruth113dc642014-12-20 02:39:18 +00001211 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001212
1213 /// \brief A collection of instructions to delete.
1214 /// We try to batch deletions to simplify code and make things a bit more
1215 /// efficient.
Chandler Carruth113dc642014-12-20 02:39:18 +00001216 SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001217
Chandler Carruthac8317f2012-10-04 12:33:50 +00001218 /// \brief Post-promotion worklist.
1219 ///
1220 /// Sometimes we discover an alloca which has a high probability of becoming
1221 /// viable for SROA after a round of promotion takes place. In those cases,
1222 /// the alloca is enqueued here for re-processing.
1223 ///
1224 /// Note that we have to be very careful to clear allocas out of this list in
1225 /// the event they are deleted.
Chandler Carruth113dc642014-12-20 02:39:18 +00001226 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
Chandler Carruthac8317f2012-10-04 12:33:50 +00001227
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001228 /// \brief A collection of alloca instructions we can directly promote.
1229 std::vector<AllocaInst *> PromotableAllocas;
1230
Chandler Carruthf0546402013-07-18 07:15:00 +00001231 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1232 ///
1233 /// All of these PHIs have been checked for the safety of speculation and by
1234 /// being speculated will allow promoting allocas currently in the promotable
1235 /// queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001236 SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
Chandler Carruthf0546402013-07-18 07:15:00 +00001237
1238 /// \brief A worklist of select instructions to speculate prior to promoting
1239 /// allocas.
1240 ///
1241 /// All of these select instructions have been checked for the safety of
1242 /// speculation and by being speculated will allow promoting allocas
1243 /// currently in the promotable queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001244 SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
Chandler Carruthf0546402013-07-18 07:15:00 +00001245
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001246public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001247 SROA(bool RequiresDomTree = true)
Chandler Carruth113dc642014-12-20 02:39:18 +00001248 : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001249 DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001250 initializeSROAPass(*PassRegistry::getPassRegistry());
1251 }
Craig Topper3e4c6972014-03-05 09:10:37 +00001252 bool runOnFunction(Function &F) override;
1253 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001254
Craig Topper3e4c6972014-03-05 09:10:37 +00001255 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001256 static char ID;
1257
1258private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001259 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001260 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001261
Chandler Carruth0715cba2015-01-01 11:54:38 +00001262 bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
Adrian Prantl565cc182015-01-20 19:42:22 +00001263 AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
1264 AllocaSlices::Partition &P);
Chandler Carruth83934062014-10-16 21:11:55 +00001265 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001266 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00001267 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +00001268 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001269 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001270};
1271}
1272
1273char SROA::ID = 0;
1274
Chandler Carruth70b44c52012-09-15 11:43:14 +00001275FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1276 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001277}
1278
Chandler Carruth113dc642014-12-20 02:39:18 +00001279INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1280 false)
Chandler Carruth66b31302015-01-04 12:03:27 +00001281INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +00001282INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth113dc642014-12-20 02:39:18 +00001283INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1284 false)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001285
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001286/// Walk the range of a partitioning looking for a common type to cover this
1287/// sequence of slices.
1288static Type *findCommonType(AllocaSlices::const_iterator B,
1289 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001290 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001291 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001292 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001293 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001294
1295 // Note that we need to look at *every* alloca slice's Use to ensure we
1296 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001297 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001298 Use *U = I->getUse();
1299 if (isa<IntrinsicInst>(*U->getUser()))
1300 continue;
1301 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1302 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001303
Craig Topperf40110f2014-04-25 05:29:35 +00001304 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001305 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001306 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001307 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001308 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001309 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001310
Chandler Carruth4de31542014-01-21 23:16:05 +00001311 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001312 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001313 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001314 // entity causing the split. Also skip if the type is not a byte width
1315 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001316 if (UserITy->getBitWidth() % 8 != 0 ||
1317 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001318 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001319
Chandler Carruth4de31542014-01-21 23:16:05 +00001320 // Track the largest bitwidth integer type used in this way in case there
1321 // is no common type.
1322 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1323 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001324 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001325
1326 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1327 // depend on types skipped above.
1328 if (!UserTy || (Ty && Ty != UserTy))
1329 TyIsCommon = false; // Give up on anything but an iN type.
1330 else
1331 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001332 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001333
1334 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001335}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001336
Chandler Carruthf0546402013-07-18 07:15:00 +00001337/// PHI instructions that use an alloca and are subsequently loaded can be
1338/// rewritten to load both input pointers in the pred blocks and then PHI the
1339/// results, allowing the load of the alloca to be promoted.
1340/// From this:
1341/// %P2 = phi [i32* %Alloca, i32* %Other]
1342/// %V = load i32* %P2
1343/// to:
1344/// %V1 = load i32* %Alloca -> will be mem2reg'd
1345/// ...
1346/// %V2 = load i32* %Other
1347/// ...
1348/// %V = phi [i32 %V1, i32 %V2]
1349///
1350/// We can do this to a select if its only uses are loads and if the operands
1351/// to the select can be loaded unconditionally.
1352///
1353/// FIXME: This should be hoisted into a generic utility, likely in
1354/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001355static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001356 // For now, we can only do this promotion if the load is in the same block
1357 // as the PHI, and if there are no stores between the phi and load.
1358 // TODO: Allow recursive phi users.
1359 // TODO: Allow stores.
1360 BasicBlock *BB = PN.getParent();
1361 unsigned MaxAlign = 0;
1362 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001363 for (User *U : PN.users()) {
1364 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001365 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001366 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001367
Chandler Carruthf0546402013-07-18 07:15:00 +00001368 // For now we only allow loads in the same block as the PHI. This is
1369 // a common case that happens when instcombine merges two loads through
1370 // a PHI.
1371 if (LI->getParent() != BB)
1372 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001373
Chandler Carruthf0546402013-07-18 07:15:00 +00001374 // Ensure that there are no instructions between the PHI and the load that
1375 // could store.
1376 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1377 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001378 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001379
Chandler Carruthf0546402013-07-18 07:15:00 +00001380 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1381 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001382 }
1383
Chandler Carruthf0546402013-07-18 07:15:00 +00001384 if (!HaveLoad)
1385 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001386
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001387 const DataLayout &DL = PN.getModule()->getDataLayout();
1388
Chandler Carruthf0546402013-07-18 07:15:00 +00001389 // We can only transform this if it is safe to push the loads into the
1390 // predecessor blocks. The only thing to watch out for is that we can't put
1391 // a possibly trapping load in the predecessor if it is a critical edge.
1392 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1393 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1394 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001395
Chandler Carruthf0546402013-07-18 07:15:00 +00001396 // If the value is produced by the terminator of the predecessor (an
1397 // invoke) or it has side-effects, there is no valid place to put a load
1398 // in the predecessor.
1399 if (TI == InVal || TI->mayHaveSideEffects())
1400 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001401
Chandler Carruthf0546402013-07-18 07:15:00 +00001402 // If the predecessor has a single successor, then the edge isn't
1403 // critical.
1404 if (TI->getNumSuccessors() == 1)
1405 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001406
Chandler Carruthf0546402013-07-18 07:15:00 +00001407 // If this pointer is always safe to load, or if we can prove that there
1408 // is already a load in the block, then we can move the load to the pred
1409 // block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001410 if (InVal->isDereferenceablePointer(DL) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001411 isSafeToLoadUnconditionally(InVal, TI, MaxAlign))
Chandler Carruthf0546402013-07-18 07:15:00 +00001412 continue;
1413
1414 return false;
1415 }
1416
1417 return true;
1418}
1419
1420static void speculatePHINodeLoads(PHINode &PN) {
1421 DEBUG(dbgs() << " original: " << PN << "\n");
1422
1423 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1424 IRBuilderTy PHIBuilder(&PN);
1425 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1426 PN.getName() + ".sroa.speculated");
1427
Hal Finkelcc39b672014-07-24 12:16:19 +00001428 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001429 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001430 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001431
1432 AAMDNodes AATags;
1433 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001434 unsigned Align = SomeLoad->getAlignment();
1435
1436 // Rewrite all loads of the PN to use the new PHI.
1437 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001438 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001439 LI->replaceAllUsesWith(NewPN);
1440 LI->eraseFromParent();
1441 }
1442
1443 // Inject loads into all of the pred blocks.
1444 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1445 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1446 TerminatorInst *TI = Pred->getTerminator();
1447 Value *InVal = PN.getIncomingValue(Idx);
1448 IRBuilderTy PredBuilder(TI);
1449
1450 LoadInst *Load = PredBuilder.CreateLoad(
1451 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1452 ++NumLoadsSpeculated;
1453 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001454 if (AATags)
1455 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001456 NewPN->addIncoming(Load, Pred);
1457 }
1458
1459 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1460 PN.eraseFromParent();
1461}
1462
1463/// Select instructions that use an alloca and are subsequently loaded can be
1464/// rewritten to load both input pointers and then select between the result,
1465/// allowing the load of the alloca to be promoted.
1466/// From this:
1467/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1468/// %V = load i32* %P2
1469/// to:
1470/// %V1 = load i32* %Alloca -> will be mem2reg'd
1471/// %V2 = load i32* %Other
1472/// %V = select i1 %cond, i32 %V1, i32 %V2
1473///
1474/// We can do this to a select if its only uses are loads and if the operand
1475/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001476static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001477 Value *TValue = SI.getTrueValue();
1478 Value *FValue = SI.getFalseValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001479 const DataLayout &DL = SI.getModule()->getDataLayout();
Hal Finkel2e42c342014-07-10 05:27:53 +00001480 bool TDerefable = TValue->isDereferenceablePointer(DL);
1481 bool FDerefable = FValue->isDereferenceablePointer(DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001482
Chandler Carruthcdf47882014-03-09 03:16:01 +00001483 for (User *U : SI.users()) {
1484 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001485 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001486 return false;
1487
1488 // Both operands to the select need to be dereferencable, either
1489 // absolutely (e.g. allocas) or at this point because we can see other
1490 // accesses to it.
1491 if (!TDerefable &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001492 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001493 return false;
1494 if (!FDerefable &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001495 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001496 return false;
1497 }
1498
1499 return true;
1500}
1501
1502static void speculateSelectInstLoads(SelectInst &SI) {
1503 DEBUG(dbgs() << " original: " << SI << "\n");
1504
1505 IRBuilderTy IRB(&SI);
1506 Value *TV = SI.getTrueValue();
1507 Value *FV = SI.getFalseValue();
1508 // Replace the loads of the select with a select of two loads.
1509 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001510 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001511 assert(LI->isSimple() && "We only speculate simple loads");
1512
1513 IRB.SetInsertPoint(LI);
1514 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001515 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001516 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001517 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001518 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001519
Hal Finkelcc39b672014-07-24 12:16:19 +00001520 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001521 TL->setAlignment(LI->getAlignment());
1522 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001523
1524 AAMDNodes Tags;
1525 LI->getAAMetadata(Tags);
1526 if (Tags) {
1527 TL->setAAMetadata(Tags);
1528 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001529 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001530
1531 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1532 LI->getName() + ".sroa.speculated");
1533
1534 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1535 LI->replaceAllUsesWith(V);
1536 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001537 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001538 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001539}
1540
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001541/// \brief Build a GEP out of a base pointer and indices.
1542///
1543/// This will return the BasePtr if that is valid, or build a new GEP
1544/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001545static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001546 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001547 if (Indices.empty())
1548 return BasePtr;
1549
1550 // A single zero index is a no-op, so check for this and avoid building a GEP
1551 // in that case.
1552 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1553 return BasePtr;
1554
David Blaikieaa41cd52015-04-03 21:33:42 +00001555 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1556 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001557}
1558
1559/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1560/// TargetTy without changing the offset of the pointer.
1561///
1562/// This routine assumes we've already established a properly offset GEP with
1563/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1564/// zero-indices down through type layers until we find one the same as
1565/// TargetTy. If we can't find one with the same type, we at least try to use
1566/// one with the same size. If none of that works, we just produce the GEP as
1567/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001568static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001569 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001570 SmallVectorImpl<Value *> &Indices,
1571 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001572 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001573 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001574
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001575 // Pointer size to use for the indices.
1576 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1577
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001578 // See if we can descend into a struct and locate a field with the correct
1579 // type.
1580 unsigned NumLayers = 0;
1581 Type *ElementTy = Ty;
1582 do {
1583 if (ElementTy->isPointerTy())
1584 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001585
1586 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1587 ElementTy = ArrayTy->getElementType();
1588 Indices.push_back(IRB.getIntN(PtrSize, 0));
1589 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1590 ElementTy = VectorTy->getElementType();
1591 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001592 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001593 if (STy->element_begin() == STy->element_end())
1594 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001595 ElementTy = *STy->element_begin();
1596 Indices.push_back(IRB.getInt32(0));
1597 } else {
1598 break;
1599 }
1600 ++NumLayers;
1601 } while (ElementTy != TargetTy);
1602 if (ElementTy != TargetTy)
1603 Indices.erase(Indices.end() - NumLayers, Indices.end());
1604
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001605 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001606}
1607
1608/// \brief Recursively compute indices for a natural GEP.
1609///
1610/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1611/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001612static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001613 Value *Ptr, Type *Ty, APInt &Offset,
1614 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001615 SmallVectorImpl<Value *> &Indices,
1616 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001617 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001618 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1619 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001620
1621 // We can't recurse through pointer types.
1622 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001623 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001624
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001625 // We try to analyze GEPs over vectors here, but note that these GEPs are
1626 // extremely poorly defined currently. The long-term goal is to remove GEPing
1627 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001628 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001629 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001630 if (ElementSizeInBits % 8 != 0) {
1631 // GEPs over non-multiple of 8 size vector elements are invalid.
1632 return nullptr;
1633 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001634 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001635 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001636 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001637 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001638 Offset -= NumSkippedElements * ElementSize;
1639 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001640 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001641 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001642 }
1643
1644 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1645 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001646 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001647 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001648 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001649 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001650
1651 Offset -= NumSkippedElements * ElementSize;
1652 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001653 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001654 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001655 }
1656
1657 StructType *STy = dyn_cast<StructType>(Ty);
1658 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001659 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001660
Chandler Carruth90a735d2013-07-19 07:21:28 +00001661 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001662 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001663 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001664 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001665 unsigned Index = SL->getElementContainingOffset(StructOffset);
1666 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1667 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001668 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001669 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001670
1671 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001672 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001673 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001674}
1675
1676/// \brief Get a natural GEP from a base pointer to a particular offset and
1677/// resulting in a particular type.
1678///
1679/// The goal is to produce a "natural" looking GEP that works with the existing
1680/// composite types to arrive at the appropriate offset and element type for
1681/// a pointer. TargetTy is the element type the returned GEP should point-to if
1682/// possible. We recurse by decreasing Offset, adding the appropriate index to
1683/// Indices, and setting Ty to the result subtype.
1684///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001685/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001686static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001687 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001688 SmallVectorImpl<Value *> &Indices,
1689 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001690 PointerType *Ty = cast<PointerType>(Ptr->getType());
1691
1692 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1693 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001694 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001695 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001696
1697 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001698 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001699 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001700 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001701 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001702 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001703 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001704
1705 Offset -= NumSkippedElements * ElementSize;
1706 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001707 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001708 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001709}
1710
1711/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1712/// resulting pointer has PointerTy.
1713///
1714/// This tries very hard to compute a "natural" GEP which arrives at the offset
1715/// and produces the pointer type desired. Where it cannot, it will try to use
1716/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1717/// fails, it will try to use an existing i8* and GEP to the byte offset and
1718/// bitcast to the type.
1719///
1720/// The strategy for finding the more natural GEPs is to peel off layers of the
1721/// pointer, walking back through bit casts and GEPs, searching for a base
1722/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001723/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001724/// a single GEP as possible, thus making each GEP more independent of the
1725/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001726static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001727 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001728 // Even though we don't look through PHI nodes, we could be called on an
1729 // instruction in an unreachable block, which may be on a cycle.
1730 SmallPtrSet<Value *, 4> Visited;
1731 Visited.insert(Ptr);
1732 SmallVector<Value *, 4> Indices;
1733
1734 // We may end up computing an offset pointer that has the wrong type. If we
1735 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001736 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001737 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001738 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001739
1740 // Remember any i8 pointer we come across to re-use if we need to do a raw
1741 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001742 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001743 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1744
1745 Type *TargetTy = PointerTy->getPointerElementType();
1746
1747 do {
1748 // First fold any existing GEPs into the offset.
1749 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1750 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001751 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001752 break;
1753 Offset += GEPOffset;
1754 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001755 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001756 break;
1757 }
1758
1759 // See if we can perform a natural GEP here.
1760 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001761 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001762 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001763 // If we have a new natural pointer at the offset, clear out any old
1764 // offset pointer we computed. Unless it is the base pointer or
1765 // a non-instruction, we built a GEP we don't need. Zap it.
1766 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1767 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1768 assert(I->use_empty() && "Built a GEP with uses some how!");
1769 I->eraseFromParent();
1770 }
1771 OffsetPtr = P;
1772 OffsetBasePtr = Ptr;
1773 // If we also found a pointer of the right type, we're done.
1774 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001775 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001776 }
1777
1778 // Stash this pointer if we've found an i8*.
1779 if (Ptr->getType()->isIntegerTy(8)) {
1780 Int8Ptr = Ptr;
1781 Int8PtrOffset = Offset;
1782 }
1783
1784 // Peel off a layer of the pointer and update the offset appropriately.
1785 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1786 Ptr = cast<Operator>(Ptr)->getOperand(0);
1787 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1788 if (GA->mayBeOverridden())
1789 break;
1790 Ptr = GA->getAliasee();
1791 } else {
1792 break;
1793 }
1794 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001795 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001796
1797 if (!OffsetPtr) {
1798 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001799 Int8Ptr = IRB.CreateBitCast(
1800 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1801 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001802 Int8PtrOffset = Offset;
1803 }
1804
Chandler Carruth113dc642014-12-20 02:39:18 +00001805 OffsetPtr = Int8PtrOffset == 0
1806 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001807 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1808 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001809 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001810 }
1811 Ptr = OffsetPtr;
1812
1813 // On the off chance we were targeting i8*, guard the bitcast here.
1814 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001815 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001816
1817 return Ptr;
1818}
1819
Chandler Carruth0715cba2015-01-01 11:54:38 +00001820/// \brief Compute the adjusted alignment for a load or store from an offset.
1821static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1822 const DataLayout &DL) {
1823 unsigned Alignment;
1824 Type *Ty;
1825 if (auto *LI = dyn_cast<LoadInst>(I)) {
1826 Alignment = LI->getAlignment();
1827 Ty = LI->getType();
1828 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1829 Alignment = SI->getAlignment();
1830 Ty = SI->getValueOperand()->getType();
1831 } else {
1832 llvm_unreachable("Only loads and stores are allowed!");
1833 }
1834
1835 if (!Alignment)
1836 Alignment = DL.getABITypeAlignment(Ty);
1837
1838 return MinAlign(Alignment, Offset);
1839}
1840
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001841/// \brief Test whether we can convert a value from the old to the new type.
1842///
1843/// This predicate should be used to guard calls to convertValue in order to
1844/// ensure that we only try to convert viable values. The strategy is that we
1845/// will peel off single element struct and array wrappings to get to an
1846/// underlying value, and convert that value.
1847static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1848 if (OldTy == NewTy)
1849 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001850 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1851 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1852 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1853 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001854 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1855 return false;
1856 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1857 return false;
1858
Benjamin Kramer56262592013-09-22 11:24:58 +00001859 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001860 // of pointers and integers.
1861 OldTy = OldTy->getScalarType();
1862 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001863 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1864 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1865 return true;
1866 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1867 return true;
1868 return false;
1869 }
1870
1871 return true;
1872}
1873
1874/// \brief Generic routine to convert an SSA value to a value of a different
1875/// type.
1876///
1877/// This will try various different casting techniques, such as bitcasts,
1878/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1879/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001880static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001881 Type *NewTy) {
1882 Type *OldTy = V->getType();
1883 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1884
1885 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001886 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001887
1888 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1889 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001890 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1891 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001892
Benjamin Kramer90901a32013-09-21 20:36:04 +00001893 // See if we need inttoptr for this type pair. A cast involving both scalars
1894 // and vectors requires and additional bitcast.
1895 if (OldTy->getScalarType()->isIntegerTy() &&
1896 NewTy->getScalarType()->isPointerTy()) {
1897 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1898 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1899 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1900 NewTy);
1901
1902 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1903 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1904 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1905 NewTy);
1906
1907 return IRB.CreateIntToPtr(V, NewTy);
1908 }
1909
1910 // See if we need ptrtoint for this type pair. A cast involving both scalars
1911 // and vectors requires and additional bitcast.
1912 if (OldTy->getScalarType()->isPointerTy() &&
1913 NewTy->getScalarType()->isIntegerTy()) {
1914 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1915 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1916 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1917 NewTy);
1918
1919 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1920 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1921 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1922 NewTy);
1923
1924 return IRB.CreatePtrToInt(V, NewTy);
1925 }
1926
1927 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001928}
1929
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001930/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001931///
1932/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001933/// for a single slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001934static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
1935 const Slice &S, VectorType *Ty,
1936 uint64_t ElementSize,
1937 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001938 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001939 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001940 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001941 uint64_t BeginIndex = BeginOffset / ElementSize;
1942 if (BeginIndex * ElementSize != BeginOffset ||
1943 BeginIndex >= Ty->getNumElements())
1944 return false;
1945 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001946 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001947 uint64_t EndIndex = EndOffset / ElementSize;
1948 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1949 return false;
1950
1951 assert(EndIndex > BeginIndex && "Empty vector!");
1952 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001953 Type *SliceTy = (NumElements == 1)
1954 ? Ty->getElementType()
1955 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001956
1957 Type *SplitIntTy =
1958 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1959
Chandler Carruthc659df92014-10-16 20:24:07 +00001960 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001961
1962 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1963 if (MI->isVolatile())
1964 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001965 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001966 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001967 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1968 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1969 II->getIntrinsicID() != Intrinsic::lifetime_end)
1970 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001971 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1972 // Disable vector promotion when there are loads or stores of an FCA.
1973 return false;
1974 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1975 if (LI->isVolatile())
1976 return false;
1977 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001978 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001979 assert(LTy->isIntegerTy());
1980 LTy = SplitIntTy;
1981 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001982 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001983 return false;
1984 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1985 if (SI->isVolatile())
1986 return false;
1987 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001988 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001989 assert(STy->isIntegerTy());
1990 STy = SplitIntTy;
1991 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001992 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001993 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001994 } else {
1995 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001996 }
1997
1998 return true;
1999}
2000
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002001/// \brief Test whether the given alloca partitioning and range of slices can be
2002/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002003///
2004/// This is a quick test to check whether we can rewrite a particular alloca
2005/// partition (and its newly formed alloca) into a vector alloca with only
2006/// whole-vector loads and stores such that it could be promoted to a vector
2007/// SSA value. We only can ensure this for a limited set of operations, and we
2008/// don't want to do the rewrites unless we are confident that the result will
2009/// be promotable, so we have an early test here.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002010static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
2011 const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00002012 // Collect the candidate types for vector-based promotion. Also track whether
2013 // we have different element types.
2014 SmallVector<VectorType *, 4> CandidateTys;
2015 Type *CommonEltTy = nullptr;
2016 bool HaveCommonEltTy = true;
2017 auto CheckCandidateType = [&](Type *Ty) {
2018 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2019 CandidateTys.push_back(VTy);
2020 if (!CommonEltTy)
2021 CommonEltTy = VTy->getElementType();
2022 else if (CommonEltTy != VTy->getElementType())
2023 HaveCommonEltTy = false;
2024 }
2025 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00002026 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002027 for (const Slice &S : P)
2028 if (S.beginOffset() == P.beginOffset() &&
2029 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00002030 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
2031 CheckCandidateType(LI->getType());
2032 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
2033 CheckCandidateType(SI->getValueOperand()->getType());
2034 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002035
Chandler Carruth2dc96822014-10-18 00:44:02 +00002036 // If we didn't find a vector type, nothing to do here.
2037 if (CandidateTys.empty())
2038 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00002039
Chandler Carruth2dc96822014-10-18 00:44:02 +00002040 // Remove non-integer vector types if we had multiple common element types.
2041 // FIXME: It'd be nice to replace them with integer vector types, but we can't
2042 // do that until all the backends are known to produce good code for all
2043 // integer vector types.
2044 if (!HaveCommonEltTy) {
2045 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
2046 [](VectorType *VTy) {
2047 return !VTy->getElementType()->isIntegerTy();
2048 }),
2049 CandidateTys.end());
2050
2051 // If there were no integer vector types, give up.
2052 if (CandidateTys.empty())
2053 return nullptr;
2054
2055 // Rank the remaining candidate vector types. This is easy because we know
2056 // they're all integer vectors. We sort by ascending number of elements.
2057 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2058 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
2059 "Cannot have vector types of different sizes!");
2060 assert(RHSTy->getElementType()->isIntegerTy() &&
2061 "All non-integer types eliminated!");
2062 assert(LHSTy->getElementType()->isIntegerTy() &&
2063 "All non-integer types eliminated!");
2064 return RHSTy->getNumElements() < LHSTy->getNumElements();
2065 };
2066 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
2067 CandidateTys.erase(
2068 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2069 CandidateTys.end());
2070 } else {
2071// The only way to have the same element type in every vector type is to
2072// have the same vector type. Check that and remove all but one.
2073#ifndef NDEBUG
2074 for (VectorType *VTy : CandidateTys) {
2075 assert(VTy->getElementType() == CommonEltTy &&
2076 "Unaccounted for element type!");
2077 assert(VTy == CandidateTys[0] &&
2078 "Different vector types with the same element type!");
2079 }
2080#endif
2081 CandidateTys.resize(1);
2082 }
2083
2084 // Try each vector type, and return the one which works.
2085 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
2086 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
2087
2088 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2089 // that aren't byte sized.
2090 if (ElementSize % 8)
2091 return false;
2092 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
2093 "vector size not a multiple of element size?");
2094 ElementSize /= 8;
2095
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002096 for (const Slice &S : P)
2097 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00002098 return false;
2099
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002100 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002101 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00002102 return false;
2103
2104 return true;
2105 };
2106 for (VectorType *VTy : CandidateTys)
2107 if (CheckVectorTypeForPromotion(VTy))
2108 return VTy;
2109
2110 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00002111}
2112
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002113/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00002114///
2115/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002116/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002117static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002118 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002119 Type *AllocaTy,
2120 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002121 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002122 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2123
Chandler Carruthc659df92014-10-16 20:24:07 +00002124 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2125 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002126
2127 // We can't reasonably handle cases where the load or store extends past
2128 // the end of the aloca's type and into its padding.
2129 if (RelEnd > Size)
2130 return false;
2131
Chandler Carruthc659df92014-10-16 20:24:07 +00002132 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002133
2134 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2135 if (LI->isVolatile())
2136 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002137 // Note that we don't count vector loads or stores as whole-alloca
2138 // operations which enable integer widening because we would prefer to use
2139 // vector widening instead.
2140 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002141 WholeAllocaOp = true;
2142 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002143 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002144 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002145 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002146 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002147 // Non-integer loads need to be convertible from the alloca type so that
2148 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002149 return false;
2150 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002151 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2152 Type *ValueTy = SI->getValueOperand()->getType();
2153 if (SI->isVolatile())
2154 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002155 // Note that we don't count vector loads or stores as whole-alloca
2156 // operations which enable integer widening because we would prefer to use
2157 // vector widening instead.
2158 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002159 WholeAllocaOp = true;
2160 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002161 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002162 return false;
2163 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002164 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002165 // Non-integer stores need to be convertible to the alloca type so that
2166 // they are promotable.
2167 return false;
2168 }
2169 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2170 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2171 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002172 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002173 return false; // Skip any unsplittable intrinsics.
2174 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2175 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2176 II->getIntrinsicID() != Intrinsic::lifetime_end)
2177 return false;
2178 } else {
2179 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002180 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002181
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002182 return true;
2183}
2184
Chandler Carruth435c4e02012-10-15 08:40:30 +00002185/// \brief Test whether the given alloca partition's integer operations can be
2186/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002187///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002188/// This is a quick test to check whether we can rewrite the integer loads and
2189/// stores to a particular alloca into wider loads and stores and be able to
2190/// promote the resulting alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002191static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
2192 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002193 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002194 // Don't create integer types larger than the maximum bitwidth.
2195 if (SizeInBits > IntegerType::MAX_INT_BITS)
2196 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002197
2198 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002199 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002200 return false;
2201
Chandler Carruth58d05562012-10-25 04:37:07 +00002202 // We need to ensure that an integer type with the appropriate bitwidth can
2203 // be converted to the alloca type, whatever that is. We don't want to force
2204 // the alloca itself to have an integer type if there is a more suitable one.
2205 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002206 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2207 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002208 return false;
2209
Chandler Carruthf0546402013-07-18 07:15:00 +00002210 // While examining uses, we ensure that the alloca has a covering load or
2211 // store. We don't want to widen the integer operations only to fail to
2212 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002213 // later). However, if there are only splittable uses, go ahead and assume
2214 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002215 // FIXME: We shouldn't consider split slices that happen to start in the
2216 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002217 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002218 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002219
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002220 for (const Slice &S : P)
2221 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2222 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002223 return false;
2224
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002225 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002226 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2227 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002228 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002229
Chandler Carruth92924fd2012-09-24 00:34:20 +00002230 return WholeAllocaOp;
2231}
2232
Chandler Carruthd177f862013-03-20 07:30:36 +00002233static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002234 IntegerType *Ty, uint64_t Offset,
2235 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002236 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002237 IntegerType *IntTy = cast<IntegerType>(V->getType());
2238 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2239 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002240 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002241 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002242 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002243 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002244 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002245 DEBUG(dbgs() << " shifted: " << *V << "\n");
2246 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002247 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2248 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002249 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002250 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002251 DEBUG(dbgs() << " trunced: " << *V << "\n");
2252 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002253 return V;
2254}
2255
Chandler Carruthd177f862013-03-20 07:30:36 +00002256static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002257 Value *V, uint64_t Offset, const Twine &Name) {
2258 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2259 IntegerType *Ty = cast<IntegerType>(V->getType());
2260 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2261 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002262 DEBUG(dbgs() << " start: " << *V << "\n");
2263 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002264 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002265 DEBUG(dbgs() << " extended: " << *V << "\n");
2266 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002267 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2268 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002269 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002270 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002271 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002272 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002273 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002274 DEBUG(dbgs() << " shifted: " << *V << "\n");
2275 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002276
2277 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2278 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2279 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002280 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002281 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002282 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002283 }
2284 return V;
2285}
2286
Chandler Carruth113dc642014-12-20 02:39:18 +00002287static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2288 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002289 VectorType *VecTy = cast<VectorType>(V->getType());
2290 unsigned NumElements = EndIndex - BeginIndex;
2291 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2292
2293 if (NumElements == VecTy->getNumElements())
2294 return V;
2295
2296 if (NumElements == 1) {
2297 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2298 Name + ".extract");
2299 DEBUG(dbgs() << " extract: " << *V << "\n");
2300 return V;
2301 }
2302
Chandler Carruth113dc642014-12-20 02:39:18 +00002303 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002304 Mask.reserve(NumElements);
2305 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2306 Mask.push_back(IRB.getInt32(i));
2307 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002308 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002309 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2310 return V;
2311}
2312
Chandler Carruthd177f862013-03-20 07:30:36 +00002313static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002314 unsigned BeginIndex, const Twine &Name) {
2315 VectorType *VecTy = cast<VectorType>(Old->getType());
2316 assert(VecTy && "Can only insert a vector into a vector");
2317
2318 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2319 if (!Ty) {
2320 // Single element to insert.
2321 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2322 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002323 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002324 return V;
2325 }
2326
2327 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2328 "Too many elements!");
2329 if (Ty->getNumElements() == VecTy->getNumElements()) {
2330 assert(V->getType() == VecTy && "Vector type mismatch");
2331 return V;
2332 }
2333 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2334
2335 // When inserting a smaller vector into the larger to store, we first
2336 // use a shuffle vector to widen it with undef elements, and then
2337 // a second shuffle vector to select between the loaded vector and the
2338 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002339 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002340 Mask.reserve(VecTy->getNumElements());
2341 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2342 if (i >= BeginIndex && i < EndIndex)
2343 Mask.push_back(IRB.getInt32(i - BeginIndex));
2344 else
2345 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2346 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002347 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002348 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002349
2350 Mask.clear();
2351 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002352 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2353
2354 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2355
2356 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002357 return V;
2358}
2359
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002360namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002361/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2362/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002363///
2364/// Also implements the rewriting to vector-based accesses when the partition
2365/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2366/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002367class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002368 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002369 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2370 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002371
Chandler Carruth90a735d2013-07-19 07:21:28 +00002372 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002373 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002374 SROA &Pass;
2375 AllocaInst &OldAI, &NewAI;
2376 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002377 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002378
Chandler Carruth2dc96822014-10-18 00:44:02 +00002379 // This is a convenience and flag variable that will be null unless the new
2380 // alloca's integer operations should be widened to this integer type due to
2381 // passing isIntegerWideningViable above. If it is non-null, the desired
2382 // integer type will be stored here for easy access during rewriting.
2383 IntegerType *IntTy;
2384
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002385 // If we are rewriting an alloca partition which can be written as pure
2386 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002387 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388 // - The new alloca is exactly the size of the vector type here.
2389 // - The accesses all either map to the entire vector or to a single
2390 // element.
2391 // - The set of accessing instructions is only one of those handled above
2392 // in isVectorPromotionViable. Generally these are the same access kinds
2393 // which are promotable via mem2reg.
2394 VectorType *VecTy;
2395 Type *ElementTy;
2396 uint64_t ElementSize;
2397
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002398 // The original offset of the slice currently being rewritten relative to
2399 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002400 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002401 // The new offsets of the slice currently being rewritten relative to the
2402 // original alloca.
2403 uint64_t NewBeginOffset, NewEndOffset;
2404
2405 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002406 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002407 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002408 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002409 Instruction *OldPtr;
2410
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002411 // Track post-rewrite users which are PHI nodes and Selects.
2412 SmallPtrSetImpl<PHINode *> &PHIUsers;
2413 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002414
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002415 // Utility IR builder, whose name prefix is setup for each visited use, and
2416 // the insertion point is set to point to the user.
2417 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002418
2419public:
Chandler Carruth83934062014-10-16 21:11:55 +00002420 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002421 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002422 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002423 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2424 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002425 SmallPtrSetImpl<PHINode *> &PHIUsers,
2426 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002427 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002428 NewAllocaBeginOffset(NewAllocaBeginOffset),
2429 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002430 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002431 IntTy(IsIntegerPromotable
2432 ? Type::getIntNTy(
2433 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002434 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002435 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002436 VecTy(PromotableVecTy),
2437 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2438 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002439 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002440 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002441 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002442 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002443 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002444 "Only multiple-of-8 sized vector elements are viable");
2445 ++NumVectorized;
2446 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002447 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002448 }
2449
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002450 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002451 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002452 BeginOffset = I->beginOffset();
2453 EndOffset = I->endOffset();
2454 IsSplittable = I->isSplittable();
2455 IsSplit =
2456 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002457 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2458 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth0715cba2015-01-01 11:54:38 +00002459 DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002460
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002461 // Compute the intersecting offset range.
2462 assert(BeginOffset < NewAllocaEndOffset);
2463 assert(EndOffset > NewAllocaBeginOffset);
2464 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2465 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2466
2467 SliceSize = NewEndOffset - NewBeginOffset;
2468
Chandler Carruthf0546402013-07-18 07:15:00 +00002469 OldUse = I->getUse();
2470 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002471
Chandler Carruthf0546402013-07-18 07:15:00 +00002472 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2473 IRB.SetInsertPoint(OldUserI);
2474 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2475 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2476
2477 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2478 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002479 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002480 return CanSROA;
2481 }
2482
2483private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002484 // Make sure the other visit overloads are visible.
2485 using Base::visit;
2486
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002487 // Every instruction which can end up as a user must have a rewrite rule.
2488 bool visitInstruction(Instruction &I) {
2489 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2490 llvm_unreachable("No rewrite rule for this instruction!");
2491 }
2492
Chandler Carruth47954c82014-02-26 05:12:43 +00002493 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2494 // Note that the offset computation can use BeginOffset or NewBeginOffset
2495 // interchangeably for unsplit slices.
2496 assert(IsSplit || BeginOffset == NewBeginOffset);
2497 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2498
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002499#ifndef NDEBUG
2500 StringRef OldName = OldPtr->getName();
2501 // Skip through the last '.sroa.' component of the name.
2502 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2503 if (LastSROAPrefix != StringRef::npos) {
2504 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2505 // Look for an SROA slice index.
2506 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2507 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2508 // Strip the index and look for the offset.
2509 OldName = OldName.substr(IndexEnd + 1);
2510 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2511 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2512 // Strip the offset.
2513 OldName = OldName.substr(OffsetEnd + 1);
2514 }
2515 }
2516 // Strip any SROA suffixes as well.
2517 OldName = OldName.substr(0, OldName.find(".sroa_"));
2518#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002519
2520 return getAdjustedPtr(IRB, DL, &NewAI,
2521 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002522#ifndef NDEBUG
2523 Twine(OldName) + "."
2524#else
2525 Twine()
2526#endif
2527 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002528 }
2529
Chandler Carruth113dc642014-12-20 02:39:18 +00002530 /// \brief Compute suitable alignment to access this slice of the *new*
2531 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002532 ///
2533 /// You can optionally pass a type to this routine and if that type's ABI
2534 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002535 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002536 unsigned NewAIAlign = NewAI.getAlignment();
2537 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002538 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002539 unsigned Align =
2540 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002541 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002542 }
2543
Chandler Carruth845b73c2012-11-21 08:16:30 +00002544 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002545 assert(VecTy && "Can only call getIndex when rewriting a vector");
2546 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2547 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2548 uint32_t Index = RelOffset / ElementSize;
2549 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002550 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002551 }
2552
2553 void deleteIfTriviallyDead(Value *V) {
2554 Instruction *I = cast<Instruction>(V);
2555 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002556 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002557 }
2558
Chandler Carruthea27cf02014-02-26 04:25:04 +00002559 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002560 unsigned BeginIndex = getIndex(NewBeginOffset);
2561 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002562 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002563
Chandler Carruth113dc642014-12-20 02:39:18 +00002564 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002565 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002566 }
2567
Chandler Carruthea27cf02014-02-26 04:25:04 +00002568 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002569 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002570 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002571 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002572 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002573 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2574 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2575 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002576 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002577 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002578 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002579 }
2580
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002581 bool visitLoadInst(LoadInst &LI) {
2582 DEBUG(dbgs() << " original: " << LI << "\n");
2583 Value *OldOp = LI.getOperand(0);
2584 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002585
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002586 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002587 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002588 bool IsPtrAdjusted = false;
2589 Value *V;
2590 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002591 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002592 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002593 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002594 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002595 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002596 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2597 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002598 } else {
2599 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002600 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002601 getSliceAlign(TargetTy), LI.isVolatile(),
2602 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002603 IsPtrAdjusted = true;
2604 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002605 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002606
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002607 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002608 assert(!LI.isVolatile());
2609 assert(LI.getType()->isIntegerTy() &&
2610 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002611 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002612 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002613 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002614 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002615 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002616 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002617 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002618 // Create a placeholder value with the same type as LI to use as the
2619 // basis for the new value. This allows us to replace the uses of LI with
2620 // the computed value, and then replace the placeholder with LI, leaving
2621 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002622 Value *Placeholder =
2623 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002624 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2625 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002626 LI.replaceAllUsesWith(V);
2627 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002628 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002629 } else {
2630 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002631 }
2632
Chandler Carruth18db7952012-11-20 01:12:50 +00002633 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002634 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002635 DEBUG(dbgs() << " to: " << *V << "\n");
2636 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002637 }
2638
Chandler Carruthea27cf02014-02-26 04:25:04 +00002639 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002640 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002641 unsigned BeginIndex = getIndex(NewBeginOffset);
2642 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002643 assert(EndIndex > BeginIndex && "Empty vector!");
2644 unsigned NumElements = EndIndex - BeginIndex;
2645 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002646 Type *SliceTy = (NumElements == 1)
2647 ? ElementTy
2648 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002649 if (V->getType() != SliceTy)
2650 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002651
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002652 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002653 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002654 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2655 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002656 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002657 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002658
2659 (void)Store;
2660 DEBUG(dbgs() << " to: " << *Store << "\n");
2661 return true;
2662 }
2663
Chandler Carruthea27cf02014-02-26 04:25:04 +00002664 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002665 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002666 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002667 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002668 Value *Old =
2669 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002670 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002671 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2672 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002673 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002674 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002675 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002676 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002677 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002678 (void)Store;
2679 DEBUG(dbgs() << " to: " << *Store << "\n");
2680 return true;
2681 }
2682
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002683 bool visitStoreInst(StoreInst &SI) {
2684 DEBUG(dbgs() << " original: " << SI << "\n");
2685 Value *OldOp = SI.getOperand(1);
2686 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002687
Chandler Carruth18db7952012-11-20 01:12:50 +00002688 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002689
Chandler Carruthac8317f2012-10-04 12:33:50 +00002690 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2691 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002692 if (V->getType()->isPointerTy())
2693 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002694 Pass.PostPromotionWorklist.insert(AI);
2695
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002696 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002697 assert(!SI.isVolatile());
2698 assert(V->getType()->isIntegerTy() &&
2699 "Only integer type loads and stores are split");
2700 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002701 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002702 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002703 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002704 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2705 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002706 }
2707
Chandler Carruth18db7952012-11-20 01:12:50 +00002708 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002709 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002710 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002711 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002712
Chandler Carruth18db7952012-11-20 01:12:50 +00002713 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002714 if (NewBeginOffset == NewAllocaBeginOffset &&
2715 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002716 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2717 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002718 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2719 SI.isVolatile());
2720 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002721 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002722 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2723 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002724 }
2725 (void)NewSI;
2726 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002727 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002728
2729 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2730 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002731 }
2732
Chandler Carruth514f34f2012-12-17 04:07:30 +00002733 /// \brief Compute an integer value from splatting an i8 across the given
2734 /// number of bytes.
2735 ///
2736 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2737 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002738 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002739 ///
2740 /// \param V The i8 value to splat.
2741 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002742 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002743 assert(Size > 0 && "Expected a positive number of bytes.");
2744 IntegerType *VTy = cast<IntegerType>(V->getType());
2745 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2746 if (Size == 1)
2747 return V;
2748
Chandler Carruth113dc642014-12-20 02:39:18 +00002749 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2750 V = IRB.CreateMul(
2751 IRB.CreateZExt(V, SplatIntTy, "zext"),
2752 ConstantExpr::getUDiv(
2753 Constant::getAllOnesValue(SplatIntTy),
2754 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2755 SplatIntTy)),
2756 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002757 return V;
2758 }
2759
Chandler Carruthccca5042012-12-17 04:07:37 +00002760 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002761 Value *getVectorSplat(Value *V, unsigned NumElements) {
2762 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002763 DEBUG(dbgs() << " splat: " << *V << "\n");
2764 return V;
2765 }
2766
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002767 bool visitMemSetInst(MemSetInst &II) {
2768 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002769 assert(II.getRawDest() == OldPtr);
2770
2771 // If the memset has a variable size, it cannot be split, just adjust the
2772 // pointer to the new alloca.
2773 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002774 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002775 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002776 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002777 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002778 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002779
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002780 deleteIfTriviallyDead(OldPtr);
2781 return false;
2782 }
2783
2784 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002785 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002786
2787 Type *AllocaTy = NewAI.getAllocatedType();
2788 Type *ScalarTy = AllocaTy->getScalarType();
2789
2790 // If this doesn't map cleanly onto the alloca type, and that type isn't
2791 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002792 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002793 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002794 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002795 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002796 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002797 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002798 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002799 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2800 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002801 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2802 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002803 (void)New;
2804 DEBUG(dbgs() << " to: " << *New << "\n");
2805 return false;
2806 }
2807
2808 // If we can represent this as a simple value, we have to build the actual
2809 // value to store, which requires expanding the byte present in memset to
2810 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002811 // splatting the byte to a sufficiently wide integer, splatting it across
2812 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002813 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002814
Chandler Carruthccca5042012-12-17 04:07:37 +00002815 if (VecTy) {
2816 // If this is a memset of a vectorized alloca, insert it.
2817 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002818
Chandler Carruthf0546402013-07-18 07:15:00 +00002819 unsigned BeginIndex = getIndex(NewBeginOffset);
2820 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002821 assert(EndIndex > BeginIndex && "Empty vector!");
2822 unsigned NumElements = EndIndex - BeginIndex;
2823 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2824
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002825 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002826 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2827 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002828 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002829 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002830
Chandler Carruth113dc642014-12-20 02:39:18 +00002831 Value *Old =
2832 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002833 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002834 } else if (IntTy) {
2835 // If this is a memset on an alloca where we can widen stores, insert the
2836 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002837 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002838
Chandler Carruthf0546402013-07-18 07:15:00 +00002839 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002840 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002841
2842 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2843 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002844 Value *Old =
2845 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002846 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002847 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002848 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002849 } else {
2850 assert(V->getType() == IntTy &&
2851 "Wrong type for an alloca wide integer!");
2852 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002853 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002854 } else {
2855 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002856 assert(NewBeginOffset == NewAllocaBeginOffset);
2857 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002858
Chandler Carruth90a735d2013-07-19 07:21:28 +00002859 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002860 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002861 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002862
Chandler Carruth90a735d2013-07-19 07:21:28 +00002863 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002864 }
2865
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002866 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002867 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002868 (void)New;
2869 DEBUG(dbgs() << " to: " << *New << "\n");
2870 return !II.isVolatile();
2871 }
2872
2873 bool visitMemTransferInst(MemTransferInst &II) {
2874 // Rewriting of memory transfer instructions can be a bit tricky. We break
2875 // them into two categories: split intrinsics and unsplit intrinsics.
2876
2877 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002878
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002879 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002880 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002881 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002882
Chandler Carruthaa72b932014-02-26 07:29:54 +00002883 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002884
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002885 // For unsplit intrinsics, we simply modify the source and destination
2886 // pointers in place. This isn't just an optimization, it is a matter of
2887 // correctness. With unsplit intrinsics we may be dealing with transfers
2888 // within a single alloca before SROA ran, or with transfers that have
2889 // a variable length. We may also be dealing with memmove instead of
2890 // memcpy, and so simply updating the pointers is the necessary for us to
2891 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002892 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002893 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002894 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002895 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002896 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002897 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002898
Chandler Carruthaa72b932014-02-26 07:29:54 +00002899 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002900 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002901 II.setAlignment(
2902 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002903 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002904
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002905 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002906 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002907 return false;
2908 }
2909 // For split transfer intrinsics we have an incredibly useful assurance:
2910 // the source and destination do not reside within the same alloca, and at
2911 // least one of them does not escape. This means that we can replace
2912 // memmove with memcpy, and we don't need to worry about all manner of
2913 // downsides to splitting and transforming the operations.
2914
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002915 // If this doesn't map cleanly onto the alloca type, and that type isn't
2916 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002917 bool EmitMemCpy =
2918 !VecTy && !IntTy &&
2919 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2920 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2921 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002922
2923 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2924 // size hasn't been shrunk based on analysis of the viable range, this is
2925 // a no-op.
2926 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002927 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002928 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002929
2930 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002931 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002932 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002933 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002934 return false;
2935 }
2936 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002937 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002938
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002939 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2940 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002941 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002942 if (AllocaInst *AI =
2943 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002944 assert(AI != &OldAI && AI != &NewAI &&
2945 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002946 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002947 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002948
Chandler Carruth286d87e2014-02-26 08:25:02 +00002949 Type *OtherPtrTy = OtherPtr->getType();
2950 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2951
Chandler Carruth181ed052014-02-26 05:33:36 +00002952 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002953 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002954 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002955 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2956 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002957
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002958 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002959 // Compute the other pointer, folding as much as possible to produce
2960 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002961 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002962 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002963
Chandler Carruth47954c82014-02-26 05:12:43 +00002964 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002965 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002966 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002967
Chandler Carruthaa72b932014-02-26 07:29:54 +00002968 CallInst *New = IRB.CreateMemCpy(
2969 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2970 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971 (void)New;
2972 DEBUG(dbgs() << " to: " << *New << "\n");
2973 return false;
2974 }
2975
Chandler Carruthf0546402013-07-18 07:15:00 +00002976 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2977 NewEndOffset == NewAllocaEndOffset;
2978 uint64_t Size = NewEndOffset - NewBeginOffset;
2979 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2980 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002981 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002982 IntegerType *SubIntTy =
2983 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002984
Chandler Carruth286d87e2014-02-26 08:25:02 +00002985 // Reset the other pointer type to match the register type we're going to
2986 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002987 if (VecTy && !IsWholeAlloca) {
2988 if (NumElements == 1)
2989 OtherPtrTy = VecTy->getElementType();
2990 else
2991 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2992
Chandler Carruth286d87e2014-02-26 08:25:02 +00002993 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002994 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002995 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2996 } else {
2997 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002998 }
2999
Chandler Carruth181ed052014-02-26 05:33:36 +00003000 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00003001 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00003002 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003003 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00003004 unsigned DstAlign = SliceAlign;
3005 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003006 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00003007 std::swap(SrcAlign, DstAlign);
3008 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003009
3010 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003011 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00003012 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003013 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003014 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00003015 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003016 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003017 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003018 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00003020 Src =
3021 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003022 }
3023
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003024 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00003025 Value *Old =
3026 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003027 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003028 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00003029 Value *Old =
3030 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003031 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003032 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003033 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3034 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003035 }
3036
Chandler Carruth871ba722012-09-26 10:27:46 +00003037 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003038 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00003039 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003040 DEBUG(dbgs() << " to: " << *Store << "\n");
3041 return !II.isVolatile();
3042 }
3043
3044 bool visitIntrinsicInst(IntrinsicInst &II) {
3045 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3046 II.getIntrinsicID() == Intrinsic::lifetime_end);
3047 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003048 assert(II.getArgOperand(1) == OldPtr);
3049
3050 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003051 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003052
Chandler Carruth113dc642014-12-20 02:39:18 +00003053 ConstantInt *Size =
3054 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003055 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00003056 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003057 Value *New;
3058 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3059 New = IRB.CreateLifetimeStart(Ptr, Size);
3060 else
3061 New = IRB.CreateLifetimeEnd(Ptr, Size);
3062
Edwin Vane82f80d42013-01-29 17:42:24 +00003063 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003064 DEBUG(dbgs() << " to: " << *New << "\n");
3065 return true;
3066 }
3067
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003068 bool visitPHINode(PHINode &PN) {
3069 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003070 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3071 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003072
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003073 // We would like to compute a new pointer in only one place, but have it be
3074 // as local as possible to the PHI. To do that, we re-use the location of
3075 // the old pointer, which necessarily must be in the right position to
3076 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003077 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003078 if (isa<PHINode>(OldPtr))
3079 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3080 else
3081 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003082 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003083
Chandler Carruth47954c82014-02-26 05:12:43 +00003084 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003085 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003086 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003087
Chandler Carruth82a57542012-10-01 10:54:05 +00003088 DEBUG(dbgs() << " to: " << PN << "\n");
3089 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003090
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003091 // PHIs can't be promoted on their own, but often can be speculated. We
3092 // check the speculation outside of the rewriter so that we see the
3093 // fully-rewritten alloca.
3094 PHIUsers.insert(&PN);
3095 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003096 }
3097
3098 bool visitSelectInst(SelectInst &SI) {
3099 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003100 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3101 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003102 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3103 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003104
Chandler Carruth47954c82014-02-26 05:12:43 +00003105 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003106 // Replace the operands which were using the old pointer.
3107 if (SI.getOperand(1) == OldPtr)
3108 SI.setOperand(1, NewPtr);
3109 if (SI.getOperand(2) == OldPtr)
3110 SI.setOperand(2, NewPtr);
3111
Chandler Carruth82a57542012-10-01 10:54:05 +00003112 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003113 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003114
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003115 // Selects can't be promoted on their own, but often can be speculated. We
3116 // check the speculation outside of the rewriter so that we see the
3117 // fully-rewritten alloca.
3118 SelectUsers.insert(&SI);
3119 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003120 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003121};
3122}
3123
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003124namespace {
3125/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3126///
3127/// This pass aggressively rewrites all aggregate loads and stores on
3128/// a particular pointer (or any pointer derived from it which we can identify)
3129/// with scalar loads and stores.
3130class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3131 // Befriend the base class so it can delegate to private visit methods.
3132 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3133
Chandler Carruth90a735d2013-07-19 07:21:28 +00003134 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003135
3136 /// Queue of pointer uses to analyze and potentially rewrite.
3137 SmallVector<Use *, 8> Queue;
3138
3139 /// Set to prevent us from cycling with phi nodes and loops.
3140 SmallPtrSet<User *, 8> Visited;
3141
3142 /// The current pointer use being rewritten. This is used to dig up the used
3143 /// value (as opposed to the user).
3144 Use *U;
3145
3146public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00003147 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003148
3149 /// Rewrite loads and stores through a pointer and all pointers derived from
3150 /// it.
3151 bool rewrite(Instruction &I) {
3152 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3153 enqueueUsers(I);
3154 bool Changed = false;
3155 while (!Queue.empty()) {
3156 U = Queue.pop_back_val();
3157 Changed |= visit(cast<Instruction>(U->getUser()));
3158 }
3159 return Changed;
3160 }
3161
3162private:
3163 /// Enqueue all the users of the given instruction for further processing.
3164 /// This uses a set to de-duplicate users.
3165 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003166 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003167 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003168 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003169 }
3170
3171 // Conservative default is to not rewrite anything.
3172 bool visitInstruction(Instruction &I) { return false; }
3173
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003174 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003175 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003176 protected:
3177 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003178 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003179 /// The indices which to be used with insert- or extractvalue to select the
3180 /// appropriate value within the aggregate.
3181 SmallVector<unsigned, 4> Indices;
3182 /// The indices to a GEP instruction which will move Ptr to the correct slot
3183 /// within the aggregate.
3184 SmallVector<Value *, 4> GEPIndices;
3185 /// The base pointer of the original op, used as a base for GEPing the
3186 /// split operations.
3187 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003188
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003189 /// Initialize the splitter with an insertion point, Ptr and start with a
3190 /// single zero GEP index.
3191 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003192 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003193
3194 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003195 /// \brief Generic recursive split emission routine.
3196 ///
3197 /// This method recursively splits an aggregate op (load or store) into
3198 /// scalar or vector ops. It splits recursively until it hits a single value
3199 /// and emits that single value operation via the template argument.
3200 ///
3201 /// The logic of this routine relies on GEPs and insertvalue and
3202 /// extractvalue all operating with the same fundamental index list, merely
3203 /// formatted differently (GEPs need actual values).
3204 ///
3205 /// \param Ty The type being split recursively into smaller ops.
3206 /// \param Agg The aggregate value being built up or stored, depending on
3207 /// whether this is splitting a load or a store respectively.
3208 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3209 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003210 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003211
3212 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3213 unsigned OldSize = Indices.size();
3214 (void)OldSize;
3215 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3216 ++Idx) {
3217 assert(Indices.size() == OldSize && "Did not return to the old size");
3218 Indices.push_back(Idx);
3219 GEPIndices.push_back(IRB.getInt32(Idx));
3220 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3221 GEPIndices.pop_back();
3222 Indices.pop_back();
3223 }
3224 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003225 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003226
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003227 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3228 unsigned OldSize = Indices.size();
3229 (void)OldSize;
3230 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3231 ++Idx) {
3232 assert(Indices.size() == OldSize && "Did not return to the old size");
3233 Indices.push_back(Idx);
3234 GEPIndices.push_back(IRB.getInt32(Idx));
3235 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3236 GEPIndices.pop_back();
3237 Indices.pop_back();
3238 }
3239 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003240 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003241
3242 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003243 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003244 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003245
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003246 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003247 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003248 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003249
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003250 /// Emit a leaf load of a single value. This is called at the leaves of the
3251 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003252 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003253 assert(Ty->isSingleValueType());
3254 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003255 Value *GEP =
3256 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003257 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003258 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3259 DEBUG(dbgs() << " to: " << *Load << "\n");
3260 }
3261 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003262
3263 bool visitLoadInst(LoadInst &LI) {
3264 assert(LI.getPointerOperand() == *U);
3265 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3266 return false;
3267
3268 // We have an aggregate being loaded, split it apart.
3269 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003270 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003271 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003272 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003273 LI.replaceAllUsesWith(V);
3274 LI.eraseFromParent();
3275 return true;
3276 }
3277
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003278 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003279 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003280 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003281
3282 /// Emit a leaf store of a single value. This is called at the leaves of the
3283 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003284 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003285 assert(Ty->isSingleValueType());
3286 // Extract the single value and store it using the indices.
3287 Value *Store = IRB.CreateStore(
Chandler Carruth113dc642014-12-20 02:39:18 +00003288 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
David Blaikieaa41cd52015-04-03 21:33:42 +00003289 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003290 (void)Store;
3291 DEBUG(dbgs() << " to: " << *Store << "\n");
3292 }
3293 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003294
3295 bool visitStoreInst(StoreInst &SI) {
3296 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3297 return false;
3298 Value *V = SI.getValueOperand();
3299 if (V->getType()->isSingleValueType())
3300 return false;
3301
3302 // We have an aggregate being stored, split it apart.
3303 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003304 StoreOpSplitter Splitter(&SI, *U);
3305 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003306 SI.eraseFromParent();
3307 return true;
3308 }
3309
3310 bool visitBitCastInst(BitCastInst &BC) {
3311 enqueueUsers(BC);
3312 return false;
3313 }
3314
3315 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3316 enqueueUsers(GEPI);
3317 return false;
3318 }
3319
3320 bool visitPHINode(PHINode &PN) {
3321 enqueueUsers(PN);
3322 return false;
3323 }
3324
3325 bool visitSelectInst(SelectInst &SI) {
3326 enqueueUsers(SI);
3327 return false;
3328 }
3329};
3330}
3331
Chandler Carruthba931992012-10-13 10:49:33 +00003332/// \brief Strip aggregate type wrapping.
3333///
3334/// This removes no-op aggregate types wrapping an underlying type. It will
3335/// strip as many layers of types as it can without changing either the type
3336/// size or the allocated size.
3337static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3338 if (Ty->isSingleValueType())
3339 return Ty;
3340
3341 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3342 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3343
3344 Type *InnerTy;
3345 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3346 InnerTy = ArrTy->getElementType();
3347 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3348 const StructLayout *SL = DL.getStructLayout(STy);
3349 unsigned Index = SL->getElementContainingOffset(0);
3350 InnerTy = STy->getElementType(Index);
3351 } else {
3352 return Ty;
3353 }
3354
3355 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3356 TypeSize > DL.getTypeSizeInBits(InnerTy))
3357 return Ty;
3358
3359 return stripAggregateTypeWrapping(DL, InnerTy);
3360}
3361
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003362/// \brief Try to find a partition of the aggregate type passed in for a given
3363/// offset and size.
3364///
3365/// This recurses through the aggregate type and tries to compute a subtype
3366/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003367/// of an array, it will even compute a new array type for that sub-section,
3368/// and the same for structs.
3369///
3370/// Note that this routine is very strict and tries to find a partition of the
3371/// type which produces the *exact* right offset and size. It is not forgiving
3372/// when the size or offset cause either end of type-based partition to be off.
3373/// Also, this is a best-effort routine. It is reasonable to give up and not
3374/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003375static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3376 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003377 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3378 return stripAggregateTypeWrapping(DL, Ty);
3379 if (Offset > DL.getTypeAllocSize(Ty) ||
3380 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003381 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003382
3383 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3384 // We can't partition pointers...
3385 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003386 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003387
3388 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003389 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003390 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003391 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003392 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003393 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003394 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003395 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003396 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003397 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003398 Offset -= NumSkippedElements * ElementSize;
3399
3400 // First check if we need to recurse.
3401 if (Offset > 0 || Size < ElementSize) {
3402 // Bail if the partition ends in a different array element.
3403 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003404 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003405 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003406 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003407 }
3408 assert(Offset == 0);
3409
3410 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003411 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003412 assert(Size > ElementSize);
3413 uint64_t NumElements = Size / ElementSize;
3414 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003415 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003416 return ArrayType::get(ElementTy, NumElements);
3417 }
3418
3419 StructType *STy = dyn_cast<StructType>(Ty);
3420 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003421 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003422
Chandler Carruth90a735d2013-07-19 07:21:28 +00003423 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003424 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003425 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003426 uint64_t EndOffset = Offset + Size;
3427 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003428 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003429
3430 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003431 Offset -= SL->getElementOffset(Index);
3432
3433 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003434 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003435 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003436 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003437
3438 // See if any partition must be contained by the element.
3439 if (Offset > 0 || Size < ElementSize) {
3440 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003441 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003442 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003443 }
3444 assert(Offset == 0);
3445
3446 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003447 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003448
3449 StructType::element_iterator EI = STy->element_begin() + Index,
3450 EE = STy->element_end();
3451 if (EndOffset < SL->getSizeInBytes()) {
3452 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3453 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003454 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003455
3456 // Don't try to form "natural" types if the elements don't line up with the
3457 // expected size.
3458 // FIXME: We could potentially recurse down through the last element in the
3459 // sub-struct to find a natural end point.
3460 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003461 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003462
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003463 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003464 EE = STy->element_begin() + EndIndex;
3465 }
3466
3467 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003468 StructType *SubTy =
3469 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003470 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003471 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003472 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003473
Chandler Carruth054a40a2012-09-14 11:08:31 +00003474 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003475}
3476
Chandler Carruth0715cba2015-01-01 11:54:38 +00003477/// \brief Pre-split loads and stores to simplify rewriting.
3478///
3479/// We want to break up the splittable load+store pairs as much as
3480/// possible. This is important to do as a preprocessing step, as once we
3481/// start rewriting the accesses to partitions of the alloca we lose the
3482/// necessary information to correctly split apart paired loads and stores
3483/// which both point into this alloca. The case to consider is something like
3484/// the following:
3485///
3486/// %a = alloca [12 x i8]
3487/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3488/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3489/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3490/// %iptr1 = bitcast i8* %gep1 to i64*
3491/// %iptr2 = bitcast i8* %gep2 to i64*
3492/// %fptr1 = bitcast i8* %gep1 to float*
3493/// %fptr2 = bitcast i8* %gep2 to float*
3494/// %fptr3 = bitcast i8* %gep3 to float*
3495/// store float 0.0, float* %fptr1
3496/// store float 1.0, float* %fptr2
3497/// %v = load i64* %iptr1
3498/// store i64 %v, i64* %iptr2
3499/// %f1 = load float* %fptr2
3500/// %f2 = load float* %fptr3
3501///
3502/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3503/// promote everything so we recover the 2 SSA values that should have been
3504/// there all along.
3505///
3506/// \returns true if any changes are made.
3507bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3508 DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3509
3510 // Track the loads and stores which are candidates for pre-splitting here, in
3511 // the order they first appear during the partition scan. These give stable
3512 // iteration order and a basis for tracking which loads and stores we
3513 // actually split.
3514 SmallVector<LoadInst *, 4> Loads;
3515 SmallVector<StoreInst *, 4> Stores;
3516
3517 // We need to accumulate the splits required of each load or store where we
3518 // can find them via a direct lookup. This is important to cross-check loads
3519 // and stores against each other. We also track the slice so that we can kill
3520 // all the slices that end up split.
3521 struct SplitOffsets {
3522 Slice *S;
3523 std::vector<uint64_t> Splits;
3524 };
3525 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3526
Chandler Carruth73b01642015-01-05 04:17:53 +00003527 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3528 // This is important as we also cannot pre-split stores of those loads!
3529 // FIXME: This is all pretty gross. It means that we can be more aggressive
3530 // in pre-splitting when the load feeding the store happens to come from
3531 // a separate alloca. Put another way, the effectiveness of SROA would be
3532 // decreased by a frontend which just concatenated all of its local allocas
3533 // into one big flat alloca. But defeating such patterns is exactly the job
3534 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3535 // change store pre-splitting to actually force pre-splitting of the load
3536 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3537 // maybe it would make it more principled?
3538 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3539
Chandler Carruth0715cba2015-01-01 11:54:38 +00003540 DEBUG(dbgs() << " Searching for candidate loads and stores\n");
3541 for (auto &P : AS.partitions()) {
3542 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003543 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3544 if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
3545 // If this was a load we have to track that it can't participate in any
3546 // pre-splitting!
3547 if (auto *LI = dyn_cast<LoadInst>(I))
3548 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003549 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003550 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003551 assert(P.endOffset() > S.beginOffset() &&
3552 "Empty or backwards partition!");
3553
3554 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003555 if (auto *LI = dyn_cast<LoadInst>(I)) {
3556 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3557
3558 // The load must be used exclusively to store into other pointers for
3559 // us to be able to arbitrarily pre-split it. The stores must also be
3560 // simple to avoid changing semantics.
3561 auto IsLoadSimplyStored = [](LoadInst *LI) {
3562 for (User *LU : LI->users()) {
3563 auto *SI = dyn_cast<StoreInst>(LU);
3564 if (!SI || !SI->isSimple())
3565 return false;
3566 }
3567 return true;
3568 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003569 if (!IsLoadSimplyStored(LI)) {
3570 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003571 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003572 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003573
3574 Loads.push_back(LI);
3575 } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
Chandler Carruth994cde82015-01-01 12:01:03 +00003576 if (!SI ||
3577 S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3578 continue;
3579 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3580 if (!StoredLoad || !StoredLoad->isSimple())
3581 continue;
3582 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003583
Chandler Carruth994cde82015-01-01 12:01:03 +00003584 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003585 } else {
3586 // Other uses cannot be pre-split.
3587 continue;
3588 }
3589
3590 // Record the initial split.
3591 DEBUG(dbgs() << " Candidate: " << *I << "\n");
3592 auto &Offsets = SplitOffsetsMap[I];
3593 assert(Offsets.Splits.empty() &&
3594 "Should not have splits the first time we see an instruction!");
3595 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003596 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003597 }
3598
3599 // Now scan the already split slices, and add a split for any of them which
3600 // we're going to pre-split.
3601 for (Slice *S : P.splitSliceTails()) {
3602 auto SplitOffsetsMapI =
3603 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3604 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3605 continue;
3606 auto &Offsets = SplitOffsetsMapI->second;
3607
3608 assert(Offsets.S == S && "Found a mismatched slice!");
3609 assert(!Offsets.Splits.empty() &&
3610 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003611 assert(Offsets.Splits.back() ==
3612 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003613 "Previous split does not end where this one begins!");
3614
3615 // Record each split. The last partition's end isn't needed as the size
3616 // of the slice dictates that.
3617 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003618 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003619 }
3620 }
3621
3622 // We may have split loads where some of their stores are split stores. For
3623 // such loads and stores, we can only pre-split them if their splits exactly
3624 // match relative to their starting offset. We have to verify this prior to
3625 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003626 Stores.erase(
Chandler Carruth994cde82015-01-01 12:01:03 +00003627 std::remove_if(Stores.begin(), Stores.end(),
Chandler Carruth73b01642015-01-05 04:17:53 +00003628 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
Chandler Carruth994cde82015-01-01 12:01:03 +00003629 // Lookup the load we are storing in our map of split
3630 // offsets.
3631 auto *LI = cast<LoadInst>(SI->getValueOperand());
Chandler Carruth73b01642015-01-05 04:17:53 +00003632 // If it was completely unsplittable, then we're done,
3633 // and this store can't be pre-split.
3634 if (UnsplittableLoads.count(LI))
3635 return true;
3636
Chandler Carruth994cde82015-01-01 12:01:03 +00003637 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3638 if (LoadOffsetsI == SplitOffsetsMap.end())
Chandler Carruth73b01642015-01-05 04:17:53 +00003639 return false; // Unrelated loads are definitely safe.
Chandler Carruth994cde82015-01-01 12:01:03 +00003640 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003641
Chandler Carruth994cde82015-01-01 12:01:03 +00003642 // Now lookup the store's offsets.
3643 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003644
Chandler Carruth994cde82015-01-01 12:01:03 +00003645 // If the relative offsets of each split in the load and
3646 // store match exactly, then we can split them and we
3647 // don't need to remove them here.
3648 if (LoadOffsets.Splits == StoreOffsets.Splits)
3649 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003650
Chandler Carruth994cde82015-01-01 12:01:03 +00003651 DEBUG(dbgs()
3652 << " Mismatched splits for load and store:\n"
3653 << " " << *LI << "\n"
3654 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003655
Chandler Carruth994cde82015-01-01 12:01:03 +00003656 // We've found a store and load that we need to split
3657 // with mismatched relative splits. Just give up on them
3658 // and remove both instructions from our list of
3659 // candidates.
Chandler Carruth73b01642015-01-05 04:17:53 +00003660 UnsplittableLoads.insert(LI);
Chandler Carruth994cde82015-01-01 12:01:03 +00003661 return true;
3662 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003663 Stores.end());
Chandler Carruth73b01642015-01-05 04:17:53 +00003664 // Now we have to go *back* through all te stores, because a later store may
3665 // have caused an earlier store's load to become unsplittable and if it is
3666 // unsplittable for the later store, then we can't rely on it being split in
3667 // the earlier store either.
3668 Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3669 [&UnsplittableLoads](StoreInst *SI) {
3670 auto *LI =
3671 cast<LoadInst>(SI->getValueOperand());
3672 return UnsplittableLoads.count(LI);
3673 }),
3674 Stores.end());
3675 // Once we've established all the loads that can't be split for some reason,
3676 // filter any that made it into our list out.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003677 Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
Chandler Carruth73b01642015-01-05 04:17:53 +00003678 [&UnsplittableLoads](LoadInst *LI) {
3679 return UnsplittableLoads.count(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003680 }),
3681 Loads.end());
3682
Chandler Carruth73b01642015-01-05 04:17:53 +00003683
Chandler Carruth0715cba2015-01-01 11:54:38 +00003684 // If no loads or stores are left, there is no pre-splitting to be done for
3685 // this alloca.
3686 if (Loads.empty() && Stores.empty())
3687 return false;
3688
3689 // From here on, we can't fail and will be building new accesses, so rig up
3690 // an IR builder.
3691 IRBuilderTy IRB(&AI);
3692
3693 // Collect the new slices which we will merge into the alloca slices.
3694 SmallVector<Slice, 4> NewSlices;
3695
3696 // Track any allocas we end up splitting loads and stores for so we iterate
3697 // on them.
3698 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3699
3700 // At this point, we have collected all of the loads and stores we can
3701 // pre-split, and the specific splits needed for them. We actually do the
3702 // splitting in a specific order in order to handle when one of the loads in
3703 // the value operand to one of the stores.
3704 //
3705 // First, we rewrite all of the split loads, and just accumulate each split
3706 // load in a parallel structure. We also build the slices for them and append
3707 // them to the alloca slices.
3708 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3709 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003710 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003711 for (LoadInst *LI : Loads) {
3712 SplitLoads.clear();
3713
3714 IntegerType *Ty = cast<IntegerType>(LI->getType());
3715 uint64_t LoadSize = Ty->getBitWidth() / 8;
3716 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3717
3718 auto &Offsets = SplitOffsetsMap[LI];
3719 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3720 "Slice size should always match load size exactly!");
3721 uint64_t BaseOffset = Offsets.S->beginOffset();
3722 assert(BaseOffset + LoadSize > BaseOffset &&
3723 "Cannot represent alloca access size using 64-bit integers!");
3724
3725 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3726 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3727
3728 DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
3729
3730 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3731 int Idx = 0, Size = Offsets.Splits.size();
3732 for (;;) {
3733 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3734 auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3735 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003736 getAdjustedPtr(IRB, DL, BasePtr,
3737 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003738 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003739 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003740 LI->getName());
3741
3742 // Append this load onto the list of split loads so we can find it later
3743 // to rewrite the stores.
3744 SplitLoads.push_back(PLoad);
3745
3746 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003747 NewSlices.push_back(
3748 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3749 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003750 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003751 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3752 << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3753 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003754
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003755 // See if we've handled all the splits.
3756 if (Idx >= Size)
3757 break;
3758
Chandler Carruth0715cba2015-01-01 11:54:38 +00003759 // Setup the next partition.
3760 PartOffset = Offsets.Splits[Idx];
3761 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003762 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3763 }
3764
3765 // Now that we have the split loads, do the slow walk over all uses of the
3766 // load and rewrite them as split stores, or save the split loads to use
3767 // below if the store is going to be split there anyways.
3768 bool DeferredStores = false;
3769 for (User *LU : LI->users()) {
3770 StoreInst *SI = cast<StoreInst>(LU);
3771 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3772 DeferredStores = true;
3773 DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
3774 continue;
3775 }
3776
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003777 Value *StoreBasePtr = SI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003778 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3779
3780 DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
3781
3782 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3783 LoadInst *PLoad = SplitLoads[Idx];
3784 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003785 auto *PartPtrTy =
3786 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003787
3788 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003789 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3790 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003791 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003792 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003793 (void)PStore;
3794 DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
3795 }
3796
3797 // We want to immediately iterate on any allocas impacted by splitting
3798 // this store, and we have to track any promotable alloca (indicated by
3799 // a direct store) as needing to be resplit because it is no longer
3800 // promotable.
3801 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3802 ResplitPromotableAllocas.insert(OtherAI);
3803 Worklist.insert(OtherAI);
3804 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3805 StoreBasePtr->stripInBoundsOffsets())) {
3806 Worklist.insert(OtherAI);
3807 }
3808
3809 // Mark the original store as dead.
3810 DeadInsts.insert(SI);
3811 }
3812
3813 // Save the split loads if there are deferred stores among the users.
3814 if (DeferredStores)
3815 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3816
3817 // Mark the original load as dead and kill the original slice.
3818 DeadInsts.insert(LI);
3819 Offsets.S->kill();
3820 }
3821
3822 // Second, we rewrite all of the split stores. At this point, we know that
3823 // all loads from this alloca have been split already. For stores of such
3824 // loads, we can simply look up the pre-existing split loads. For stores of
3825 // other loads, we split those loads first and then write split stores of
3826 // them.
3827 for (StoreInst *SI : Stores) {
3828 auto *LI = cast<LoadInst>(SI->getValueOperand());
3829 IntegerType *Ty = cast<IntegerType>(LI->getType());
3830 uint64_t StoreSize = Ty->getBitWidth() / 8;
3831 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3832
3833 auto &Offsets = SplitOffsetsMap[SI];
3834 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3835 "Slice size should always match load size exactly!");
3836 uint64_t BaseOffset = Offsets.S->beginOffset();
3837 assert(BaseOffset + StoreSize > BaseOffset &&
3838 "Cannot represent alloca access size using 64-bit integers!");
3839
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003840 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003841 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3842
3843 DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
3844
3845 // Check whether we have an already split load.
3846 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3847 std::vector<LoadInst *> *SplitLoads = nullptr;
3848 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3849 SplitLoads = &SplitLoadsMapI->second;
3850 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3851 "Too few split loads for the number of splits in the store!");
3852 } else {
3853 DEBUG(dbgs() << " of load: " << *LI << "\n");
3854 }
3855
Chandler Carruth0715cba2015-01-01 11:54:38 +00003856 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3857 int Idx = 0, Size = Offsets.Splits.size();
3858 for (;;) {
3859 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3860 auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3861
3862 // Either lookup a split load or create one.
3863 LoadInst *PLoad;
3864 if (SplitLoads) {
3865 PLoad = (*SplitLoads)[Idx];
3866 } else {
3867 IRB.SetInsertPoint(BasicBlock::iterator(LI));
3868 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003869 getAdjustedPtr(IRB, DL, LoadBasePtr,
3870 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003871 PartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003872 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003873 LI->getName());
3874 }
3875
3876 // And store this partition.
3877 IRB.SetInsertPoint(BasicBlock::iterator(SI));
3878 StoreInst *PStore = IRB.CreateAlignedStore(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003879 PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3880 APInt(DL.getPointerSizeInBits(), PartOffset),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003881 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003882 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003883
3884 // Now build a new slice for the alloca.
3885 NewSlices.push_back(
3886 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3887 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003888 /*IsSplittable*/ false));
Chandler Carruth6044c0b2015-01-01 12:56:47 +00003889 DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3890 << ", " << NewSlices.back().endOffset() << "): " << *PStore
3891 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003892 if (!SplitLoads) {
3893 DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
3894 }
3895
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003896 // See if we've finished all the splits.
3897 if (Idx >= Size)
3898 break;
3899
Chandler Carruth0715cba2015-01-01 11:54:38 +00003900 // Setup the next partition.
3901 PartOffset = Offsets.Splits[Idx];
3902 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003903 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3904 }
3905
3906 // We want to immediately iterate on any allocas impacted by splitting
3907 // this load, which is only relevant if it isn't a load of this alloca and
3908 // thus we didn't already split the loads above. We also have to keep track
3909 // of any promotable allocas we split loads on as they can no longer be
3910 // promoted.
3911 if (!SplitLoads) {
3912 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3913 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3914 ResplitPromotableAllocas.insert(OtherAI);
3915 Worklist.insert(OtherAI);
3916 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3917 LoadBasePtr->stripInBoundsOffsets())) {
3918 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3919 Worklist.insert(OtherAI);
3920 }
3921 }
3922
3923 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003924 // slice. Note that we leave the original load in place unless this store
3925 // was its ownly use. It may in turn be split up if it is an alloca load
3926 // for some other alloca, but it may be a normal load. This may introduce
3927 // redundant loads, but where those can be merged the rest of the optimizer
3928 // should handle the merging, and this uncovers SSA splits which is more
3929 // important. In practice, the original loads will almost always be fully
3930 // split and removed eventually, and the splits will be merged by any
3931 // trivial CSE, including instcombine.
3932 if (LI->hasOneUse()) {
3933 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3934 DeadInsts.insert(LI);
3935 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003936 DeadInsts.insert(SI);
3937 Offsets.S->kill();
3938 }
3939
Chandler Carruth24ac8302015-01-02 03:55:54 +00003940 // Remove the killed slices that have ben pre-split.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003941 AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3942 return S.isDead();
3943 }), AS.end());
3944
Chandler Carruth24ac8302015-01-02 03:55:54 +00003945 // Insert our new slices. This will sort and merge them into the sorted
3946 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003947 AS.insert(NewSlices);
3948
3949 DEBUG(dbgs() << " Pre-split slices:\n");
3950#ifndef NDEBUG
3951 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3952 DEBUG(AS.print(dbgs(), I, " "));
3953#endif
3954
3955 // Finally, don't try to promote any allocas that new require re-splitting.
3956 // They have already been added to the worklist above.
3957 PromotableAllocas.erase(
3958 std::remove_if(
3959 PromotableAllocas.begin(), PromotableAllocas.end(),
3960 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3961 PromotableAllocas.end());
3962
3963 return true;
3964}
3965
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003966/// \brief Rewrite an alloca partition's users.
3967///
3968/// This routine drives both of the rewriting goals of the SROA pass. It tries
3969/// to rewrite uses of an alloca partition to be conducive for SSA value
3970/// promotion. If the partition needs a new, more refined alloca, this will
3971/// build that new alloca, preserving as much type information as possible, and
3972/// rewrite the uses of the old alloca to point at the new one and have the
3973/// appropriate new offsets. It also evaluates how successful the rewrite was
3974/// at enabling promotion and if it was successful queues the alloca to be
3975/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00003976AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3977 AllocaSlices::Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003978 // Try to compute a friendly type for this partition of the alloca. This
3979 // won't always succeed, in which case we fall back to a legal integer type
3980 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003981 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003982 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003983 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003984 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003985 SliceTy = CommonUseTy;
3986 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003987 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003988 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003989 SliceTy = TypePartitionTy;
3990 if ((!SliceTy || (SliceTy->isArrayTy() &&
3991 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003992 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003993 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003994 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003995 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003996 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003997
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003998 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003999
Chandler Carruth2dc96822014-10-18 00:44:02 +00004000 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004001 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004002 if (VecTy)
4003 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004004
4005 // Check for the case where we're going to rewrite to a new alloca of the
4006 // exact same type as the original, and with the same access offsets. In that
4007 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004008 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004009 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004010 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004011 assert(P.beginOffset() == 0 &&
4012 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004013 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004014 // FIXME: We should be able to bail at this point with "nothing changed".
4015 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004016 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004017 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00004018 unsigned Alignment = AI.getAlignment();
4019 if (!Alignment) {
4020 // The minimum alignment which users can rely on when the explicit
4021 // alignment is omitted or zero is that required by the ABI for this
4022 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004023 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00004024 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004025 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004026 // If we will get at least this much alignment from the type alone, leave
4027 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004028 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00004029 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004030 NewAI = new AllocaInst(
4031 SliceTy, nullptr, Alignment,
4032 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004033 ++NumNewAllocas;
4034 }
4035
4036 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004037 << "[" << P.beginOffset() << "," << P.endOffset()
4038 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004039
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004040 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004041 // promoted allocas. We will reset it to this point if the alloca is not in
4042 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004043 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004044 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004045 SmallPtrSet<PHINode *, 8> PHIUsers;
4046 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004047
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004048 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004049 P.endOffset(), IsIntegerPromotable, VecTy,
4050 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004051 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004052 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004053 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004054 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004055 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004056 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004057 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004058 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004059 }
4060
Chandler Carruth6c321c12013-07-19 10:57:36 +00004061 NumAllocaPartitionUses += NumUses;
4062 MaxUsesPerAllocaPartition =
4063 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004064
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004065 // Now that we've processed all the slices in the new partition, check if any
4066 // PHIs or Selects would block promotion.
4067 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
4068 E = PHIUsers.end();
4069 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004070 if (!isSafePHIToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004071 Promotable = false;
4072 PHIUsers.clear();
4073 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004074 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004075 }
4076 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
4077 E = SelectUsers.end();
4078 I != E; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004079 if (!isSafeSelectToSpeculate(**I)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004080 Promotable = false;
4081 PHIUsers.clear();
4082 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004083 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004084 }
4085
4086 if (Promotable) {
4087 if (PHIUsers.empty() && SelectUsers.empty()) {
4088 // Promote the alloca.
4089 PromotableAllocas.push_back(NewAI);
4090 } else {
4091 // If we have either PHIs or Selects to speculate, add them to those
4092 // worklists and re-queue the new alloca so that we promote in on the
4093 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004094 for (PHINode *PHIUser : PHIUsers)
4095 SpeculatablePHIs.insert(PHIUser);
4096 for (SelectInst *SelectUser : SelectUsers)
4097 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004098 Worklist.insert(NewAI);
4099 }
4100 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004101 // If we can't promote the alloca, iterate on it to check for new
4102 // refinements exposed by splitting the current alloca. Don't iterate on an
4103 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004104 if (NewAI != &AI)
4105 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00004106
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004107 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004108 while (PostPromotionWorklist.size() > PPWOldSize)
4109 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00004110 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004111
Adrian Prantl565cc182015-01-20 19:42:22 +00004112 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004113}
4114
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004115/// \brief Walks the slices of an alloca and form partitions based on them,
4116/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004117bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4118 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004119 return false;
4120
Chandler Carruth6c321c12013-07-19 10:57:36 +00004121 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004122 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004123 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004124
Chandler Carruth24ac8302015-01-02 03:55:54 +00004125 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004126 Changed |= presplitLoadsAndStores(AI, AS);
4127
Chandler Carruth24ac8302015-01-02 03:55:54 +00004128 // Now that we have identified any pre-splitting opportunities, mark any
4129 // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
4130 // to split these during pre-splitting, we want to force them to be
4131 // rewritten into a partition.
4132 bool IsSorted = true;
4133 for (Slice &S : AS) {
4134 if (!S.isSplittable())
4135 continue;
4136 // FIXME: We currently leave whole-alloca splittable loads and stores. This
4137 // used to be the only splittable loads and stores and we need to be
4138 // confident that the above handling of splittable loads and stores is
4139 // completely sufficient before we forcibly disable the remaining handling.
4140 if (S.beginOffset() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004141 S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
Chandler Carruth24ac8302015-01-02 03:55:54 +00004142 continue;
4143 if (isa<LoadInst>(S.getUse()->getUser()) ||
4144 isa<StoreInst>(S.getUse()->getUser())) {
4145 S.makeUnsplittable();
4146 IsSorted = false;
4147 }
4148 }
4149 if (!IsSorted)
4150 std::sort(AS.begin(), AS.end());
4151
Adrian Prantl565cc182015-01-20 19:42:22 +00004152 /// \brief Describes the allocas introduced by rewritePartition
4153 /// in order to migrate the debug info.
4154 struct Piece {
4155 AllocaInst *Alloca;
4156 uint64_t Offset;
4157 uint64_t Size;
4158 Piece(AllocaInst *AI, uint64_t O, uint64_t S)
4159 : Alloca(AI), Offset(O), Size(S) {}
4160 };
4161 SmallVector<Piece, 4> Pieces;
4162
Chandler Carruth0715cba2015-01-01 11:54:38 +00004163 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004164 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004165 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4166 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004167 if (NewAI != &AI) {
4168 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004169 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004170 // Don't include any padding.
4171 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4172 Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
4173 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004174 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004175 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004176 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004177
Chandler Carruth6c321c12013-07-19 10:57:36 +00004178 NumAllocaPartitions += NumPartitions;
4179 MaxPartitionsPerAlloca =
4180 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004181
Adrian Prantl565cc182015-01-20 19:42:22 +00004182 // Migrate debug information from the old alloca to the new alloca(s)
4183 // and the individial partitions.
4184 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
4185 DIVariable Var(DbgDecl->getVariable());
4186 DIExpression Expr(DbgDecl->getExpression());
4187 DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
4188 /*AllowUnresolved*/ false);
4189 bool IsSplit = Pieces.size() > 1;
4190 for (auto Piece : Pieces) {
4191 // Create a piece expression describing the new partition or reuse AI's
4192 // expression if there is only one partition.
Adrian Prantl152ac392015-02-01 00:58:04 +00004193 DIExpression PieceExpr = Expr;
Adrian Prantl27bd01f2015-02-09 23:57:15 +00004194 if (IsSplit || Expr.isBitPiece()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004195 // If this alloca is already a scalar replacement of a larger aggregate,
4196 // Piece.Offset describes the offset inside the scalar.
Adrian Prantl34e75902015-02-09 23:57:22 +00004197 uint64_t Offset = Expr.isBitPiece() ? Expr.getBitPieceOffset() : 0;
4198 uint64_t Start = Offset + Piece.Offset;
4199 uint64_t Size = Piece.Size;
4200 if (Expr.isBitPiece()) {
4201 uint64_t AbsEnd = Expr.getBitPieceOffset() + Expr.getBitPieceSize();
4202 if (Start >= AbsEnd)
4203 // No need to describe a SROAed padding.
4204 continue;
4205 Size = std::min(Size, AbsEnd - Start);
4206 }
4207 PieceExpr = DIB.createBitPieceExpression(Start, Size);
Adrian Prantl152ac392015-02-01 00:58:04 +00004208 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004209
4210 // Remove any existing dbg.declare intrinsic describing the same alloca.
4211 if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
4212 OldDDI->eraseFromParent();
4213
Adrian Prantl152ac392015-02-01 00:58:04 +00004214 auto *NewDDI = DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004215 NewDDI->setDebugLoc(DbgDecl->getDebugLoc());
4216 }
4217 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004218 return Changed;
4219}
4220
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004221/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4222void SROA::clobberUse(Use &U) {
4223 Value *OldV = U;
4224 // Replace the use with an undef value.
4225 U = UndefValue::get(OldV->getType());
4226
4227 // Check for this making an instruction dead. We have to garbage collect
4228 // all the dead instructions to ensure the uses of any alloca end up being
4229 // minimal.
4230 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4231 if (isInstructionTriviallyDead(OldI)) {
4232 DeadInsts.insert(OldI);
4233 }
4234}
4235
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004236/// \brief Analyze an alloca for SROA.
4237///
4238/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004239/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004240/// rewritten as needed.
4241bool SROA::runOnAlloca(AllocaInst &AI) {
4242 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4243 ++NumAllocasAnalyzed;
4244
4245 // Special case dead allocas, as they're trivial.
4246 if (AI.use_empty()) {
4247 AI.eraseFromParent();
4248 return true;
4249 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004250 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004251
4252 // Skip alloca forms that this analysis can't handle.
4253 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004254 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004255 return false;
4256
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004257 bool Changed = false;
4258
4259 // First, split any FCA loads and stores touching this alloca to promote
4260 // better splitting and promotion opportunities.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004261 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004262 Changed |= AggRewriter.rewrite(AI);
4263
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004264 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004265 AllocaSlices AS(DL, AI);
Chandler Carruth83934062014-10-16 21:11:55 +00004266 DEBUG(AS.print(dbgs()));
4267 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004268 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004269
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004270 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004271 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004272 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004273 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004274 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004275
4276 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004277 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004278
4279 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004280 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004281 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004282 }
Chandler Carruth83934062014-10-16 21:11:55 +00004283 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004284 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004285 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004286 }
4287
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004288 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004289 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004290 return Changed;
4291
Chandler Carruth83934062014-10-16 21:11:55 +00004292 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004293
4294 DEBUG(dbgs() << " Speculating PHIs\n");
4295 while (!SpeculatablePHIs.empty())
4296 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4297
4298 DEBUG(dbgs() << " Speculating Selects\n");
4299 while (!SpeculatableSelects.empty())
4300 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4301
4302 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004303}
4304
Chandler Carruth19450da2012-09-14 10:26:38 +00004305/// \brief Delete the dead instructions accumulated in this run.
4306///
4307/// Recursively deletes the dead instructions we've accumulated. This is done
4308/// at the very end to maximize locality of the recursive delete and to
4309/// minimize the problems of invalidated instruction pointers as such pointers
4310/// are used heavily in the intermediate stages of the algorithm.
4311///
4312/// We also record the alloca instructions deleted here so that they aren't
4313/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00004314void SROA::deleteDeadInstructions(
4315 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004316 while (!DeadInsts.empty()) {
4317 Instruction *I = DeadInsts.pop_back_val();
4318 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4319
Chandler Carruth58d05562012-10-25 04:37:07 +00004320 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4321
Chandler Carruth1583e992014-03-03 10:42:58 +00004322 for (Use &Operand : I->operands())
4323 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004324 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004325 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004326 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004327 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004328 }
4329
Adrian Prantl565cc182015-01-20 19:42:22 +00004330 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004331 DeletedAllocas.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004332 if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4333 DbgDecl->eraseFromParent();
4334 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004335
4336 ++NumDeleted;
4337 I->eraseFromParent();
4338 }
4339}
4340
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004341static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00004342 SmallVectorImpl<Instruction *> &Worklist,
Craig Topper71b7b682014-08-21 05:55:13 +00004343 SmallPtrSetImpl<Instruction *> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004344 for (User *U : I.users())
David Blaikie70573dc2014-11-19 07:49:26 +00004345 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00004346 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004347}
4348
Chandler Carruth70b44c52012-09-15 11:43:14 +00004349/// \brief Promote the allocas, using the best available technique.
4350///
4351/// This attempts to promote whatever allocas have been identified as viable in
4352/// the PromotableAllocas list. If that list is empty, there is nothing to do.
4353/// If there is a domtree available, we attempt to promote using the full power
4354/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
4355/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004356/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004357bool SROA::promoteAllocas(Function &F) {
4358 if (PromotableAllocas.empty())
4359 return false;
4360
4361 NumPromoted += PromotableAllocas.size();
4362
4363 if (DT && !ForceSSAUpdater) {
4364 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Chandler Carruth66b31302015-01-04 12:03:27 +00004365 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004366 PromotableAllocas.clear();
4367 return true;
4368 }
4369
4370 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
4371 SSAUpdater SSA;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004372 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Chandler Carruth45b136f2013-08-11 01:03:18 +00004373 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00004374
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004375 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00004376 SmallVector<Instruction *, 8> Worklist;
4377 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004378 SmallVector<Instruction *, 32> DeadInsts;
4379
Chandler Carruth70b44c52012-09-15 11:43:14 +00004380 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
4381 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00004382 Insts.clear();
4383 Worklist.clear();
4384 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004385
Chandler Carruth45b136f2013-08-11 01:03:18 +00004386 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004387
Chandler Carruth45b136f2013-08-11 01:03:18 +00004388 while (!Worklist.empty()) {
4389 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004390
Chandler Carruth70b44c52012-09-15 11:43:14 +00004391 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
4392 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
4393 // leading to them) here. Eventually it should use them to optimize the
4394 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00004395 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00004396 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
4397 II->getIntrinsicID() == Intrinsic::lifetime_end);
4398 II->eraseFromParent();
4399 continue;
4400 }
4401
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004402 // Push the loads and stores we find onto the list. SROA will already
4403 // have validated that all loads and stores are viable candidates for
4404 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00004405 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004406 assert(LI->getType() == AI->getAllocatedType());
4407 Insts.push_back(LI);
4408 continue;
4409 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00004410 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004411 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
4412 Insts.push_back(SI);
4413 continue;
4414 }
4415
4416 // For everything else, we know that only no-op bitcasts and GEPs will
4417 // make it this far, just recurse through them and recall them for later
4418 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00004419 DeadInsts.push_back(I);
4420 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004421 }
4422 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00004423 while (!DeadInsts.empty())
4424 DeadInsts.pop_back_val()->eraseFromParent();
4425 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00004426 }
4427
4428 PromotableAllocas.clear();
4429 return true;
4430}
4431
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004432bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00004433 if (skipOptnoneFunction(F))
4434 return false;
4435
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004436 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4437 C = &F.getContext();
Chandler Carruth73523022014-01-13 13:07:17 +00004438 DominatorTreeWrapperPass *DTWP =
4439 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00004440 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chandler Carruth66b31302015-01-04 12:03:27 +00004441 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004442
4443 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004444 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004445 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004446 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4447 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004448 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004449
4450 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004451 // A set of deleted alloca instruction pointers which should be removed from
4452 // the list of promotable allocas.
4453 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4454
Chandler Carruthac8317f2012-10-04 12:33:50 +00004455 do {
4456 while (!Worklist.empty()) {
4457 Changed |= runOnAlloca(*Worklist.pop_back_val());
4458 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004459
Chandler Carruthac8317f2012-10-04 12:33:50 +00004460 // Remove the deleted allocas from various lists so that we don't try to
4461 // continue processing them.
4462 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004463 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004464 Worklist.remove_if(IsInSet);
4465 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00004466 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4467 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004468 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004469 PromotableAllocas.end());
4470 DeletedAllocas.clear();
4471 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004472 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004473
Chandler Carruthac8317f2012-10-04 12:33:50 +00004474 Changed |= promoteAllocas(F);
4475
4476 Worklist = PostPromotionWorklist;
4477 PostPromotionWorklist.clear();
4478 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004479
4480 return Changed;
4481}
4482
4483void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth66b31302015-01-04 12:03:27 +00004484 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth70b44c52012-09-15 11:43:14 +00004485 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00004486 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004487 AU.setPreservesCFG();
4488}