blob: 688755f0704be82d88aedbbd1cf083c1610ea582 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth1b398ae2012-09-14 09:22:59 +000026#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Hal Finkel60db0582014-09-07 18:57:58 +000031#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000033#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000036#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000043#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Operator.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000050#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000054#include "llvm/Support/TimeValue.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000056#include "llvm/Transforms/Utils/Local.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include "llvm/Transforms/Utils/SSAUpdater.h"
Chandler Carruth83cee772014-02-25 03:59:29 +000059
60#if __cplusplus >= 201103L && !defined(NDEBUG)
61// We only use this for a debug check in C++11
62#include <random>
63#endif
64
Chandler Carruth1b398ae2012-09-14 09:22:59 +000065using namespace llvm;
66
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "sroa"
68
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000070STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +000071STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000074STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000076STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000077STATISTIC(NumDeleted, "Number of instructions deleted");
78STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079
Chandler Carruth70b44c52012-09-15 11:43:14 +000080/// Hidden option to force the pass to not use DomTree and mem2reg, instead
81/// forming SSA values through the SSAUpdater infrastructure.
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 Carruthe2f66ce2014-12-22 22:46:00 +0000240 // Forward declare an iterator to befriend it.
241 class partition_iterator;
242
243 /// \brief A partition of the slices.
244 ///
245 /// An ephemeral representation for a range of slices which can be viewed as
246 /// a partition of the alloca. This range represents a span of the alloca's
247 /// memory which cannot be split, and provides access to all of the slices
248 /// overlapping some part of the partition.
249 ///
250 /// Objects of this type are produced by traversing the alloca's slices, but
251 /// are only ephemeral and not persistent.
252 class Partition {
253 private:
254 friend class AllocaSlices;
255 friend class AllocaSlices::partition_iterator;
256
257 /// \brief The begining and ending offsets of the alloca for this partition.
258 uint64_t BeginOffset, EndOffset;
259
260 /// \brief The start end end iterators of this partition.
261 iterator SI, SJ;
262
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000263 /// \brief A collection of split slice tails overlapping the partition.
264 SmallVector<Slice *, 4> SplitTails;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000265
266 /// \brief Raw constructor builds an empty partition starting and ending at
267 /// the given iterator.
268 Partition(iterator SI) : SI(SI), SJ(SI) {}
269
270 public:
271 /// \brief The start offset of this partition.
272 ///
273 /// All of the contained slices start at or after this offset.
274 uint64_t beginOffset() const { return BeginOffset; }
275
276 /// \brief The end offset of this partition.
277 ///
278 /// All of the contained slices end at or before this offset.
279 uint64_t endOffset() const { return EndOffset; }
280
281 /// \brief The size of the partition.
282 ///
283 /// Note that this can never be zero.
284 uint64_t size() const {
285 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
286 return EndOffset - BeginOffset;
287 }
288
289 /// \brief Test whether this partition contains no slices, and merely spans
290 /// a region occupied by split slices.
291 bool empty() const { return SI == SJ; }
292
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000293 /// \name Iterate slices that start within the partition.
294 /// These may be splittable or unsplittable. They have a begin offset >= the
295 /// partition begin offset.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000296 /// @{
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000297 // FIXME: We should probably define a "concat_iterator" helper and use that
298 // to stitch together pointee_iterators over the split tails and the
299 // contiguous iterators of the partition. That would give a much nicer
300 // interface here. We could then additionally expose filtered iterators for
301 // split, unsplit, and unsplittable splices based on the usage patterns.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000302 iterator begin() const { return SI; }
303 iterator end() const { return SJ; }
304 /// @}
305
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000306 /// \brief Get the sequence of split slice tails.
307 ///
308 /// These tails are of slices which start before this partition but are
309 /// split and overlap into the partition. We accumulate these while forming
310 /// partitions.
311 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000312 };
313
314 /// \brief An iterator over partitions of the alloca's slices.
315 ///
316 /// This iterator implements the core algorithm for partitioning the alloca's
317 /// slices. It is a forward iterator as we don't support backtracking for
318 /// efficiency reasons, and re-use a single storage area to maintain the
319 /// current set of split slices.
320 ///
321 /// It is templated on the slice iterator type to use so that it can operate
322 /// with either const or non-const slice iterators.
323 class partition_iterator
324 : public iterator_facade_base<partition_iterator,
325 std::forward_iterator_tag, Partition> {
326 friend class AllocaSlices;
327
328 /// \brief Most of the state for walking the partitions is held in a class
329 /// with a nice interface for examining them.
330 Partition P;
331
332 /// \brief We need to keep the end of the slices to know when to stop.
333 AllocaSlices::iterator SE;
334
335 /// \brief We also need to keep track of the maximum split end offset seen.
336 /// FIXME: Do we really?
337 uint64_t MaxSplitSliceEndOffset;
338
339 /// \brief Sets the partition to be empty at given iterator, and sets the
340 /// end iterator.
341 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
342 : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
343 // If not already at the end, advance our state to form the initial
344 // partition.
345 if (SI != SE)
346 advance();
347 }
348
349 /// \brief Advance the iterator to the next partition.
350 ///
351 /// Requires that the iterator not be at the end of the slices.
352 void advance() {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000353 assert((P.SI != SE || !P.SplitTails.empty()) &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000354 "Cannot advance past the end of the slices!");
355
356 // Clear out any split uses which have ended.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000357 if (!P.SplitTails.empty()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000358 if (P.EndOffset >= MaxSplitSliceEndOffset) {
359 // If we've finished all splits, this is easy.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000360 P.SplitTails.clear();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000361 MaxSplitSliceEndOffset = 0;
362 } else {
363 // Remove the uses which have ended in the prior partition. This
364 // cannot change the max split slice end because we just checked that
365 // the prior partition ended prior to that max.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000366 P.SplitTails.erase(
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000367 std::remove_if(
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000368 P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000369 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000370 P.SplitTails.end());
371 assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000372 [&](Slice *S) {
373 return S->endOffset() == MaxSplitSliceEndOffset;
374 }) &&
375 "Could not find the current max split slice offset!");
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000376 assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000377 [&](Slice *S) {
378 return S->endOffset() <= MaxSplitSliceEndOffset;
379 }) &&
380 "Max split slice end offset is not actually the max!");
381 }
382 }
383
384 // If P.SI is already at the end, then we've cleared the split tail and
385 // now have an end iterator.
386 if (P.SI == SE) {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000387 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000388 return;
389 }
390
391 // If we had a non-empty partition previously, set up the state for
392 // subsequent partitions.
393 if (P.SI != P.SJ) {
394 // Accumulate all the splittable slices which started in the old
395 // partition into the split list.
396 for (Slice &S : P)
397 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000398 P.SplitTails.push_back(&S);
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000399 MaxSplitSliceEndOffset =
400 std::max(S.endOffset(), MaxSplitSliceEndOffset);
401 }
402
403 // Start from the end of the previous partition.
404 P.SI = P.SJ;
405
406 // If P.SI is now at the end, we at most have a tail of split slices.
407 if (P.SI == SE) {
408 P.BeginOffset = P.EndOffset;
409 P.EndOffset = MaxSplitSliceEndOffset;
410 return;
411 }
412
413 // If the we have split slices and the next slice is after a gap and is
414 // not splittable immediately form an empty partition for the split
415 // slices up until the next slice begins.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000416 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000417 !P.SI->isSplittable()) {
418 P.BeginOffset = P.EndOffset;
419 P.EndOffset = P.SI->beginOffset();
420 return;
421 }
422 }
423
424 // OK, we need to consume new slices. Set the end offset based on the
425 // current slice, and step SJ past it. The beginning offset of the
426 // parttion is the beginning offset of the next slice unless we have
427 // pre-existing split slices that are continuing, in which case we begin
428 // at the prior end offset.
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000429 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000430 P.EndOffset = P.SI->endOffset();
431 ++P.SJ;
432
433 // There are two strategies to form a partition based on whether the
434 // partition starts with an unsplittable slice or a splittable slice.
435 if (!P.SI->isSplittable()) {
436 // When we're forming an unsplittable region, it must always start at
437 // the first slice and will extend through its end.
438 assert(P.BeginOffset == P.SI->beginOffset());
439
440 // Form a partition including all of the overlapping slices with this
441 // unsplittable slice.
442 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
443 if (!P.SJ->isSplittable())
444 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
445 ++P.SJ;
446 }
447
448 // We have a partition across a set of overlapping unsplittable
449 // partitions.
450 return;
451 }
452
453 // If we're starting with a splittable slice, then we need to form
454 // a synthetic partition spanning it and any other overlapping splittable
455 // splices.
456 assert(P.SI->isSplittable() && "Forming a splittable partition!");
457
458 // Collect all of the overlapping splittable slices.
459 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
460 P.SJ->isSplittable()) {
461 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
462 ++P.SJ;
463 }
464
465 // Back upiP.EndOffset if we ended the span early when encountering an
466 // unsplittable slice. This synthesizes the early end offset of
467 // a partition spanning only splittable slices.
468 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
469 assert(!P.SJ->isSplittable());
470 P.EndOffset = P.SJ->beginOffset();
471 }
472 }
473
474 public:
475 bool operator==(const partition_iterator &RHS) const {
476 assert(SE == RHS.SE &&
477 "End iterators don't match between compared partition iterators!");
478
479 // The observed positions of partitions is marked by the P.SI iterator and
480 // the emptyness of the split slices. The latter is only relevant when
481 // P.SI == SE, as the end iterator will additionally have an empty split
482 // slices list, but the prior may have the same P.SI and a tail of split
483 // slices.
484 if (P.SI == RHS.P.SI &&
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000485 P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000486 assert(P.SJ == RHS.P.SJ &&
487 "Same set of slices formed two different sized partitions!");
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000488 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000489 "Same slice position with differently sized non-empty split "
Chandler Carruthffb7ce52014-12-24 01:48:09 +0000490 "slice tails!");
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000491 return true;
492 }
493 return false;
494 }
495
496 partition_iterator &operator++() {
497 advance();
498 return *this;
499 }
500
501 Partition &operator*() { return P; }
502 };
503
504 /// \brief A forward range over the partitions of the alloca's slices.
505 ///
506 /// This accesses an iterator range over the partitions of the alloca's
507 /// slices. It computes these partitions on the fly based on the overlapping
508 /// offsets of the slices and the ability to split them. It will visit "empty"
509 /// partitions to cover regions of the alloca only accessed via split
510 /// slices.
511 iterator_range<partition_iterator> partitions() {
512 return make_range(partition_iterator(begin(), end()),
513 partition_iterator(end(), end()));
514 }
515
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000516 /// \brief Access the dead users for this alloca.
517 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000518
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000519 /// \brief Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000520 ///
521 /// These are operands which have cannot actually be used to refer to the
522 /// alloca as they are outside its range and the user doesn't correct for
523 /// that. These mostly consist of PHI node inputs and the like which we just
524 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000525 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000526
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000527#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000528 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000529 void printSlice(raw_ostream &OS, const_iterator I,
530 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000531 void printUse(raw_ostream &OS, const_iterator I,
532 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000533 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000534 void dump(const_iterator I) const;
535 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000536#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000537
538private:
539 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000540 class SliceBuilder;
541 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000542
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000543#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000544 /// \brief Handle to alloca instruction to simplify method interfaces.
545 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000546#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000547
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000548 /// \brief The instruction responsible for this alloca not having a known set
549 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000550 ///
551 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000552 /// store a pointer to that here and abort trying to form slices of the
553 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000554 Instruction *PointerEscapingInstr;
555
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000556 /// \brief The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000557 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000558 /// We store a vector of the slices formed by uses of the alloca here. This
559 /// vector is sorted by increasing begin offset, and then the unsplittable
560 /// slices before the splittable ones. See the Slice inner class for more
561 /// details.
562 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000563
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000564 /// \brief Instructions which will become dead if we rewrite the alloca.
565 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000566 /// Note that these are not separated by slice. This is because we expect an
567 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
568 /// all these instructions can simply be removed and replaced with undef as
569 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000570 SmallVector<Instruction *, 8> DeadUsers;
571
572 /// \brief Operands which will become dead if we rewrite the alloca.
573 ///
574 /// These are operands that in their particular use can be replaced with
575 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
576 /// to PHI nodes and the like. They aren't entirely dead (there might be
577 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
578 /// want to swap this particular input for undef to simplify the use lists of
579 /// the alloca.
580 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000581};
582}
583
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000584static Value *foldSelectInst(SelectInst &SI) {
585 // If the condition being selected on is a constant or the same value is
586 // being selected between, fold the select. Yes this does (rarely) happen
587 // early on.
588 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000589 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000590 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000591 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000592
Craig Topperf40110f2014-04-25 05:29:35 +0000593 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000594}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000595
Jingyue Wuec33fa92014-08-22 22:45:57 +0000596/// \brief A helper that folds a PHI node or a select.
597static Value *foldPHINodeOrSelectInst(Instruction &I) {
598 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
599 // If PN merges together the same value, return that value.
600 return PN->hasConstantValue();
601 }
602 return foldSelectInst(cast<SelectInst>(I));
603}
604
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000605/// \brief Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000606///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000607/// This class builds a set of alloca slices by recursively visiting the uses
608/// of an alloca and making a slice for each load and store at each offset.
609class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
610 friend class PtrUseVisitor<SliceBuilder>;
611 friend class InstVisitor<SliceBuilder>;
612 typedef PtrUseVisitor<SliceBuilder> Base;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000613
614 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000615 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000616
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000617 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000618 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
619
620 /// \brief Set to de-duplicate dead instructions found in the use walk.
621 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000622
623public:
Chandler Carruth83934062014-10-16 21:11:55 +0000624 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000625 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000626 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000627
628private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000629 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000630 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000631 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000632 }
633
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000634 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000635 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000636 // Completely skip uses which have a zero size or start either before or
637 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000638 if (Size == 0 || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000639 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000640 << " which has zero size or starts outside of the "
641 << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000642 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000643 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000644 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000645 }
646
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000647 uint64_t BeginOffset = Offset.getZExtValue();
648 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000649
650 // Clamp the end offset to the end of the allocation. Note that this is
651 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000652 // This may appear superficially to be something we could ignore entirely,
653 // but that is not so! There may be widened loads or PHI-node uses where
654 // some instructions are dead but not others. We can't completely ignore
655 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000656 assert(AllocSize >= BeginOffset); // Established above.
657 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000658 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
659 << " to remain within the " << AllocSize << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000660 << " alloca: " << AS.AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661 << " use: " << I << "\n");
662 EndOffset = AllocSize;
663 }
664
Chandler Carruth83934062014-10-16 21:11:55 +0000665 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000666 }
667
668 void visitBitCastInst(BitCastInst &BC) {
669 if (BC.use_empty())
670 return markAsDead(BC);
671
672 return Base::visitBitCastInst(BC);
673 }
674
675 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
676 if (GEPI.use_empty())
677 return markAsDead(GEPI);
678
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000679 if (SROAStrictInbounds && GEPI.isInBounds()) {
680 // FIXME: This is a manually un-factored variant of the basic code inside
681 // of GEPs with checking of the inbounds invariant specified in the
682 // langref in a very strict sense. If we ever want to enable
683 // SROAStrictInbounds, this code should be factored cleanly into
684 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
685 // by writing out the code here where we have tho underlying allocation
686 // size readily available.
687 APInt GEPOffset = Offset;
688 for (gep_type_iterator GTI = gep_type_begin(GEPI),
689 GTE = gep_type_end(GEPI);
690 GTI != GTE; ++GTI) {
691 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
692 if (!OpC)
693 break;
694
695 // Handle a struct index, which adds its field offset to the pointer.
696 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
697 unsigned ElementIdx = OpC->getZExtValue();
698 const StructLayout *SL = DL.getStructLayout(STy);
699 GEPOffset +=
700 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
701 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000702 // For array or vector indices, scale the index by the size of the
703 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000704 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
705 GEPOffset += Index * APInt(Offset.getBitWidth(),
706 DL.getTypeAllocSize(GTI.getIndexedType()));
707 }
708
709 // If this index has computed an intermediate pointer which is not
710 // inbounds, then the result of the GEP is a poison value and we can
711 // delete it and all uses.
712 if (GEPOffset.ugt(AllocSize))
713 return markAsDead(GEPI);
714 }
715 }
716
Chandler Carruthf0546402013-07-18 07:15:00 +0000717 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000718 }
719
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000720 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000721 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000722 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000723 // and cover the entire alloca. This prevents us from splitting over
724 // eagerly.
725 // FIXME: In the great blue eventually, we should eagerly split all integer
726 // loads and stores, and then have a separate step that merges adjacent
727 // alloca partitions into a single partition suitable for integer widening.
728 // Or we should skip the merge step and rely on GVN and other passes to
729 // merge adjacent loads and stores that survive mem2reg.
730 bool IsSplittable =
731 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000732
733 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000734 }
735
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000736 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000737 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
738 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000739
740 if (!IsOffsetKnown)
741 return PI.setAborted(&LI);
742
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000743 uint64_t Size = DL.getTypeStoreSize(LI.getType());
744 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000745 }
746
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000747 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000748 Value *ValOp = SI.getValueOperand();
749 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000750 return PI.setEscapedAndAborted(&SI);
751 if (!IsOffsetKnown)
752 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000753
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000754 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
755
756 // If this memory access can be shown to *statically* extend outside the
757 // bounds of of the allocation, it's behavior is undefined, so simply
758 // ignore it. Note that this is more strict than the generic clamping
759 // behavior of insertUse. We also try to handle cases which might run the
760 // risk of overflow.
761 // FIXME: We should instead consider the pointer to have escaped if this
762 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000763 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000764 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
765 << " which extends past the end of the " << AllocSize
766 << " byte alloca:\n"
Chandler Carruth83934062014-10-16 21:11:55 +0000767 << " alloca: " << AS.AI << "\n"
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000768 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000769 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000770 }
771
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000772 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
773 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000774 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000775 }
776
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000777 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000778 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000779 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000780 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000781 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000782 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000783 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000784
785 if (!IsOffsetKnown)
786 return PI.setAborted(&II);
787
Chandler Carruth113dc642014-12-20 02:39:18 +0000788 insertUse(II, Offset, Length ? Length->getLimitedValue()
789 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000790 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000791 }
792
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000793 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000794 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000795 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000796 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000797 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000798
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000799 // Because we can visit these intrinsics twice, also check to see if the
800 // first time marked this instruction as dead. If so, skip it.
801 if (VisitedDeadInsts.count(&II))
802 return;
803
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000804 if (!IsOffsetKnown)
805 return PI.setAborted(&II);
806
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000807 // This side of the transfer is completely out-of-bounds, and so we can
808 // nuke the entire transfer. However, we also need to nuke the other side
809 // if already added to our partitions.
810 // FIXME: Yet another place we really should bypass this when
811 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000812 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000813 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
814 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000815 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000816 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000817 return markAsDead(II);
818 }
819
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000820 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000821 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000822
Chandler Carruthf0546402013-07-18 07:15:00 +0000823 // Check for the special case where the same exact value is used for both
824 // source and dest.
825 if (*U == II.getRawDest() && *U == II.getRawSource()) {
826 // For non-volatile transfers this is a no-op.
827 if (!II.isVolatile())
828 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000830 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000831 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000832
Chandler Carruthf0546402013-07-18 07:15:00 +0000833 // If we have seen both source and destination for a mem transfer, then
834 // they both point to the same alloca.
835 bool Inserted;
836 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000837 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000838 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000839 unsigned PrevIdx = MTPI->second;
840 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000841 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000842
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000843 // Check if the begin offsets match and this is a non-volatile transfer.
844 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000845 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
846 PrevP.kill();
847 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000848 }
849
850 // Otherwise we have an offset transfer within the same alloca. We can't
851 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000852 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000853 }
854
Chandler Carruthe3899f22013-07-15 17:36:21 +0000855 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000856 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000857
Chandler Carruthf0546402013-07-18 07:15:00 +0000858 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000859 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000860 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000861 }
862
863 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000864 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000865 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000866 void visitIntrinsicInst(IntrinsicInst &II) {
867 if (!IsOffsetKnown)
868 return PI.setAborted(&II);
869
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000870 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
871 II.getIntrinsicID() == Intrinsic::lifetime_end) {
872 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000873 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
874 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000875 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000876 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000877 }
878
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000879 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000880 }
881
882 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
883 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000884 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000885 // are considered unsplittable and the size is the maximum loaded or stored
886 // size.
887 SmallPtrSet<Instruction *, 4> Visited;
888 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
889 Visited.insert(Root);
890 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000891 // If there are no loads or stores, the access is dead. We mark that as
892 // a size zero access.
893 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000894 do {
895 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000896 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000897
898 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000899 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000900 continue;
901 }
902 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
903 Value *Op = SI->getOperand(0);
904 if (Op == UsedI)
905 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000906 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000907 continue;
908 }
909
910 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
911 if (!GEP->hasAllZeroIndices())
912 return GEP;
913 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
914 !isa<SelectInst>(I)) {
915 return I;
916 }
917
Chandler Carruthcdf47882014-03-09 03:16:01 +0000918 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000919 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000920 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000921 } while (!Uses.empty());
922
Craig Topperf40110f2014-04-25 05:29:35 +0000923 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000924 }
925
Jingyue Wuec33fa92014-08-22 22:45:57 +0000926 void visitPHINodeOrSelectInst(Instruction &I) {
927 assert(isa<PHINode>(I) || isa<SelectInst>(I));
928 if (I.use_empty())
929 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000930
Jingyue Wuec33fa92014-08-22 22:45:57 +0000931 // TODO: We could use SimplifyInstruction here to fold PHINodes and
932 // SelectInsts. However, doing so requires to change the current
933 // dead-operand-tracking mechanism. For instance, suppose neither loading
934 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
935 // trap either. However, if we simply replace %U with undef using the
936 // current dead-operand-tracking mechanism, "load (select undef, undef,
937 // %other)" may trap because the select may return the first operand
938 // "undef".
939 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000940 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000941 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000942 // through the PHI/select as if we had RAUW'ed it.
943 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000944 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000945 // Otherwise the operand to the PHI/select is dead, and we can replace
946 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000947 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000948
949 return;
950 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000951
Chandler Carruthf0546402013-07-18 07:15:00 +0000952 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000953 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000954
Chandler Carruthf0546402013-07-18 07:15:00 +0000955 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000956 uint64_t &Size = PHIOrSelectSizes[&I];
957 if (!Size) {
958 // This is a new PHI/Select, check for an unsafe use of it.
959 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000960 return PI.setAborted(UnsafeI);
961 }
962
963 // For PHI and select operands outside the alloca, we can't nuke the entire
964 // phi or select -- the other side might still be relevant, so we special
965 // case them here and use a separate structure to track the operands
966 // themselves which should be replaced with undef.
967 // FIXME: This should instead be escaped in the event we're instrumenting
968 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000969 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +0000970 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +0000971 return;
972 }
973
Jingyue Wuec33fa92014-08-22 22:45:57 +0000974 insertUse(I, Offset, Size);
975 }
976
Chandler Carruth113dc642014-12-20 02:39:18 +0000977 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000978
Chandler Carruth113dc642014-12-20 02:39:18 +0000979 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000980
Chandler Carruthf0546402013-07-18 07:15:00 +0000981 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +0000982 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000983};
984
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000985AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000986 :
987#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
988 AI(AI),
989#endif
Craig Topperf40110f2014-04-25 05:29:35 +0000990 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000991 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000992 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000993 if (PtrI.isEscaped() || PtrI.isAborted()) {
994 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000995 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000996 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
997 : PtrI.getAbortingInst();
998 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000999 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001000 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001001
Benjamin Kramer08e50702013-07-20 08:38:34 +00001002 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
Chandler Carruth68ea4152014-12-18 05:19:47 +00001003 [](const Slice &S) {
1004 return S.isDead();
1005 }),
Benjamin Kramer08e50702013-07-20 08:38:34 +00001006 Slices.end());
1007
Chandler Carruth83cee772014-02-25 03:59:29 +00001008#if __cplusplus >= 201103L && !defined(NDEBUG)
1009 if (SROARandomShuffleSlices) {
1010 std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1011 std::shuffle(Slices.begin(), Slices.end(), MT);
1012 }
1013#endif
1014
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001015 // Sort the uses. This arranges for the offsets to be in ascending order,
1016 // and the sizes to be in descending order.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001017 std::sort(Slices.begin(), Slices.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001018}
1019
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001020#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1021
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001022void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1023 StringRef Indent) const {
1024 printSlice(OS, I, Indent);
Chandler Carruthf0546402013-07-18 07:15:00 +00001025 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001026}
1027
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001028void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1029 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001030 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001031 << " slice #" << (I - begin())
Chandler Carruthf0546402013-07-18 07:15:00 +00001032 << (I->isSplittable() ? " (splittable)" : "") << "\n";
1033}
1034
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001035void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1036 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001037 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001038}
1039
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001040void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001041 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001042 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001043 << " A pointer to this alloca escaped by:\n"
1044 << " " << *PointerEscapingInstr << "\n";
1045 return;
1046 }
1047
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001048 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001049 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001050 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001051}
1052
Alp Tokerf929e092014-01-04 22:47:48 +00001053LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1054 print(dbgs(), I);
1055}
1056LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001057
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001058#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1059
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001060namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001061/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1062///
1063/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1064/// the loads and stores of an alloca instruction, as well as updating its
1065/// debug information. This is used when a domtree is unavailable and thus
1066/// mem2reg in its full form can't be used to handle promotion of allocas to
1067/// scalar values.
1068class AllocaPromoter : public LoadAndStorePromoter {
1069 AllocaInst &AI;
1070 DIBuilder &DIB;
1071
1072 SmallVector<DbgDeclareInst *, 4> DDIs;
1073 SmallVector<DbgValueInst *, 4> DVIs;
1074
1075public:
Chandler Carruth45b136f2013-08-11 01:03:18 +00001076 AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
Chandler Carruth70b44c52012-09-15 11:43:14 +00001077 AllocaInst &AI, DIBuilder &DIB)
Chandler Carruth45b136f2013-08-11 01:03:18 +00001078 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
Chandler Carruth70b44c52012-09-15 11:43:14 +00001079
Chandler Carruth113dc642014-12-20 02:39:18 +00001080 void run(const SmallVectorImpl<Instruction *> &Insts) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00001081 // Retain the debug information attached to the alloca for use when
1082 // rewriting loads and stores.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001083 if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
1084 if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
1085 for (User *U : DebugNode->users())
1086 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1087 DDIs.push_back(DDI);
1088 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1089 DVIs.push_back(DVI);
1090 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00001091 }
1092
1093 LoadAndStorePromoter::run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00001094
1095 // While we have the debug information, clear it off of the alloca. The
1096 // caller takes care of deleting the alloca.
Chandler Carruth70b44c52012-09-15 11:43:14 +00001097 while (!DDIs.empty())
1098 DDIs.pop_back_val()->eraseFromParent();
1099 while (!DVIs.empty())
1100 DVIs.pop_back_val()->eraseFromParent();
1101 }
1102
Chandler Carruth113dc642014-12-20 02:39:18 +00001103 bool
1104 isInstInList(Instruction *I,
1105 const SmallVectorImpl<Instruction *> &Insts) const override {
Chandler Carruthc17283b2013-08-11 01:56:15 +00001106 Value *Ptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001107 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Chandler Carruthc17283b2013-08-11 01:56:15 +00001108 Ptr = LI->getOperand(0);
1109 else
1110 Ptr = cast<StoreInst>(I)->getPointerOperand();
1111
1112 // Only used to detect cycles, which will be rare and quickly found as
1113 // we're walking up a chain of defs rather than down through uses.
1114 SmallPtrSet<Value *, 4> Visited;
1115
1116 do {
1117 if (Ptr == &AI)
1118 return true;
1119
1120 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
1121 Ptr = BCI->getOperand(0);
1122 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1123 Ptr = GEPI->getPointerOperand();
1124 else
1125 return false;
1126
David Blaikie70573dc2014-11-19 07:49:26 +00001127 } while (Visited.insert(Ptr).second);
Chandler Carruthc17283b2013-08-11 01:56:15 +00001128
1129 return false;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001130 }
1131
Craig Topper3e4c6972014-03-05 09:10:37 +00001132 void updateDebugInfo(Instruction *Inst) const override {
Chandler Carruth61747042014-10-16 21:05:14 +00001133 for (DbgDeclareInst *DDI : DDIs)
Chandler Carruth70b44c52012-09-15 11:43:14 +00001134 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1135 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1136 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1137 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
Chandler Carruth61747042014-10-16 21:05:14 +00001138 for (DbgValueInst *DVI : DVIs) {
Craig Topperf40110f2014-04-25 05:29:35 +00001139 Value *Arg = nullptr;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001140 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1141 // If an argument is zero extended then use argument directly. The ZExt
1142 // may be zapped by an optimization pass in future.
1143 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1144 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001145 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +00001146 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1147 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001148 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001149 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001150 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001151 } else {
1152 continue;
1153 }
1154 Instruction *DbgVal =
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001155 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1156 DIExpression(DVI->getExpression()), Inst);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001157 DbgVal->setDebugLoc(DVI->getDebugLoc());
1158 }
1159 }
1160};
1161} // end anon namespace
1162
Chandler Carruth70b44c52012-09-15 11:43:14 +00001163namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001164/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1165///
1166/// This pass takes allocations which can be completely analyzed (that is, they
1167/// don't escape) and tries to turn them into scalar SSA values. There are
1168/// a few steps to this process.
1169///
1170/// 1) It takes allocations of aggregates and analyzes the ways in which they
1171/// are used to try to split them into smaller allocations, ideally of
1172/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001173/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001174/// 2) It will transform accesses into forms which are suitable for SSA value
1175/// promotion. This can be replacing a memset with a scalar store of an
1176/// integer value, or it can involve speculating operations on a PHI or
1177/// select to be a PHI or select of the results.
1178/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1179/// onto insert and extract operations on a vector value, and convert them to
1180/// this form. By doing so, it will enable promotion of vector aggregates to
1181/// SSA vector values.
1182class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001183 const bool RequiresDomTree;
1184
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001185 LLVMContext *C;
Chandler Carruth90a735d2013-07-19 07:21:28 +00001186 const DataLayout *DL;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001187 DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +00001188 AssumptionTracker *AT;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001189
1190 /// \brief Worklist of alloca instructions to simplify.
1191 ///
1192 /// Each alloca in the function is added to this. Each new alloca formed gets
1193 /// added to it as well to recursively simplify unless that alloca can be
1194 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1195 /// the one being actively rewritten, we add it back onto the list if not
1196 /// already present to ensure it is re-visited.
Chandler Carruth113dc642014-12-20 02:39:18 +00001197 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001198
1199 /// \brief A collection of instructions to delete.
1200 /// We try to batch deletions to simplify code and make things a bit more
1201 /// efficient.
Chandler Carruth113dc642014-12-20 02:39:18 +00001202 SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001203
Chandler Carruthac8317f2012-10-04 12:33:50 +00001204 /// \brief Post-promotion worklist.
1205 ///
1206 /// Sometimes we discover an alloca which has a high probability of becoming
1207 /// viable for SROA after a round of promotion takes place. In those cases,
1208 /// the alloca is enqueued here for re-processing.
1209 ///
1210 /// Note that we have to be very careful to clear allocas out of this list in
1211 /// the event they are deleted.
Chandler Carruth113dc642014-12-20 02:39:18 +00001212 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
Chandler Carruthac8317f2012-10-04 12:33:50 +00001213
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001214 /// \brief A collection of alloca instructions we can directly promote.
1215 std::vector<AllocaInst *> PromotableAllocas;
1216
Chandler Carruthf0546402013-07-18 07:15:00 +00001217 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
1218 ///
1219 /// All of these PHIs have been checked for the safety of speculation and by
1220 /// being speculated will allow promoting allocas currently in the promotable
1221 /// queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001222 SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
Chandler Carruthf0546402013-07-18 07:15:00 +00001223
1224 /// \brief A worklist of select instructions to speculate prior to promoting
1225 /// allocas.
1226 ///
1227 /// All of these select instructions have been checked for the safety of
1228 /// speculation and by being speculated will allow promoting allocas
1229 /// currently in the promotable queue.
Chandler Carruth113dc642014-12-20 02:39:18 +00001230 SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
Chandler Carruthf0546402013-07-18 07:15:00 +00001231
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001232public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001233 SROA(bool RequiresDomTree = true)
Chandler Carruth113dc642014-12-20 02:39:18 +00001234 : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
1235 DL(nullptr), DT(nullptr) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001236 initializeSROAPass(*PassRegistry::getPassRegistry());
1237 }
Craig Topper3e4c6972014-03-05 09:10:37 +00001238 bool runOnFunction(Function &F) override;
1239 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001240
Craig Topper3e4c6972014-03-05 09:10:37 +00001241 const char *getPassName() const override { return "SROA"; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001242 static char ID;
1243
1244private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001245 friend class PHIOrSelectSpeculator;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001246 friend class AllocaSliceRewriter;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001247
Chandler Carruth83934062014-10-16 21:11:55 +00001248 bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00001249 AllocaSlices::Partition &P);
Chandler Carruth83934062014-10-16 21:11:55 +00001250 bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001251 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00001252 void clobberUse(Use &U);
Craig Topper71b7b682014-08-21 05:55:13 +00001253 void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001254 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001255};
1256}
1257
1258char SROA::ID = 0;
1259
Chandler Carruth70b44c52012-09-15 11:43:14 +00001260FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1261 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001262}
1263
Chandler Carruth113dc642014-12-20 02:39:18 +00001264INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1265 false)
Hal Finkel60db0582014-09-07 18:57:58 +00001266INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chandler Carruth73523022014-01-13 13:07:17 +00001267INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth113dc642014-12-20 02:39:18 +00001268INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
1269 false)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001270
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001271/// Walk the range of a partitioning looking for a common type to cover this
1272/// sequence of slices.
1273static Type *findCommonType(AllocaSlices::const_iterator B,
1274 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001275 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001276 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001277 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001278 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001279
1280 // Note that we need to look at *every* alloca slice's Use to ensure we
1281 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001282 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001283 Use *U = I->getUse();
1284 if (isa<IntrinsicInst>(*U->getUser()))
1285 continue;
1286 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1287 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001288
Craig Topperf40110f2014-04-25 05:29:35 +00001289 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001290 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001291 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001292 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001293 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001294 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001295
Chandler Carruth4de31542014-01-21 23:16:05 +00001296 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001297 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001298 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001299 // entity causing the split. Also skip if the type is not a byte width
1300 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001301 if (UserITy->getBitWidth() % 8 != 0 ||
1302 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001303 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001304
Chandler Carruth4de31542014-01-21 23:16:05 +00001305 // Track the largest bitwidth integer type used in this way in case there
1306 // is no common type.
1307 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1308 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001309 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001310
1311 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1312 // depend on types skipped above.
1313 if (!UserTy || (Ty && Ty != UserTy))
1314 TyIsCommon = false; // Give up on anything but an iN type.
1315 else
1316 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001317 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001318
1319 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001320}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001321
Chandler Carruthf0546402013-07-18 07:15:00 +00001322/// PHI instructions that use an alloca and are subsequently loaded can be
1323/// rewritten to load both input pointers in the pred blocks and then PHI the
1324/// results, allowing the load of the alloca to be promoted.
1325/// From this:
1326/// %P2 = phi [i32* %Alloca, i32* %Other]
1327/// %V = load i32* %P2
1328/// to:
1329/// %V1 = load i32* %Alloca -> will be mem2reg'd
1330/// ...
1331/// %V2 = load i32* %Other
1332/// ...
1333/// %V = phi [i32 %V1, i32 %V2]
1334///
1335/// We can do this to a select if its only uses are loads and if the operands
1336/// to the select can be loaded unconditionally.
1337///
1338/// FIXME: This should be hoisted into a generic utility, likely in
1339/// Transforms/Util/Local.h
Chandler Carruth113dc642014-12-20 02:39:18 +00001340static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001341 // For now, we can only do this promotion if the load is in the same block
1342 // as the PHI, and if there are no stores between the phi and load.
1343 // TODO: Allow recursive phi users.
1344 // TODO: Allow stores.
1345 BasicBlock *BB = PN.getParent();
1346 unsigned MaxAlign = 0;
1347 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001348 for (User *U : PN.users()) {
1349 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001350 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001351 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001352
Chandler Carruthf0546402013-07-18 07:15:00 +00001353 // For now we only allow loads in the same block as the PHI. This is
1354 // a common case that happens when instcombine merges two loads through
1355 // a PHI.
1356 if (LI->getParent() != BB)
1357 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001358
Chandler Carruthf0546402013-07-18 07:15:00 +00001359 // Ensure that there are no instructions between the PHI and the load that
1360 // could store.
1361 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1362 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001363 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001364
Chandler Carruthf0546402013-07-18 07:15:00 +00001365 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1366 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001367 }
1368
Chandler Carruthf0546402013-07-18 07:15:00 +00001369 if (!HaveLoad)
1370 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001371
Chandler Carruthf0546402013-07-18 07:15:00 +00001372 // We can only transform this if it is safe to push the loads into the
1373 // predecessor blocks. The only thing to watch out for is that we can't put
1374 // a possibly trapping load in the predecessor if it is a critical edge.
1375 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1376 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1377 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001378
Chandler Carruthf0546402013-07-18 07:15:00 +00001379 // If the value is produced by the terminator of the predecessor (an
1380 // invoke) or it has side-effects, there is no valid place to put a load
1381 // in the predecessor.
1382 if (TI == InVal || TI->mayHaveSideEffects())
1383 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001384
Chandler Carruthf0546402013-07-18 07:15:00 +00001385 // If the predecessor has a single successor, then the edge isn't
1386 // critical.
1387 if (TI->getNumSuccessors() == 1)
1388 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001389
Chandler Carruthf0546402013-07-18 07:15:00 +00001390 // If this pointer is always safe to load, or if we can prove that there
1391 // is already a load in the block, then we can move the load to the pred
1392 // block.
Hal Finkel2e42c342014-07-10 05:27:53 +00001393 if (InVal->isDereferenceablePointer(DL) ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001394 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001395 continue;
1396
1397 return false;
1398 }
1399
1400 return true;
1401}
1402
1403static void speculatePHINodeLoads(PHINode &PN) {
1404 DEBUG(dbgs() << " original: " << PN << "\n");
1405
1406 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1407 IRBuilderTy PHIBuilder(&PN);
1408 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1409 PN.getName() + ".sroa.speculated");
1410
Hal Finkelcc39b672014-07-24 12:16:19 +00001411 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001412 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001413 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001414
1415 AAMDNodes AATags;
1416 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001417 unsigned Align = SomeLoad->getAlignment();
1418
1419 // Rewrite all loads of the PN to use the new PHI.
1420 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001421 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001422 LI->replaceAllUsesWith(NewPN);
1423 LI->eraseFromParent();
1424 }
1425
1426 // Inject loads into all of the pred blocks.
1427 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1428 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1429 TerminatorInst *TI = Pred->getTerminator();
1430 Value *InVal = PN.getIncomingValue(Idx);
1431 IRBuilderTy PredBuilder(TI);
1432
1433 LoadInst *Load = PredBuilder.CreateLoad(
1434 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1435 ++NumLoadsSpeculated;
1436 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001437 if (AATags)
1438 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001439 NewPN->addIncoming(Load, Pred);
1440 }
1441
1442 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1443 PN.eraseFromParent();
1444}
1445
1446/// Select instructions that use an alloca and are subsequently loaded can be
1447/// rewritten to load both input pointers and then select between the result,
1448/// allowing the load of the alloca to be promoted.
1449/// From this:
1450/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1451/// %V = load i32* %P2
1452/// to:
1453/// %V1 = load i32* %Alloca -> will be mem2reg'd
1454/// %V2 = load i32* %Other
1455/// %V = select i1 %cond, i32 %V1, i32 %V2
1456///
1457/// We can do this to a select if its only uses are loads and if the operand
1458/// to the select can be loaded unconditionally.
Craig Topperf40110f2014-04-25 05:29:35 +00001459static bool isSafeSelectToSpeculate(SelectInst &SI,
1460 const DataLayout *DL = nullptr) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001461 Value *TValue = SI.getTrueValue();
1462 Value *FValue = SI.getFalseValue();
Hal Finkel2e42c342014-07-10 05:27:53 +00001463 bool TDerefable = TValue->isDereferenceablePointer(DL);
1464 bool FDerefable = FValue->isDereferenceablePointer(DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00001465
Chandler Carruthcdf47882014-03-09 03:16:01 +00001466 for (User *U : SI.users()) {
1467 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001468 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001469 return false;
1470
1471 // Both operands to the select need to be dereferencable, either
1472 // absolutely (e.g. allocas) or at this point because we can see other
1473 // accesses to it.
1474 if (!TDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001475 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001476 return false;
1477 if (!FDerefable &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00001478 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
Chandler Carruthf0546402013-07-18 07:15:00 +00001479 return false;
1480 }
1481
1482 return true;
1483}
1484
1485static void speculateSelectInstLoads(SelectInst &SI) {
1486 DEBUG(dbgs() << " original: " << SI << "\n");
1487
1488 IRBuilderTy IRB(&SI);
1489 Value *TV = SI.getTrueValue();
1490 Value *FV = SI.getFalseValue();
1491 // Replace the loads of the select with a select of two loads.
1492 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001493 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001494 assert(LI->isSimple() && "We only speculate simple loads");
1495
1496 IRB.SetInsertPoint(LI);
1497 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001498 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001499 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001500 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001501 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001502
Hal Finkelcc39b672014-07-24 12:16:19 +00001503 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001504 TL->setAlignment(LI->getAlignment());
1505 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001506
1507 AAMDNodes Tags;
1508 LI->getAAMetadata(Tags);
1509 if (Tags) {
1510 TL->setAAMetadata(Tags);
1511 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001512 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001513
1514 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1515 LI->getName() + ".sroa.speculated");
1516
1517 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1518 LI->replaceAllUsesWith(V);
1519 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001520 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001521 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001522}
1523
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001524/// \brief Build a GEP out of a base pointer and indices.
1525///
1526/// This will return the BasePtr if that is valid, or build a new GEP
1527/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001528static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001529 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001530 if (Indices.empty())
1531 return BasePtr;
1532
1533 // A single zero index is a no-op, so check for this and avoid building a GEP
1534 // in that case.
1535 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1536 return BasePtr;
1537
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001538 return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001539}
1540
1541/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1542/// TargetTy without changing the offset of the pointer.
1543///
1544/// This routine assumes we've already established a properly offset GEP with
1545/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1546/// zero-indices down through type layers until we find one the same as
1547/// TargetTy. If we can't find one with the same type, we at least try to use
1548/// one with the same size. If none of that works, we just produce the GEP as
1549/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001550static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001551 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001552 SmallVectorImpl<Value *> &Indices,
1553 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001554 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001555 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001556
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001557 // Pointer size to use for the indices.
1558 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1559
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001560 // See if we can descend into a struct and locate a field with the correct
1561 // type.
1562 unsigned NumLayers = 0;
1563 Type *ElementTy = Ty;
1564 do {
1565 if (ElementTy->isPointerTy())
1566 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001567
1568 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1569 ElementTy = ArrayTy->getElementType();
1570 Indices.push_back(IRB.getIntN(PtrSize, 0));
1571 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1572 ElementTy = VectorTy->getElementType();
1573 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001574 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001575 if (STy->element_begin() == STy->element_end())
1576 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001577 ElementTy = *STy->element_begin();
1578 Indices.push_back(IRB.getInt32(0));
1579 } else {
1580 break;
1581 }
1582 ++NumLayers;
1583 } while (ElementTy != TargetTy);
1584 if (ElementTy != TargetTy)
1585 Indices.erase(Indices.end() - NumLayers, Indices.end());
1586
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001587 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001588}
1589
1590/// \brief Recursively compute indices for a natural GEP.
1591///
1592/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1593/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001594static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001595 Value *Ptr, Type *Ty, APInt &Offset,
1596 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001597 SmallVectorImpl<Value *> &Indices,
1598 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001599 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001600 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1601 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001602
1603 // We can't recurse through pointer types.
1604 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001605 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001606
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001607 // We try to analyze GEPs over vectors here, but note that these GEPs are
1608 // extremely poorly defined currently. The long-term goal is to remove GEPing
1609 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001610 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001611 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001612 if (ElementSizeInBits % 8 != 0) {
1613 // GEPs over non-multiple of 8 size vector elements are invalid.
1614 return nullptr;
1615 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001616 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001617 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001618 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001619 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001620 Offset -= NumSkippedElements * ElementSize;
1621 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001622 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001623 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001624 }
1625
1626 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1627 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001628 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001629 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001630 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001631 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001632
1633 Offset -= NumSkippedElements * ElementSize;
1634 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001635 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001636 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001637 }
1638
1639 StructType *STy = dyn_cast<StructType>(Ty);
1640 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001641 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001642
Chandler Carruth90a735d2013-07-19 07:21:28 +00001643 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001644 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001645 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001646 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001647 unsigned Index = SL->getElementContainingOffset(StructOffset);
1648 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1649 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001650 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001651 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001652
1653 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001654 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001655 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001656}
1657
1658/// \brief Get a natural GEP from a base pointer to a particular offset and
1659/// resulting in a particular type.
1660///
1661/// The goal is to produce a "natural" looking GEP that works with the existing
1662/// composite types to arrive at the appropriate offset and element type for
1663/// a pointer. TargetTy is the element type the returned GEP should point-to if
1664/// possible. We recurse by decreasing Offset, adding the appropriate index to
1665/// Indices, and setting Ty to the result subtype.
1666///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001667/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001668static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001669 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001670 SmallVectorImpl<Value *> &Indices,
1671 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001672 PointerType *Ty = cast<PointerType>(Ptr->getType());
1673
1674 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1675 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001676 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001677 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001678
1679 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001680 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001681 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001682 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001683 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001684 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001685 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001686
1687 Offset -= NumSkippedElements * ElementSize;
1688 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001689 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001690 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001691}
1692
1693/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1694/// resulting pointer has PointerTy.
1695///
1696/// This tries very hard to compute a "natural" GEP which arrives at the offset
1697/// and produces the pointer type desired. Where it cannot, it will try to use
1698/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1699/// fails, it will try to use an existing i8* and GEP to the byte offset and
1700/// bitcast to the type.
1701///
1702/// The strategy for finding the more natural GEPs is to peel off layers of the
1703/// pointer, walking back through bit casts and GEPs, searching for a base
1704/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001705/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001706/// a single GEP as possible, thus making each GEP more independent of the
1707/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001708static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Chandler Carruth113dc642014-12-20 02:39:18 +00001709 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001710 // Even though we don't look through PHI nodes, we could be called on an
1711 // instruction in an unreachable block, which may be on a cycle.
1712 SmallPtrSet<Value *, 4> Visited;
1713 Visited.insert(Ptr);
1714 SmallVector<Value *, 4> Indices;
1715
1716 // We may end up computing an offset pointer that has the wrong type. If we
1717 // never are able to compute one directly that has the correct type, we'll
1718 // fall back to it, so keep it around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001719 Value *OffsetPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001720
1721 // Remember any i8 pointer we come across to re-use if we need to do a raw
1722 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001723 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001724 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1725
1726 Type *TargetTy = PointerTy->getPointerElementType();
1727
1728 do {
1729 // First fold any existing GEPs into the offset.
1730 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1731 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001732 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001733 break;
1734 Offset += GEPOffset;
1735 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001736 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001737 break;
1738 }
1739
1740 // See if we can perform a natural GEP here.
1741 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001742 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001743 Indices, NamePrefix)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001744 if (P->getType() == PointerTy) {
1745 // Zap any offset pointer that we ended up computing in previous rounds.
1746 if (OffsetPtr && OffsetPtr->use_empty())
1747 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1748 I->eraseFromParent();
1749 return P;
1750 }
1751 if (!OffsetPtr) {
1752 OffsetPtr = P;
1753 }
1754 }
1755
1756 // Stash this pointer if we've found an i8*.
1757 if (Ptr->getType()->isIntegerTy(8)) {
1758 Int8Ptr = Ptr;
1759 Int8PtrOffset = Offset;
1760 }
1761
1762 // Peel off a layer of the pointer and update the offset appropriately.
1763 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1764 Ptr = cast<Operator>(Ptr)->getOperand(0);
1765 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1766 if (GA->mayBeOverridden())
1767 break;
1768 Ptr = GA->getAliasee();
1769 } else {
1770 break;
1771 }
1772 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001773 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001774
1775 if (!OffsetPtr) {
1776 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001777 Int8Ptr = IRB.CreateBitCast(
1778 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1779 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001780 Int8PtrOffset = Offset;
1781 }
1782
Chandler Carruth113dc642014-12-20 02:39:18 +00001783 OffsetPtr = Int8PtrOffset == 0
1784 ? Int8Ptr
1785 : IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1786 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001787 }
1788 Ptr = OffsetPtr;
1789
1790 // On the off chance we were targeting i8*, guard the bitcast here.
1791 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001792 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001793
1794 return Ptr;
1795}
1796
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001797/// \brief Test whether we can convert a value from the old to the new type.
1798///
1799/// This predicate should be used to guard calls to convertValue in order to
1800/// ensure that we only try to convert viable values. The strategy is that we
1801/// will peel off single element struct and array wrappings to get to an
1802/// underlying value, and convert that value.
1803static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1804 if (OldTy == NewTy)
1805 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001806 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1807 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1808 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1809 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001810 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1811 return false;
1812 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1813 return false;
1814
Benjamin Kramer56262592013-09-22 11:24:58 +00001815 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001816 // of pointers and integers.
1817 OldTy = OldTy->getScalarType();
1818 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001819 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1820 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1821 return true;
1822 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1823 return true;
1824 return false;
1825 }
1826
1827 return true;
1828}
1829
1830/// \brief Generic routine to convert an SSA value to a value of a different
1831/// type.
1832///
1833/// This will try various different casting techniques, such as bitcasts,
1834/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1835/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001836static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001837 Type *NewTy) {
1838 Type *OldTy = V->getType();
1839 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1840
1841 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001842 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001843
1844 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1845 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001846 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1847 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001848
Benjamin Kramer90901a32013-09-21 20:36:04 +00001849 // See if we need inttoptr for this type pair. A cast involving both scalars
1850 // and vectors requires and additional bitcast.
1851 if (OldTy->getScalarType()->isIntegerTy() &&
1852 NewTy->getScalarType()->isPointerTy()) {
1853 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1854 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1855 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1856 NewTy);
1857
1858 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1859 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1860 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1861 NewTy);
1862
1863 return IRB.CreateIntToPtr(V, NewTy);
1864 }
1865
1866 // See if we need ptrtoint for this type pair. A cast involving both scalars
1867 // and vectors requires and additional bitcast.
1868 if (OldTy->getScalarType()->isPointerTy() &&
1869 NewTy->getScalarType()->isIntegerTy()) {
1870 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1871 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1872 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1873 NewTy);
1874
1875 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1876 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1877 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1878 NewTy);
1879
1880 return IRB.CreatePtrToInt(V, NewTy);
1881 }
1882
1883 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001884}
1885
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001886/// \brief Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001887///
1888/// This function is called to test each entry in a partioning which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001889/// for a single slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001890static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
1891 const Slice &S, VectorType *Ty,
1892 uint64_t ElementSize,
1893 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001894 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001895 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001896 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001897 uint64_t BeginIndex = BeginOffset / ElementSize;
1898 if (BeginIndex * ElementSize != BeginOffset ||
1899 BeginIndex >= Ty->getNumElements())
1900 return false;
1901 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001902 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001903 uint64_t EndIndex = EndOffset / ElementSize;
1904 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1905 return false;
1906
1907 assert(EndIndex > BeginIndex && "Empty vector!");
1908 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001909 Type *SliceTy = (NumElements == 1)
1910 ? Ty->getElementType()
1911 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001912
1913 Type *SplitIntTy =
1914 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1915
Chandler Carruthc659df92014-10-16 20:24:07 +00001916 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001917
1918 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1919 if (MI->isVolatile())
1920 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001921 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001922 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001923 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1924 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1925 II->getIntrinsicID() != Intrinsic::lifetime_end)
1926 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001927 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1928 // Disable vector promotion when there are loads or stores of an FCA.
1929 return false;
1930 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1931 if (LI->isVolatile())
1932 return false;
1933 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001934 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001935 assert(LTy->isIntegerTy());
1936 LTy = SplitIntTy;
1937 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001938 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001939 return false;
1940 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1941 if (SI->isVolatile())
1942 return false;
1943 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001944 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001945 assert(STy->isIntegerTy());
1946 STy = SplitIntTy;
1947 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001948 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001949 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001950 } else {
1951 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001952 }
1953
1954 return true;
1955}
1956
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001957/// \brief Test whether the given alloca partitioning and range of slices can be
1958/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001959///
1960/// This is a quick test to check whether we can rewrite a particular alloca
1961/// partition (and its newly formed alloca) into a vector alloca with only
1962/// whole-vector loads and stores such that it could be promoted to a vector
1963/// SSA value. We only can ensure this for a limited set of operations, and we
1964/// don't want to do the rewrites unless we are confident that the result will
1965/// be promotable, so we have an early test here.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001966static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
1967 const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001968 // Collect the candidate types for vector-based promotion. Also track whether
1969 // we have different element types.
1970 SmallVector<VectorType *, 4> CandidateTys;
1971 Type *CommonEltTy = nullptr;
1972 bool HaveCommonEltTy = true;
1973 auto CheckCandidateType = [&](Type *Ty) {
1974 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1975 CandidateTys.push_back(VTy);
1976 if (!CommonEltTy)
1977 CommonEltTy = VTy->getElementType();
1978 else if (CommonEltTy != VTy->getElementType())
1979 HaveCommonEltTy = false;
1980 }
1981 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001982 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001983 for (const Slice &S : P)
1984 if (S.beginOffset() == P.beginOffset() &&
1985 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001986 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1987 CheckCandidateType(LI->getType());
1988 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1989 CheckCandidateType(SI->getValueOperand()->getType());
1990 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001991
Chandler Carruth2dc96822014-10-18 00:44:02 +00001992 // If we didn't find a vector type, nothing to do here.
1993 if (CandidateTys.empty())
1994 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001995
Chandler Carruth2dc96822014-10-18 00:44:02 +00001996 // Remove non-integer vector types if we had multiple common element types.
1997 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1998 // do that until all the backends are known to produce good code for all
1999 // integer vector types.
2000 if (!HaveCommonEltTy) {
2001 CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
2002 [](VectorType *VTy) {
2003 return !VTy->getElementType()->isIntegerTy();
2004 }),
2005 CandidateTys.end());
2006
2007 // If there were no integer vector types, give up.
2008 if (CandidateTys.empty())
2009 return nullptr;
2010
2011 // Rank the remaining candidate vector types. This is easy because we know
2012 // they're all integer vectors. We sort by ascending number of elements.
2013 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
2014 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
2015 "Cannot have vector types of different sizes!");
2016 assert(RHSTy->getElementType()->isIntegerTy() &&
2017 "All non-integer types eliminated!");
2018 assert(LHSTy->getElementType()->isIntegerTy() &&
2019 "All non-integer types eliminated!");
2020 return RHSTy->getNumElements() < LHSTy->getNumElements();
2021 };
2022 std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
2023 CandidateTys.erase(
2024 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
2025 CandidateTys.end());
2026 } else {
2027// The only way to have the same element type in every vector type is to
2028// have the same vector type. Check that and remove all but one.
2029#ifndef NDEBUG
2030 for (VectorType *VTy : CandidateTys) {
2031 assert(VTy->getElementType() == CommonEltTy &&
2032 "Unaccounted for element type!");
2033 assert(VTy == CandidateTys[0] &&
2034 "Different vector types with the same element type!");
2035 }
2036#endif
2037 CandidateTys.resize(1);
2038 }
2039
2040 // Try each vector type, and return the one which works.
2041 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
2042 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
2043
2044 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2045 // that aren't byte sized.
2046 if (ElementSize % 8)
2047 return false;
2048 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
2049 "vector size not a multiple of element size?");
2050 ElementSize /= 8;
2051
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002052 for (const Slice &S : P)
2053 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00002054 return false;
2055
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002056 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002057 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00002058 return false;
2059
2060 return true;
2061 };
2062 for (VectorType *VTy : CandidateTys)
2063 if (CheckVectorTypeForPromotion(VTy))
2064 return VTy;
2065
2066 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00002067}
2068
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002069/// \brief Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00002070///
2071/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002072/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002073static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002074 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002075 Type *AllocaTy,
2076 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002077 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002078 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2079
Chandler Carruthc659df92014-10-16 20:24:07 +00002080 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2081 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002082
2083 // We can't reasonably handle cases where the load or store extends past
2084 // the end of the aloca's type and into its padding.
2085 if (RelEnd > Size)
2086 return false;
2087
Chandler Carruthc659df92014-10-16 20:24:07 +00002088 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002089
2090 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2091 if (LI->isVolatile())
2092 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002093 // Note that we don't count vector loads or stores as whole-alloca
2094 // operations which enable integer widening because we would prefer to use
2095 // vector widening instead.
2096 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002097 WholeAllocaOp = true;
2098 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002099 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002100 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002101 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002102 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002103 // Non-integer loads need to be convertible from the alloca type so that
2104 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002105 return false;
2106 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002107 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2108 Type *ValueTy = SI->getValueOperand()->getType();
2109 if (SI->isVolatile())
2110 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002111 // Note that we don't count vector loads or stores as whole-alloca
2112 // operations which enable integer widening because we would prefer to use
2113 // vector widening instead.
2114 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002115 WholeAllocaOp = true;
2116 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002117 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002118 return false;
2119 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002120 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002121 // Non-integer stores need to be convertible to the alloca type so that
2122 // they are promotable.
2123 return false;
2124 }
2125 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2126 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2127 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002128 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002129 return false; // Skip any unsplittable intrinsics.
2130 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2131 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2132 II->getIntrinsicID() != Intrinsic::lifetime_end)
2133 return false;
2134 } else {
2135 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002136 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002137
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002138 return true;
2139}
2140
Chandler Carruth435c4e02012-10-15 08:40:30 +00002141/// \brief Test whether the given alloca partition's integer operations can be
2142/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002143///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002144/// This is a quick test to check whether we can rewrite the integer loads and
2145/// stores to a particular alloca into wider loads and stores and be able to
2146/// promote the resulting alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002147static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
2148 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002149 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002150 // Don't create integer types larger than the maximum bitwidth.
2151 if (SizeInBits > IntegerType::MAX_INT_BITS)
2152 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002153
2154 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002155 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002156 return false;
2157
Chandler Carruth58d05562012-10-25 04:37:07 +00002158 // We need to ensure that an integer type with the appropriate bitwidth can
2159 // be converted to the alloca type, whatever that is. We don't want to force
2160 // the alloca itself to have an integer type if there is a more suitable one.
2161 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002162 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2163 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002164 return false;
2165
Chandler Carruthf0546402013-07-18 07:15:00 +00002166 // While examining uses, we ensure that the alloca has a covering load or
2167 // store. We don't want to widen the integer operations only to fail to
2168 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002169 // later). However, if there are only splittable uses, go ahead and assume
2170 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002171 // FIXME: We shouldn't consider split slices that happen to start in the
2172 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002173 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002174 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002175
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002176 for (const Slice &S : P)
2177 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2178 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002179 return false;
2180
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002181 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002182 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2183 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002184 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002185
Chandler Carruth92924fd2012-09-24 00:34:20 +00002186 return WholeAllocaOp;
2187}
2188
Chandler Carruthd177f862013-03-20 07:30:36 +00002189static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002190 IntegerType *Ty, uint64_t Offset,
2191 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002192 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002193 IntegerType *IntTy = cast<IntegerType>(V->getType());
2194 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2195 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002196 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002197 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002198 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002199 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002200 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002201 DEBUG(dbgs() << " shifted: " << *V << "\n");
2202 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002203 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2204 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002205 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002206 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002207 DEBUG(dbgs() << " trunced: " << *V << "\n");
2208 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002209 return V;
2210}
2211
Chandler Carruthd177f862013-03-20 07:30:36 +00002212static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002213 Value *V, uint64_t Offset, const Twine &Name) {
2214 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2215 IntegerType *Ty = cast<IntegerType>(V->getType());
2216 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2217 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002218 DEBUG(dbgs() << " start: " << *V << "\n");
2219 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002220 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002221 DEBUG(dbgs() << " extended: " << *V << "\n");
2222 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002223 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2224 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002225 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002226 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002227 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002228 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002229 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002230 DEBUG(dbgs() << " shifted: " << *V << "\n");
2231 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002232
2233 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2234 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2235 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002236 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002237 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002238 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002239 }
2240 return V;
2241}
2242
Chandler Carruth113dc642014-12-20 02:39:18 +00002243static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2244 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002245 VectorType *VecTy = cast<VectorType>(V->getType());
2246 unsigned NumElements = EndIndex - BeginIndex;
2247 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2248
2249 if (NumElements == VecTy->getNumElements())
2250 return V;
2251
2252 if (NumElements == 1) {
2253 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2254 Name + ".extract");
2255 DEBUG(dbgs() << " extract: " << *V << "\n");
2256 return V;
2257 }
2258
Chandler Carruth113dc642014-12-20 02:39:18 +00002259 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002260 Mask.reserve(NumElements);
2261 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2262 Mask.push_back(IRB.getInt32(i));
2263 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002264 ConstantVector::get(Mask), Name + ".extract");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002265 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2266 return V;
2267}
2268
Chandler Carruthd177f862013-03-20 07:30:36 +00002269static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002270 unsigned BeginIndex, const Twine &Name) {
2271 VectorType *VecTy = cast<VectorType>(Old->getType());
2272 assert(VecTy && "Can only insert a vector into a vector");
2273
2274 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2275 if (!Ty) {
2276 // Single element to insert.
2277 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2278 Name + ".insert");
Chandler Carruth113dc642014-12-20 02:39:18 +00002279 DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002280 return V;
2281 }
2282
2283 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2284 "Too many elements!");
2285 if (Ty->getNumElements() == VecTy->getNumElements()) {
2286 assert(V->getType() == VecTy && "Vector type mismatch");
2287 return V;
2288 }
2289 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2290
2291 // When inserting a smaller vector into the larger to store, we first
2292 // use a shuffle vector to widen it with undef elements, and then
2293 // a second shuffle vector to select between the loaded vector and the
2294 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002295 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002296 Mask.reserve(VecTy->getNumElements());
2297 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2298 if (i >= BeginIndex && i < EndIndex)
2299 Mask.push_back(IRB.getInt32(i - BeginIndex));
2300 else
2301 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2302 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002303 ConstantVector::get(Mask), Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002304 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002305
2306 Mask.clear();
2307 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002308 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2309
2310 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2311
2312 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002313 return V;
2314}
2315
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002316namespace {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002317/// \brief Visitor to rewrite instructions using p particular slice of an alloca
2318/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002319///
2320/// Also implements the rewriting to vector-based accesses when the partition
2321/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2322/// lives here.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002323class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002324 // Befriend the base class so it can delegate to private visit methods.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002325 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2326 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002327
Chandler Carruth90a735d2013-07-19 07:21:28 +00002328 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002329 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002330 SROA &Pass;
2331 AllocaInst &OldAI, &NewAI;
2332 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002333 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002334
Chandler Carruth2dc96822014-10-18 00:44:02 +00002335 // This is a convenience and flag variable that will be null unless the new
2336 // alloca's integer operations should be widened to this integer type due to
2337 // passing isIntegerWideningViable above. If it is non-null, the desired
2338 // integer type will be stored here for easy access during rewriting.
2339 IntegerType *IntTy;
2340
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002341 // If we are rewriting an alloca partition which can be written as pure
2342 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002343 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002344 // - The new alloca is exactly the size of the vector type here.
2345 // - The accesses all either map to the entire vector or to a single
2346 // element.
2347 // - The set of accessing instructions is only one of those handled above
2348 // in isVectorPromotionViable. Generally these are the same access kinds
2349 // which are promotable via mem2reg.
2350 VectorType *VecTy;
2351 Type *ElementTy;
2352 uint64_t ElementSize;
2353
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002354 // The original offset of the slice currently being rewritten relative to
2355 // the original alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002356 uint64_t BeginOffset, EndOffset;
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002357 // The new offsets of the slice currently being rewritten relative to the
2358 // original alloca.
2359 uint64_t NewBeginOffset, NewEndOffset;
2360
2361 uint64_t SliceSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00002362 bool IsSplittable;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002363 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002364 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002365 Instruction *OldPtr;
2366
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002367 // Track post-rewrite users which are PHI nodes and Selects.
2368 SmallPtrSetImpl<PHINode *> &PHIUsers;
2369 SmallPtrSetImpl<SelectInst *> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002370
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002371 // Utility IR builder, whose name prefix is setup for each visited use, and
2372 // the insertion point is set to point to the user.
2373 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002374
2375public:
Chandler Carruth83934062014-10-16 21:11:55 +00002376 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002377 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002378 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002379 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2380 VectorType *PromotableVecTy,
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002381 SmallPtrSetImpl<PHINode *> &PHIUsers,
2382 SmallPtrSetImpl<SelectInst *> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002383 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002384 NewAllocaBeginOffset(NewAllocaBeginOffset),
2385 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002386 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002387 IntTy(IsIntegerPromotable
2388 ? Type::getIntNTy(
2389 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002390 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002391 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002392 VecTy(PromotableVecTy),
2393 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2394 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Chandler Carruthf0546402013-07-18 07:15:00 +00002395 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002396 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002397 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002398 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002399 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002400 "Only multiple-of-8 sized vector elements are viable");
2401 ++NumVectorized;
2402 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002403 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002404 }
2405
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002406 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002407 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002408 BeginOffset = I->beginOffset();
2409 EndOffset = I->endOffset();
2410 IsSplittable = I->isSplittable();
2411 IsSplit =
2412 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002413 DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2414 DEBUG(AS.printSlice(dbgs(), I, ""));
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002415
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002416 // Compute the intersecting offset range.
2417 assert(BeginOffset < NewAllocaEndOffset);
2418 assert(EndOffset > NewAllocaBeginOffset);
2419 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2420 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2421
2422 SliceSize = NewEndOffset - NewBeginOffset;
2423
Chandler Carruthf0546402013-07-18 07:15:00 +00002424 OldUse = I->getUse();
2425 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002426
Chandler Carruthf0546402013-07-18 07:15:00 +00002427 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2428 IRB.SetInsertPoint(OldUserI);
2429 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2430 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2431
2432 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2433 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002434 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002435 return CanSROA;
2436 }
2437
2438private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002439 // Make sure the other visit overloads are visible.
2440 using Base::visit;
2441
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002442 // Every instruction which can end up as a user must have a rewrite rule.
2443 bool visitInstruction(Instruction &I) {
2444 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2445 llvm_unreachable("No rewrite rule for this instruction!");
2446 }
2447
Chandler Carruth47954c82014-02-26 05:12:43 +00002448 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2449 // Note that the offset computation can use BeginOffset or NewBeginOffset
2450 // interchangeably for unsplit slices.
2451 assert(IsSplit || BeginOffset == NewBeginOffset);
2452 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2453
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002454#ifndef NDEBUG
2455 StringRef OldName = OldPtr->getName();
2456 // Skip through the last '.sroa.' component of the name.
2457 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2458 if (LastSROAPrefix != StringRef::npos) {
2459 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2460 // Look for an SROA slice index.
2461 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2462 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2463 // Strip the index and look for the offset.
2464 OldName = OldName.substr(IndexEnd + 1);
2465 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2466 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2467 // Strip the offset.
2468 OldName = OldName.substr(OffsetEnd + 1);
2469 }
2470 }
2471 // Strip any SROA suffixes as well.
2472 OldName = OldName.substr(0, OldName.find(".sroa_"));
2473#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002474
2475 return getAdjustedPtr(IRB, DL, &NewAI,
2476 APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002477#ifndef NDEBUG
2478 Twine(OldName) + "."
2479#else
2480 Twine()
2481#endif
2482 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002483 }
2484
Chandler Carruth113dc642014-12-20 02:39:18 +00002485 /// \brief Compute suitable alignment to access this slice of the *new*
2486 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002487 ///
2488 /// You can optionally pass a type to this routine and if that type's ABI
2489 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002490 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002491 unsigned NewAIAlign = NewAI.getAlignment();
2492 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002493 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002494 unsigned Align =
2495 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002496 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002497 }
2498
Chandler Carruth845b73c2012-11-21 08:16:30 +00002499 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500 assert(VecTy && "Can only call getIndex when rewriting a vector");
2501 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2502 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2503 uint32_t Index = RelOffset / ElementSize;
2504 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002505 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002506 }
2507
2508 void deleteIfTriviallyDead(Value *V) {
2509 Instruction *I = cast<Instruction>(V);
2510 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002511 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002512 }
2513
Chandler Carruthea27cf02014-02-26 04:25:04 +00002514 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002515 unsigned BeginIndex = getIndex(NewBeginOffset);
2516 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002517 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002518
Chandler Carruth113dc642014-12-20 02:39:18 +00002519 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002520 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002521 }
2522
Chandler Carruthea27cf02014-02-26 04:25:04 +00002523 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002524 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002525 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002526 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002527 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002528 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2529 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2530 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002531 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002532 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002533 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002534 }
2535
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002536 bool visitLoadInst(LoadInst &LI) {
2537 DEBUG(dbgs() << " original: " << LI << "\n");
2538 Value *OldOp = LI.getOperand(0);
2539 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002540
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002541 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002542 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002543 bool IsPtrAdjusted = false;
2544 Value *V;
2545 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002546 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002547 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002548 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002549 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002550 canConvertValue(DL, NewAllocaTy, LI.getType())) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002551 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2552 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002553 } else {
2554 Type *LTy = TargetTy->getPointerTo();
Chandler Carruth47954c82014-02-26 05:12:43 +00002555 V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
Chandler Carruth2659e502014-02-26 05:02:19 +00002556 getSliceAlign(TargetTy), LI.isVolatile(),
2557 LI.getName());
Chandler Carruth18db7952012-11-20 01:12:50 +00002558 IsPtrAdjusted = true;
2559 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002560 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002561
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002562 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002563 assert(!LI.isVolatile());
2564 assert(LI.getType()->isIntegerTy() &&
2565 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002566 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002567 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002568 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002569 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002570 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002571 // Move the insertion point just past the load so that we can refer to it.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002572 IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002573 // Create a placeholder value with the same type as LI to use as the
2574 // basis for the new value. This allows us to replace the uses of LI with
2575 // the computed value, and then replace the placeholder with LI, leaving
2576 // LI only used for this computation.
Chandler Carruth113dc642014-12-20 02:39:18 +00002577 Value *Placeholder =
2578 new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2579 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002580 LI.replaceAllUsesWith(V);
2581 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002582 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002583 } else {
2584 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002585 }
2586
Chandler Carruth18db7952012-11-20 01:12:50 +00002587 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002588 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002589 DEBUG(dbgs() << " to: " << *V << "\n");
2590 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002591 }
2592
Chandler Carruthea27cf02014-02-26 04:25:04 +00002593 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002594 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002595 unsigned BeginIndex = getIndex(NewBeginOffset);
2596 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002597 assert(EndIndex > BeginIndex && "Empty vector!");
2598 unsigned NumElements = EndIndex - BeginIndex;
2599 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002600 Type *SliceTy = (NumElements == 1)
2601 ? ElementTy
2602 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002603 if (V->getType() != SliceTy)
2604 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002605
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002606 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002607 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002608 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2609 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002610 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002611 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002612
2613 (void)Store;
2614 DEBUG(dbgs() << " to: " << *Store << "\n");
2615 return true;
2616 }
2617
Chandler Carruthea27cf02014-02-26 04:25:04 +00002618 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002619 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002620 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002621 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002622 Value *Old =
2623 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002624 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002625 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2626 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002627 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002628 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002629 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002630 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002631 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002632 (void)Store;
2633 DEBUG(dbgs() << " to: " << *Store << "\n");
2634 return true;
2635 }
2636
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002637 bool visitStoreInst(StoreInst &SI) {
2638 DEBUG(dbgs() << " original: " << SI << "\n");
2639 Value *OldOp = SI.getOperand(1);
2640 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002641
Chandler Carruth18db7952012-11-20 01:12:50 +00002642 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002643
Chandler Carruthac8317f2012-10-04 12:33:50 +00002644 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2645 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002646 if (V->getType()->isPointerTy())
2647 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002648 Pass.PostPromotionWorklist.insert(AI);
2649
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002650 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002651 assert(!SI.isVolatile());
2652 assert(V->getType()->isIntegerTy() &&
2653 "Only integer type loads and stores are split");
2654 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002655 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002656 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002657 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth113dc642014-12-20 02:39:18 +00002658 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002659 }
2660
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 if (VecTy)
Chandler Carruthea27cf02014-02-26 04:25:04 +00002662 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002663 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruthea27cf02014-02-26 04:25:04 +00002664 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002665
Chandler Carruth18db7952012-11-20 01:12:50 +00002666 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002667 if (NewBeginOffset == NewAllocaBeginOffset &&
2668 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruth90a735d2013-07-19 07:21:28 +00002669 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2670 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002671 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2672 SI.isVolatile());
2673 } else {
Chandler Carruth47954c82014-02-26 05:12:43 +00002674 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
Chandler Carruth2659e502014-02-26 05:02:19 +00002675 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2676 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002677 }
2678 (void)NewSI;
2679 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002680 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002681
2682 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2683 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002684 }
2685
Chandler Carruth514f34f2012-12-17 04:07:30 +00002686 /// \brief Compute an integer value from splatting an i8 across the given
2687 /// number of bytes.
2688 ///
2689 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2690 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002691 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002692 ///
2693 /// \param V The i8 value to splat.
2694 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002695 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002696 assert(Size > 0 && "Expected a positive number of bytes.");
2697 IntegerType *VTy = cast<IntegerType>(V->getType());
2698 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2699 if (Size == 1)
2700 return V;
2701
Chandler Carruth113dc642014-12-20 02:39:18 +00002702 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2703 V = IRB.CreateMul(
2704 IRB.CreateZExt(V, SplatIntTy, "zext"),
2705 ConstantExpr::getUDiv(
2706 Constant::getAllOnesValue(SplatIntTy),
2707 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2708 SplatIntTy)),
2709 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002710 return V;
2711 }
2712
Chandler Carruthccca5042012-12-17 04:07:37 +00002713 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002714 Value *getVectorSplat(Value *V, unsigned NumElements) {
2715 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002716 DEBUG(dbgs() << " splat: " << *V << "\n");
2717 return V;
2718 }
2719
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002720 bool visitMemSetInst(MemSetInst &II) {
2721 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002722 assert(II.getRawDest() == OldPtr);
2723
2724 // If the memset has a variable size, it cannot be split, just adjust the
2725 // pointer to the new alloca.
2726 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002727 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002728 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002729 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002730 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth2659e502014-02-26 05:02:19 +00002731 II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002732
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002733 deleteIfTriviallyDead(OldPtr);
2734 return false;
2735 }
2736
2737 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002738 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002739
2740 Type *AllocaTy = NewAI.getAllocatedType();
2741 Type *ScalarTy = AllocaTy->getScalarType();
2742
2743 // If this doesn't map cleanly onto the alloca type, and that type isn't
2744 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002745 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002746 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002747 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002748 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002749 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002750 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002751 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002752 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2753 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002754 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2755 getSliceAlign(), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002756 (void)New;
2757 DEBUG(dbgs() << " to: " << *New << "\n");
2758 return false;
2759 }
2760
2761 // If we can represent this as a simple value, we have to build the actual
2762 // value to store, which requires expanding the byte present in memset to
2763 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002764 // splatting the byte to a sufficiently wide integer, splatting it across
2765 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002766 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002767
Chandler Carruthccca5042012-12-17 04:07:37 +00002768 if (VecTy) {
2769 // If this is a memset of a vectorized alloca, insert it.
2770 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002771
Chandler Carruthf0546402013-07-18 07:15:00 +00002772 unsigned BeginIndex = getIndex(NewBeginOffset);
2773 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002774 assert(EndIndex > BeginIndex && "Empty vector!");
2775 unsigned NumElements = EndIndex - BeginIndex;
2776 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2777
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002778 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002779 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2780 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002781 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002782 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002783
Chandler Carruth113dc642014-12-20 02:39:18 +00002784 Value *Old =
2785 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002786 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002787 } else if (IntTy) {
2788 // If this is a memset on an alloca where we can widen stores, insert the
2789 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002790 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002791
Chandler Carruthf0546402013-07-18 07:15:00 +00002792 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002793 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002794
2795 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2796 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002797 Value *Old =
2798 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002799 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002800 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002801 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002802 } else {
2803 assert(V->getType() == IntTy &&
2804 "Wrong type for an alloca wide integer!");
2805 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002806 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002807 } else {
2808 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002809 assert(NewBeginOffset == NewAllocaBeginOffset);
2810 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002811
Chandler Carruth90a735d2013-07-19 07:21:28 +00002812 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002813 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002814 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002815
Chandler Carruth90a735d2013-07-19 07:21:28 +00002816 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002817 }
2818
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002819 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002820 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002821 (void)New;
2822 DEBUG(dbgs() << " to: " << *New << "\n");
2823 return !II.isVolatile();
2824 }
2825
2826 bool visitMemTransferInst(MemTransferInst &II) {
2827 // Rewriting of memory transfer instructions can be a bit tricky. We break
2828 // them into two categories: split intrinsics and unsplit intrinsics.
2829
2830 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002831
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002832 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002833 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002834 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002835
Chandler Carruthaa72b932014-02-26 07:29:54 +00002836 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002837
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002838 // For unsplit intrinsics, we simply modify the source and destination
2839 // pointers in place. This isn't just an optimization, it is a matter of
2840 // correctness. With unsplit intrinsics we may be dealing with transfers
2841 // within a single alloca before SROA ran, or with transfers that have
2842 // a variable length. We may also be dealing with memmove instead of
2843 // memcpy, and so simply updating the pointers is the necessary for us to
2844 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002845 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002846 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002847 if (IsDest)
Chandler Carruth8183a502014-02-25 11:08:02 +00002848 II.setDest(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002849 else
Chandler Carruth8183a502014-02-25 11:08:02 +00002850 II.setSource(AdjustedPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002851
Chandler Carruthaa72b932014-02-26 07:29:54 +00002852 if (II.getAlignment() > SliceAlign) {
Chandler Carruth181ed052014-02-26 05:33:36 +00002853 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthaa72b932014-02-26 07:29:54 +00002854 II.setAlignment(
2855 ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
Chandler Carruth181ed052014-02-26 05:33:36 +00002856 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002857
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002858 DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002859 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002860 return false;
2861 }
2862 // For split transfer intrinsics we have an incredibly useful assurance:
2863 // the source and destination do not reside within the same alloca, and at
2864 // least one of them does not escape. This means that we can replace
2865 // memmove with memcpy, and we don't need to worry about all manner of
2866 // downsides to splitting and transforming the operations.
2867
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002868 // If this doesn't map cleanly onto the alloca type, and that type isn't
2869 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002870 bool EmitMemCpy =
2871 !VecTy && !IntTy &&
2872 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2873 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2874 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002875
2876 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2877 // size hasn't been shrunk based on analysis of the viable range, this is
2878 // a no-op.
2879 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002880 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002881 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002882
2883 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002884 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002885 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002886 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887 return false;
2888 }
2889 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002890 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002891
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002892 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2893 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002894 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002895 if (AllocaInst *AI =
2896 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002897 assert(AI != &OldAI && AI != &NewAI &&
2898 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002899 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002900 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002901
Chandler Carruth286d87e2014-02-26 08:25:02 +00002902 Type *OtherPtrTy = OtherPtr->getType();
2903 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2904
Chandler Carruth181ed052014-02-26 05:33:36 +00002905 // Compute the relative offset for the other pointer within the transfer.
Chandler Carruth286d87e2014-02-26 08:25:02 +00002906 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
Chandler Carruth181ed052014-02-26 05:33:36 +00002907 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002908 unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2909 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002910
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002911 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002912 // Compute the other pointer, folding as much as possible to produce
2913 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002914 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002915 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002916
Chandler Carruth47954c82014-02-26 05:12:43 +00002917 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002918 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002919 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920
Chandler Carruthaa72b932014-02-26 07:29:54 +00002921 CallInst *New = IRB.CreateMemCpy(
2922 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2923 MinAlign(SliceAlign, OtherAlign), II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002924 (void)New;
2925 DEBUG(dbgs() << " to: " << *New << "\n");
2926 return false;
2927 }
2928
Chandler Carruthf0546402013-07-18 07:15:00 +00002929 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2930 NewEndOffset == NewAllocaEndOffset;
2931 uint64_t Size = NewEndOffset - NewBeginOffset;
2932 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2933 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002934 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002935 IntegerType *SubIntTy =
2936 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002937
Chandler Carruth286d87e2014-02-26 08:25:02 +00002938 // Reset the other pointer type to match the register type we're going to
2939 // use, but using the address space of the original other pointer.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002940 if (VecTy && !IsWholeAlloca) {
2941 if (NumElements == 1)
2942 OtherPtrTy = VecTy->getElementType();
2943 else
2944 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2945
Chandler Carruth286d87e2014-02-26 08:25:02 +00002946 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002947 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002948 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2949 } else {
2950 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002951 }
2952
Chandler Carruth181ed052014-02-26 05:33:36 +00002953 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002954 OtherPtr->getName() + ".");
Chandler Carruthaa72b932014-02-26 07:29:54 +00002955 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002956 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002957 unsigned DstAlign = SliceAlign;
2958 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002959 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002960 std::swap(SrcAlign, DstAlign);
2961 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002962
2963 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002964 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002965 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002966 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002967 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002968 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002969 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002970 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002971 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002972 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +00002973 Src =
2974 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002975 }
2976
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002977 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002978 Value *Old =
2979 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002980 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002981 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002982 Value *Old =
2983 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002984 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002985 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002986 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2987 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002988 }
2989
Chandler Carruth871ba722012-09-26 10:27:46 +00002990 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00002991 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Chandler Carruth871ba722012-09-26 10:27:46 +00002992 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002993 DEBUG(dbgs() << " to: " << *Store << "\n");
2994 return !II.isVolatile();
2995 }
2996
2997 bool visitIntrinsicInst(IntrinsicInst &II) {
2998 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2999 II.getIntrinsicID() == Intrinsic::lifetime_end);
3000 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003001 assert(II.getArgOperand(1) == OldPtr);
3002
3003 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003004 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003005
Chandler Carruth113dc642014-12-20 02:39:18 +00003006 ConstantInt *Size =
3007 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003008 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00003009 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003010 Value *New;
3011 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3012 New = IRB.CreateLifetimeStart(Ptr, Size);
3013 else
3014 New = IRB.CreateLifetimeEnd(Ptr, Size);
3015
Edwin Vane82f80d42013-01-29 17:42:24 +00003016 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003017 DEBUG(dbgs() << " to: " << *New << "\n");
3018 return true;
3019 }
3020
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003021 bool visitPHINode(PHINode &PN) {
3022 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003023 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3024 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003025
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003026 // We would like to compute a new pointer in only one place, but have it be
3027 // as local as possible to the PHI. To do that, we re-use the location of
3028 // the old pointer, which necessarily must be in the right position to
3029 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003030 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003031 if (isa<PHINode>(OldPtr))
3032 PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
3033 else
3034 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003035 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003036
Chandler Carruth47954c82014-02-26 05:12:43 +00003037 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003038 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003039 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003040
Chandler Carruth82a57542012-10-01 10:54:05 +00003041 DEBUG(dbgs() << " to: " << PN << "\n");
3042 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003043
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003044 // PHIs can't be promoted on their own, but often can be speculated. We
3045 // check the speculation outside of the rewriter so that we see the
3046 // fully-rewritten alloca.
3047 PHIUsers.insert(&PN);
3048 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003049 }
3050
3051 bool visitSelectInst(SelectInst &SI) {
3052 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003053 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3054 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003055 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3056 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003057
Chandler Carruth47954c82014-02-26 05:12:43 +00003058 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003059 // Replace the operands which were using the old pointer.
3060 if (SI.getOperand(1) == OldPtr)
3061 SI.setOperand(1, NewPtr);
3062 if (SI.getOperand(2) == OldPtr)
3063 SI.setOperand(2, NewPtr);
3064
Chandler Carruth82a57542012-10-01 10:54:05 +00003065 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003066 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003067
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003068 // Selects can't be promoted on their own, but often can be speculated. We
3069 // check the speculation outside of the rewriter so that we see the
3070 // fully-rewritten alloca.
3071 SelectUsers.insert(&SI);
3072 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003073 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003074};
3075}
3076
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003077namespace {
3078/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3079///
3080/// This pass aggressively rewrites all aggregate loads and stores on
3081/// a particular pointer (or any pointer derived from it which we can identify)
3082/// with scalar loads and stores.
3083class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3084 // Befriend the base class so it can delegate to private visit methods.
3085 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3086
Chandler Carruth90a735d2013-07-19 07:21:28 +00003087 const DataLayout &DL;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003088
3089 /// Queue of pointer uses to analyze and potentially rewrite.
3090 SmallVector<Use *, 8> Queue;
3091
3092 /// Set to prevent us from cycling with phi nodes and loops.
3093 SmallPtrSet<User *, 8> Visited;
3094
3095 /// The current pointer use being rewritten. This is used to dig up the used
3096 /// value (as opposed to the user).
3097 Use *U;
3098
3099public:
Chandler Carruth90a735d2013-07-19 07:21:28 +00003100 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003101
3102 /// Rewrite loads and stores through a pointer and all pointers derived from
3103 /// it.
3104 bool rewrite(Instruction &I) {
3105 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3106 enqueueUsers(I);
3107 bool Changed = false;
3108 while (!Queue.empty()) {
3109 U = Queue.pop_back_val();
3110 Changed |= visit(cast<Instruction>(U->getUser()));
3111 }
3112 return Changed;
3113 }
3114
3115private:
3116 /// Enqueue all the users of the given instruction for further processing.
3117 /// This uses a set to de-duplicate users.
3118 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003119 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003120 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003121 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003122 }
3123
3124 // Conservative default is to not rewrite anything.
3125 bool visitInstruction(Instruction &I) { return false; }
3126
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003127 /// \brief Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003128 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003129 protected:
3130 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003131 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003132 /// The indices which to be used with insert- or extractvalue to select the
3133 /// appropriate value within the aggregate.
3134 SmallVector<unsigned, 4> Indices;
3135 /// The indices to a GEP instruction which will move Ptr to the correct slot
3136 /// within the aggregate.
3137 SmallVector<Value *, 4> GEPIndices;
3138 /// The base pointer of the original op, used as a base for GEPing the
3139 /// split operations.
3140 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003141
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003142 /// Initialize the splitter with an insertion point, Ptr and start with a
3143 /// single zero GEP index.
3144 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003145 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003146
3147 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003148 /// \brief Generic recursive split emission routine.
3149 ///
3150 /// This method recursively splits an aggregate op (load or store) into
3151 /// scalar or vector ops. It splits recursively until it hits a single value
3152 /// and emits that single value operation via the template argument.
3153 ///
3154 /// The logic of this routine relies on GEPs and insertvalue and
3155 /// extractvalue all operating with the same fundamental index list, merely
3156 /// formatted differently (GEPs need actual values).
3157 ///
3158 /// \param Ty The type being split recursively into smaller ops.
3159 /// \param Agg The aggregate value being built up or stored, depending on
3160 /// whether this is splitting a load or a store respectively.
3161 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3162 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003163 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003164
3165 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3166 unsigned OldSize = Indices.size();
3167 (void)OldSize;
3168 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3169 ++Idx) {
3170 assert(Indices.size() == OldSize && "Did not return to the old size");
3171 Indices.push_back(Idx);
3172 GEPIndices.push_back(IRB.getInt32(Idx));
3173 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3174 GEPIndices.pop_back();
3175 Indices.pop_back();
3176 }
3177 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003178 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003179
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003180 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3181 unsigned OldSize = Indices.size();
3182 (void)OldSize;
3183 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3184 ++Idx) {
3185 assert(Indices.size() == OldSize && "Did not return to the old size");
3186 Indices.push_back(Idx);
3187 GEPIndices.push_back(IRB.getInt32(Idx));
3188 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3189 GEPIndices.pop_back();
3190 Indices.pop_back();
3191 }
3192 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003193 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003194
3195 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003196 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003197 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003198
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003199 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003200 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003201 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003202
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003203 /// Emit a leaf load of a single value. This is called at the leaves of the
3204 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003205 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003206 assert(Ty->isSingleValueType());
3207 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003208 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3209 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003210 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3211 DEBUG(dbgs() << " to: " << *Load << "\n");
3212 }
3213 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003214
3215 bool visitLoadInst(LoadInst &LI) {
3216 assert(LI.getPointerOperand() == *U);
3217 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3218 return false;
3219
3220 // We have an aggregate being loaded, split it apart.
3221 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003222 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003223 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003224 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003225 LI.replaceAllUsesWith(V);
3226 LI.eraseFromParent();
3227 return true;
3228 }
3229
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003230 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003231 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003232 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003233
3234 /// Emit a leaf store of a single value. This is called at the leaves of the
3235 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003236 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003237 assert(Ty->isSingleValueType());
3238 // Extract the single value and store it using the indices.
3239 Value *Store = IRB.CreateStore(
Chandler Carruth113dc642014-12-20 02:39:18 +00003240 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3241 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003242 (void)Store;
3243 DEBUG(dbgs() << " to: " << *Store << "\n");
3244 }
3245 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003246
3247 bool visitStoreInst(StoreInst &SI) {
3248 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3249 return false;
3250 Value *V = SI.getValueOperand();
3251 if (V->getType()->isSingleValueType())
3252 return false;
3253
3254 // We have an aggregate being stored, split it apart.
3255 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003256 StoreOpSplitter Splitter(&SI, *U);
3257 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003258 SI.eraseFromParent();
3259 return true;
3260 }
3261
3262 bool visitBitCastInst(BitCastInst &BC) {
3263 enqueueUsers(BC);
3264 return false;
3265 }
3266
3267 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3268 enqueueUsers(GEPI);
3269 return false;
3270 }
3271
3272 bool visitPHINode(PHINode &PN) {
3273 enqueueUsers(PN);
3274 return false;
3275 }
3276
3277 bool visitSelectInst(SelectInst &SI) {
3278 enqueueUsers(SI);
3279 return false;
3280 }
3281};
3282}
3283
Chandler Carruthba931992012-10-13 10:49:33 +00003284/// \brief Strip aggregate type wrapping.
3285///
3286/// This removes no-op aggregate types wrapping an underlying type. It will
3287/// strip as many layers of types as it can without changing either the type
3288/// size or the allocated size.
3289static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3290 if (Ty->isSingleValueType())
3291 return Ty;
3292
3293 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3294 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3295
3296 Type *InnerTy;
3297 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3298 InnerTy = ArrTy->getElementType();
3299 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3300 const StructLayout *SL = DL.getStructLayout(STy);
3301 unsigned Index = SL->getElementContainingOffset(0);
3302 InnerTy = STy->getElementType(Index);
3303 } else {
3304 return Ty;
3305 }
3306
3307 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3308 TypeSize > DL.getTypeSizeInBits(InnerTy))
3309 return Ty;
3310
3311 return stripAggregateTypeWrapping(DL, InnerTy);
3312}
3313
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003314/// \brief Try to find a partition of the aggregate type passed in for a given
3315/// offset and size.
3316///
3317/// This recurses through the aggregate type and tries to compute a subtype
3318/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003319/// of an array, it will even compute a new array type for that sub-section,
3320/// and the same for structs.
3321///
3322/// Note that this routine is very strict and tries to find a partition of the
3323/// type which produces the *exact* right offset and size. It is not forgiving
3324/// when the size or offset cause either end of type-based partition to be off.
3325/// Also, this is a best-effort routine. It is reasonable to give up and not
3326/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003327static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3328 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003329 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3330 return stripAggregateTypeWrapping(DL, Ty);
3331 if (Offset > DL.getTypeAllocSize(Ty) ||
3332 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003333 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003334
3335 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3336 // We can't partition pointers...
3337 if (SeqTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003338 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003339
3340 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003341 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003342 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003343 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003344 if (NumSkippedElements >= ArrTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003345 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003346 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003347 if (NumSkippedElements >= VecTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +00003348 return nullptr;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003349 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003350 Offset -= NumSkippedElements * ElementSize;
3351
3352 // First check if we need to recurse.
3353 if (Offset > 0 || Size < ElementSize) {
3354 // Bail if the partition ends in a different array element.
3355 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003356 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003357 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003358 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003359 }
3360 assert(Offset == 0);
3361
3362 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003363 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003364 assert(Size > ElementSize);
3365 uint64_t NumElements = Size / ElementSize;
3366 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003367 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003368 return ArrayType::get(ElementTy, NumElements);
3369 }
3370
3371 StructType *STy = dyn_cast<StructType>(Ty);
3372 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003373 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003374
Chandler Carruth90a735d2013-07-19 07:21:28 +00003375 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003376 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003377 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003378 uint64_t EndOffset = Offset + Size;
3379 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003380 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003381
3382 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003383 Offset -= SL->getElementOffset(Index);
3384
3385 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003386 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003387 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003388 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003389
3390 // See if any partition must be contained by the element.
3391 if (Offset > 0 || Size < ElementSize) {
3392 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003393 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003394 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003395 }
3396 assert(Offset == 0);
3397
3398 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003399 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003400
3401 StructType::element_iterator EI = STy->element_begin() + Index,
3402 EE = STy->element_end();
3403 if (EndOffset < SL->getSizeInBytes()) {
3404 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3405 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003406 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003407
3408 // Don't try to form "natural" types if the elements don't line up with the
3409 // expected size.
3410 // FIXME: We could potentially recurse down through the last element in the
3411 // sub-struct to find a natural end point.
3412 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003413 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003414
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003415 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003416 EE = STy->element_begin() + EndIndex;
3417 }
3418
3419 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003420 StructType *SubTy =
3421 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003422 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003423 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003424 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003425
Chandler Carruth054a40a2012-09-14 11:08:31 +00003426 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003427}
3428
3429/// \brief Rewrite an alloca partition's users.
3430///
3431/// This routine drives both of the rewriting goals of the SROA pass. It tries
3432/// to rewrite uses of an alloca partition to be conducive for SSA value
3433/// promotion. If the partition needs a new, more refined alloca, this will
3434/// build that new alloca, preserving as much type information as possible, and
3435/// rewrite the uses of the old alloca to point at the new one and have the
3436/// appropriate new offsets. It also evaluates how successful the rewrite was
3437/// at enabling promotion and if it was successful queues the alloca to be
3438/// promoted.
Chandler Carruth83934062014-10-16 21:11:55 +00003439bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003440 AllocaSlices::Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003441 // Try to compute a friendly type for this partition of the alloca. This
3442 // won't always succeed, in which case we fall back to a legal integer type
3443 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00003444 Type *SliceTy = nullptr;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003445 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3446 if (DL->getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003447 SliceTy = CommonUseTy;
3448 if (!SliceTy)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003449 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003450 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003451 SliceTy = TypePartitionTy;
3452 if ((!SliceTy || (SliceTy->isArrayTy() &&
3453 SliceTy->getArrayElementType()->isIntegerTy())) &&
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003454 DL->isLegalInteger(P.size() * 8))
3455 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003456 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003457 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3458 assert(DL->getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00003459
Chandler Carruth5031bbe2014-12-24 01:05:14 +00003460 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, *DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00003461
Chandler Carruth2dc96822014-10-18 00:44:02 +00003462 VectorType *VecTy =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00003463 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, *DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00003464 if (VecTy)
3465 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003466
3467 // Check for the case where we're going to rewrite to a new alloca of the
3468 // exact same type as the original, and with the same access offsets. In that
3469 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003470 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003471 AllocaInst *NewAI;
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003472 if (SliceTy == AI.getAllocatedType()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003473 assert(P.beginOffset() == 0 &&
3474 "Non-zero begin offset but same alloca type");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003475 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00003476 // FIXME: We should be able to bail at this point with "nothing changed".
3477 // FIXME: We might want to defer PHI speculation until after here.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003478 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003479 unsigned Alignment = AI.getAlignment();
3480 if (!Alignment) {
3481 // The minimum alignment which users can rely on when the explicit
3482 // alignment is omitted or zero is that required by the ABI for this
3483 // type.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003484 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00003485 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003486 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00003487 // If we will get at least this much alignment from the type alone, leave
3488 // the alloca's alignment unconstrained.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003489 if (Alignment <= DL->getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00003490 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003491 NewAI = new AllocaInst(
3492 SliceTy, nullptr, Alignment,
3493 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003494 ++NumNewAllocas;
3495 }
3496
3497 DEBUG(dbgs() << "Rewriting alloca partition "
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003498 << "[" << P.beginOffset() << "," << P.endOffset()
3499 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003500
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003501 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00003502 // promoted allocas. We will reset it to this point if the alloca is not in
3503 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003504 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00003505 unsigned NumUses = 0;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003506 SmallPtrSet<PHINode *, 8> PHIUsers;
3507 SmallPtrSet<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00003508
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003509 AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, P.beginOffset(),
3510 P.endOffset(), IsIntegerPromotable, VecTy,
3511 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00003512 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00003513 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003514 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003515 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003516 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003517 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003518 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003519 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00003520 }
3521
Chandler Carruth6c321c12013-07-19 10:57:36 +00003522 NumAllocaPartitionUses += NumUses;
3523 MaxUsesPerAllocaPartition =
3524 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003525
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003526 // Now that we've processed all the slices in the new partition, check if any
3527 // PHIs or Selects would block promotion.
3528 for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3529 E = PHIUsers.end();
3530 I != E; ++I)
3531 if (!isSafePHIToSpeculate(**I, DL)) {
3532 Promotable = false;
3533 PHIUsers.clear();
3534 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003535 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003536 }
3537 for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3538 E = SelectUsers.end();
3539 I != E; ++I)
3540 if (!isSafeSelectToSpeculate(**I, DL)) {
3541 Promotable = false;
3542 PHIUsers.clear();
3543 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00003544 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003545 }
3546
3547 if (Promotable) {
3548 if (PHIUsers.empty() && SelectUsers.empty()) {
3549 // Promote the alloca.
3550 PromotableAllocas.push_back(NewAI);
3551 } else {
3552 // If we have either PHIs or Selects to speculate, add them to those
3553 // worklists and re-queue the new alloca so that we promote in on the
3554 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00003555 for (PHINode *PHIUser : PHIUsers)
3556 SpeculatablePHIs.insert(PHIUser);
3557 for (SelectInst *SelectUser : SelectUsers)
3558 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003559 Worklist.insert(NewAI);
3560 }
3561 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003562 // If we can't promote the alloca, iterate on it to check for new
3563 // refinements exposed by splitting the current alloca. Don't iterate on an
3564 // alloca which didn't actually change and didn't get promoted.
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003565 if (NewAI != &AI)
3566 Worklist.insert(NewAI);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003567
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003568 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00003569 while (PostPromotionWorklist.size() > PPWOldSize)
3570 PostPromotionWorklist.pop_back();
Chandler Carruthf0546402013-07-18 07:15:00 +00003571 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003572
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003573 return true;
3574}
3575
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003576/// \brief Walks the slices of an alloca and form partitions based on them,
3577/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00003578bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3579 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00003580 return false;
3581
Chandler Carruth6c321c12013-07-19 10:57:36 +00003582 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003583 bool Changed = false;
Chandler Carruthf0546402013-07-18 07:15:00 +00003584
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00003585 // Rewrite each parttion.
3586 for (auto &P : AS.partitions()) {
3587 Changed |= rewritePartition(AI, AS, P);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003588 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00003589 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003590
Chandler Carruth6c321c12013-07-19 10:57:36 +00003591 NumAllocaPartitions += NumPartitions;
3592 MaxPartitionsPerAlloca =
3593 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
Chandler Carruth6c321c12013-07-19 10:57:36 +00003594
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003595 return Changed;
3596}
3597
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003598/// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3599void SROA::clobberUse(Use &U) {
3600 Value *OldV = U;
3601 // Replace the use with an undef value.
3602 U = UndefValue::get(OldV->getType());
3603
3604 // Check for this making an instruction dead. We have to garbage collect
3605 // all the dead instructions to ensure the uses of any alloca end up being
3606 // minimal.
3607 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3608 if (isInstructionTriviallyDead(OldI)) {
3609 DeadInsts.insert(OldI);
3610 }
3611}
3612
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003613/// \brief Analyze an alloca for SROA.
3614///
3615/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003616/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003617/// rewritten as needed.
3618bool SROA::runOnAlloca(AllocaInst &AI) {
3619 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3620 ++NumAllocasAnalyzed;
3621
3622 // Special case dead allocas, as they're trivial.
3623 if (AI.use_empty()) {
3624 AI.eraseFromParent();
3625 return true;
3626 }
3627
3628 // Skip alloca forms that this analysis can't handle.
3629 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00003630 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003631 return false;
3632
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003633 bool Changed = false;
3634
3635 // First, split any FCA loads and stores touching this alloca to promote
3636 // better splitting and promotion opportunities.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003637 AggLoadStoreRewriter AggRewriter(*DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003638 Changed |= AggRewriter.rewrite(AI);
3639
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003640 // Build the slices using a recursive instruction-visiting builder.
Chandler Carruth83934062014-10-16 21:11:55 +00003641 AllocaSlices AS(*DL, AI);
3642 DEBUG(AS.print(dbgs()));
3643 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003644 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003645
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003646 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00003647 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003648 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003649 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00003650 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003651
3652 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003653 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003654
3655 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003656 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003657 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003658 }
Chandler Carruth83934062014-10-16 21:11:55 +00003659 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00003660 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00003661 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003662 }
3663
Chandler Carruth9f21fe12013-07-19 09:13:58 +00003664 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00003665 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003666 return Changed;
3667
Chandler Carruth83934062014-10-16 21:11:55 +00003668 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00003669
3670 DEBUG(dbgs() << " Speculating PHIs\n");
3671 while (!SpeculatablePHIs.empty())
3672 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3673
3674 DEBUG(dbgs() << " Speculating Selects\n");
3675 while (!SpeculatableSelects.empty())
3676 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3677
3678 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003679}
3680
Chandler Carruth19450da2012-09-14 10:26:38 +00003681/// \brief Delete the dead instructions accumulated in this run.
3682///
3683/// Recursively deletes the dead instructions we've accumulated. This is done
3684/// at the very end to maximize locality of the recursive delete and to
3685/// minimize the problems of invalidated instruction pointers as such pointers
3686/// are used heavily in the intermediate stages of the algorithm.
3687///
3688/// We also record the alloca instructions deleted here so that they aren't
3689/// subsequently handed to mem2reg to promote.
Chandler Carruth113dc642014-12-20 02:39:18 +00003690void SROA::deleteDeadInstructions(
3691 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003692 while (!DeadInsts.empty()) {
3693 Instruction *I = DeadInsts.pop_back_val();
3694 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3695
Chandler Carruth58d05562012-10-25 04:37:07 +00003696 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3697
Chandler Carruth1583e992014-03-03 10:42:58 +00003698 for (Use &Operand : I->operands())
3699 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003700 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00003701 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003702 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003703 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003704 }
3705
3706 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3707 DeletedAllocas.insert(AI);
3708
3709 ++NumDeleted;
3710 I->eraseFromParent();
3711 }
3712}
3713
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003714static void enqueueUsersInWorklist(Instruction &I,
Chandler Carruth45b136f2013-08-11 01:03:18 +00003715 SmallVectorImpl<Instruction *> &Worklist,
Craig Topper71b7b682014-08-21 05:55:13 +00003716 SmallPtrSetImpl<Instruction *> &Visited) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003717 for (User *U : I.users())
David Blaikie70573dc2014-11-19 07:49:26 +00003718 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003719 Worklist.push_back(cast<Instruction>(U));
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003720}
3721
Chandler Carruth70b44c52012-09-15 11:43:14 +00003722/// \brief Promote the allocas, using the best available technique.
3723///
3724/// This attempts to promote whatever allocas have been identified as viable in
3725/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3726/// If there is a domtree available, we attempt to promote using the full power
3727/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3728/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003729/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003730bool SROA::promoteAllocas(Function &F) {
3731 if (PromotableAllocas.empty())
3732 return false;
3733
3734 NumPromoted += PromotableAllocas.size();
3735
3736 if (DT && !ForceSSAUpdater) {
3737 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Hal Finkel60db0582014-09-07 18:57:58 +00003738 PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003739 PromotableAllocas.clear();
3740 return true;
3741 }
3742
3743 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3744 SSAUpdater SSA;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003745 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Chandler Carruth45b136f2013-08-11 01:03:18 +00003746 SmallVector<Instruction *, 64> Insts;
Chandler Carruth70b44c52012-09-15 11:43:14 +00003747
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003748 // We need a worklist to walk the uses of each alloca.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003749 SmallVector<Instruction *, 8> Worklist;
3750 SmallPtrSet<Instruction *, 8> Visited;
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003751 SmallVector<Instruction *, 32> DeadInsts;
3752
Chandler Carruth70b44c52012-09-15 11:43:14 +00003753 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3754 AllocaInst *AI = PromotableAllocas[Idx];
Chandler Carruth45b136f2013-08-11 01:03:18 +00003755 Insts.clear();
3756 Worklist.clear();
3757 Visited.clear();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003758
Chandler Carruth45b136f2013-08-11 01:03:18 +00003759 enqueueUsersInWorklist(*AI, Worklist, Visited);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003760
Chandler Carruth45b136f2013-08-11 01:03:18 +00003761 while (!Worklist.empty()) {
3762 Instruction *I = Worklist.pop_back_val();
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003763
Chandler Carruth70b44c52012-09-15 11:43:14 +00003764 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3765 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3766 // leading to them) here. Eventually it should use them to optimize the
3767 // scalar values produced.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003768 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003769 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3770 II->getIntrinsicID() == Intrinsic::lifetime_end);
3771 II->eraseFromParent();
3772 continue;
3773 }
3774
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003775 // Push the loads and stores we find onto the list. SROA will already
3776 // have validated that all loads and stores are viable candidates for
3777 // promotion.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003778 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003779 assert(LI->getType() == AI->getAllocatedType());
3780 Insts.push_back(LI);
3781 continue;
3782 }
Chandler Carruth45b136f2013-08-11 01:03:18 +00003783 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003784 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3785 Insts.push_back(SI);
3786 continue;
3787 }
3788
3789 // For everything else, we know that only no-op bitcasts and GEPs will
3790 // make it this far, just recurse through them and recall them for later
3791 // removal.
Chandler Carruth45b136f2013-08-11 01:03:18 +00003792 DeadInsts.push_back(I);
3793 enqueueUsersInWorklist(*I, Worklist, Visited);
Chandler Carruth70b44c52012-09-15 11:43:14 +00003794 }
3795 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Chandler Carruthcd7c8cd2013-07-29 09:06:53 +00003796 while (!DeadInsts.empty())
3797 DeadInsts.pop_back_val()->eraseFromParent();
3798 AI->eraseFromParent();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003799 }
3800
3801 PromotableAllocas.clear();
3802 return true;
3803}
3804
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003805bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00003806 if (skipOptnoneFunction(F))
3807 return false;
3808
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003809 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3810 C = &F.getContext();
Rafael Espindola93512512014-02-25 17:30:31 +00003811 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3812 if (!DLP) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003813 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3814 return false;
3815 }
Rafael Espindola93512512014-02-25 17:30:31 +00003816 DL = &DLP->getDataLayout();
Chandler Carruth73523022014-01-13 13:07:17 +00003817 DominatorTreeWrapperPass *DTWP =
3818 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003819 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +00003820 AT = &getAnalysis<AssumptionTracker>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003821
3822 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003823 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Chandler Carruthc7d1e242014-12-23 02:58:14 +00003824 I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003825 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3826 Worklist.insert(AI);
3827
3828 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003829 // A set of deleted alloca instruction pointers which should be removed from
3830 // the list of promotable allocas.
3831 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3832
Chandler Carruthac8317f2012-10-04 12:33:50 +00003833 do {
3834 while (!Worklist.empty()) {
3835 Changed |= runOnAlloca(*Worklist.pop_back_val());
3836 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003837
Chandler Carruthac8317f2012-10-04 12:33:50 +00003838 // Remove the deleted allocas from various lists so that we don't try to
3839 // continue processing them.
3840 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00003841 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003842 Worklist.remove_if(IsInSet);
3843 PostPromotionWorklist.remove_if(IsInSet);
Chandler Carruthac8317f2012-10-04 12:33:50 +00003844 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3845 PromotableAllocas.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00003846 IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00003847 PromotableAllocas.end());
3848 DeletedAllocas.clear();
3849 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003850 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003851
Chandler Carruthac8317f2012-10-04 12:33:50 +00003852 Changed |= promoteAllocas(F);
3853
3854 Worklist = PostPromotionWorklist;
3855 PostPromotionWorklist.clear();
3856 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003857
3858 return Changed;
3859}
3860
3861void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel60db0582014-09-07 18:57:58 +00003862 AU.addRequired<AssumptionTracker>();
Chandler Carruth70b44c52012-09-15 11:43:14 +00003863 if (RequiresDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00003864 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003865 AU.setPreservesCFG();
3866}