blob: 0e57e5cc12ff06cc29990dd78fa3c74def2bc638 [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
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruthdbd69582012-11-30 03:08:41 +000047#include "llvm/InstVisitor.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 Carruth1b398ae2012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Transforms/Utils/Local.h"
55#include "llvm/Transforms/Utils/PromoteMemToReg.h"
56#include "llvm/Transforms/Utils/SSAUpdater.h"
57using namespace llvm;
58
59STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
60STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
61STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
62STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
63STATISTIC(NumDeleted, "Number of instructions deleted");
64STATISTIC(NumVectorized, "Number of vectorized aggregates");
65
Chandler Carruth70b44c52012-09-15 11:43:14 +000066/// Hidden option to force the pass to not use DomTree and mem2reg, instead
67/// forming SSA values through the SSAUpdater infrastructure.
68static cl::opt<bool>
69ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
70
Chandler Carruth1b398ae2012-09-14 09:22:59 +000071namespace {
Chandler Carruthf74654d2013-03-18 08:36:46 +000072/// \brief A common base class for representing a half-open byte range.
73struct ByteRange {
74 /// \brief The beginning offset of the range.
75 uint64_t BeginOffset;
76
77 /// \brief The ending offset, not included in the range.
78 uint64_t EndOffset;
79
80 ByteRange() : BeginOffset(), EndOffset() {}
81 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
82 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
83
84 /// \brief Support for ordering ranges.
85 ///
86 /// This provides an ordering over ranges such that start offsets are
87 /// always increasing, and within equal start offsets, the end offsets are
88 /// decreasing. Thus the spanning range comes first in a cluster with the
89 /// same start position.
90 bool operator<(const ByteRange &RHS) const {
91 if (BeginOffset < RHS.BeginOffset) return true;
92 if (BeginOffset > RHS.BeginOffset) return false;
93 if (EndOffset > RHS.EndOffset) return true;
94 return false;
95 }
96
97 /// \brief Support comparison with a single offset to allow binary searches.
98 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
99 return LHS.BeginOffset < RHSOffset;
100 }
101
102 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
103 const ByteRange &RHS) {
104 return LHSOffset < RHS.BeginOffset;
105 }
106
107 bool operator==(const ByteRange &RHS) const {
108 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
109 }
110 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
111};
112
113/// \brief A partition of an alloca.
114///
115/// This structure represents a contiguous partition of the alloca. These are
116/// formed by examining the uses of the alloca. During formation, they may
117/// overlap but once an AllocaPartitioning is built, the Partitions within it
118/// are all disjoint.
119struct Partition : public ByteRange {
120 /// \brief Whether this partition is splittable into smaller partitions.
121 ///
122 /// We flag partitions as splittable when they are formed entirely due to
123 /// accesses by trivially splittable operations such as memset and memcpy.
124 bool IsSplittable;
125
126 /// \brief Test whether a partition has been marked as dead.
127 bool isDead() const {
128 if (BeginOffset == UINT64_MAX) {
129 assert(EndOffset == UINT64_MAX);
130 return true;
131 }
132 return false;
133 }
134
135 /// \brief Kill a partition.
136 /// This is accomplished by setting both its beginning and end offset to
137 /// the maximum possible value.
138 void kill() {
139 assert(!isDead() && "He's Dead, Jim!");
140 BeginOffset = EndOffset = UINT64_MAX;
141 }
142
143 Partition() : ByteRange(), IsSplittable() {}
144 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
145 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
146};
147
148/// \brief A particular use of a partition of the alloca.
149///
150/// This structure is used to associate uses of a partition with it. They
151/// mark the range of bytes which are referenced by a particular instruction,
152/// and includes a handle to the user itself and the pointer value in use.
153/// The bounds of these uses are determined by intersecting the bounds of the
154/// memory use itself with a particular partition. As a consequence there is
155/// intentionally overlap between various uses of the same partition.
156class PartitionUse : public ByteRange {
157 /// \brief Combined storage for both the Use* and split state.
158 PointerIntPair<Use*, 1, bool> UsePtrAndIsSplit;
159
160public:
161 PartitionUse() : ByteRange(), UsePtrAndIsSplit() {}
162 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U,
163 bool IsSplit)
164 : ByteRange(BeginOffset, EndOffset), UsePtrAndIsSplit(U, IsSplit) {}
165
166 /// \brief The use in question. Provides access to both user and used value.
167 ///
168 /// Note that this may be null if the partition use is *dead*, that is, it
169 /// should be ignored.
170 Use *getUse() const { return UsePtrAndIsSplit.getPointer(); }
171
172 /// \brief Set the use for this partition use range.
173 void setUse(Use *U) { UsePtrAndIsSplit.setPointer(U); }
174
175 /// \brief Whether this use is split across multiple partitions.
176 bool isSplit() const { return UsePtrAndIsSplit.getInt(); }
177};
178}
179
180namespace llvm {
181template <> struct isPodLike<Partition> : llvm::true_type {};
182template <> struct isPodLike<PartitionUse> : llvm::true_type {};
183}
184
185namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000186/// \brief Alloca partitioning representation.
187///
188/// This class represents a partitioning of an alloca into slices, and
189/// information about the nature of uses of each slice of the alloca. The goal
190/// is that this information is sufficient to decide if and how to split the
191/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth93a21e72012-09-14 10:18:49 +0000192/// structure can capture the relevant information needed both to decide about
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000193/// and to enact these transformations.
194class AllocaPartitioning {
195public:
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000196 /// \brief Construct a partitioning of a particular alloca.
197 ///
198 /// Construction does most of the work for partitioning the alloca. This
199 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000200 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000201
202 /// \brief Test whether a pointer to the allocation escapes our analysis.
203 ///
204 /// If this is true, the partitioning is never fully built and should be
205 /// ignored.
206 bool isEscaped() const { return PointerEscapingInstr; }
207
208 /// \brief Support for iterating over the partitions.
209 /// @{
210 typedef SmallVectorImpl<Partition>::iterator iterator;
211 iterator begin() { return Partitions.begin(); }
212 iterator end() { return Partitions.end(); }
213
214 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
215 const_iterator begin() const { return Partitions.begin(); }
216 const_iterator end() const { return Partitions.end(); }
217 /// @}
218
219 /// \brief Support for iterating over and manipulating a particular
220 /// partition's uses.
221 ///
222 /// The iteration support provided for uses is more limited, but also
223 /// includes some manipulation routines to support rewriting the uses of
224 /// partitions during SROA.
225 /// @{
226 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
227 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
228 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
229 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
230 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000231
232 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
233 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
234 const_use_iterator use_begin(const_iterator I) const {
235 return Uses[I - begin()].begin();
236 }
237 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
238 const_use_iterator use_end(const_iterator I) const {
239 return Uses[I - begin()].end();
240 }
Chandler Carruth3903e052012-10-02 17:49:47 +0000241
242 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
243 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
244 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
245 return Uses[PIdx][UIdx];
246 }
247 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
248 return Uses[I - begin()][UIdx];
249 }
250
251 void use_push_back(unsigned Idx, const PartitionUse &PU) {
252 Uses[Idx].push_back(PU);
253 }
254 void use_push_back(const_iterator I, const PartitionUse &PU) {
255 Uses[I - begin()].push_back(PU);
256 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000257 /// @}
258
259 /// \brief Allow iterating the dead users for this alloca.
260 ///
261 /// These are instructions which will never actually use the alloca as they
262 /// are outside the allocated range. They are safe to replace with undef and
263 /// delete.
264 /// @{
265 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
266 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
267 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
268 /// @}
269
Chandler Carruth93a21e72012-09-14 10:18:49 +0000270 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000271 ///
272 /// These are operands which have cannot actually be used to refer to the
273 /// alloca as they are outside its range and the user doesn't correct for
274 /// that. These mostly consist of PHI node inputs and the like which we just
275 /// need to replace with undef.
276 /// @{
277 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
278 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
279 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
280 /// @}
281
282 /// \brief MemTransferInst auxiliary data.
283 /// This struct provides some auxiliary data about memory transfer
284 /// intrinsics such as memcpy and memmove. These intrinsics can use two
285 /// different ranges within the same alloca, and provide other challenges to
286 /// correctly represent. We stash extra data to help us untangle this
287 /// after the partitioning is complete.
288 struct MemTransferOffsets {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000289 /// The destination begin and end offsets when the destination is within
290 /// this alloca. If the end offset is zero the destination is not within
291 /// this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000292 uint64_t DestBegin, DestEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000293
294 /// The source begin and end offsets when the source is within this alloca.
295 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296 uint64_t SourceBegin, SourceEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000297
298 /// Flag for whether an alloca is splittable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000299 bool IsSplittable;
300 };
301 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
302 return MemTransferInstData.lookup(&II);
303 }
304
305 /// \brief Map from a PHI or select operand back to a partition.
306 ///
307 /// When manipulating PHI nodes or selects, they can use more than one
308 /// partition of an alloca. We store a special mapping to allow finding the
309 /// partition referenced by each of these operands, if any.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000310 iterator findPartitionForPHIOrSelectOperand(Use *U) {
311 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
312 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000313 if (MapIt == PHIOrSelectOpMap.end())
314 return end();
315
316 return begin() + MapIt->second.first;
317 }
318
319 /// \brief Map from a PHI or select operand back to the specific use of
320 /// a partition.
321 ///
322 /// Similar to mapping these operands back to the partitions, this maps
323 /// directly to the use structure of that partition.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000324 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
325 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
326 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000327 assert(MapIt != PHIOrSelectOpMap.end());
328 return Uses[MapIt->second.first].begin() + MapIt->second.second;
329 }
330
331 /// \brief Compute a common type among the uses of a particular partition.
332 ///
333 /// This routines walks all of the uses of a particular partition and tries
334 /// to find a common type between them. Untyped operations such as memset and
335 /// memcpy are ignored.
336 Type *getCommonType(iterator I) const;
337
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000338#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000339 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
340 void printUsers(raw_ostream &OS, const_iterator I,
341 StringRef Indent = " ") const;
342 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000343 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
344 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000345#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000346
347private:
348 template <typename DerivedT, typename RetT = void> class BuilderBase;
349 class PartitionBuilder;
350 friend class AllocaPartitioning::PartitionBuilder;
351 class UseBuilder;
352 friend class AllocaPartitioning::UseBuilder;
353
Chandler Carruthb7915f72012-11-20 10:23:07 +0000354#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000355 /// \brief Handle to alloca instruction to simplify method interfaces.
356 AllocaInst &AI;
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000357#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000358
359 /// \brief The instruction responsible for this alloca having no partitioning.
360 ///
361 /// When an instruction (potentially) escapes the pointer to the alloca, we
362 /// store a pointer to that here and abort trying to partition the alloca.
363 /// This will be null if the alloca is partitioned successfully.
364 Instruction *PointerEscapingInstr;
365
366 /// \brief The partitions of the alloca.
367 ///
368 /// We store a vector of the partitions over the alloca here. This vector is
369 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth93a21e72012-09-14 10:18:49 +0000370 /// the Partition inner class for more details. Initially (during
371 /// construction) there are overlaps, but we form a disjoint sequence of
372 /// partitions while finishing construction and a fully constructed object is
373 /// expected to always have this as a disjoint space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000374 SmallVector<Partition, 8> Partitions;
375
376 /// \brief The uses of the partitions.
377 ///
378 /// This is essentially a mapping from each partition to a list of uses of
379 /// that partition. The mapping is done with a Uses vector that has the exact
380 /// same number of entries as the partition vector. Each entry is itself
381 /// a vector of the uses.
382 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
383
384 /// \brief Instructions which will become dead if we rewrite the alloca.
385 ///
386 /// Note that these are not separated by partition. This is because we expect
387 /// a partitioned alloca to be completely rewritten or not rewritten at all.
388 /// If rewritten, all these instructions can simply be removed and replaced
389 /// with undef as they come from outside of the allocated space.
390 SmallVector<Instruction *, 8> DeadUsers;
391
392 /// \brief Operands which will become dead if we rewrite the alloca.
393 ///
394 /// These are operands that in their particular use can be replaced with
395 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
396 /// to PHI nodes and the like. They aren't entirely dead (there might be
397 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
398 /// want to swap this particular input for undef to simplify the use lists of
399 /// the alloca.
400 SmallVector<Use *, 8> DeadOperands;
401
402 /// \brief The underlying storage for auxiliary memcpy and memset info.
403 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
404
405 /// \brief A side datastructure used when building up the partitions and uses.
406 ///
407 /// This mapping is only really used during the initial building of the
408 /// partitioning so that we can retain information about PHI and select nodes
409 /// processed.
410 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
411
412 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000413 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000414
415 /// \brief A utility routine called from the constructor.
416 ///
417 /// This does what it says on the tin. It is the key of the alloca partition
418 /// splitting and merging. After it is called we have the desired disjoint
419 /// collection of partitions.
420 void splitAndMergePartitions();
421};
422}
423
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000424static Value *foldSelectInst(SelectInst &SI) {
425 // If the condition being selected on is a constant or the same value is
426 // being selected between, fold the select. Yes this does (rarely) happen
427 // early on.
428 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
429 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000430 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000431 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000432
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000433 return 0;
434}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000435
436/// \brief Builder for the alloca partitioning.
437///
438/// This class builds an alloca partitioning by recursively visiting the uses
439/// of an alloca and splitting the partitions for each load and store at each
440/// offset.
441class AllocaPartitioning::PartitionBuilder
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000442 : public PtrUseVisitor<PartitionBuilder> {
443 friend class PtrUseVisitor<PartitionBuilder>;
444 friend class InstVisitor<PartitionBuilder>;
445 typedef PtrUseVisitor<PartitionBuilder> Base;
446
447 const uint64_t AllocSize;
448 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000449
450 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
451
452public:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000453 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
454 : PtrUseVisitor<PartitionBuilder>(DL),
455 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
456 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000457
458private:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000459 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000460 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000461 // Completely skip uses which have a zero size or start either before or
462 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000463 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000464 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000465 << " which has zero size or starts outside of the "
466 << AllocSize << " byte alloca:\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000467 << " alloca: " << P.AI << "\n"
468 << " use: " << I << "\n");
469 return;
470 }
471
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000472 uint64_t BeginOffset = Offset.getZExtValue();
473 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000474
475 // Clamp the end offset to the end of the allocation. Note that this is
476 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000477 // This may appear superficially to be something we could ignore entirely,
478 // but that is not so! There may be widened loads or PHI-node uses where
479 // some instructions are dead but not others. We can't completely ignore
480 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000481 assert(AllocSize >= BeginOffset); // Established above.
482 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000483 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
484 << " to remain within the " << AllocSize << " byte alloca:\n"
485 << " alloca: " << P.AI << "\n"
486 << " use: " << I << "\n");
487 EndOffset = AllocSize;
488 }
489
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000490 Partition New(BeginOffset, EndOffset, IsSplittable);
491 P.Partitions.push_back(New);
492 }
493
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000494 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000495 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000496 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000497 // and cover the entire alloca. This prevents us from splitting over
498 // eagerly.
499 // FIXME: In the great blue eventually, we should eagerly split all integer
500 // loads and stores, and then have a separate step that merges adjacent
501 // alloca partitions into a single partition suitable for integer widening.
502 // Or we should skip the merge step and rely on GVN and other passes to
503 // merge adjacent loads and stores that survive mem2reg.
504 bool IsSplittable =
505 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000506
507 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000508 }
509
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000510 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000511 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
512 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000513
514 if (!IsOffsetKnown)
515 return PI.setAborted(&LI);
516
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000517 uint64_t Size = DL.getTypeStoreSize(LI.getType());
518 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000519 }
520
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000521 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000522 Value *ValOp = SI.getValueOperand();
523 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000524 return PI.setEscapedAndAborted(&SI);
525 if (!IsOffsetKnown)
526 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000527
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000528 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
529
530 // If this memory access can be shown to *statically* extend outside the
531 // bounds of of the allocation, it's behavior is undefined, so simply
532 // ignore it. Note that this is more strict than the generic clamping
533 // behavior of insertUse. We also try to handle cases which might run the
534 // risk of overflow.
535 // FIXME: We should instead consider the pointer to have escaped if this
536 // function is being instrumented for addressing bugs or race conditions.
537 if (Offset.isNegative() || Size > AllocSize ||
538 Offset.ugt(AllocSize - Size)) {
539 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
540 << " which extends past the end of the " << AllocSize
541 << " byte alloca:\n"
542 << " alloca: " << P.AI << "\n"
543 << " use: " << SI << "\n");
544 return;
545 }
546
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000547 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
548 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000549 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000550 }
551
552
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000553 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000554 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000555 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000556 if ((Length && Length->getValue() == 0) ||
557 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
558 // Zero-length mem transfer intrinsics can be ignored entirely.
559 return;
560
561 if (!IsOffsetKnown)
562 return PI.setAborted(&II);
563
564 insertUse(II, Offset,
565 Length ? Length->getLimitedValue()
566 : AllocSize - Offset.getLimitedValue(),
567 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000568 }
569
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000570 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000571 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000572 if ((Length && Length->getValue() == 0) ||
573 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000574 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000575 return;
576
577 if (!IsOffsetKnown)
578 return PI.setAborted(&II);
579
580 uint64_t RawOffset = Offset.getLimitedValue();
581 uint64_t Size = Length ? Length->getLimitedValue()
582 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000583
584 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
585
586 // Only intrinsics with a constant length can be split.
587 Offsets.IsSplittable = Length;
588
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000589 if (*U == II.getRawDest()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000590 Offsets.DestBegin = RawOffset;
591 Offsets.DestEnd = RawOffset + Size;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000592 }
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000593 if (*U == II.getRawSource()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000594 Offsets.SourceBegin = RawOffset;
595 Offsets.SourceEnd = RawOffset + Size;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000596 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000597
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000598 // If we have set up end offsets for both the source and the destination,
599 // we have found both sides of this transfer pointing at the same alloca.
600 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
601 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
602 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000603
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000604 // Check if the begin offsets match and this is a non-volatile transfer.
605 // In that case, we can completely elide the transfer.
606 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
607 P.Partitions[PrevIdx].kill();
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000608 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000609 }
610
611 // Otherwise we have an offset transfer within the same alloca. We can't
612 // split those.
613 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
614 } else if (SeenBothEnds) {
615 // Handle the case where this exact use provides both ends of the
616 // operation.
617 assert(II.getRawDest() == II.getRawSource());
618
619 // For non-volatile transfers this is a no-op.
620 if (!II.isVolatile())
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000621 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000622
623 // Otherwise just suppress splitting.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000624 Offsets.IsSplittable = false;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000625 }
626
627
628 // Insert the use now that we've fixed up the splittable nature.
629 insertUse(II, Offset, Size, Offsets.IsSplittable);
630
631 // Setup the mapping from intrinsic to partition of we've not seen both
632 // ends of this transfer.
633 if (!SeenBothEnds) {
634 unsigned NewIdx = P.Partitions.size() - 1;
635 bool Inserted
636 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
637 assert(Inserted &&
638 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi605fe782012-10-05 13:56:23 +0000639 (void)Inserted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000640 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000641 }
642
643 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000644 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000645 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000646 void visitIntrinsicInst(IntrinsicInst &II) {
647 if (!IsOffsetKnown)
648 return PI.setAborted(&II);
649
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000650 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
651 II.getIntrinsicID() == Intrinsic::lifetime_end) {
652 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000653 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
654 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000655 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000656 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000657 }
658
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000659 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000660 }
661
662 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
663 // We consider any PHI or select that results in a direct load or store of
664 // the same offset to be a viable use for partitioning purposes. These uses
665 // are considered unsplittable and the size is the maximum loaded or stored
666 // size.
667 SmallPtrSet<Instruction *, 4> Visited;
668 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
669 Visited.insert(Root);
670 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000671 // If there are no loads or stores, the access is dead. We mark that as
672 // a size zero access.
673 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000674 do {
675 Instruction *I, *UsedI;
676 llvm::tie(UsedI, I) = Uses.pop_back_val();
677
678 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000679 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000680 continue;
681 }
682 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
683 Value *Op = SI->getOperand(0);
684 if (Op == UsedI)
685 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000686 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000687 continue;
688 }
689
690 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
691 if (!GEP->hasAllZeroIndices())
692 return GEP;
693 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
694 !isa<SelectInst>(I)) {
695 return I;
696 }
697
698 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
699 ++UI)
700 if (Visited.insert(cast<Instruction>(*UI)))
701 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
702 } while (!Uses.empty());
703
704 return 0;
705 }
706
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000707 void visitPHINode(PHINode &PN) {
708 if (PN.use_empty())
709 return;
710 if (!IsOffsetKnown)
711 return PI.setAborted(&PN);
712
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000713 // See if we already have computed info on this node.
714 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
715 if (PHIInfo.first) {
716 PHIInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000717 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000718 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000719 }
720
721 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000722 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
723 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000724
Chandler Carruth97121172012-09-16 19:39:50 +0000725 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000726 }
727
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000728 void visitSelectInst(SelectInst &SI) {
729 if (SI.use_empty())
730 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000731 if (Value *Result = foldSelectInst(SI)) {
732 if (Result == *U)
733 // If the result of the constant fold will be the pointer, recurse
734 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000735 enqueueUsers(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000736
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000737 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000738 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000739 if (!IsOffsetKnown)
740 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000741
742 // See if we already have computed info on this node.
743 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
744 if (SelectInfo.first) {
745 SelectInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000746 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000747 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000748 }
749
750 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000751 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
752 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000753
Chandler Carruth97121172012-09-16 19:39:50 +0000754 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000755 }
756
757 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000758 void visitInstruction(Instruction &I) {
759 PI.setAborted(&I);
760 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000761};
762
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000763/// \brief Use adder for the alloca partitioning.
764///
Chandler Carruth93a21e72012-09-14 10:18:49 +0000765/// This class adds the uses of an alloca to all of the partitions which they
766/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000767/// walk of the partitions, but the number of steps remains bounded by the
768/// total result instruction size:
769/// - The number of partitions is a result of the number unsplittable
770/// instructions using the alloca.
771/// - The number of users of each partition is at worst the total number of
772/// splittable instructions using the alloca.
773/// Thus we will produce N * M instructions in the end, where N are the number
774/// of unsplittable uses and M are the number of splittable. This visitor does
775/// the exact same number of updates to the partitioning.
776///
777/// In the more common case, this visitor will leverage the fact that the
778/// partition space is pre-sorted, and do a logarithmic search for the
779/// partition needed, making the total visit a classical ((N + M) * log(N))
780/// complexity operation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000781class AllocaPartitioning::UseBuilder : public PtrUseVisitor<UseBuilder> {
782 friend class PtrUseVisitor<UseBuilder>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000783 friend class InstVisitor<UseBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000784 typedef PtrUseVisitor<UseBuilder> Base;
785
786 const uint64_t AllocSize;
787 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000788
789 /// \brief Set to de-duplicate dead instructions found in the use walk.
790 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
791
792public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000793 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000794 : PtrUseVisitor<UseBuilder>(TD),
795 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
796 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000797
798private:
799 void markAsDead(Instruction &I) {
800 if (VisitedDeadInsts.insert(&I))
801 P.DeadUsers.push_back(&I);
802 }
803
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000804 void insertUse(Instruction &User, const APInt &Offset, uint64_t Size) {
Chandler Carruth8b907e82012-09-25 10:03:40 +0000805 // If the use has a zero size or extends outside of the allocation, record
806 // it as a dead use for elimination later.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000807 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000808 return markAsDead(User);
809
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000810 uint64_t BeginOffset = Offset.getZExtValue();
811 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000812
813 // Clamp the end offset to the end of the allocation. Note that this is
814 // formulated to handle even the case where "BeginOffset + Size" overflows.
815 assert(AllocSize >= BeginOffset); // Established above.
816 if (Size > AllocSize - BeginOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000817 EndOffset = AllocSize;
818
819 // NB: This only works if we have zero overlapping partitions.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000820 iterator I = std::lower_bound(P.begin(), P.end(), BeginOffset);
821 if (I != P.begin() && llvm::prior(I)->EndOffset > BeginOffset)
822 I = llvm::prior(I);
823 iterator E = P.end();
824 bool IsSplit = llvm::next(I) != E && llvm::next(I)->BeginOffset < EndOffset;
825 for (; I != E && I->BeginOffset < EndOffset; ++I) {
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000826 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000827 std::min(I->EndOffset, EndOffset), U, IsSplit);
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000828 P.use_push_back(I, NewPU);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000830 P.PHIOrSelectOpMap[U]
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000831 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
832 }
833 }
834
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000835 void visitBitCastInst(BitCastInst &BC) {
836 if (BC.use_empty())
837 return markAsDead(BC);
838
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000839 return Base::visitBitCastInst(BC);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000840 }
841
842 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
843 if (GEPI.use_empty())
844 return markAsDead(GEPI);
845
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000846 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000847 }
848
849 void visitLoadInst(LoadInst &LI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000850 assert(IsOffsetKnown);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000851 uint64_t Size = DL.getTypeStoreSize(LI.getType());
852 insertUse(LI, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000853 }
854
855 void visitStoreInst(StoreInst &SI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000856 assert(IsOffsetKnown);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000857 uint64_t Size = DL.getTypeStoreSize(SI.getOperand(0)->getType());
858
859 // If this memory access can be shown to *statically* extend outside the
860 // bounds of of the allocation, it's behavior is undefined, so simply
861 // ignore it. Note that this is more strict than the generic clamping
862 // behavior of insertUse.
863 if (Offset.isNegative() || Size > AllocSize ||
864 Offset.ugt(AllocSize - Size))
865 return markAsDead(SI);
866
867 insertUse(SI, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000868 }
869
870 void visitMemSetInst(MemSetInst &II) {
871 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000872 if ((Length && Length->getValue() == 0) ||
873 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
874 return markAsDead(II);
875
876 assert(IsOffsetKnown);
877 insertUse(II, Offset, Length ? Length->getLimitedValue()
878 : AllocSize - Offset.getLimitedValue());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000879 }
880
881 void visitMemTransferInst(MemTransferInst &II) {
882 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000883 if ((Length && Length->getValue() == 0) ||
884 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000885 return markAsDead(II);
886
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000887 assert(IsOffsetKnown);
888 uint64_t Size = Length ? Length->getLimitedValue()
889 : AllocSize - Offset.getLimitedValue();
890
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000891 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
892 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
893 Offsets.DestBegin == Offsets.SourceBegin)
894 return markAsDead(II); // Skip identity transfers without side-effects.
895
Chandler Carruth97121172012-09-16 19:39:50 +0000896 insertUse(II, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000897 }
898
899 void visitIntrinsicInst(IntrinsicInst &II) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000900 assert(IsOffsetKnown);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000901 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
902 II.getIntrinsicID() == Intrinsic::lifetime_end);
903
904 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000905 insertUse(II, Offset, std::min(Length->getLimitedValue(),
906 AllocSize - Offset.getLimitedValue()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000907 }
908
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000909 void insertPHIOrSelect(Instruction &User, const APInt &Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000910 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
911
912 // For PHI and select operands outside the alloca, we can't nuke the entire
913 // phi or select -- the other side might still be relevant, so we special
914 // case them here and use a separate structure to track the operands
915 // themselves which should be replaced with undef.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000916 if ((Offset.isNegative() && Offset.uge(Size)) ||
917 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000918 P.DeadOperands.push_back(U);
919 return;
920 }
921
Chandler Carruth97121172012-09-16 19:39:50 +0000922 insertUse(User, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000923 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000924
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000925 void visitPHINode(PHINode &PN) {
926 if (PN.use_empty())
927 return markAsDead(PN);
928
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000929 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000930 insertPHIOrSelect(PN, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000931 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000932
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000933 void visitSelectInst(SelectInst &SI) {
934 if (SI.use_empty())
935 return markAsDead(SI);
936
937 if (Value *Result = foldSelectInst(SI)) {
938 if (Result == *U)
939 // If the result of the constant fold will be the pointer, recurse
940 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000941 enqueueUsers(SI);
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000942 else
943 // Otherwise the operand to the select is dead, and we can replace it
944 // with undef.
945 P.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000946
947 return;
948 }
949
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000950 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000951 insertPHIOrSelect(SI, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000952 }
953
954 /// \brief Unreachable, we've already visited the alloca once.
955 void visitInstruction(Instruction &I) {
956 llvm_unreachable("Unhandled instruction in use builder.");
957 }
958};
959
960void AllocaPartitioning::splitAndMergePartitions() {
961 size_t NumDeadPartitions = 0;
962
963 // Track the range of splittable partitions that we pass when accumulating
964 // overlapping unsplittable partitions.
965 uint64_t SplitEndOffset = 0ull;
966
967 Partition New(0ull, 0ull, false);
968
969 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
970 ++j;
971
972 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
973 assert(New.BeginOffset == New.EndOffset);
974 New = Partitions[i];
975 } else {
976 assert(New.IsSplittable);
977 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
978 }
979 assert(New.BeginOffset != New.EndOffset);
980
981 // Scan the overlapping partitions.
982 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
983 // If the new partition we are forming is splittable, stop at the first
984 // unsplittable partition.
985 if (New.IsSplittable && !Partitions[j].IsSplittable)
986 break;
987
988 // Grow the new partition to include any equally splittable range. 'j' is
989 // always equally splittable when New is splittable, but when New is not
990 // splittable, we may subsume some (or part of some) splitable partition
991 // without growing the new one.
992 if (New.IsSplittable == Partitions[j].IsSplittable) {
993 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
994 } else {
995 assert(!New.IsSplittable);
996 assert(Partitions[j].IsSplittable);
997 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
998 }
999
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001000 Partitions[j].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001001 ++NumDeadPartitions;
1002 ++j;
1003 }
1004
1005 // If the new partition is splittable, chop off the end as soon as the
1006 // unsplittable subsequent partition starts and ensure we eventually cover
1007 // the splittable area.
1008 if (j != e && New.IsSplittable) {
1009 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1010 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1011 }
1012
1013 // Add the new partition if it differs from the original one and is
1014 // non-empty. We can end up with an empty partition here if it was
1015 // splittable but there is an unsplittable one that starts at the same
1016 // offset.
1017 if (New != Partitions[i]) {
1018 if (New.BeginOffset != New.EndOffset)
1019 Partitions.push_back(New);
1020 // Mark the old one for removal.
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001021 Partitions[i].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001022 ++NumDeadPartitions;
1023 }
1024
1025 New.BeginOffset = New.EndOffset;
1026 if (!New.IsSplittable) {
1027 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1028 if (j != e && !Partitions[j].IsSplittable)
1029 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1030 New.IsSplittable = true;
1031 // If there is a trailing splittable partition which won't be fused into
1032 // the next splittable partition go ahead and add it onto the partitions
1033 // list.
1034 if (New.BeginOffset < New.EndOffset &&
1035 (j == e || !Partitions[j].IsSplittable ||
1036 New.EndOffset < Partitions[j].BeginOffset)) {
1037 Partitions.push_back(New);
1038 New.BeginOffset = New.EndOffset = 0ull;
1039 }
1040 }
1041 }
1042
1043 // Re-sort the partitions now that they have been split and merged into
1044 // disjoint set of partitions. Also remove any of the dead partitions we've
1045 // replaced in the process.
1046 std::sort(Partitions.begin(), Partitions.end());
1047 if (NumDeadPartitions) {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001048 assert(Partitions.back().isDead());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001049 assert((ptrdiff_t)NumDeadPartitions ==
1050 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1051 }
1052 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1053}
1054
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001055AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001056 :
Chandler Carruthb7915f72012-11-20 10:23:07 +00001057#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001058 AI(AI),
1059#endif
1060 PointerEscapingInstr(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001061 PartitionBuilder PB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001062 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1063 if (PtrI.isEscaped() || PtrI.isAborted()) {
1064 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1065 // possibly by just storing the PtrInfo in the AllocaPartitioning.
1066 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1067 : PtrI.getAbortingInst();
1068 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001069 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001070 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001071
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001072 // Sort the uses. This arranges for the offsets to be in ascending order,
1073 // and the sizes to be in descending order.
1074 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001075
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001076 // Remove any partitions from the back which are marked as dead.
1077 while (!Partitions.empty() && Partitions.back().isDead())
1078 Partitions.pop_back();
1079
1080 if (Partitions.size() > 1) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001081 // Intersect splittability for all partitions with equal offsets and sizes.
1082 // Then remove all but the first so that we have a sequence of non-equal but
1083 // potentially overlapping partitions.
1084 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1085 I = J) {
1086 ++J;
1087 while (J != E && *I == *J) {
1088 I->IsSplittable &= J->IsSplittable;
1089 ++J;
1090 }
1091 }
1092 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1093 Partitions.end());
1094
1095 // Split splittable and merge unsplittable partitions into a disjoint set
1096 // of partitions over the used space of the allocation.
1097 splitAndMergePartitions();
1098 }
1099
1100 // Now build up the user lists for each of these disjoint partitions by
1101 // re-walking the recursive users of the alloca.
1102 Uses.resize(Partitions.size());
1103 UseBuilder UB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001104 PtrI = UB.visitPtr(AI);
1105 assert(!PtrI.isEscaped() && "Previously analyzed pointer now escapes!");
1106 assert(!PtrI.isAborted() && "Early aborted the visit of the pointer.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001107}
1108
1109Type *AllocaPartitioning::getCommonType(iterator I) const {
1110 Type *Ty = 0;
1111 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001112 Use *U = UI->getUse();
1113 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001114 continue; // Skip dead uses.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001115 if (isa<IntrinsicInst>(*U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001116 continue;
1117 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruthd356fd02012-09-18 17:49:37 +00001118 continue;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001119
1120 Type *UserTy = 0;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001121 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001122 UserTy = LI->getType();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001123 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001124 UserTy = SI->getValueOperand()->getType();
Jakub Staszakfd566112013-03-07 22:20:06 +00001125 else
Chandler Carruth58d05562012-10-25 04:37:07 +00001126 return 0; // Bail if we have weird uses.
Chandler Carruth58d05562012-10-25 04:37:07 +00001127
1128 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1129 // If the type is larger than the partition, skip it. We only encounter
1130 // this for split integer operations where we want to use the type of the
1131 // entity causing the split.
1132 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1133 continue;
1134
1135 // If we have found an integer type use covering the alloca, use that
1136 // regardless of the other types, as integers are often used for a "bucket
1137 // of bits" type.
1138 return ITy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001139 }
1140
1141 if (Ty && Ty != UserTy)
1142 return 0;
1143
1144 Ty = UserTy;
1145 }
1146 return Ty;
1147}
1148
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001149#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1150
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001151void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1152 StringRef Indent) const {
1153 OS << Indent << "partition #" << (I - begin())
1154 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1155 << (I->IsSplittable ? " (splittable)" : "")
1156 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1157 << "\n";
1158}
1159
1160void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1161 StringRef Indent) const {
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001162 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001163 if (!UI->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001164 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001165 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001166 << "used by: " << *UI->getUse()->getUser() << "\n";
1167 if (MemTransferInst *II =
1168 dyn_cast<MemTransferInst>(UI->getUse()->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001169 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1170 bool IsDest;
1171 if (!MTO.IsSplittable)
1172 IsDest = UI->BeginOffset == MTO.DestBegin;
1173 else
1174 IsDest = MTO.DestBegin != 0u;
1175 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1176 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1177 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1178 }
1179 }
1180}
1181
1182void AllocaPartitioning::print(raw_ostream &OS) const {
1183 if (PointerEscapingInstr) {
1184 OS << "No partitioning for alloca: " << AI << "\n"
1185 << " A pointer to this alloca escaped by:\n"
1186 << " " << *PointerEscapingInstr << "\n";
1187 return;
1188 }
1189
1190 OS << "Partitioning of alloca: " << AI << "\n";
Jakub Staszakae2fd9c2013-02-19 22:17:58 +00001191 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001192 print(OS, I);
1193 printUsers(OS, I);
1194 }
1195}
1196
1197void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1198void AllocaPartitioning::dump() const { print(dbgs()); }
1199
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001200#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1201
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001202
1203namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001204/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1205///
1206/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1207/// the loads and stores of an alloca instruction, as well as updating its
1208/// debug information. This is used when a domtree is unavailable and thus
1209/// mem2reg in its full form can't be used to handle promotion of allocas to
1210/// scalar values.
1211class AllocaPromoter : public LoadAndStorePromoter {
1212 AllocaInst &AI;
1213 DIBuilder &DIB;
1214
1215 SmallVector<DbgDeclareInst *, 4> DDIs;
1216 SmallVector<DbgValueInst *, 4> DVIs;
1217
1218public:
1219 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1220 AllocaInst &AI, DIBuilder &DIB)
1221 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1222
1223 void run(const SmallVectorImpl<Instruction*> &Insts) {
1224 // Remember which alloca we're promoting (for isInstInList).
1225 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1226 for (Value::use_iterator UI = DebugNode->use_begin(),
1227 UE = DebugNode->use_end();
1228 UI != UE; ++UI)
1229 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1230 DDIs.push_back(DDI);
1231 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1232 DVIs.push_back(DVI);
1233 }
1234
1235 LoadAndStorePromoter::run(Insts);
1236 AI.eraseFromParent();
1237 while (!DDIs.empty())
1238 DDIs.pop_back_val()->eraseFromParent();
1239 while (!DVIs.empty())
1240 DVIs.pop_back_val()->eraseFromParent();
1241 }
1242
1243 virtual bool isInstInList(Instruction *I,
1244 const SmallVectorImpl<Instruction*> &Insts) const {
1245 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1246 return LI->getOperand(0) == &AI;
1247 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1248 }
1249
1250 virtual void updateDebugInfo(Instruction *Inst) const {
1251 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1252 E = DDIs.end(); I != E; ++I) {
1253 DbgDeclareInst *DDI = *I;
1254 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1255 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1256 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1257 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1258 }
1259 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1260 E = DVIs.end(); I != E; ++I) {
1261 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001262 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001263 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1264 // If an argument is zero extended then use argument directly. The ZExt
1265 // may be zapped by an optimization pass in future.
1266 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1267 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1268 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1269 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1270 if (!Arg)
1271 Arg = SI->getOperand(0);
1272 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1273 Arg = LI->getOperand(0);
1274 } else {
1275 continue;
1276 }
1277 Instruction *DbgVal =
1278 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1279 Inst);
1280 DbgVal->setDebugLoc(DVI->getDebugLoc());
1281 }
1282 }
1283};
1284} // end anon namespace
1285
1286
1287namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001288/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1289///
1290/// This pass takes allocations which can be completely analyzed (that is, they
1291/// don't escape) and tries to turn them into scalar SSA values. There are
1292/// a few steps to this process.
1293///
1294/// 1) It takes allocations of aggregates and analyzes the ways in which they
1295/// are used to try to split them into smaller allocations, ideally of
1296/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001297/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001298/// 2) It will transform accesses into forms which are suitable for SSA value
1299/// promotion. This can be replacing a memset with a scalar store of an
1300/// integer value, or it can involve speculating operations on a PHI or
1301/// select to be a PHI or select of the results.
1302/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1303/// onto insert and extract operations on a vector value, and convert them to
1304/// this form. By doing so, it will enable promotion of vector aggregates to
1305/// SSA vector values.
1306class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001307 const bool RequiresDomTree;
1308
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001309 LLVMContext *C;
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001310 const DataLayout *TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001311 DominatorTree *DT;
1312
1313 /// \brief Worklist of alloca instructions to simplify.
1314 ///
1315 /// Each alloca in the function is added to this. Each new alloca formed gets
1316 /// added to it as well to recursively simplify unless that alloca can be
1317 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1318 /// the one being actively rewritten, we add it back onto the list if not
1319 /// already present to ensure it is re-visited.
1320 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1321
1322 /// \brief A collection of instructions to delete.
1323 /// We try to batch deletions to simplify code and make things a bit more
1324 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +00001325 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001326
Chandler Carruthac8317f2012-10-04 12:33:50 +00001327 /// \brief Post-promotion worklist.
1328 ///
1329 /// Sometimes we discover an alloca which has a high probability of becoming
1330 /// viable for SROA after a round of promotion takes place. In those cases,
1331 /// the alloca is enqueued here for re-processing.
1332 ///
1333 /// Note that we have to be very careful to clear allocas out of this list in
1334 /// the event they are deleted.
1335 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1336
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001337 /// \brief A collection of alloca instructions we can directly promote.
1338 std::vector<AllocaInst *> PromotableAllocas;
1339
1340public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001341 SROA(bool RequiresDomTree = true)
1342 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1343 C(0), TD(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001344 initializeSROAPass(*PassRegistry::getPassRegistry());
1345 }
1346 bool runOnFunction(Function &F);
1347 void getAnalysisUsage(AnalysisUsage &AU) const;
1348
1349 const char *getPassName() const { return "SROA"; }
1350 static char ID;
1351
1352private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001353 friend class PHIOrSelectSpeculator;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001354 friend class AllocaPartitionRewriter;
1355 friend class AllocaPartitionVectorRewriter;
1356
1357 bool rewriteAllocaPartition(AllocaInst &AI,
1358 AllocaPartitioning &P,
1359 AllocaPartitioning::iterator PI);
1360 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1361 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +00001362 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001363 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001364};
1365}
1366
1367char SROA::ID = 0;
1368
Chandler Carruth70b44c52012-09-15 11:43:14 +00001369FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1370 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001371}
1372
1373INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1374 false, false)
1375INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1376INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1377 false, false)
1378
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001379namespace {
1380/// \brief Visitor to speculate PHIs and Selects where possible.
1381class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1382 // Befriend the base class so it can delegate to private visit methods.
1383 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1384
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001385 const DataLayout &TD;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001386 AllocaPartitioning &P;
1387 SROA &Pass;
1388
1389public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001390 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001391 : TD(TD), P(P), Pass(Pass) {}
1392
1393 /// \brief Visit the users of an alloca partition and rewrite them.
1394 void visitUsers(AllocaPartitioning::const_iterator PI) {
1395 // Note that we need to use an index here as the underlying vector of uses
1396 // may be grown during speculation. However, we never need to re-visit the
1397 // new uses, and so we can use the initial size bound.
1398 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
Chandler Carruthf74654d2013-03-18 08:36:46 +00001399 const PartitionUse &PU = P.getUse(PI, Idx);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001400 if (!PU.getUse())
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001401 continue; // Skip dead use.
1402
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001403 visit(cast<Instruction>(PU.getUse()->getUser()));
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001404 }
1405 }
1406
1407private:
1408 // By default, skip this instruction.
1409 void visitInstruction(Instruction &I) {}
1410
1411 /// PHI instructions that use an alloca and are subsequently loaded can be
1412 /// rewritten to load both input pointers in the pred blocks and then PHI the
1413 /// results, allowing the load of the alloca to be promoted.
1414 /// From this:
1415 /// %P2 = phi [i32* %Alloca, i32* %Other]
1416 /// %V = load i32* %P2
1417 /// to:
1418 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1419 /// ...
1420 /// %V2 = load i32* %Other
1421 /// ...
1422 /// %V = phi [i32 %V1, i32 %V2]
1423 ///
1424 /// We can do this to a select if its only uses are loads and if the operands
1425 /// to the select can be loaded unconditionally.
1426 ///
1427 /// FIXME: This should be hoisted into a generic utility, likely in
1428 /// Transforms/Util/Local.h
1429 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1430 // For now, we can only do this promotion if the load is in the same block
1431 // as the PHI, and if there are no stores between the phi and load.
1432 // TODO: Allow recursive phi users.
1433 // TODO: Allow stores.
1434 BasicBlock *BB = PN.getParent();
1435 unsigned MaxAlign = 0;
1436 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1437 UI != UE; ++UI) {
1438 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1439 if (LI == 0 || !LI->isSimple()) return false;
1440
1441 // For now we only allow loads in the same block as the PHI. This is
1442 // a common case that happens when instcombine merges two loads through
1443 // a PHI.
1444 if (LI->getParent() != BB) return false;
1445
1446 // Ensure that there are no instructions between the PHI and the load that
1447 // could store.
1448 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1449 if (BBI->mayWriteToMemory())
1450 return false;
1451
1452 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1453 Loads.push_back(LI);
1454 }
1455
1456 // We can only transform this if it is safe to push the loads into the
1457 // predecessor blocks. The only thing to watch out for is that we can't put
1458 // a possibly trapping load in the predecessor if it is a critical edge.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001459 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001460 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1461 Value *InVal = PN.getIncomingValue(Idx);
1462
1463 // If the value is produced by the terminator of the predecessor (an
1464 // invoke) or it has side-effects, there is no valid place to put a load
1465 // in the predecessor.
1466 if (TI == InVal || TI->mayHaveSideEffects())
1467 return false;
1468
1469 // If the predecessor has a single successor, then the edge isn't
1470 // critical.
1471 if (TI->getNumSuccessors() == 1)
1472 continue;
1473
1474 // If this pointer is always safe to load, or if we can prove that there
1475 // is already a load in the block, then we can move the load to the pred
1476 // block.
1477 if (InVal->isDereferenceablePointer() ||
1478 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1479 continue;
1480
1481 return false;
1482 }
1483
1484 return true;
1485 }
1486
1487 void visitPHINode(PHINode &PN) {
1488 DEBUG(dbgs() << " original: " << PN << "\n");
1489
1490 SmallVector<LoadInst *, 4> Loads;
1491 if (!isSafePHIToSpeculate(PN, Loads))
1492 return;
1493
1494 assert(!Loads.empty());
1495
1496 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1497 IRBuilder<> PHIBuilder(&PN);
1498 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1499 PN.getName() + ".sroa.speculated");
1500
1501 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001502 // matter which one we get and if any differ.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001503 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1504 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1505 unsigned Align = SomeLoad->getAlignment();
1506
1507 // Rewrite all loads of the PN to use the new PHI.
1508 do {
1509 LoadInst *LI = Loads.pop_back_val();
1510 LI->replaceAllUsesWith(NewPN);
Chandler Carruth18db7952012-11-20 01:12:50 +00001511 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001512 } while (!Loads.empty());
1513
1514 // Inject loads into all of the pred blocks.
1515 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1516 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1517 TerminatorInst *TI = Pred->getTerminator();
1518 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1519 Value *InVal = PN.getIncomingValue(Idx);
1520 IRBuilder<> PredBuilder(TI);
1521
1522 LoadInst *Load
1523 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1524 Pred->getName()));
1525 ++NumLoadsSpeculated;
1526 Load->setAlignment(Align);
1527 if (TBAATag)
1528 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1529 NewPN->addIncoming(Load, Pred);
1530
1531 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1532 if (!Ptr)
1533 // No uses to rewrite.
1534 continue;
1535
1536 // Try to lookup and rewrite any partition uses corresponding to this phi
1537 // input.
1538 AllocaPartitioning::iterator PI
1539 = P.findPartitionForPHIOrSelectOperand(InUse);
1540 if (PI == P.end())
1541 continue;
1542
1543 // Replace the Use in the PartitionUse for this operand with the Use
1544 // inside the load.
1545 AllocaPartitioning::use_iterator UI
1546 = P.findPartitionUseForPHIOrSelectOperand(InUse);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001547 assert(isa<PHINode>(*UI->getUse()->getUser()));
1548 UI->setUse(&Load->getOperandUse(Load->getPointerOperandIndex()));
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001549 }
1550 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1551 }
1552
1553 /// Select instructions that use an alloca and are subsequently loaded can be
1554 /// rewritten to load both input pointers and then select between the result,
1555 /// allowing the load of the alloca to be promoted.
1556 /// From this:
1557 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1558 /// %V = load i32* %P2
1559 /// to:
1560 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1561 /// %V2 = load i32* %Other
1562 /// %V = select i1 %cond, i32 %V1, i32 %V2
1563 ///
1564 /// We can do this to a select if its only uses are loads and if the operand
1565 /// to the select can be loaded unconditionally.
1566 bool isSafeSelectToSpeculate(SelectInst &SI,
1567 SmallVectorImpl<LoadInst *> &Loads) {
1568 Value *TValue = SI.getTrueValue();
1569 Value *FValue = SI.getFalseValue();
1570 bool TDerefable = TValue->isDereferenceablePointer();
1571 bool FDerefable = FValue->isDereferenceablePointer();
1572
1573 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1574 UI != UE; ++UI) {
1575 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1576 if (LI == 0 || !LI->isSimple()) return false;
1577
1578 // Both operands to the select need to be dereferencable, either
1579 // absolutely (e.g. allocas) or at this point because we can see other
1580 // accesses to it.
1581 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1582 LI->getAlignment(), &TD))
1583 return false;
1584 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1585 LI->getAlignment(), &TD))
1586 return false;
1587 Loads.push_back(LI);
1588 }
1589
1590 return true;
1591 }
1592
1593 void visitSelectInst(SelectInst &SI) {
1594 DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001595
1596 // If the select isn't safe to speculate, just use simple logic to emit it.
1597 SmallVector<LoadInst *, 4> Loads;
1598 if (!isSafeSelectToSpeculate(SI, Loads))
1599 return;
1600
Jakub Staszakdb4579d2013-03-07 22:10:33 +00001601 IRBuilder<> IRB(&SI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001602 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1603 AllocaPartitioning::iterator PIs[2];
Chandler Carruthf74654d2013-03-18 08:36:46 +00001604 PartitionUse PUs[2];
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001605 for (unsigned i = 0, e = 2; i != e; ++i) {
1606 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1607 if (PIs[i] != P.end()) {
1608 // If the pointer is within the partitioning, remove the select from
1609 // its uses. We'll add in the new loads below.
1610 AllocaPartitioning::use_iterator UI
1611 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1612 PUs[i] = *UI;
1613 // Clear out the use here so that the offsets into the use list remain
1614 // stable but this use is ignored when rewriting.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001615 UI->setUse(0);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001616 }
1617 }
1618
1619 Value *TV = SI.getTrueValue();
1620 Value *FV = SI.getFalseValue();
1621 // Replace the loads of the select with a select of two loads.
1622 while (!Loads.empty()) {
1623 LoadInst *LI = Loads.pop_back_val();
1624
1625 IRB.SetInsertPoint(LI);
1626 LoadInst *TL =
1627 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1628 LoadInst *FL =
1629 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1630 NumLoadsSpeculated += 2;
1631
1632 // Transfer alignment and TBAA info if present.
1633 TL->setAlignment(LI->getAlignment());
1634 FL->setAlignment(LI->getAlignment());
1635 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1636 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1637 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1638 }
1639
1640 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1641 LI->getName() + ".sroa.speculated");
1642
1643 LoadInst *Loads[2] = { TL, FL };
1644 for (unsigned i = 0, e = 2; i != e; ++i) {
1645 if (PIs[i] != P.end()) {
1646 Use *LoadUse = &Loads[i]->getOperandUse(0);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001647 assert(PUs[i].getUse()->get() == LoadUse->get());
1648 PUs[i].setUse(LoadUse);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001649 P.use_push_back(PIs[i], PUs[i]);
1650 }
1651 }
1652
1653 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1654 LI->replaceAllUsesWith(V);
Chandler Carruth18db7952012-11-20 01:12:50 +00001655 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001656 }
1657 }
1658};
1659}
1660
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001661/// \brief Build a GEP out of a base pointer and indices.
1662///
1663/// This will return the BasePtr if that is valid, or build a new GEP
1664/// instruction using the IRBuilder if GEP-ing is needed.
1665static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1666 SmallVectorImpl<Value *> &Indices,
1667 const Twine &Prefix) {
1668 if (Indices.empty())
1669 return BasePtr;
1670
1671 // A single zero index is a no-op, so check for this and avoid building a GEP
1672 // in that case.
1673 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1674 return BasePtr;
1675
1676 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1677}
1678
1679/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1680/// TargetTy without changing the offset of the pointer.
1681///
1682/// This routine assumes we've already established a properly offset GEP with
1683/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1684/// zero-indices down through type layers until we find one the same as
1685/// TargetTy. If we can't find one with the same type, we at least try to use
1686/// one with the same size. If none of that works, we just produce the GEP as
1687/// indicated by Indices to have the correct offset.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001688static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001689 Value *BasePtr, Type *Ty, Type *TargetTy,
1690 SmallVectorImpl<Value *> &Indices,
1691 const Twine &Prefix) {
1692 if (Ty == TargetTy)
1693 return buildGEP(IRB, BasePtr, Indices, Prefix);
1694
1695 // See if we can descend into a struct and locate a field with the correct
1696 // type.
1697 unsigned NumLayers = 0;
1698 Type *ElementTy = Ty;
1699 do {
1700 if (ElementTy->isPointerTy())
1701 break;
1702 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1703 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001704 // Note that we use the default address space as this index is over an
1705 // array or a vector, not a pointer.
1706 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001707 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001708 if (STy->element_begin() == STy->element_end())
1709 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001710 ElementTy = *STy->element_begin();
1711 Indices.push_back(IRB.getInt32(0));
1712 } else {
1713 break;
1714 }
1715 ++NumLayers;
1716 } while (ElementTy != TargetTy);
1717 if (ElementTy != TargetTy)
1718 Indices.erase(Indices.end() - NumLayers, Indices.end());
1719
1720 return buildGEP(IRB, BasePtr, Indices, Prefix);
1721}
1722
1723/// \brief Recursively compute indices for a natural GEP.
1724///
1725/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1726/// element types adding appropriate indices for the GEP.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001727static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001728 Value *Ptr, Type *Ty, APInt &Offset,
1729 Type *TargetTy,
1730 SmallVectorImpl<Value *> &Indices,
1731 const Twine &Prefix) {
1732 if (Offset == 0)
1733 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1734
1735 // We can't recurse through pointer types.
1736 if (Ty->isPointerTy())
1737 return 0;
1738
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001739 // We try to analyze GEPs over vectors here, but note that these GEPs are
1740 // extremely poorly defined currently. The long-term goal is to remove GEPing
1741 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001742 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Nadav Rotema5024fc2012-12-18 05:23:31 +00001743 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001744 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001745 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001746 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001747 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001748 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1749 return 0;
1750 Offset -= NumSkippedElements * ElementSize;
1751 Indices.push_back(IRB.getInt(NumSkippedElements));
1752 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1753 Offset, TargetTy, Indices, Prefix);
1754 }
1755
1756 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1757 Type *ElementTy = ArrTy->getElementType();
1758 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001759 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001760 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1761 return 0;
1762
1763 Offset -= NumSkippedElements * ElementSize;
1764 Indices.push_back(IRB.getInt(NumSkippedElements));
1765 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1766 Indices, Prefix);
1767 }
1768
1769 StructType *STy = dyn_cast<StructType>(Ty);
1770 if (!STy)
1771 return 0;
1772
1773 const StructLayout *SL = TD.getStructLayout(STy);
1774 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001775 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001776 return 0;
1777 unsigned Index = SL->getElementContainingOffset(StructOffset);
1778 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1779 Type *ElementTy = STy->getElementType(Index);
1780 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1781 return 0; // The offset points into alignment padding.
1782
1783 Indices.push_back(IRB.getInt32(Index));
1784 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1785 Indices, Prefix);
1786}
1787
1788/// \brief Get a natural GEP from a base pointer to a particular offset and
1789/// resulting in a particular type.
1790///
1791/// The goal is to produce a "natural" looking GEP that works with the existing
1792/// composite types to arrive at the appropriate offset and element type for
1793/// a pointer. TargetTy is the element type the returned GEP should point-to if
1794/// possible. We recurse by decreasing Offset, adding the appropriate index to
1795/// Indices, and setting Ty to the result subtype.
1796///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001797/// If no natural GEP can be constructed, this function returns null.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001798static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001799 Value *Ptr, APInt Offset, Type *TargetTy,
1800 SmallVectorImpl<Value *> &Indices,
1801 const Twine &Prefix) {
1802 PointerType *Ty = cast<PointerType>(Ptr->getType());
1803
1804 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1805 // an i8.
1806 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1807 return 0;
1808
1809 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001810 if (!ElementTy->isSized())
1811 return 0; // We can't GEP through an unsized element.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001812 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1813 if (ElementSize == 0)
1814 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001815 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001816
1817 Offset -= NumSkippedElements * ElementSize;
1818 Indices.push_back(IRB.getInt(NumSkippedElements));
1819 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1820 Indices, Prefix);
1821}
1822
1823/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1824/// resulting pointer has PointerTy.
1825///
1826/// This tries very hard to compute a "natural" GEP which arrives at the offset
1827/// and produces the pointer type desired. Where it cannot, it will try to use
1828/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1829/// fails, it will try to use an existing i8* and GEP to the byte offset and
1830/// bitcast to the type.
1831///
1832/// The strategy for finding the more natural GEPs is to peel off layers of the
1833/// pointer, walking back through bit casts and GEPs, searching for a base
1834/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001835/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001836/// a single GEP as possible, thus making each GEP more independent of the
1837/// surrounding code.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001838static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001839 Value *Ptr, APInt Offset, Type *PointerTy,
1840 const Twine &Prefix) {
1841 // Even though we don't look through PHI nodes, we could be called on an
1842 // instruction in an unreachable block, which may be on a cycle.
1843 SmallPtrSet<Value *, 4> Visited;
1844 Visited.insert(Ptr);
1845 SmallVector<Value *, 4> Indices;
1846
1847 // We may end up computing an offset pointer that has the wrong type. If we
1848 // never are able to compute one directly that has the correct type, we'll
1849 // fall back to it, so keep it around here.
1850 Value *OffsetPtr = 0;
1851
1852 // Remember any i8 pointer we come across to re-use if we need to do a raw
1853 // byte offset.
1854 Value *Int8Ptr = 0;
1855 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1856
1857 Type *TargetTy = PointerTy->getPointerElementType();
1858
1859 do {
1860 // First fold any existing GEPs into the offset.
1861 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1862 APInt GEPOffset(Offset.getBitWidth(), 0);
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001863 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001864 break;
1865 Offset += GEPOffset;
1866 Ptr = GEP->getPointerOperand();
1867 if (!Visited.insert(Ptr))
1868 break;
1869 }
1870
1871 // See if we can perform a natural GEP here.
1872 Indices.clear();
1873 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1874 Indices, Prefix)) {
1875 if (P->getType() == PointerTy) {
1876 // Zap any offset pointer that we ended up computing in previous rounds.
1877 if (OffsetPtr && OffsetPtr->use_empty())
1878 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1879 I->eraseFromParent();
1880 return P;
1881 }
1882 if (!OffsetPtr) {
1883 OffsetPtr = P;
1884 }
1885 }
1886
1887 // Stash this pointer if we've found an i8*.
1888 if (Ptr->getType()->isIntegerTy(8)) {
1889 Int8Ptr = Ptr;
1890 Int8PtrOffset = Offset;
1891 }
1892
1893 // Peel off a layer of the pointer and update the offset appropriately.
1894 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1895 Ptr = cast<Operator>(Ptr)->getOperand(0);
1896 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1897 if (GA->mayBeOverridden())
1898 break;
1899 Ptr = GA->getAliasee();
1900 } else {
1901 break;
1902 }
1903 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1904 } while (Visited.insert(Ptr));
1905
1906 if (!OffsetPtr) {
1907 if (!Int8Ptr) {
1908 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1909 Prefix + ".raw_cast");
1910 Int8PtrOffset = Offset;
1911 }
1912
1913 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1914 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1915 Prefix + ".raw_idx");
1916 }
1917 Ptr = OffsetPtr;
1918
1919 // On the off chance we were targeting i8*, guard the bitcast here.
1920 if (Ptr->getType() != PointerTy)
1921 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1922
1923 return Ptr;
1924}
1925
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001926/// \brief Test whether we can convert a value from the old to the new type.
1927///
1928/// This predicate should be used to guard calls to convertValue in order to
1929/// ensure that we only try to convert viable values. The strategy is that we
1930/// will peel off single element struct and array wrappings to get to an
1931/// underlying value, and convert that value.
1932static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1933 if (OldTy == NewTy)
1934 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001935 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1936 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1937 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1938 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001939 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1940 return false;
1941 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1942 return false;
1943
1944 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1945 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1946 return true;
1947 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1948 return true;
1949 return false;
1950 }
1951
1952 return true;
1953}
1954
1955/// \brief Generic routine to convert an SSA value to a value of a different
1956/// type.
1957///
1958/// This will try various different casting techniques, such as bitcasts,
1959/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1960/// two types for viability with this routine.
1961static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
1962 Type *Ty) {
1963 assert(canConvertValue(DL, V->getType(), Ty) &&
1964 "Value not convertable to type");
1965 if (V->getType() == Ty)
1966 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001967 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1968 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1969 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1970 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001971 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1972 return IRB.CreateIntToPtr(V, Ty);
1973 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1974 return IRB.CreatePtrToInt(V, Ty);
1975
1976 return IRB.CreateBitCast(V, Ty);
1977}
1978
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001979/// \brief Test whether the given alloca partition can be promoted to a vector.
1980///
1981/// This is a quick test to check whether we can rewrite a particular alloca
1982/// partition (and its newly formed alloca) into a vector alloca with only
1983/// whole-vector loads and stores such that it could be promoted to a vector
1984/// SSA value. We only can ensure this for a limited set of operations, and we
1985/// don't want to do the rewrites unless we are confident that the result will
1986/// be promotable, so we have an early test here.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001987static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001988 Type *AllocaTy,
1989 AllocaPartitioning &P,
1990 uint64_t PartitionBeginOffset,
1991 uint64_t PartitionEndOffset,
1992 AllocaPartitioning::const_use_iterator I,
1993 AllocaPartitioning::const_use_iterator E) {
1994 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1995 if (!Ty)
1996 return false;
1997
Nadav Rotema5024fc2012-12-18 05:23:31 +00001998 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001999
2000 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2001 // that aren't byte sized.
2002 if (ElementSize % 8)
2003 return false;
Benjamin Kramerc003a452013-01-01 16:13:35 +00002004 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
2005 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002006 ElementSize /= 8;
2007
2008 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002009 Use *U = I->getUse();
2010 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002011 continue; // Skip dead use.
2012
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002013 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2014 uint64_t BeginIndex = BeginOffset / ElementSize;
2015 if (BeginIndex * ElementSize != BeginOffset ||
2016 BeginIndex >= Ty->getNumElements())
2017 return false;
2018 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2019 uint64_t EndIndex = EndOffset / ElementSize;
2020 if (EndIndex * ElementSize != EndOffset ||
2021 EndIndex > Ty->getNumElements())
2022 return false;
2023
Chandler Carruth845b73c2012-11-21 08:16:30 +00002024 assert(EndIndex > BeginIndex && "Empty vector!");
2025 uint64_t NumElements = EndIndex - BeginIndex;
2026 Type *PartitionTy
2027 = (NumElements == 1) ? Ty->getElementType()
2028 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002029
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002030 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002031 if (MI->isVolatile())
2032 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002033 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002034 const AllocaPartitioning::MemTransferOffsets &MTO
2035 = P.getMemTransferOffsets(*MTI);
2036 if (!MTO.IsSplittable)
2037 return false;
2038 }
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002039 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002040 // Disable vector promotion when there are loads or stores of an FCA.
2041 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002042 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002043 if (LI->isVolatile())
2044 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002045 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2046 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002047 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002048 if (SI->isVolatile())
2049 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002050 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2051 return false;
Chandler Carruth18db7952012-11-20 01:12:50 +00002052 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002053 return false;
2054 }
2055 }
2056 return true;
2057}
2058
Chandler Carruth435c4e02012-10-15 08:40:30 +00002059/// \brief Test whether the given alloca partition's integer operations can be
2060/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002061///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002062/// This is a quick test to check whether we can rewrite the integer loads and
2063/// stores to a particular alloca into wider loads and stores and be able to
2064/// promote the resulting alloca.
2065static bool isIntegerWideningViable(const DataLayout &TD,
2066 Type *AllocaTy,
2067 uint64_t AllocBeginOffset,
2068 AllocaPartitioning &P,
2069 AllocaPartitioning::const_use_iterator I,
2070 AllocaPartitioning::const_use_iterator E) {
2071 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002072 // Don't create integer types larger than the maximum bitwidth.
2073 if (SizeInBits > IntegerType::MAX_INT_BITS)
2074 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002075
2076 // Don't try to handle allocas with bit-padding.
2077 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002078 return false;
2079
Chandler Carruth58d05562012-10-25 04:37:07 +00002080 // We need to ensure that an integer type with the appropriate bitwidth can
2081 // be converted to the alloca type, whatever that is. We don't want to force
2082 // the alloca itself to have an integer type if there is a more suitable one.
2083 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2084 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2085 !canConvertValue(TD, IntTy, AllocaTy))
2086 return false;
2087
Chandler Carruth435c4e02012-10-15 08:40:30 +00002088 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2089
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002090 // Check the uses to ensure the uses are (likely) promotable integer uses.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002091 // Also ensure that the alloca has a covering load or store. We don't want
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002092 // to widen the integer operations only to fail to promote due to some other
Chandler Carruth435c4e02012-10-15 08:40:30 +00002093 // unsplittable entry (which we may make splittable later).
Chandler Carruth92924fd2012-09-24 00:34:20 +00002094 bool WholeAllocaOp = false;
2095 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002096 Use *U = I->getUse();
2097 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002098 continue; // Skip dead use.
Chandler Carruth43c8b462012-10-04 10:39:28 +00002099
Chandler Carruth435c4e02012-10-15 08:40:30 +00002100 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2101 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2102
Chandler Carruth43c8b462012-10-04 10:39:28 +00002103 // We can't reasonably handle cases where the load or store extends past
2104 // the end of the aloca's type and into its padding.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002105 if (RelEnd > Size)
Chandler Carruth43c8b462012-10-04 10:39:28 +00002106 return false;
2107
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002108 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002109 if (LI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002110 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002111 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002112 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002113 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002114 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002115 return false;
2116 continue;
2117 }
2118 // Non-integer loads need to be convertible from the alloca type so that
2119 // they are promotable.
2120 if (RelBegin != 0 || RelEnd != Size ||
2121 !canConvertValue(TD, AllocaTy, LI->getType()))
2122 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002123 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002124 Type *ValueTy = SI->getValueOperand()->getType();
2125 if (SI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002126 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002127 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002128 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002129 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002130 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002131 return false;
2132 continue;
2133 }
2134 // Non-integer stores need to be convertible to the alloca type so that
2135 // they are promotable.
2136 if (RelBegin != 0 || RelEnd != Size ||
2137 !canConvertValue(TD, ValueTy, AllocaTy))
2138 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002139 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
Chandler Carruthe3f41192012-12-17 18:48:07 +00002140 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002141 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002142 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
Chandler Carruth92924fd2012-09-24 00:34:20 +00002143 const AllocaPartitioning::MemTransferOffsets &MTO
2144 = P.getMemTransferOffsets(*MTI);
2145 if (!MTO.IsSplittable)
2146 return false;
2147 }
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002148 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002149 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2150 II->getIntrinsicID() != Intrinsic::lifetime_end)
2151 return false;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002152 } else {
2153 return false;
2154 }
2155 }
2156 return WholeAllocaOp;
2157}
2158
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002159static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2160 IntegerType *Ty, uint64_t Offset,
2161 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002162 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002163 IntegerType *IntTy = cast<IntegerType>(V->getType());
2164 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2165 "Element extends past full value");
2166 uint64_t ShAmt = 8*Offset;
2167 if (DL.isBigEndian())
2168 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002169 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002170 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002171 DEBUG(dbgs() << " shifted: " << *V << "\n");
2172 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002173 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2174 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002175 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002176 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002177 DEBUG(dbgs() << " trunced: " << *V << "\n");
2178 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002179 return V;
2180}
2181
2182static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2183 Value *V, uint64_t Offset, const Twine &Name) {
2184 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2185 IntegerType *Ty = cast<IntegerType>(V->getType());
2186 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2187 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002188 DEBUG(dbgs() << " start: " << *V << "\n");
2189 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002190 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002191 DEBUG(dbgs() << " extended: " << *V << "\n");
2192 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002193 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2194 "Element store outside of alloca store");
2195 uint64_t ShAmt = 8*Offset;
2196 if (DL.isBigEndian())
2197 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002198 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002199 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002200 DEBUG(dbgs() << " shifted: " << *V << "\n");
2201 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002202
2203 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2204 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2205 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002206 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002207 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002208 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002209 }
2210 return V;
2211}
2212
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002213static Value *extractVector(IRBuilder<> &IRB, Value *V,
2214 unsigned BeginIndex, unsigned EndIndex,
2215 const Twine &Name) {
2216 VectorType *VecTy = cast<VectorType>(V->getType());
2217 unsigned NumElements = EndIndex - BeginIndex;
2218 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2219
2220 if (NumElements == VecTy->getNumElements())
2221 return V;
2222
2223 if (NumElements == 1) {
2224 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2225 Name + ".extract");
2226 DEBUG(dbgs() << " extract: " << *V << "\n");
2227 return V;
2228 }
2229
2230 SmallVector<Constant*, 8> Mask;
2231 Mask.reserve(NumElements);
2232 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2233 Mask.push_back(IRB.getInt32(i));
2234 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2235 ConstantVector::get(Mask),
2236 Name + ".extract");
2237 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2238 return V;
2239}
2240
Chandler Carruthce4562b2012-12-17 13:41:21 +00002241static Value *insertVector(IRBuilder<> &IRB, Value *Old, Value *V,
2242 unsigned BeginIndex, const Twine &Name) {
2243 VectorType *VecTy = cast<VectorType>(Old->getType());
2244 assert(VecTy && "Can only insert a vector into a vector");
2245
2246 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2247 if (!Ty) {
2248 // Single element to insert.
2249 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2250 Name + ".insert");
2251 DEBUG(dbgs() << " insert: " << *V << "\n");
2252 return V;
2253 }
2254
2255 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2256 "Too many elements!");
2257 if (Ty->getNumElements() == VecTy->getNumElements()) {
2258 assert(V->getType() == VecTy && "Vector type mismatch");
2259 return V;
2260 }
2261 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2262
2263 // When inserting a smaller vector into the larger to store, we first
2264 // use a shuffle vector to widen it with undef elements, and then
2265 // a second shuffle vector to select between the loaded vector and the
2266 // incoming vector.
2267 SmallVector<Constant*, 8> Mask;
2268 Mask.reserve(VecTy->getNumElements());
2269 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2270 if (i >= BeginIndex && i < EndIndex)
2271 Mask.push_back(IRB.getInt32(i - BeginIndex));
2272 else
2273 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2274 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2275 ConstantVector::get(Mask),
2276 Name + ".expand");
2277 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2278
2279 Mask.clear();
2280 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2281 if (i >= BeginIndex && i < EndIndex)
2282 Mask.push_back(IRB.getInt32(i));
2283 else
2284 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2285 V = IRB.CreateShuffleVector(V, Old, ConstantVector::get(Mask),
2286 Name + "insert");
2287 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2288 return V;
2289}
2290
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002291namespace {
2292/// \brief Visitor to rewrite instructions using a partition of an alloca to
2293/// use a new alloca.
2294///
2295/// Also implements the rewriting to vector-based accesses when the partition
2296/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2297/// lives here.
2298class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2299 bool> {
2300 // Befriend the base class so it can delegate to private visit methods.
2301 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2302
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002303 const DataLayout &TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002304 AllocaPartitioning &P;
2305 SROA &Pass;
2306 AllocaInst &OldAI, &NewAI;
2307 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002308 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002309
2310 // If we are rewriting an alloca partition which can be written as pure
2311 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002312 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002313 // - The new alloca is exactly the size of the vector type here.
2314 // - The accesses all either map to the entire vector or to a single
2315 // element.
2316 // - The set of accessing instructions is only one of those handled above
2317 // in isVectorPromotionViable. Generally these are the same access kinds
2318 // which are promotable via mem2reg.
2319 VectorType *VecTy;
2320 Type *ElementTy;
2321 uint64_t ElementSize;
2322
Chandler Carruth92924fd2012-09-24 00:34:20 +00002323 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002324 // alloca's integer operations should be widened to this integer type due to
2325 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002326 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002327 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002328
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002329 // The offset of the partition user currently being rewritten.
2330 uint64_t BeginOffset, EndOffset;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002331 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002332 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002333 Instruction *OldPtr;
2334
2335 // The name prefix to use when rewriting instructions for this alloca.
2336 std::string NamePrefix;
2337
2338public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002339 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002340 AllocaPartitioning::iterator PI,
2341 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2342 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2343 : TD(TD), P(P), Pass(Pass),
2344 OldAI(OldAI), NewAI(NewAI),
2345 NewAllocaBeginOffset(NewBeginOffset),
2346 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth891fec02012-10-13 02:41:05 +00002347 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth435c4e02012-10-15 08:40:30 +00002348 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002349 BeginOffset(), EndOffset(), IsSplit(), OldUse(), OldPtr() {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002350 }
2351
2352 /// \brief Visit the users of the alloca partition and rewrite them.
2353 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2354 AllocaPartitioning::const_use_iterator E) {
2355 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2356 NewAllocaBeginOffset, NewAllocaEndOffset,
2357 I, E)) {
2358 ++NumVectorized;
2359 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2360 ElementTy = VecTy->getElementType();
Nadav Rotema5024fc2012-12-18 05:23:31 +00002361 assert((TD.getTypeSizeInBits(VecTy->getScalarType()) % 8) == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002362 "Only multiple-of-8 sized vector elements are viable");
Nadav Rotema5024fc2012-12-18 05:23:31 +00002363 ElementSize = TD.getTypeSizeInBits(VecTy->getScalarType()) / 8;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002364 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2365 NewAllocaBeginOffset, P, I, E)) {
2366 IntTy = Type::getIntNTy(NewAI.getContext(),
2367 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002368 }
2369 bool CanSROA = true;
2370 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002371 if (!I->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002372 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002373 BeginOffset = I->BeginOffset;
2374 EndOffset = I->EndOffset;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002375 IsSplit = I->isSplit();
2376 OldUse = I->getUse();
2377 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002378 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002379 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002380 }
2381 if (VecTy) {
2382 assert(CanSROA);
2383 VecTy = 0;
2384 ElementTy = 0;
2385 ElementSize = 0;
2386 }
Chandler Carruth435c4e02012-10-15 08:40:30 +00002387 if (IntTy) {
2388 assert(CanSROA);
2389 IntTy = 0;
2390 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002391 return CanSROA;
2392 }
2393
2394private:
2395 // Every instruction which can end up as a user must have a rewrite rule.
2396 bool visitInstruction(Instruction &I) {
2397 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2398 llvm_unreachable("No rewrite rule for this instruction!");
2399 }
2400
2401 Twine getName(const Twine &Suffix) {
2402 return NamePrefix + Suffix;
2403 }
2404
2405 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2406 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth5da3f052012-11-01 09:14:31 +00002407 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002408 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2409 }
2410
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002411 /// \brief Compute suitable alignment to access an offset into the new alloca.
2412 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002413 unsigned NewAIAlign = NewAI.getAlignment();
2414 if (!NewAIAlign)
2415 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2416 return MinAlign(NewAIAlign, Offset);
2417 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002418
2419 /// \brief Compute suitable alignment to access this partition of the new
2420 /// alloca.
2421 unsigned getPartitionAlign() {
2422 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002423 }
2424
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002425 /// \brief Compute suitable alignment to access a type at an offset of the
2426 /// new alloca.
2427 ///
2428 /// \returns zero if the type's ABI alignment is a suitable alignment,
2429 /// otherwise returns the maximal suitable alignment.
2430 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2431 unsigned Align = getOffsetAlign(Offset);
2432 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2433 }
2434
2435 /// \brief Compute suitable alignment to access a type at the beginning of
2436 /// this partition of the new alloca.
2437 ///
2438 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2439 unsigned getPartitionTypeAlign(Type *Ty) {
2440 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002441 }
2442
Chandler Carruth845b73c2012-11-21 08:16:30 +00002443 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002444 assert(VecTy && "Can only call getIndex when rewriting a vector");
2445 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2446 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2447 uint32_t Index = RelOffset / ElementSize;
2448 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002449 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002450 }
2451
2452 void deleteIfTriviallyDead(Value *V) {
2453 Instruction *I = cast<Instruction>(V);
2454 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002455 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002456 }
2457
Chandler Carruth769445e2012-12-17 12:50:21 +00002458 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB) {
2459 unsigned BeginIndex = getIndex(BeginOffset);
2460 unsigned EndIndex = getIndex(EndOffset);
2461 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002462
2463 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2464 getName(".load"));
2465 return extractVector(IRB, V, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth769445e2012-12-17 12:50:21 +00002466 }
2467
Chandler Carruth18db7952012-11-20 01:12:50 +00002468 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002469 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002470 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002471 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2472 getName(".load"));
2473 V = convertValue(TD, IRB, V, IntTy);
2474 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2475 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth18db7952012-11-20 01:12:50 +00002476 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2477 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2478 getName(".extract"));
2479 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002480 }
2481
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002482 bool visitLoadInst(LoadInst &LI) {
2483 DEBUG(dbgs() << " original: " << LI << "\n");
2484 Value *OldOp = LI.getOperand(0);
2485 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002486
Chandler Carruth58d05562012-10-25 04:37:07 +00002487 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002488
Jakub Staszakdb4579d2013-03-07 22:10:33 +00002489 IRBuilder<> IRB(&LI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002490 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2491 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002492 bool IsPtrAdjusted = false;
2493 Value *V;
2494 if (VecTy) {
Chandler Carruth769445e2012-12-17 12:50:21 +00002495 V = rewriteVectorizedLoadInst(IRB);
Chandler Carruth18db7952012-11-20 01:12:50 +00002496 } else if (IntTy && LI.getType()->isIntegerTy()) {
2497 V = rewriteIntegerLoad(IRB, LI);
2498 } else if (BeginOffset == NewAllocaBeginOffset &&
2499 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2500 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2501 LI.isVolatile(), getName(".load"));
2502 } else {
2503 Type *LTy = TargetTy->getPointerTo();
2504 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2505 getPartitionTypeAlign(TargetTy),
2506 LI.isVolatile(), getName(".load"));
2507 IsPtrAdjusted = true;
2508 }
2509 V = convertValue(TD, IRB, V, TargetTy);
2510
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002511 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002512 assert(!LI.isVolatile());
2513 assert(LI.getType()->isIntegerTy() &&
2514 "Only integer type loads and stores are split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002515 assert(Size < TD.getTypeStoreSize(LI.getType()) &&
2516 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002517 assert(LI.getType()->getIntegerBitWidth() ==
2518 TD.getTypeStoreSizeInBits(LI.getType()) &&
2519 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002520 // Move the insertion point just past the load so that we can refer to it.
2521 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002522 // Create a placeholder value with the same type as LI to use as the
2523 // basis for the new value. This allows us to replace the uses of LI with
2524 // the computed value, and then replace the placeholder with LI, leaving
2525 // LI only used for this computation.
2526 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002527 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth58d05562012-10-25 04:37:07 +00002528 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2529 getName(".insert"));
2530 LI.replaceAllUsesWith(V);
2531 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002532 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002533 } else {
2534 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002535 }
2536
Chandler Carruth18db7952012-11-20 01:12:50 +00002537 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002538 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002539 DEBUG(dbgs() << " to: " << *V << "\n");
2540 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002541 }
2542
Chandler Carruth18db7952012-11-20 01:12:50 +00002543 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2544 StoreInst &SI, Value *OldOp) {
Chandler Carruth845b73c2012-11-21 08:16:30 +00002545 unsigned BeginIndex = getIndex(BeginOffset);
2546 unsigned EndIndex = getIndex(EndOffset);
2547 assert(EndIndex > BeginIndex && "Empty vector!");
2548 unsigned NumElements = EndIndex - BeginIndex;
2549 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2550 Type *PartitionTy
2551 = (NumElements == 1) ? ElementTy
2552 : VectorType::get(ElementTy, NumElements);
2553 if (V->getType() != PartitionTy)
2554 V = convertValue(TD, IRB, V, PartitionTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002555
Chandler Carrutheae65a52012-12-17 04:07:35 +00002556 // Mix in the existing elements.
Chandler Carruthce4562b2012-12-17 13:41:21 +00002557 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2558 getName(".load"));
2559 V = insertVector(IRB, Old, V, BeginIndex, getName(".vec"));
Chandler Carrutheae65a52012-12-17 04:07:35 +00002560
Chandler Carruth871ba722012-09-26 10:27:46 +00002561 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002562 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002563
2564 (void)Store;
2565 DEBUG(dbgs() << " to: " << *Store << "\n");
2566 return true;
2567 }
2568
Chandler Carruth18db7952012-11-20 01:12:50 +00002569 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002570 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002571 assert(!SI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002572 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2573 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2574 getName(".oldload"));
2575 Old = convertValue(TD, IRB, Old, IntTy);
2576 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2577 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2578 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2579 getName(".insert"));
2580 }
2581 V = convertValue(TD, IRB, V, NewAllocaTy);
2582 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002583 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002584 (void)Store;
2585 DEBUG(dbgs() << " to: " << *Store << "\n");
2586 return true;
2587 }
2588
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002589 bool visitStoreInst(StoreInst &SI) {
2590 DEBUG(dbgs() << " original: " << SI << "\n");
2591 Value *OldOp = SI.getOperand(1);
2592 assert(OldOp == OldPtr);
2593 IRBuilder<> IRB(&SI);
2594
Chandler Carruth18db7952012-11-20 01:12:50 +00002595 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002596
Chandler Carruthac8317f2012-10-04 12:33:50 +00002597 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2598 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002599 if (V->getType()->isPointerTy())
2600 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002601 Pass.PostPromotionWorklist.insert(AI);
2602
Chandler Carruth18db7952012-11-20 01:12:50 +00002603 uint64_t Size = EndOffset - BeginOffset;
2604 if (Size < TD.getTypeStoreSize(V->getType())) {
2605 assert(!SI.isVolatile());
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002606 assert(IsSplit && "A seemingly split store isn't splittable");
Chandler Carruth18db7952012-11-20 01:12:50 +00002607 assert(V->getType()->isIntegerTy() &&
2608 "Only integer type loads and stores are split");
2609 assert(V->getType()->getIntegerBitWidth() ==
2610 TD.getTypeStoreSizeInBits(V->getType()) &&
2611 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002612 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2613 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2614 getName(".extract"));
Chandler Carruth891fec02012-10-13 02:41:05 +00002615 }
2616
Chandler Carruth18db7952012-11-20 01:12:50 +00002617 if (VecTy)
2618 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2619 if (IntTy && V->getType()->isIntegerTy())
2620 return rewriteIntegerStore(IRB, V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002621
Chandler Carruth18db7952012-11-20 01:12:50 +00002622 StoreInst *NewSI;
2623 if (BeginOffset == NewAllocaBeginOffset &&
2624 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2625 V = convertValue(TD, IRB, V, NewAllocaTy);
2626 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2627 SI.isVolatile());
2628 } else {
2629 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2630 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2631 getPartitionTypeAlign(V->getType()),
2632 SI.isVolatile());
2633 }
2634 (void)NewSI;
2635 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002636 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002637
2638 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2639 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002640 }
2641
Chandler Carruth514f34f2012-12-17 04:07:30 +00002642 /// \brief Compute an integer value from splatting an i8 across the given
2643 /// number of bytes.
2644 ///
2645 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2646 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002647 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002648 ///
2649 /// \param V The i8 value to splat.
2650 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2651 Value *getIntegerSplat(IRBuilder<> &IRB, Value *V, unsigned Size) {
2652 assert(Size > 0 && "Expected a positive number of bytes.");
2653 IntegerType *VTy = cast<IntegerType>(V->getType());
2654 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2655 if (Size == 1)
2656 return V;
2657
2658 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2659 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2660 ConstantExpr::getUDiv(
2661 Constant::getAllOnesValue(SplatIntTy),
2662 ConstantExpr::getZExt(
2663 Constant::getAllOnesValue(V->getType()),
2664 SplatIntTy)),
2665 getName(".isplat"));
2666 return V;
2667 }
2668
Chandler Carruthccca5042012-12-17 04:07:37 +00002669 /// \brief Compute a vector splat for a given element value.
2670 Value *getVectorSplat(IRBuilder<> &IRB, Value *V, unsigned NumElements) {
Benjamin Kramer614b5e82013-01-01 19:55:16 +00002671 V = IRB.CreateVectorSplat(NumElements, V, NamePrefix);
Chandler Carruthccca5042012-12-17 04:07:37 +00002672 DEBUG(dbgs() << " splat: " << *V << "\n");
2673 return V;
2674 }
2675
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002676 bool visitMemSetInst(MemSetInst &II) {
2677 DEBUG(dbgs() << " original: " << II << "\n");
2678 IRBuilder<> IRB(&II);
2679 assert(II.getRawDest() == OldPtr);
2680
2681 // If the memset has a variable size, it cannot be split, just adjust the
2682 // pointer to the new alloca.
2683 if (!isa<Constant>(II.getLength())) {
2684 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002685 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002686 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002687
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002688 deleteIfTriviallyDead(OldPtr);
2689 return false;
2690 }
2691
2692 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002693 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002694
2695 Type *AllocaTy = NewAI.getAllocatedType();
2696 Type *ScalarTy = AllocaTy->getScalarType();
2697
2698 // If this doesn't map cleanly onto the alloca type, and that type isn't
2699 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002700 if (!VecTy && !IntTy &&
2701 (BeginOffset != NewAllocaBeginOffset ||
2702 EndOffset != NewAllocaEndOffset ||
2703 !AllocaTy->isSingleValueType() ||
Chandler Carruthccca5042012-12-17 04:07:37 +00002704 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2705 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002706 Type *SizeTy = II.getLength()->getType();
2707 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002708 CallInst *New
2709 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2710 II.getRawDest()->getType()),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002711 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002712 II.isVolatile());
2713 (void)New;
2714 DEBUG(dbgs() << " to: " << *New << "\n");
2715 return false;
2716 }
2717
2718 // If we can represent this as a simple value, we have to build the actual
2719 // value to store, which requires expanding the byte present in memset to
2720 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002721 // splatting the byte to a sufficiently wide integer, splatting it across
2722 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002723 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002724
Chandler Carruthccca5042012-12-17 04:07:37 +00002725 if (VecTy) {
2726 // If this is a memset of a vectorized alloca, insert it.
2727 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002728
Chandler Carruthccca5042012-12-17 04:07:37 +00002729 unsigned BeginIndex = getIndex(BeginOffset);
2730 unsigned EndIndex = getIndex(EndOffset);
2731 assert(EndIndex > BeginIndex && "Empty vector!");
2732 unsigned NumElements = EndIndex - BeginIndex;
2733 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2734
2735 Value *Splat = getIntegerSplat(IRB, II.getValue(),
2736 TD.getTypeSizeInBits(ElementTy)/8);
Chandler Carruthcacda252012-12-17 14:03:01 +00002737 Splat = convertValue(TD, IRB, Splat, ElementTy);
2738 if (NumElements > 1)
Chandler Carruthccca5042012-12-17 04:07:37 +00002739 Splat = getVectorSplat(IRB, Splat, NumElements);
2740
Chandler Carruthce4562b2012-12-17 13:41:21 +00002741 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2742 getName(".oldload"));
2743 V = insertVector(IRB, Old, Splat, BeginIndex, getName(".vec"));
Chandler Carruthccca5042012-12-17 04:07:37 +00002744 } else if (IntTy) {
2745 // If this is a memset on an alloca where we can widen stores, insert the
2746 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002747 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002748
Benjamin Kramerc003a452013-01-01 16:13:35 +00002749 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruthccca5042012-12-17 04:07:37 +00002750 V = getIntegerSplat(IRB, II.getValue(), Size);
2751
2752 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2753 EndOffset != NewAllocaBeginOffset)) {
2754 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2755 getName(".oldload"));
2756 Old = convertValue(TD, IRB, Old, IntTy);
2757 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2758 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2759 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2760 } else {
2761 assert(V->getType() == IntTy &&
2762 "Wrong type for an alloca wide integer!");
2763 }
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002764 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002765 } else {
2766 // Established these invariants above.
2767 assert(BeginOffset == NewAllocaBeginOffset);
2768 assert(EndOffset == NewAllocaEndOffset);
2769
2770 V = getIntegerSplat(IRB, II.getValue(),
2771 TD.getTypeSizeInBits(ScalarTy)/8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002772 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2773 V = getVectorSplat(IRB, V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002774
2775 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002776 }
2777
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002778 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002779 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002780 (void)New;
2781 DEBUG(dbgs() << " to: " << *New << "\n");
2782 return !II.isVolatile();
2783 }
2784
2785 bool visitMemTransferInst(MemTransferInst &II) {
2786 // Rewriting of memory transfer instructions can be a bit tricky. We break
2787 // them into two categories: split intrinsics and unsplit intrinsics.
2788
2789 DEBUG(dbgs() << " original: " << II << "\n");
2790 IRBuilder<> IRB(&II);
2791
2792 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2793 bool IsDest = II.getRawDest() == OldPtr;
2794
2795 const AllocaPartitioning::MemTransferOffsets &MTO
2796 = P.getMemTransferOffsets(II);
2797
Chandler Carruth176ca712012-10-01 12:16:54 +00002798 // Compute the relative offset within the transfer.
Chandler Carruth5da3f052012-11-01 09:14:31 +00002799 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth176ca712012-10-01 12:16:54 +00002800 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2801 : MTO.SourceBegin));
2802
2803 unsigned Align = II.getAlignment();
2804 if (Align > 1)
2805 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002806 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth176ca712012-10-01 12:16:54 +00002807
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002808 // For unsplit intrinsics, we simply modify the source and destination
2809 // pointers in place. This isn't just an optimization, it is a matter of
2810 // correctness. With unsplit intrinsics we may be dealing with transfers
2811 // within a single alloca before SROA ran, or with transfers that have
2812 // a variable length. We may also be dealing with memmove instead of
2813 // memcpy, and so simply updating the pointers is the necessary for us to
2814 // update both source and dest of a single call.
2815 if (!MTO.IsSplittable) {
2816 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2817 if (IsDest)
2818 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2819 else
2820 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2821
Chandler Carruth208124f2012-09-26 10:59:22 +00002822 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002823 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002824
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002825 DEBUG(dbgs() << " to: " << II << "\n");
2826 deleteIfTriviallyDead(OldOp);
2827 return false;
2828 }
2829 // For split transfer intrinsics we have an incredibly useful assurance:
2830 // the source and destination do not reside within the same alloca, and at
2831 // least one of them does not escape. This means that we can replace
2832 // memmove with memcpy, and we don't need to worry about all manner of
2833 // downsides to splitting and transforming the operations.
2834
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002835 // If this doesn't map cleanly onto the alloca type, and that type isn't
2836 // a single value type, just emit a memcpy.
2837 bool EmitMemCpy
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002838 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2839 EndOffset != NewAllocaEndOffset ||
2840 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002841
2842 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2843 // size hasn't been shrunk based on analysis of the viable range, this is
2844 // a no-op.
2845 if (EmitMemCpy && &OldAI == &NewAI) {
2846 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2847 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2848 // Ensure the start lines up.
2849 assert(BeginOffset == OrigBegin);
Benjamin Kramer4622cd72012-09-14 13:08:09 +00002850 (void)OrigBegin;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002851
2852 // Rewrite the size as needed.
2853 if (EndOffset != OrigEnd)
2854 II.setLength(ConstantInt::get(II.getLength()->getType(),
2855 EndOffset - BeginOffset));
2856 return false;
2857 }
2858 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002859 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002860
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002861 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2862 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002863 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002864 if (AllocaInst *AI
2865 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002866 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002867
2868 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002869 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2870 : II.getRawDest()->getType();
2871
2872 // Compute the other pointer, folding as much as possible to produce
2873 // a single, simple GEP in most cases.
2874 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2875 getName("." + OtherPtr->getName()));
2876
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002877 Value *OurPtr
2878 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2879 : II.getRawSource()->getType());
2880 Type *SizeTy = II.getLength()->getType();
2881 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2882
2883 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2884 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002885 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002886 (void)New;
2887 DEBUG(dbgs() << " to: " << *New << "\n");
2888 return false;
2889 }
2890
Chandler Carruth08e5f492012-10-03 08:26:28 +00002891 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2892 // is equivalent to 1, but that isn't true if we end up rewriting this as
2893 // a load or store.
2894 if (!Align)
2895 Align = 1;
2896
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002897 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2898 EndOffset == NewAllocaEndOffset;
2899 uint64_t Size = EndOffset - BeginOffset;
2900 unsigned BeginIndex = VecTy ? getIndex(BeginOffset) : 0;
2901 unsigned EndIndex = VecTy ? getIndex(EndOffset) : 0;
2902 unsigned NumElements = EndIndex - BeginIndex;
2903 IntegerType *SubIntTy
2904 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2905
2906 Type *OtherPtrTy = NewAI.getType();
2907 if (VecTy && !IsWholeAlloca) {
2908 if (NumElements == 1)
2909 OtherPtrTy = VecTy->getElementType();
2910 else
2911 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2912
2913 OtherPtrTy = OtherPtrTy->getPointerTo();
2914 } else if (IntTy && !IsWholeAlloca) {
2915 OtherPtrTy = SubIntTy->getPointerTo();
2916 }
2917
2918 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2919 getName("." + OtherPtr->getName()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920 Value *DstPtr = &NewAI;
2921 if (!IsDest)
2922 std::swap(SrcPtr, DstPtr);
2923
2924 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002925 if (VecTy && !IsWholeAlloca && !IsDest) {
2926 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2927 getName(".load"));
2928 Src = extractVector(IRB, Src, BeginIndex, EndIndex, getName(".vec"));
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002929 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002930 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2931 getName(".load"));
2932 Src = convertValue(TD, IRB, Src, IntTy);
2933 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2934 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2935 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002936 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002937 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2938 getName(".copyload"));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002939 }
2940
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002941 if (VecTy && !IsWholeAlloca && IsDest) {
2942 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2943 getName(".oldload"));
2944 Src = insertVector(IRB, Old, Src, BeginIndex, getName(".vec"));
2945 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002946 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2947 getName(".oldload"));
2948 Old = convertValue(TD, IRB, Old, IntTy);
2949 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2950 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2951 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2952 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002953 }
2954
Chandler Carruth871ba722012-09-26 10:27:46 +00002955 StoreInst *Store = cast<StoreInst>(
2956 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2957 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002958 DEBUG(dbgs() << " to: " << *Store << "\n");
2959 return !II.isVolatile();
2960 }
2961
2962 bool visitIntrinsicInst(IntrinsicInst &II) {
2963 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2964 II.getIntrinsicID() == Intrinsic::lifetime_end);
2965 DEBUG(dbgs() << " original: " << II << "\n");
2966 IRBuilder<> IRB(&II);
2967 assert(II.getArgOperand(1) == OldPtr);
2968
2969 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002970 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971
2972 ConstantInt *Size
2973 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2974 EndOffset - BeginOffset);
2975 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2976 Value *New;
2977 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2978 New = IRB.CreateLifetimeStart(Ptr, Size);
2979 else
2980 New = IRB.CreateLifetimeEnd(Ptr, Size);
2981
Edwin Vane82f80d42013-01-29 17:42:24 +00002982 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002983 DEBUG(dbgs() << " to: " << *New << "\n");
2984 return true;
2985 }
2986
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002987 bool visitPHINode(PHINode &PN) {
2988 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00002989
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002990 // We would like to compute a new pointer in only one place, but have it be
2991 // as local as possible to the PHI. To do that, we re-use the location of
2992 // the old pointer, which necessarily must be in the right position to
2993 // dominate the PHI.
2994 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2995
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002996 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00002997 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00002998 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002999
Chandler Carruth82a57542012-10-01 10:54:05 +00003000 DEBUG(dbgs() << " to: " << PN << "\n");
3001 deleteIfTriviallyDead(OldPtr);
3002 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003003 }
3004
3005 bool visitSelectInst(SelectInst &SI) {
3006 DEBUG(dbgs() << " original: " << SI << "\n");
3007 IRBuilder<> IRB(&SI);
3008
3009 // Find the operand we need to rewrite here.
3010 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3011 if (IsTrueVal)
3012 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3013 else
3014 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth82a57542012-10-01 10:54:05 +00003015
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003016 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003017 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3018 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003019 deleteIfTriviallyDead(OldPtr);
Chandler Carruth82a57542012-10-01 10:54:05 +00003020 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003021 }
3022
3023};
3024}
3025
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003026namespace {
3027/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3028///
3029/// This pass aggressively rewrites all aggregate loads and stores on
3030/// a particular pointer (or any pointer derived from it which we can identify)
3031/// with scalar loads and stores.
3032class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3033 // Befriend the base class so it can delegate to private visit methods.
3034 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3035
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003036 const DataLayout &TD;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003037
3038 /// Queue of pointer uses to analyze and potentially rewrite.
3039 SmallVector<Use *, 8> Queue;
3040
3041 /// Set to prevent us from cycling with phi nodes and loops.
3042 SmallPtrSet<User *, 8> Visited;
3043
3044 /// The current pointer use being rewritten. This is used to dig up the used
3045 /// value (as opposed to the user).
3046 Use *U;
3047
3048public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003049 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003050
3051 /// Rewrite loads and stores through a pointer and all pointers derived from
3052 /// it.
3053 bool rewrite(Instruction &I) {
3054 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3055 enqueueUsers(I);
3056 bool Changed = false;
3057 while (!Queue.empty()) {
3058 U = Queue.pop_back_val();
3059 Changed |= visit(cast<Instruction>(U->getUser()));
3060 }
3061 return Changed;
3062 }
3063
3064private:
3065 /// Enqueue all the users of the given instruction for further processing.
3066 /// This uses a set to de-duplicate users.
3067 void enqueueUsers(Instruction &I) {
3068 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3069 ++UI)
3070 if (Visited.insert(*UI))
3071 Queue.push_back(&UI.getUse());
3072 }
3073
3074 // Conservative default is to not rewrite anything.
3075 bool visitInstruction(Instruction &I) { return false; }
3076
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003077 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003078 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003079 class OpSplitter {
3080 protected:
3081 /// The builder used to form new instructions.
3082 IRBuilder<> IRB;
3083 /// The indices which to be used with insert- or extractvalue to select the
3084 /// appropriate value within the aggregate.
3085 SmallVector<unsigned, 4> Indices;
3086 /// The indices to a GEP instruction which will move Ptr to the correct slot
3087 /// within the aggregate.
3088 SmallVector<Value *, 4> GEPIndices;
3089 /// The base pointer of the original op, used as a base for GEPing the
3090 /// split operations.
3091 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003092
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003093 /// Initialize the splitter with an insertion point, Ptr and start with a
3094 /// single zero GEP index.
3095 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003096 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003097
3098 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003099 /// \brief Generic recursive split emission routine.
3100 ///
3101 /// This method recursively splits an aggregate op (load or store) into
3102 /// scalar or vector ops. It splits recursively until it hits a single value
3103 /// and emits that single value operation via the template argument.
3104 ///
3105 /// The logic of this routine relies on GEPs and insertvalue and
3106 /// extractvalue all operating with the same fundamental index list, merely
3107 /// formatted differently (GEPs need actual values).
3108 ///
3109 /// \param Ty The type being split recursively into smaller ops.
3110 /// \param Agg The aggregate value being built up or stored, depending on
3111 /// whether this is splitting a load or a store respectively.
3112 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3113 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003114 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003115
3116 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3117 unsigned OldSize = Indices.size();
3118 (void)OldSize;
3119 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3120 ++Idx) {
3121 assert(Indices.size() == OldSize && "Did not return to the old size");
3122 Indices.push_back(Idx);
3123 GEPIndices.push_back(IRB.getInt32(Idx));
3124 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3125 GEPIndices.pop_back();
3126 Indices.pop_back();
3127 }
3128 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003129 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003130
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003131 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3132 unsigned OldSize = Indices.size();
3133 (void)OldSize;
3134 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3135 ++Idx) {
3136 assert(Indices.size() == OldSize && "Did not return to the old size");
3137 Indices.push_back(Idx);
3138 GEPIndices.push_back(IRB.getInt32(Idx));
3139 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3140 GEPIndices.pop_back();
3141 Indices.pop_back();
3142 }
3143 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003144 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003145
3146 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003147 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003148 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003149
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003150 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003151 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003152 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003153
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003154 /// Emit a leaf load of a single value. This is called at the leaves of the
3155 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003156 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003157 assert(Ty->isSingleValueType());
3158 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003159 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3160 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003161 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3162 DEBUG(dbgs() << " to: " << *Load << "\n");
3163 }
3164 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003165
3166 bool visitLoadInst(LoadInst &LI) {
3167 assert(LI.getPointerOperand() == *U);
3168 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3169 return false;
3170
3171 // We have an aggregate being loaded, split it apart.
3172 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003173 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003174 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003175 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003176 LI.replaceAllUsesWith(V);
3177 LI.eraseFromParent();
3178 return true;
3179 }
3180
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003181 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003182 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003183 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003184
3185 /// Emit a leaf store of a single value. This is called at the leaves of the
3186 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003187 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003188 assert(Ty->isSingleValueType());
3189 // Extract the single value and store it using the indices.
3190 Value *Store = IRB.CreateStore(
3191 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3192 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3193 (void)Store;
3194 DEBUG(dbgs() << " to: " << *Store << "\n");
3195 }
3196 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003197
3198 bool visitStoreInst(StoreInst &SI) {
3199 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3200 return false;
3201 Value *V = SI.getValueOperand();
3202 if (V->getType()->isSingleValueType())
3203 return false;
3204
3205 // We have an aggregate being stored, split it apart.
3206 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003207 StoreOpSplitter Splitter(&SI, *U);
3208 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003209 SI.eraseFromParent();
3210 return true;
3211 }
3212
3213 bool visitBitCastInst(BitCastInst &BC) {
3214 enqueueUsers(BC);
3215 return false;
3216 }
3217
3218 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3219 enqueueUsers(GEPI);
3220 return false;
3221 }
3222
3223 bool visitPHINode(PHINode &PN) {
3224 enqueueUsers(PN);
3225 return false;
3226 }
3227
3228 bool visitSelectInst(SelectInst &SI) {
3229 enqueueUsers(SI);
3230 return false;
3231 }
3232};
3233}
3234
Chandler Carruthba931992012-10-13 10:49:33 +00003235/// \brief Strip aggregate type wrapping.
3236///
3237/// This removes no-op aggregate types wrapping an underlying type. It will
3238/// strip as many layers of types as it can without changing either the type
3239/// size or the allocated size.
3240static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3241 if (Ty->isSingleValueType())
3242 return Ty;
3243
3244 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3245 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3246
3247 Type *InnerTy;
3248 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3249 InnerTy = ArrTy->getElementType();
3250 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3251 const StructLayout *SL = DL.getStructLayout(STy);
3252 unsigned Index = SL->getElementContainingOffset(0);
3253 InnerTy = STy->getElementType(Index);
3254 } else {
3255 return Ty;
3256 }
3257
3258 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3259 TypeSize > DL.getTypeSizeInBits(InnerTy))
3260 return Ty;
3261
3262 return stripAggregateTypeWrapping(DL, InnerTy);
3263}
3264
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003265/// \brief Try to find a partition of the aggregate type passed in for a given
3266/// offset and size.
3267///
3268/// This recurses through the aggregate type and tries to compute a subtype
3269/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003270/// of an array, it will even compute a new array type for that sub-section,
3271/// and the same for structs.
3272///
3273/// Note that this routine is very strict and tries to find a partition of the
3274/// type which produces the *exact* right offset and size. It is not forgiving
3275/// when the size or offset cause either end of type-based partition to be off.
3276/// Also, this is a best-effort routine. It is reasonable to give up and not
3277/// return a type if necessary.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003278static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003279 uint64_t Offset, uint64_t Size) {
3280 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruthba931992012-10-13 10:49:33 +00003281 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carruth58d05562012-10-25 04:37:07 +00003282 if (Offset > TD.getTypeAllocSize(Ty) ||
3283 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3284 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003285
3286 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3287 // We can't partition pointers...
3288 if (SeqTy->isPointerTy())
3289 return 0;
3290
3291 Type *ElementTy = SeqTy->getElementType();
3292 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3293 uint64_t NumSkippedElements = Offset / ElementSize;
3294 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3295 if (NumSkippedElements >= ArrTy->getNumElements())
3296 return 0;
3297 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3298 if (NumSkippedElements >= VecTy->getNumElements())
3299 return 0;
3300 Offset -= NumSkippedElements * ElementSize;
3301
3302 // First check if we need to recurse.
3303 if (Offset > 0 || Size < ElementSize) {
3304 // Bail if the partition ends in a different array element.
3305 if ((Offset + Size) > ElementSize)
3306 return 0;
3307 // Recurse through the element type trying to peel off offset bytes.
3308 return getTypePartition(TD, ElementTy, Offset, Size);
3309 }
3310 assert(Offset == 0);
3311
3312 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003313 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003314 assert(Size > ElementSize);
3315 uint64_t NumElements = Size / ElementSize;
3316 if (NumElements * ElementSize != Size)
3317 return 0;
3318 return ArrayType::get(ElementTy, NumElements);
3319 }
3320
3321 StructType *STy = dyn_cast<StructType>(Ty);
3322 if (!STy)
3323 return 0;
3324
3325 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003326 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003327 return 0;
3328 uint64_t EndOffset = Offset + Size;
3329 if (EndOffset > SL->getSizeInBytes())
3330 return 0;
3331
3332 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003333 Offset -= SL->getElementOffset(Index);
3334
3335 Type *ElementTy = STy->getElementType(Index);
3336 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3337 if (Offset >= ElementSize)
3338 return 0; // The offset points into alignment padding.
3339
3340 // See if any partition must be contained by the element.
3341 if (Offset > 0 || Size < ElementSize) {
3342 if ((Offset + Size) > ElementSize)
3343 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003344 return getTypePartition(TD, ElementTy, Offset, Size);
3345 }
3346 assert(Offset == 0);
3347
3348 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003349 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003350
3351 StructType::element_iterator EI = STy->element_begin() + Index,
3352 EE = STy->element_end();
3353 if (EndOffset < SL->getSizeInBytes()) {
3354 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3355 if (Index == EndIndex)
3356 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003357
3358 // Don't try to form "natural" types if the elements don't line up with the
3359 // expected size.
3360 // FIXME: We could potentially recurse down through the last element in the
3361 // sub-struct to find a natural end point.
3362 if (SL->getElementOffset(EndIndex) != EndOffset)
3363 return 0;
3364
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003365 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003366 EE = STy->element_begin() + EndIndex;
3367 }
3368
3369 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003370 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003371 STy->isPacked());
3372 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003373 if (Size != SubSL->getSizeInBytes())
3374 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003375
Chandler Carruth054a40a2012-09-14 11:08:31 +00003376 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003377}
3378
3379/// \brief Rewrite an alloca partition's users.
3380///
3381/// This routine drives both of the rewriting goals of the SROA pass. It tries
3382/// to rewrite uses of an alloca partition to be conducive for SSA value
3383/// promotion. If the partition needs a new, more refined alloca, this will
3384/// build that new alloca, preserving as much type information as possible, and
3385/// rewrite the uses of the old alloca to point at the new one and have the
3386/// appropriate new offsets. It also evaluates how successful the rewrite was
3387/// at enabling promotion and if it was successful queues the alloca to be
3388/// promoted.
3389bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3390 AllocaPartitioning &P,
3391 AllocaPartitioning::iterator PI) {
3392 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003393 bool IsLive = false;
3394 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3395 UE = P.use_end(PI);
3396 UI != UE && !IsLive; ++UI)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00003397 if (UI->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003398 IsLive = true;
3399 if (!IsLive)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003400 return false; // No live uses left of this partition.
3401
Chandler Carruth82a57542012-10-01 10:54:05 +00003402 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3403 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3404
3405 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3406 DEBUG(dbgs() << " speculating ");
3407 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruth3903e052012-10-02 17:49:47 +00003408 Speculator.visitUsers(PI);
Chandler Carruth82a57542012-10-01 10:54:05 +00003409
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003410 // Try to compute a friendly type for this partition of the alloca. This
3411 // won't always succeed, in which case we fall back to a legal integer type
3412 // or an i8 array of an appropriate size.
3413 Type *AllocaTy = 0;
3414 if (Type *PartitionTy = P.getCommonType(PI))
3415 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3416 AllocaTy = PartitionTy;
3417 if (!AllocaTy)
3418 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3419 PI->BeginOffset, AllocaSize))
3420 AllocaTy = PartitionTy;
3421 if ((!AllocaTy ||
3422 (AllocaTy->isArrayTy() &&
3423 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3424 TD->isLegalInteger(AllocaSize * 8))
3425 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3426 if (!AllocaTy)
3427 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb0de6dd2012-09-14 10:26:34 +00003428 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003429
3430 // Check for the case where we're going to rewrite to a new alloca of the
3431 // exact same type as the original, and with the same access offsets. In that
3432 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003433 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003434 AllocaInst *NewAI;
3435 if (AllocaTy == AI.getAllocatedType()) {
3436 assert(PI->BeginOffset == 0 &&
3437 "Non-zero begin offset but same alloca type");
3438 assert(PI == P.begin() && "Begin offset is zero on later partition");
3439 NewAI = &AI;
3440 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003441 unsigned Alignment = AI.getAlignment();
3442 if (!Alignment) {
3443 // The minimum alignment which users can rely on when the explicit
3444 // alignment is omitted or zero is that required by the ABI for this
3445 // type.
3446 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3447 }
3448 Alignment = MinAlign(Alignment, PI->BeginOffset);
3449 // If we will get at least this much alignment from the type alone, leave
3450 // the alloca's alignment unconstrained.
3451 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3452 Alignment = 0;
3453 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003454 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3455 &AI);
3456 ++NumNewAllocas;
3457 }
3458
3459 DEBUG(dbgs() << "Rewriting alloca partition "
3460 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3461 << *NewAI << "\n");
3462
Chandler Carruthac8317f2012-10-04 12:33:50 +00003463 // Track the high watermark of the post-promotion worklist. We will reset it
3464 // to this point if the alloca is not in fact scheduled for promotion.
3465 unsigned PPWOldSize = PostPromotionWorklist.size();
3466
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003467 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3468 PI->BeginOffset, PI->EndOffset);
3469 DEBUG(dbgs() << " rewriting ");
3470 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthac8317f2012-10-04 12:33:50 +00003471 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3472 if (Promotable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003473 DEBUG(dbgs() << " and queuing for promotion\n");
3474 PromotableAllocas.push_back(NewAI);
3475 } else if (NewAI != &AI) {
3476 // If we can't promote the alloca, iterate on it to check for new
3477 // refinements exposed by splitting the current alloca. Don't iterate on an
3478 // alloca which didn't actually change and didn't get promoted.
3479 Worklist.insert(NewAI);
3480 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003481
3482 // Drop any post-promotion work items if promotion didn't happen.
3483 if (!Promotable)
3484 while (PostPromotionWorklist.size() > PPWOldSize)
3485 PostPromotionWorklist.pop_back();
3486
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003487 return true;
3488}
3489
3490/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3491bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3492 bool Changed = false;
3493 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3494 ++PI)
3495 Changed |= rewriteAllocaPartition(AI, P, PI);
3496
3497 return Changed;
3498}
3499
3500/// \brief Analyze an alloca for SROA.
3501///
3502/// This analyzes the alloca to ensure we can reason about it, builds
3503/// a partitioning of the alloca, and then hands it off to be split and
3504/// rewritten as needed.
3505bool SROA::runOnAlloca(AllocaInst &AI) {
3506 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3507 ++NumAllocasAnalyzed;
3508
3509 // Special case dead allocas, as they're trivial.
3510 if (AI.use_empty()) {
3511 AI.eraseFromParent();
3512 return true;
3513 }
3514
3515 // Skip alloca forms that this analysis can't handle.
3516 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3517 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3518 return false;
3519
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003520 bool Changed = false;
3521
3522 // First, split any FCA loads and stores touching this alloca to promote
3523 // better splitting and promotion opportunities.
3524 AggLoadStoreRewriter AggRewriter(*TD);
3525 Changed |= AggRewriter.rewrite(AI);
3526
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003527 // Build the partition set using a recursive instruction-visiting builder.
3528 AllocaPartitioning P(*TD, AI);
3529 DEBUG(P.print(dbgs()));
3530 if (P.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003531 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003532
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003533 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003534 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3535 DE = P.dead_user_end();
3536 DI != DE; ++DI) {
3537 Changed = true;
3538 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003539 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003540 }
3541 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3542 DE = P.dead_op_end();
3543 DO != DE; ++DO) {
3544 Value *OldV = **DO;
3545 // Clobber the use with an undef value.
3546 **DO = UndefValue::get(OldV->getType());
3547 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3548 if (isInstructionTriviallyDead(OldI)) {
3549 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003550 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003551 }
3552 }
3553
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003554 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3555 if (P.begin() == P.end())
3556 return Changed;
3557
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003558 return splitAlloca(AI, P) || Changed;
3559}
3560
Chandler Carruth19450da2012-09-14 10:26:38 +00003561/// \brief Delete the dead instructions accumulated in this run.
3562///
3563/// Recursively deletes the dead instructions we've accumulated. This is done
3564/// at the very end to maximize locality of the recursive delete and to
3565/// minimize the problems of invalidated instruction pointers as such pointers
3566/// are used heavily in the intermediate stages of the algorithm.
3567///
3568/// We also record the alloca instructions deleted here so that they aren't
3569/// subsequently handed to mem2reg to promote.
3570void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003571 while (!DeadInsts.empty()) {
3572 Instruction *I = DeadInsts.pop_back_val();
3573 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3574
Chandler Carruth58d05562012-10-25 04:37:07 +00003575 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3576
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003577 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3578 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3579 // Zero out the operand and see if it becomes trivially dead.
3580 *OI = 0;
3581 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003582 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003583 }
3584
3585 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3586 DeletedAllocas.insert(AI);
3587
3588 ++NumDeleted;
3589 I->eraseFromParent();
3590 }
3591}
3592
Chandler Carruth70b44c52012-09-15 11:43:14 +00003593/// \brief Promote the allocas, using the best available technique.
3594///
3595/// This attempts to promote whatever allocas have been identified as viable in
3596/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3597/// If there is a domtree available, we attempt to promote using the full power
3598/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3599/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003600/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003601bool SROA::promoteAllocas(Function &F) {
3602 if (PromotableAllocas.empty())
3603 return false;
3604
3605 NumPromoted += PromotableAllocas.size();
3606
3607 if (DT && !ForceSSAUpdater) {
3608 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3609 PromoteMemToReg(PromotableAllocas, *DT);
3610 PromotableAllocas.clear();
3611 return true;
3612 }
3613
3614 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3615 SSAUpdater SSA;
3616 DIBuilder DIB(*F.getParent());
3617 SmallVector<Instruction*, 64> Insts;
3618
3619 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3620 AllocaInst *AI = PromotableAllocas[Idx];
3621 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3622 UI != UE;) {
3623 Instruction *I = cast<Instruction>(*UI++);
3624 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3625 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3626 // leading to them) here. Eventually it should use them to optimize the
3627 // scalar values produced.
3628 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3629 assert(onlyUsedByLifetimeMarkers(I) &&
3630 "Found a bitcast used outside of a lifetime marker.");
3631 while (!I->use_empty())
3632 cast<Instruction>(*I->use_begin())->eraseFromParent();
3633 I->eraseFromParent();
3634 continue;
3635 }
3636 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3637 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3638 II->getIntrinsicID() == Intrinsic::lifetime_end);
3639 II->eraseFromParent();
3640 continue;
3641 }
3642
3643 Insts.push_back(I);
3644 }
3645 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3646 Insts.clear();
3647 }
3648
3649 PromotableAllocas.clear();
3650 return true;
3651}
3652
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003653namespace {
3654 /// \brief A predicate to test whether an alloca belongs to a set.
3655 class IsAllocaInSet {
3656 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3657 const SetType &Set;
3658
3659 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003660 typedef AllocaInst *argument_type;
3661
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003662 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003663 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003664 };
3665}
3666
3667bool SROA::runOnFunction(Function &F) {
3668 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3669 C = &F.getContext();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003670 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003671 if (!TD) {
3672 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3673 return false;
3674 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003675 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003676
3677 BasicBlock &EntryBB = F.getEntryBlock();
3678 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3679 I != E; ++I)
3680 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3681 Worklist.insert(AI);
3682
3683 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003684 // A set of deleted alloca instruction pointers which should be removed from
3685 // the list of promotable allocas.
3686 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3687
Chandler Carruthac8317f2012-10-04 12:33:50 +00003688 do {
3689 while (!Worklist.empty()) {
3690 Changed |= runOnAlloca(*Worklist.pop_back_val());
3691 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003692
Chandler Carruthac8317f2012-10-04 12:33:50 +00003693 // Remove the deleted allocas from various lists so that we don't try to
3694 // continue processing them.
3695 if (!DeletedAllocas.empty()) {
3696 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3697 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3698 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3699 PromotableAllocas.end(),
3700 IsAllocaInSet(DeletedAllocas)),
3701 PromotableAllocas.end());
3702 DeletedAllocas.clear();
3703 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003704 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003705
Chandler Carruthac8317f2012-10-04 12:33:50 +00003706 Changed |= promoteAllocas(F);
3707
3708 Worklist = PostPromotionWorklist;
3709 PostPromotionWorklist.clear();
3710 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003711
3712 return Changed;
3713}
3714
3715void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003716 if (RequiresDomTree)
3717 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003718 AU.setPreservesCFG();
3719}