blob: 3a27d020845582f26636db4ed657e8cc2a9a2f16 [file] [log] [blame]
Chandler Carruth713aa942012-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"
28#include "llvm/Constants.h"
29#include "llvm/DIBuilder.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/DerivedTypes.h"
32#include "llvm/Function.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000033#include "llvm/IRBuilder.h"
34#include "llvm/Instructions.h"
35#include "llvm/IntrinsicInst.h"
36#include "llvm/LLVMContext.h"
37#include "llvm/Module.h"
38#include "llvm/Operator.h"
39#include "llvm/Pass.h"
40#include "llvm/ADT/SetVector.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000044#include "llvm/Analysis/Dominators.h"
45#include "llvm/Analysis/Loads.h"
46#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000047#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetData.h"
55#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
58using namespace llvm;
59
60STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
62STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
63STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
64STATISTIC(NumDeleted, "Number of instructions deleted");
65STATISTIC(NumVectorized, "Number of vectorized aggregates");
66
Chandler Carruth1c8db502012-09-15 11:43:14 +000067/// Hidden option to force the pass to not use DomTree and mem2reg, instead
68/// forming SSA values through the SSAUpdater infrastructure.
69static cl::opt<bool>
70ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
71
Chandler Carruth713aa942012-09-14 09:22:59 +000072namespace {
73/// \brief Alloca partitioning representation.
74///
75/// This class represents a partitioning of an alloca into slices, and
76/// information about the nature of uses of each slice of the alloca. The goal
77/// is that this information is sufficient to decide if and how to split the
78/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth7f5bede2012-09-14 10:18:49 +000079/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000080/// and to enact these transformations.
81class AllocaPartitioning {
82public:
83 /// \brief A common base class for representing a half-open byte range.
84 struct ByteRange {
85 /// \brief The beginning offset of the range.
86 uint64_t BeginOffset;
87
88 /// \brief The ending offset, not included in the range.
89 uint64_t EndOffset;
90
91 ByteRange() : BeginOffset(), EndOffset() {}
92 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
93 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
94
95 /// \brief Support for ordering ranges.
96 ///
97 /// This provides an ordering over ranges such that start offsets are
98 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth7f5bede2012-09-14 10:18:49 +000099 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000100 /// same start position.
101 bool operator<(const ByteRange &RHS) const {
102 if (BeginOffset < RHS.BeginOffset) return true;
103 if (BeginOffset > RHS.BeginOffset) return false;
104 if (EndOffset > RHS.EndOffset) return true;
105 return false;
106 }
107
108 /// \brief Support comparison with a single offset to allow binary searches.
Benjamin Kramer2d1c2a22012-09-17 16:42:36 +0000109 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
110 return LHS.BeginOffset < RHSOffset;
111 }
112
113 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
114 const ByteRange &RHS) {
115 return LHSOffset < RHS.BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000116 }
117
118 bool operator==(const ByteRange &RHS) const {
119 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
120 }
121 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
122 };
123
124 /// \brief A partition of an alloca.
125 ///
126 /// This structure represents a contiguous partition of the alloca. These are
127 /// formed by examining the uses of the alloca. During formation, they may
128 /// overlap but once an AllocaPartitioning is built, the Partitions within it
129 /// are all disjoint.
130 struct Partition : public ByteRange {
131 /// \brief Whether this partition is splittable into smaller partitions.
132 ///
133 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000134 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000135 ///
136 /// FIXME: At some point we should consider loads and stores of FCAs to be
137 /// splittable and eagerly split them into scalar values.
138 bool IsSplittable;
139
Chandler Carruthfca3f402012-10-05 01:29:09 +0000140 /// \brief Test whether a partition has been marked as dead.
141 bool isDead() const {
142 if (BeginOffset == UINT64_MAX) {
143 assert(EndOffset == UINT64_MAX);
144 return true;
145 }
146 return false;
147 }
148
149 /// \brief Kill a partition.
150 /// This is accomplished by setting both its beginning and end offset to
151 /// the maximum possible value.
152 void kill() {
153 assert(!isDead() && "He's Dead, Jim!");
154 BeginOffset = EndOffset = UINT64_MAX;
155 }
156
Chandler Carruth713aa942012-09-14 09:22:59 +0000157 Partition() : ByteRange(), IsSplittable() {}
158 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
159 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
160 };
161
162 /// \brief A particular use of a partition of the alloca.
163 ///
164 /// This structure is used to associate uses of a partition with it. They
165 /// mark the range of bytes which are referenced by a particular instruction,
166 /// and includes a handle to the user itself and the pointer value in use.
167 /// The bounds of these uses are determined by intersecting the bounds of the
168 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000169 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000170 struct PartitionUse : public ByteRange {
Chandler Carruth77c12702012-10-01 01:49:22 +0000171 /// \brief The use in question. Provides access to both user and used value.
Chandler Carruthfdb15852012-10-02 18:57:13 +0000172 ///
173 /// Note that this may be null if the partition use is *dead*, that is, it
174 /// should be ignored.
175 Use *U;
Chandler Carruth713aa942012-09-14 09:22:59 +0000176
Chandler Carruth77c12702012-10-01 01:49:22 +0000177 PartitionUse() : ByteRange(), U() {}
178 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
179 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000180 };
181
182 /// \brief Construct a partitioning of a particular alloca.
183 ///
184 /// Construction does most of the work for partitioning the alloca. This
185 /// performs the necessary walks of users and builds a partitioning from it.
186 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
187
188 /// \brief Test whether a pointer to the allocation escapes our analysis.
189 ///
190 /// If this is true, the partitioning is never fully built and should be
191 /// ignored.
192 bool isEscaped() const { return PointerEscapingInstr; }
193
194 /// \brief Support for iterating over the partitions.
195 /// @{
196 typedef SmallVectorImpl<Partition>::iterator iterator;
197 iterator begin() { return Partitions.begin(); }
198 iterator end() { return Partitions.end(); }
199
200 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
201 const_iterator begin() const { return Partitions.begin(); }
202 const_iterator end() const { return Partitions.end(); }
203 /// @}
204
205 /// \brief Support for iterating over and manipulating a particular
206 /// partition's uses.
207 ///
208 /// The iteration support provided for uses is more limited, but also
209 /// includes some manipulation routines to support rewriting the uses of
210 /// partitions during SROA.
211 /// @{
212 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
213 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
214 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
215 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
216 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth713aa942012-09-14 09:22:59 +0000217
218 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
219 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
220 const_use_iterator use_begin(const_iterator I) const {
221 return Uses[I - begin()].begin();
222 }
223 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
224 const_use_iterator use_end(const_iterator I) const {
225 return Uses[I - begin()].end();
226 }
Chandler Carrutha346f462012-10-02 17:49:47 +0000227
228 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
229 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
230 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
231 return Uses[PIdx][UIdx];
232 }
233 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
234 return Uses[I - begin()][UIdx];
235 }
236
237 void use_push_back(unsigned Idx, const PartitionUse &PU) {
238 Uses[Idx].push_back(PU);
239 }
240 void use_push_back(const_iterator I, const PartitionUse &PU) {
241 Uses[I - begin()].push_back(PU);
242 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000243 /// @}
244
245 /// \brief Allow iterating the dead users for this alloca.
246 ///
247 /// These are instructions which will never actually use the alloca as they
248 /// are outside the allocated range. They are safe to replace with undef and
249 /// delete.
250 /// @{
251 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
252 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
253 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
254 /// @}
255
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000256 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000257 ///
258 /// These are operands which have cannot actually be used to refer to the
259 /// alloca as they are outside its range and the user doesn't correct for
260 /// that. These mostly consist of PHI node inputs and the like which we just
261 /// need to replace with undef.
262 /// @{
263 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
264 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
265 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
266 /// @}
267
268 /// \brief MemTransferInst auxiliary data.
269 /// This struct provides some auxiliary data about memory transfer
270 /// intrinsics such as memcpy and memmove. These intrinsics can use two
271 /// different ranges within the same alloca, and provide other challenges to
272 /// correctly represent. We stash extra data to help us untangle this
273 /// after the partitioning is complete.
274 struct MemTransferOffsets {
Chandler Carruthfca3f402012-10-05 01:29:09 +0000275 /// The destination begin and end offsets when the destination is within
276 /// this alloca. If the end offset is zero the destination is not within
277 /// this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000278 uint64_t DestBegin, DestEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000279
280 /// The source begin and end offsets when the source is within this alloca.
281 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000282 uint64_t SourceBegin, SourceEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000283
284 /// Flag for whether an alloca is splittable.
Chandler Carruth713aa942012-09-14 09:22:59 +0000285 bool IsSplittable;
286 };
287 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
288 return MemTransferInstData.lookup(&II);
289 }
290
291 /// \brief Map from a PHI or select operand back to a partition.
292 ///
293 /// When manipulating PHI nodes or selects, they can use more than one
294 /// partition of an alloca. We store a special mapping to allow finding the
295 /// partition referenced by each of these operands, if any.
Chandler Carruth77c12702012-10-01 01:49:22 +0000296 iterator findPartitionForPHIOrSelectOperand(Use *U) {
297 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
298 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000299 if (MapIt == PHIOrSelectOpMap.end())
300 return end();
301
302 return begin() + MapIt->second.first;
303 }
304
305 /// \brief Map from a PHI or select operand back to the specific use of
306 /// a partition.
307 ///
308 /// Similar to mapping these operands back to the partitions, this maps
309 /// directly to the use structure of that partition.
Chandler Carruth77c12702012-10-01 01:49:22 +0000310 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
311 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
312 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000313 assert(MapIt != PHIOrSelectOpMap.end());
314 return Uses[MapIt->second.first].begin() + MapIt->second.second;
315 }
316
317 /// \brief Compute a common type among the uses of a particular partition.
318 ///
319 /// This routines walks all of the uses of a particular partition and tries
320 /// to find a common type between them. Untyped operations such as memset and
321 /// memcpy are ignored.
322 Type *getCommonType(iterator I) const;
323
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000324#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000325 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
326 void printUsers(raw_ostream &OS, const_iterator I,
327 StringRef Indent = " ") const;
328 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000329 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
330 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000331#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000332
333private:
334 template <typename DerivedT, typename RetT = void> class BuilderBase;
335 class PartitionBuilder;
336 friend class AllocaPartitioning::PartitionBuilder;
337 class UseBuilder;
338 friend class AllocaPartitioning::UseBuilder;
339
Benjamin Kramerd0807692012-09-14 13:08:09 +0000340#ifndef NDEBUG
Chandler Carruth713aa942012-09-14 09:22:59 +0000341 /// \brief Handle to alloca instruction to simplify method interfaces.
342 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000343#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000344
345 /// \brief The instruction responsible for this alloca having no partitioning.
346 ///
347 /// When an instruction (potentially) escapes the pointer to the alloca, we
348 /// store a pointer to that here and abort trying to partition the alloca.
349 /// This will be null if the alloca is partitioned successfully.
350 Instruction *PointerEscapingInstr;
351
352 /// \brief The partitions of the alloca.
353 ///
354 /// We store a vector of the partitions over the alloca here. This vector is
355 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000356 /// the Partition inner class for more details. Initially (during
357 /// construction) there are overlaps, but we form a disjoint sequence of
358 /// partitions while finishing construction and a fully constructed object is
359 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000360 SmallVector<Partition, 8> Partitions;
361
362 /// \brief The uses of the partitions.
363 ///
364 /// This is essentially a mapping from each partition to a list of uses of
365 /// that partition. The mapping is done with a Uses vector that has the exact
366 /// same number of entries as the partition vector. Each entry is itself
367 /// a vector of the uses.
368 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
369
370 /// \brief Instructions which will become dead if we rewrite the alloca.
371 ///
372 /// Note that these are not separated by partition. This is because we expect
373 /// a partitioned alloca to be completely rewritten or not rewritten at all.
374 /// If rewritten, all these instructions can simply be removed and replaced
375 /// with undef as they come from outside of the allocated space.
376 SmallVector<Instruction *, 8> DeadUsers;
377
378 /// \brief Operands which will become dead if we rewrite the alloca.
379 ///
380 /// These are operands that in their particular use can be replaced with
381 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
382 /// to PHI nodes and the like. They aren't entirely dead (there might be
383 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
384 /// want to swap this particular input for undef to simplify the use lists of
385 /// the alloca.
386 SmallVector<Use *, 8> DeadOperands;
387
388 /// \brief The underlying storage for auxiliary memcpy and memset info.
389 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
390
391 /// \brief A side datastructure used when building up the partitions and uses.
392 ///
393 /// This mapping is only really used during the initial building of the
394 /// partitioning so that we can retain information about PHI and select nodes
395 /// processed.
396 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
397
398 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth77c12702012-10-01 01:49:22 +0000399 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth713aa942012-09-14 09:22:59 +0000400
401 /// \brief A utility routine called from the constructor.
402 ///
403 /// This does what it says on the tin. It is the key of the alloca partition
404 /// splitting and merging. After it is called we have the desired disjoint
405 /// collection of partitions.
406 void splitAndMergePartitions();
407};
408}
409
410template <typename DerivedT, typename RetT>
411class AllocaPartitioning::BuilderBase
412 : public InstVisitor<DerivedT, RetT> {
413public:
414 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
415 : TD(TD),
416 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
417 P(P) {
418 enqueueUsers(AI, 0);
419 }
420
421protected:
422 const TargetData &TD;
423 const uint64_t AllocSize;
424 AllocaPartitioning &P;
425
Chandler Carruth77c12702012-10-01 01:49:22 +0000426 SmallPtrSet<Use *, 8> VisitedUses;
427
Chandler Carruth713aa942012-09-14 09:22:59 +0000428 struct OffsetUse {
429 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000430 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000431 };
432 SmallVector<OffsetUse, 8> Queue;
433
434 // The active offset and use while visiting.
435 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000436 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000437
Chandler Carruth02e92a02012-09-23 11:43:14 +0000438 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000439 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
440 UI != UE; ++UI) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000441 if (VisitedUses.insert(&UI.getUse())) {
442 OffsetUse OU = { &UI.getUse(), UserOffset };
443 Queue.push_back(OU);
444 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000445 }
446 }
447
Chandler Carruth02e92a02012-09-23 11:43:14 +0000448 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000449 GEPOffset = Offset;
450 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
451 GTI != GTE; ++GTI) {
452 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
453 if (!OpC)
454 return false;
455 if (OpC->isZero())
456 continue;
457
458 // Handle a struct index, which adds its field offset to the pointer.
459 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
460 unsigned ElementIdx = OpC->getZExtValue();
461 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000462 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
463 // Check that we can continue to model this GEP in a signed 64-bit offset.
464 if (ElementOffset > INT64_MAX ||
465 (GEPOffset >= 0 &&
466 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
467 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
468 << "what can be represented in an int64_t!\n"
469 << " alloca: " << P.AI << "\n");
470 return false;
471 }
472 if (GEPOffset < 0)
473 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
474 else
475 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000476 continue;
477 }
478
Chandler Carruth02e92a02012-09-23 11:43:14 +0000479 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
480 Index *= APInt(Index.getBitWidth(),
481 TD.getTypeAllocSize(GTI.getIndexedType()));
482 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
483 /*isSigned*/true);
484 // Check if the result can be stored in our int64_t offset.
485 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
486 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
487 << "what can be represented in an int64_t!\n"
488 << " alloca: " << P.AI << "\n");
489 return false;
490 }
491
492 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000493 }
494 return true;
495 }
496
497 Value *foldSelectInst(SelectInst &SI) {
498 // If the condition being selected on is a constant or the same value is
499 // being selected between, fold the select. Yes this does (rarely) happen
500 // early on.
501 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
502 return SI.getOperand(1+CI->isZero());
503 if (SI.getOperand(1) == SI.getOperand(2)) {
504 assert(*U == SI.getOperand(1));
505 return SI.getOperand(1);
506 }
507 return 0;
508 }
509};
510
511/// \brief Builder for the alloca partitioning.
512///
513/// This class builds an alloca partitioning by recursively visiting the uses
514/// of an alloca and splitting the partitions for each load and store at each
515/// offset.
516class AllocaPartitioning::PartitionBuilder
517 : public BuilderBase<PartitionBuilder, bool> {
518 friend class InstVisitor<PartitionBuilder, bool>;
519
520 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
521
522public:
523 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000524 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000525
526 /// \brief Run the builder over the allocation.
527 bool operator()() {
528 // Note that we have to re-evaluate size on each trip through the loop as
529 // the queue grows at the tail.
530 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
531 U = Queue[Idx].U;
532 Offset = Queue[Idx].Offset;
533 if (!visit(cast<Instruction>(U->getUser())))
534 return false;
535 }
536 return true;
537 }
538
539private:
540 bool markAsEscaping(Instruction &I) {
541 P.PointerEscapingInstr = &I;
542 return false;
543 }
544
Chandler Carruth02e92a02012-09-23 11:43:14 +0000545 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000546 bool IsSplittable = false) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000547 // Completely skip uses which have a zero size or don't overlap the
548 // allocation.
549 if (Size == 0 ||
550 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000551 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000552 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
553 << " which starts past the end of the " << AllocSize
554 << " byte alloca:\n"
555 << " alloca: " << P.AI << "\n"
556 << " use: " << I << "\n");
557 return;
558 }
559
Chandler Carruth02e92a02012-09-23 11:43:14 +0000560 // Clamp the start to the beginning of the allocation.
561 if (Offset < 0) {
562 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
563 << " to start at the beginning of the alloca:\n"
564 << " alloca: " << P.AI << "\n"
565 << " use: " << I << "\n");
566 Size -= (uint64_t)-Offset;
567 Offset = 0;
568 }
569
570 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
571
572 // Clamp the end offset to the end of the allocation. Note that this is
573 // formulated to handle even the case where "BeginOffset + Size" overflows.
574 assert(AllocSize >= BeginOffset); // Established above.
575 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000576 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
577 << " to remain within the " << AllocSize << " byte alloca:\n"
578 << " alloca: " << P.AI << "\n"
579 << " use: " << I << "\n");
580 EndOffset = AllocSize;
581 }
582
Chandler Carruth713aa942012-09-14 09:22:59 +0000583 Partition New(BeginOffset, EndOffset, IsSplittable);
584 P.Partitions.push_back(New);
585 }
586
Chandler Carruth02e92a02012-09-23 11:43:14 +0000587 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000588 uint64_t Size = TD.getTypeStoreSize(Ty);
589
590 // If this memory access can be shown to *statically* extend outside the
591 // bounds of of the allocation, it's behavior is undefined, so simply
592 // ignore it. Note that this is more strict than the generic clamping
593 // behavior of insertUse. We also try to handle cases which might run the
594 // risk of overflow.
595 // FIXME: We should instead consider the pointer to have escaped if this
596 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000597 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
598 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000599 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
600 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
601 << " which extends past the end of the " << AllocSize
602 << " byte alloca:\n"
603 << " alloca: " << P.AI << "\n"
604 << " use: " << I << "\n");
605 return true;
606 }
607
Chandler Carruth63392ea2012-09-16 19:39:50 +0000608 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000609 return true;
610 }
611
612 bool visitBitCastInst(BitCastInst &BC) {
613 enqueueUsers(BC, Offset);
614 return true;
615 }
616
617 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000618 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000619 if (!computeConstantGEPOffset(GEPI, GEPOffset))
620 return markAsEscaping(GEPI);
621
622 enqueueUsers(GEPI, GEPOffset);
623 return true;
624 }
625
626 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000627 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
628 "All simple FCA loads should have been pre-split");
Chandler Carruth63392ea2012-09-16 19:39:50 +0000629 return handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000630 }
631
632 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000633 Value *ValOp = SI.getValueOperand();
634 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000635 return markAsEscaping(SI);
636
Chandler Carruthc370acd2012-09-18 12:57:43 +0000637 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
638 "All simple FCA stores should have been pre-split");
639 return handleLoadOrStore(ValOp->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000640 }
641
642
643 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000644 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000645 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000646 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
647 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000648 return true;
649 }
650
651 bool visitMemTransferInst(MemTransferInst &II) {
652 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
653 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
654 if (!Size)
655 // Zero-length mem transfer intrinsics can be ignored entirely.
656 return true;
657
658 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
659
660 // Only intrinsics with a constant length can be split.
661 Offsets.IsSplittable = Length;
662
Chandler Carruthfca3f402012-10-05 01:29:09 +0000663 if (*U == II.getRawDest()) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000664 Offsets.DestBegin = Offset;
665 Offsets.DestEnd = Offset + Size;
666 }
Chandler Carruthfca3f402012-10-05 01:29:09 +0000667 if (*U == II.getRawSource()) {
668 Offsets.SourceBegin = Offset;
669 Offsets.SourceEnd = Offset + Size;
670 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000671
Chandler Carruthfca3f402012-10-05 01:29:09 +0000672 // If we have set up end offsets for both the source and the destination,
673 // we have found both sides of this transfer pointing at the same alloca.
674 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
675 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
676 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth713aa942012-09-14 09:22:59 +0000677
Chandler Carruthfca3f402012-10-05 01:29:09 +0000678 // Check if the begin offsets match and this is a non-volatile transfer.
679 // In that case, we can completely elide the transfer.
680 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
681 P.Partitions[PrevIdx].kill();
682 return true;
683 }
684
685 // Otherwise we have an offset transfer within the same alloca. We can't
686 // split those.
687 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
688 } else if (SeenBothEnds) {
689 // Handle the case where this exact use provides both ends of the
690 // operation.
691 assert(II.getRawDest() == II.getRawSource());
692
693 // For non-volatile transfers this is a no-op.
694 if (!II.isVolatile())
695 return true;
696
697 // Otherwise just suppress splitting.
Chandler Carruth713aa942012-09-14 09:22:59 +0000698 Offsets.IsSplittable = false;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000699 }
700
701
702 // Insert the use now that we've fixed up the splittable nature.
703 insertUse(II, Offset, Size, Offsets.IsSplittable);
704
705 // Setup the mapping from intrinsic to partition of we've not seen both
706 // ends of this transfer.
707 if (!SeenBothEnds) {
708 unsigned NewIdx = P.Partitions.size() - 1;
709 bool Inserted
710 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
711 assert(Inserted &&
712 "Already have intrinsic in map but haven't seen both ends");
Chandler Carruth713aa942012-09-14 09:22:59 +0000713 }
714
715 return true;
716 }
717
718 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000719 // FIXME: What about debug instrinsics? This matches old behavior, but
720 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000721 bool visitIntrinsicInst(IntrinsicInst &II) {
722 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
723 II.getIntrinsicID() == Intrinsic::lifetime_end) {
724 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
725 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000726 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000727 return true;
728 }
729
730 return markAsEscaping(II);
731 }
732
733 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
734 // We consider any PHI or select that results in a direct load or store of
735 // the same offset to be a viable use for partitioning purposes. These uses
736 // are considered unsplittable and the size is the maximum loaded or stored
737 // size.
738 SmallPtrSet<Instruction *, 4> Visited;
739 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
740 Visited.insert(Root);
741 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000742 // If there are no loads or stores, the access is dead. We mark that as
743 // a size zero access.
744 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000745 do {
746 Instruction *I, *UsedI;
747 llvm::tie(UsedI, I) = Uses.pop_back_val();
748
749 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
750 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
751 continue;
752 }
753 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
754 Value *Op = SI->getOperand(0);
755 if (Op == UsedI)
756 return SI;
757 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
758 continue;
759 }
760
761 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
762 if (!GEP->hasAllZeroIndices())
763 return GEP;
764 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
765 !isa<SelectInst>(I)) {
766 return I;
767 }
768
769 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
770 ++UI)
771 if (Visited.insert(cast<Instruction>(*UI)))
772 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
773 } while (!Uses.empty());
774
775 return 0;
776 }
777
778 bool visitPHINode(PHINode &PN) {
779 // See if we already have computed info on this node.
780 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
781 if (PHIInfo.first) {
782 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000783 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000784 return true;
785 }
786
787 // Check for an unsafe use of the PHI node.
788 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
789 return markAsEscaping(*EscapingI);
790
Chandler Carruth63392ea2012-09-16 19:39:50 +0000791 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000792 return true;
793 }
794
795 bool visitSelectInst(SelectInst &SI) {
796 if (Value *Result = foldSelectInst(SI)) {
797 if (Result == *U)
798 // If the result of the constant fold will be the pointer, recurse
799 // through the select as if we had RAUW'ed it.
800 enqueueUsers(SI, Offset);
801
802 return true;
803 }
804
805 // See if we already have computed info on this node.
806 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
807 if (SelectInfo.first) {
808 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000809 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000810 return true;
811 }
812
813 // Check for an unsafe use of the PHI node.
814 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
815 return markAsEscaping(*EscapingI);
816
Chandler Carruth63392ea2012-09-16 19:39:50 +0000817 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000818 return true;
819 }
820
821 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
822 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
823};
824
825
826/// \brief Use adder for the alloca partitioning.
827///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000828/// This class adds the uses of an alloca to all of the partitions which they
829/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000830/// walk of the partitions, but the number of steps remains bounded by the
831/// total result instruction size:
832/// - The number of partitions is a result of the number unsplittable
833/// instructions using the alloca.
834/// - The number of users of each partition is at worst the total number of
835/// splittable instructions using the alloca.
836/// Thus we will produce N * M instructions in the end, where N are the number
837/// of unsplittable uses and M are the number of splittable. This visitor does
838/// the exact same number of updates to the partitioning.
839///
840/// In the more common case, this visitor will leverage the fact that the
841/// partition space is pre-sorted, and do a logarithmic search for the
842/// partition needed, making the total visit a classical ((N + M) * log(N))
843/// complexity operation.
844class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
845 friend class InstVisitor<UseBuilder>;
846
847 /// \brief Set to de-duplicate dead instructions found in the use walk.
848 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
849
850public:
851 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000852 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000853
854 /// \brief Run the builder over the allocation.
855 void operator()() {
856 // Note that we have to re-evaluate size on each trip through the loop as
857 // the queue grows at the tail.
858 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
859 U = Queue[Idx].U;
860 Offset = Queue[Idx].Offset;
861 this->visit(cast<Instruction>(U->getUser()));
862 }
863 }
864
865private:
866 void markAsDead(Instruction &I) {
867 if (VisitedDeadInsts.insert(&I))
868 P.DeadUsers.push_back(&I);
869 }
870
Chandler Carruth02e92a02012-09-23 11:43:14 +0000871 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000872 // If the use has a zero size or extends outside of the allocation, record
873 // it as a dead use for elimination later.
874 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000875 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000876 return markAsDead(User);
877
Chandler Carruth02e92a02012-09-23 11:43:14 +0000878 // Clamp the start to the beginning of the allocation.
879 if (Offset < 0) {
880 Size -= (uint64_t)-Offset;
881 Offset = 0;
882 }
883
884 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
885
886 // Clamp the end offset to the end of the allocation. Note that this is
887 // formulated to handle even the case where "BeginOffset + Size" overflows.
888 assert(AllocSize >= BeginOffset); // Established above.
889 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000890 EndOffset = AllocSize;
891
892 // NB: This only works if we have zero overlapping partitions.
893 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
894 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
895 B = llvm::prior(B);
896 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
897 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000898 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
899 std::min(I->EndOffset, EndOffset), U);
900 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000901 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000902 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000903 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
904 }
905 }
906
Chandler Carruth02e92a02012-09-23 11:43:14 +0000907 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000908 uint64_t Size = TD.getTypeStoreSize(Ty);
909
910 // If this memory access can be shown to *statically* extend outside the
911 // bounds of of the allocation, it's behavior is undefined, so simply
912 // ignore it. Note that this is more strict than the generic clamping
913 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000914 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
915 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000916 return markAsDead(I);
917
Chandler Carruth63392ea2012-09-16 19:39:50 +0000918 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000919 }
920
921 void visitBitCastInst(BitCastInst &BC) {
922 if (BC.use_empty())
923 return markAsDead(BC);
924
925 enqueueUsers(BC, Offset);
926 }
927
928 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
929 if (GEPI.use_empty())
930 return markAsDead(GEPI);
931
Chandler Carruth02e92a02012-09-23 11:43:14 +0000932 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000933 if (!computeConstantGEPOffset(GEPI, GEPOffset))
934 llvm_unreachable("Unable to compute constant offset for use");
935
936 enqueueUsers(GEPI, GEPOffset);
937 }
938
939 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000940 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000941 }
942
943 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000944 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000945 }
946
947 void visitMemSetInst(MemSetInst &II) {
948 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000949 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
950 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000951 }
952
953 void visitMemTransferInst(MemTransferInst &II) {
954 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000955 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000956 if (!Size)
957 return markAsDead(II);
958
959 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
960 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
961 Offsets.DestBegin == Offsets.SourceBegin)
962 return markAsDead(II); // Skip identity transfers without side-effects.
963
Chandler Carruth63392ea2012-09-16 19:39:50 +0000964 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000965 }
966
967 void visitIntrinsicInst(IntrinsicInst &II) {
968 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
969 II.getIntrinsicID() == Intrinsic::lifetime_end);
970
971 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000972 insertUse(II, Offset,
973 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000974 }
975
Chandler Carruth63392ea2012-09-16 19:39:50 +0000976 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000977 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
978
979 // For PHI and select operands outside the alloca, we can't nuke the entire
980 // phi or select -- the other side might still be relevant, so we special
981 // case them here and use a separate structure to track the operands
982 // themselves which should be replaced with undef.
983 if (Offset >= AllocSize) {
984 P.DeadOperands.push_back(U);
985 return;
986 }
987
Chandler Carruth63392ea2012-09-16 19:39:50 +0000988 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000989 }
990 void visitPHINode(PHINode &PN) {
991 if (PN.use_empty())
992 return markAsDead(PN);
993
Chandler Carruth63392ea2012-09-16 19:39:50 +0000994 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000995 }
996 void visitSelectInst(SelectInst &SI) {
997 if (SI.use_empty())
998 return markAsDead(SI);
999
1000 if (Value *Result = foldSelectInst(SI)) {
1001 if (Result == *U)
1002 // If the result of the constant fold will be the pointer, recurse
1003 // through the select as if we had RAUW'ed it.
1004 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +00001005 else
1006 // Otherwise the operand to the select is dead, and we can replace it
1007 // with undef.
1008 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00001009
1010 return;
1011 }
1012
Chandler Carruth63392ea2012-09-16 19:39:50 +00001013 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001014 }
1015
1016 /// \brief Unreachable, we've already visited the alloca once.
1017 void visitInstruction(Instruction &I) {
1018 llvm_unreachable("Unhandled instruction in use builder.");
1019 }
1020};
1021
1022void AllocaPartitioning::splitAndMergePartitions() {
1023 size_t NumDeadPartitions = 0;
1024
1025 // Track the range of splittable partitions that we pass when accumulating
1026 // overlapping unsplittable partitions.
1027 uint64_t SplitEndOffset = 0ull;
1028
1029 Partition New(0ull, 0ull, false);
1030
1031 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1032 ++j;
1033
1034 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1035 assert(New.BeginOffset == New.EndOffset);
1036 New = Partitions[i];
1037 } else {
1038 assert(New.IsSplittable);
1039 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1040 }
1041 assert(New.BeginOffset != New.EndOffset);
1042
1043 // Scan the overlapping partitions.
1044 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1045 // If the new partition we are forming is splittable, stop at the first
1046 // unsplittable partition.
1047 if (New.IsSplittable && !Partitions[j].IsSplittable)
1048 break;
1049
1050 // Grow the new partition to include any equally splittable range. 'j' is
1051 // always equally splittable when New is splittable, but when New is not
1052 // splittable, we may subsume some (or part of some) splitable partition
1053 // without growing the new one.
1054 if (New.IsSplittable == Partitions[j].IsSplittable) {
1055 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1056 } else {
1057 assert(!New.IsSplittable);
1058 assert(Partitions[j].IsSplittable);
1059 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1060 }
1061
Chandler Carruthfca3f402012-10-05 01:29:09 +00001062 Partitions[j].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001063 ++NumDeadPartitions;
1064 ++j;
1065 }
1066
1067 // If the new partition is splittable, chop off the end as soon as the
1068 // unsplittable subsequent partition starts and ensure we eventually cover
1069 // the splittable area.
1070 if (j != e && New.IsSplittable) {
1071 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1072 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1073 }
1074
1075 // Add the new partition if it differs from the original one and is
1076 // non-empty. We can end up with an empty partition here if it was
1077 // splittable but there is an unsplittable one that starts at the same
1078 // offset.
1079 if (New != Partitions[i]) {
1080 if (New.BeginOffset != New.EndOffset)
1081 Partitions.push_back(New);
1082 // Mark the old one for removal.
Chandler Carruthfca3f402012-10-05 01:29:09 +00001083 Partitions[i].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001084 ++NumDeadPartitions;
1085 }
1086
1087 New.BeginOffset = New.EndOffset;
1088 if (!New.IsSplittable) {
1089 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1090 if (j != e && !Partitions[j].IsSplittable)
1091 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1092 New.IsSplittable = true;
1093 // If there is a trailing splittable partition which won't be fused into
1094 // the next splittable partition go ahead and add it onto the partitions
1095 // list.
1096 if (New.BeginOffset < New.EndOffset &&
1097 (j == e || !Partitions[j].IsSplittable ||
1098 New.EndOffset < Partitions[j].BeginOffset)) {
1099 Partitions.push_back(New);
1100 New.BeginOffset = New.EndOffset = 0ull;
1101 }
1102 }
1103 }
1104
1105 // Re-sort the partitions now that they have been split and merged into
1106 // disjoint set of partitions. Also remove any of the dead partitions we've
1107 // replaced in the process.
1108 std::sort(Partitions.begin(), Partitions.end());
1109 if (NumDeadPartitions) {
Chandler Carruthfca3f402012-10-05 01:29:09 +00001110 assert(Partitions.back().isDead());
Chandler Carruth713aa942012-09-14 09:22:59 +00001111 assert((ptrdiff_t)NumDeadPartitions ==
1112 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1113 }
1114 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1115}
1116
1117AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001118 :
1119#ifndef NDEBUG
1120 AI(AI),
1121#endif
1122 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001123 PartitionBuilder PB(TD, AI, *this);
1124 if (!PB())
1125 return;
1126
Chandler Carruthfca3f402012-10-05 01:29:09 +00001127 // Sort the uses. This arranges for the offsets to be in ascending order,
1128 // and the sizes to be in descending order.
1129 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth713aa942012-09-14 09:22:59 +00001130
Chandler Carruthfca3f402012-10-05 01:29:09 +00001131 // Remove any partitions from the back which are marked as dead.
1132 while (!Partitions.empty() && Partitions.back().isDead())
1133 Partitions.pop_back();
1134
1135 if (Partitions.size() > 1) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001136 // Intersect splittability for all partitions with equal offsets and sizes.
1137 // Then remove all but the first so that we have a sequence of non-equal but
1138 // potentially overlapping partitions.
1139 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1140 I = J) {
1141 ++J;
1142 while (J != E && *I == *J) {
1143 I->IsSplittable &= J->IsSplittable;
1144 ++J;
1145 }
1146 }
1147 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1148 Partitions.end());
1149
1150 // Split splittable and merge unsplittable partitions into a disjoint set
1151 // of partitions over the used space of the allocation.
1152 splitAndMergePartitions();
1153 }
1154
1155 // Now build up the user lists for each of these disjoint partitions by
1156 // re-walking the recursive users of the alloca.
1157 Uses.resize(Partitions.size());
1158 UseBuilder UB(TD, AI, *this);
1159 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001160}
1161
1162Type *AllocaPartitioning::getCommonType(iterator I) const {
1163 Type *Ty = 0;
1164 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001165 if (!UI->U)
1166 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001167 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001168 continue;
1169 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001170 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001171
1172 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001173 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001174 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001175 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001176 UserTy = SI->getValueOperand()->getType();
Chandler Carruth713aa942012-09-14 09:22:59 +00001177 }
1178
1179 if (Ty && Ty != UserTy)
1180 return 0;
1181
1182 Ty = UserTy;
1183 }
1184 return Ty;
1185}
1186
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001187#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1188
Chandler Carruth713aa942012-09-14 09:22:59 +00001189void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1190 StringRef Indent) const {
1191 OS << Indent << "partition #" << (I - begin())
1192 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1193 << (I->IsSplittable ? " (splittable)" : "")
1194 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1195 << "\n";
1196}
1197
1198void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1199 StringRef Indent) const {
1200 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1201 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001202 if (!UI->U)
1203 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001204 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001205 << "used by: " << *UI->U->getUser() << "\n";
1206 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001207 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1208 bool IsDest;
1209 if (!MTO.IsSplittable)
1210 IsDest = UI->BeginOffset == MTO.DestBegin;
1211 else
1212 IsDest = MTO.DestBegin != 0u;
1213 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1214 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1215 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1216 }
1217 }
1218}
1219
1220void AllocaPartitioning::print(raw_ostream &OS) const {
1221 if (PointerEscapingInstr) {
1222 OS << "No partitioning for alloca: " << AI << "\n"
1223 << " A pointer to this alloca escaped by:\n"
1224 << " " << *PointerEscapingInstr << "\n";
1225 return;
1226 }
1227
1228 OS << "Partitioning of alloca: " << AI << "\n";
1229 unsigned Num = 0;
1230 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1231 print(OS, I);
1232 printUsers(OS, I);
1233 }
1234}
1235
1236void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1237void AllocaPartitioning::dump() const { print(dbgs()); }
1238
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001239#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1240
Chandler Carruth713aa942012-09-14 09:22:59 +00001241
1242namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001243/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1244///
1245/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1246/// the loads and stores of an alloca instruction, as well as updating its
1247/// debug information. This is used when a domtree is unavailable and thus
1248/// mem2reg in its full form can't be used to handle promotion of allocas to
1249/// scalar values.
1250class AllocaPromoter : public LoadAndStorePromoter {
1251 AllocaInst &AI;
1252 DIBuilder &DIB;
1253
1254 SmallVector<DbgDeclareInst *, 4> DDIs;
1255 SmallVector<DbgValueInst *, 4> DVIs;
1256
1257public:
1258 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1259 AllocaInst &AI, DIBuilder &DIB)
1260 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1261
1262 void run(const SmallVectorImpl<Instruction*> &Insts) {
1263 // Remember which alloca we're promoting (for isInstInList).
1264 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1265 for (Value::use_iterator UI = DebugNode->use_begin(),
1266 UE = DebugNode->use_end();
1267 UI != UE; ++UI)
1268 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1269 DDIs.push_back(DDI);
1270 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1271 DVIs.push_back(DVI);
1272 }
1273
1274 LoadAndStorePromoter::run(Insts);
1275 AI.eraseFromParent();
1276 while (!DDIs.empty())
1277 DDIs.pop_back_val()->eraseFromParent();
1278 while (!DVIs.empty())
1279 DVIs.pop_back_val()->eraseFromParent();
1280 }
1281
1282 virtual bool isInstInList(Instruction *I,
1283 const SmallVectorImpl<Instruction*> &Insts) const {
1284 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1285 return LI->getOperand(0) == &AI;
1286 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1287 }
1288
1289 virtual void updateDebugInfo(Instruction *Inst) const {
1290 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1291 E = DDIs.end(); I != E; ++I) {
1292 DbgDeclareInst *DDI = *I;
1293 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1294 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1295 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1296 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1297 }
1298 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1299 E = DVIs.end(); I != E; ++I) {
1300 DbgValueInst *DVI = *I;
1301 Value *Arg = NULL;
1302 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1303 // If an argument is zero extended then use argument directly. The ZExt
1304 // may be zapped by an optimization pass in future.
1305 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1306 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1307 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1308 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1309 if (!Arg)
1310 Arg = SI->getOperand(0);
1311 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1312 Arg = LI->getOperand(0);
1313 } else {
1314 continue;
1315 }
1316 Instruction *DbgVal =
1317 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1318 Inst);
1319 DbgVal->setDebugLoc(DVI->getDebugLoc());
1320 }
1321 }
1322};
1323} // end anon namespace
1324
1325
1326namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001327/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1328///
1329/// This pass takes allocations which can be completely analyzed (that is, they
1330/// don't escape) and tries to turn them into scalar SSA values. There are
1331/// a few steps to this process.
1332///
1333/// 1) It takes allocations of aggregates and analyzes the ways in which they
1334/// are used to try to split them into smaller allocations, ideally of
1335/// a single scalar data type. It will split up memcpy and memset accesses
1336/// as necessary and try to isolate invidual scalar accesses.
1337/// 2) It will transform accesses into forms which are suitable for SSA value
1338/// promotion. This can be replacing a memset with a scalar store of an
1339/// integer value, or it can involve speculating operations on a PHI or
1340/// select to be a PHI or select of the results.
1341/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1342/// onto insert and extract operations on a vector value, and convert them to
1343/// this form. By doing so, it will enable promotion of vector aggregates to
1344/// SSA vector values.
1345class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001346 const bool RequiresDomTree;
1347
Chandler Carruth713aa942012-09-14 09:22:59 +00001348 LLVMContext *C;
1349 const TargetData *TD;
1350 DominatorTree *DT;
1351
1352 /// \brief Worklist of alloca instructions to simplify.
1353 ///
1354 /// Each alloca in the function is added to this. Each new alloca formed gets
1355 /// added to it as well to recursively simplify unless that alloca can be
1356 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1357 /// the one being actively rewritten, we add it back onto the list if not
1358 /// already present to ensure it is re-visited.
1359 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1360
1361 /// \brief A collection of instructions to delete.
1362 /// We try to batch deletions to simplify code and make things a bit more
1363 /// efficient.
1364 SmallVector<Instruction *, 8> DeadInsts;
1365
1366 /// \brief A set to prevent repeatedly marking an instruction split into many
1367 /// uses as dead. Only used to guard insertion into DeadInsts.
1368 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1369
Chandler Carruthb2d98c22012-10-04 12:33:50 +00001370 /// \brief Post-promotion worklist.
1371 ///
1372 /// Sometimes we discover an alloca which has a high probability of becoming
1373 /// viable for SROA after a round of promotion takes place. In those cases,
1374 /// the alloca is enqueued here for re-processing.
1375 ///
1376 /// Note that we have to be very careful to clear allocas out of this list in
1377 /// the event they are deleted.
1378 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1379
Chandler Carruth713aa942012-09-14 09:22:59 +00001380 /// \brief A collection of alloca instructions we can directly promote.
1381 std::vector<AllocaInst *> PromotableAllocas;
1382
1383public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001384 SROA(bool RequiresDomTree = true)
1385 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1386 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001387 initializeSROAPass(*PassRegistry::getPassRegistry());
1388 }
1389 bool runOnFunction(Function &F);
1390 void getAnalysisUsage(AnalysisUsage &AU) const;
1391
1392 const char *getPassName() const { return "SROA"; }
1393 static char ID;
1394
1395private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001396 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001397 friend class AllocaPartitionRewriter;
1398 friend class AllocaPartitionVectorRewriter;
1399
1400 bool rewriteAllocaPartition(AllocaInst &AI,
1401 AllocaPartitioning &P,
1402 AllocaPartitioning::iterator PI);
1403 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1404 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001405 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001406 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001407};
1408}
1409
1410char SROA::ID = 0;
1411
Chandler Carruth1c8db502012-09-15 11:43:14 +00001412FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1413 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001414}
1415
1416INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1417 false, false)
1418INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1419INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1420 false, false)
1421
Chandler Carruth0e9da582012-10-05 01:29:06 +00001422namespace {
1423/// \brief Visitor to speculate PHIs and Selects where possible.
1424class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1425 // Befriend the base class so it can delegate to private visit methods.
1426 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1427
1428 const TargetData &TD;
1429 AllocaPartitioning &P;
1430 SROA &Pass;
1431
1432public:
1433 PHIOrSelectSpeculator(const TargetData &TD, AllocaPartitioning &P, SROA &Pass)
1434 : TD(TD), P(P), Pass(Pass) {}
1435
1436 /// \brief Visit the users of an alloca partition and rewrite them.
1437 void visitUsers(AllocaPartitioning::const_iterator PI) {
1438 // Note that we need to use an index here as the underlying vector of uses
1439 // may be grown during speculation. However, we never need to re-visit the
1440 // new uses, and so we can use the initial size bound.
1441 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1442 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1443 if (!PU.U)
1444 continue; // Skip dead use.
1445
1446 visit(cast<Instruction>(PU.U->getUser()));
1447 }
1448 }
1449
1450private:
1451 // By default, skip this instruction.
1452 void visitInstruction(Instruction &I) {}
1453
1454 /// PHI instructions that use an alloca and are subsequently loaded can be
1455 /// rewritten to load both input pointers in the pred blocks and then PHI the
1456 /// results, allowing the load of the alloca to be promoted.
1457 /// From this:
1458 /// %P2 = phi [i32* %Alloca, i32* %Other]
1459 /// %V = load i32* %P2
1460 /// to:
1461 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1462 /// ...
1463 /// %V2 = load i32* %Other
1464 /// ...
1465 /// %V = phi [i32 %V1, i32 %V2]
1466 ///
1467 /// We can do this to a select if its only uses are loads and if the operands
1468 /// to the select can be loaded unconditionally.
1469 ///
1470 /// FIXME: This should be hoisted into a generic utility, likely in
1471 /// Transforms/Util/Local.h
1472 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1473 // For now, we can only do this promotion if the load is in the same block
1474 // as the PHI, and if there are no stores between the phi and load.
1475 // TODO: Allow recursive phi users.
1476 // TODO: Allow stores.
1477 BasicBlock *BB = PN.getParent();
1478 unsigned MaxAlign = 0;
1479 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1480 UI != UE; ++UI) {
1481 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1482 if (LI == 0 || !LI->isSimple()) return false;
1483
1484 // For now we only allow loads in the same block as the PHI. This is
1485 // a common case that happens when instcombine merges two loads through
1486 // a PHI.
1487 if (LI->getParent() != BB) return false;
1488
1489 // Ensure that there are no instructions between the PHI and the load that
1490 // could store.
1491 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1492 if (BBI->mayWriteToMemory())
1493 return false;
1494
1495 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1496 Loads.push_back(LI);
1497 }
1498
1499 // We can only transform this if it is safe to push the loads into the
1500 // predecessor blocks. The only thing to watch out for is that we can't put
1501 // a possibly trapping load in the predecessor if it is a critical edge.
1502 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1503 ++Idx) {
1504 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1505 Value *InVal = PN.getIncomingValue(Idx);
1506
1507 // If the value is produced by the terminator of the predecessor (an
1508 // invoke) or it has side-effects, there is no valid place to put a load
1509 // in the predecessor.
1510 if (TI == InVal || TI->mayHaveSideEffects())
1511 return false;
1512
1513 // If the predecessor has a single successor, then the edge isn't
1514 // critical.
1515 if (TI->getNumSuccessors() == 1)
1516 continue;
1517
1518 // If this pointer is always safe to load, or if we can prove that there
1519 // is already a load in the block, then we can move the load to the pred
1520 // block.
1521 if (InVal->isDereferenceablePointer() ||
1522 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1523 continue;
1524
1525 return false;
1526 }
1527
1528 return true;
1529 }
1530
1531 void visitPHINode(PHINode &PN) {
1532 DEBUG(dbgs() << " original: " << PN << "\n");
1533
1534 SmallVector<LoadInst *, 4> Loads;
1535 if (!isSafePHIToSpeculate(PN, Loads))
1536 return;
1537
1538 assert(!Loads.empty());
1539
1540 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1541 IRBuilder<> PHIBuilder(&PN);
1542 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1543 PN.getName() + ".sroa.speculated");
1544
1545 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1546 // matter which one we get and if any differ, it doesn't matter.
1547 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1548 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1549 unsigned Align = SomeLoad->getAlignment();
1550
1551 // Rewrite all loads of the PN to use the new PHI.
1552 do {
1553 LoadInst *LI = Loads.pop_back_val();
1554 LI->replaceAllUsesWith(NewPN);
1555 Pass.DeadInsts.push_back(LI);
1556 } while (!Loads.empty());
1557
1558 // Inject loads into all of the pred blocks.
1559 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1560 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1561 TerminatorInst *TI = Pred->getTerminator();
1562 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1563 Value *InVal = PN.getIncomingValue(Idx);
1564 IRBuilder<> PredBuilder(TI);
1565
1566 LoadInst *Load
1567 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1568 Pred->getName()));
1569 ++NumLoadsSpeculated;
1570 Load->setAlignment(Align);
1571 if (TBAATag)
1572 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1573 NewPN->addIncoming(Load, Pred);
1574
1575 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1576 if (!Ptr)
1577 // No uses to rewrite.
1578 continue;
1579
1580 // Try to lookup and rewrite any partition uses corresponding to this phi
1581 // input.
1582 AllocaPartitioning::iterator PI
1583 = P.findPartitionForPHIOrSelectOperand(InUse);
1584 if (PI == P.end())
1585 continue;
1586
1587 // Replace the Use in the PartitionUse for this operand with the Use
1588 // inside the load.
1589 AllocaPartitioning::use_iterator UI
1590 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1591 assert(isa<PHINode>(*UI->U->getUser()));
1592 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1593 }
1594 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1595 }
1596
1597 /// Select instructions that use an alloca and are subsequently loaded can be
1598 /// rewritten to load both input pointers and then select between the result,
1599 /// allowing the load of the alloca to be promoted.
1600 /// From this:
1601 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1602 /// %V = load i32* %P2
1603 /// to:
1604 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1605 /// %V2 = load i32* %Other
1606 /// %V = select i1 %cond, i32 %V1, i32 %V2
1607 ///
1608 /// We can do this to a select if its only uses are loads and if the operand
1609 /// to the select can be loaded unconditionally.
1610 bool isSafeSelectToSpeculate(SelectInst &SI,
1611 SmallVectorImpl<LoadInst *> &Loads) {
1612 Value *TValue = SI.getTrueValue();
1613 Value *FValue = SI.getFalseValue();
1614 bool TDerefable = TValue->isDereferenceablePointer();
1615 bool FDerefable = FValue->isDereferenceablePointer();
1616
1617 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1618 UI != UE; ++UI) {
1619 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1620 if (LI == 0 || !LI->isSimple()) return false;
1621
1622 // Both operands to the select need to be dereferencable, either
1623 // absolutely (e.g. allocas) or at this point because we can see other
1624 // accesses to it.
1625 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1626 LI->getAlignment(), &TD))
1627 return false;
1628 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1629 LI->getAlignment(), &TD))
1630 return false;
1631 Loads.push_back(LI);
1632 }
1633
1634 return true;
1635 }
1636
1637 void visitSelectInst(SelectInst &SI) {
1638 DEBUG(dbgs() << " original: " << SI << "\n");
1639 IRBuilder<> IRB(&SI);
1640
1641 // If the select isn't safe to speculate, just use simple logic to emit it.
1642 SmallVector<LoadInst *, 4> Loads;
1643 if (!isSafeSelectToSpeculate(SI, Loads))
1644 return;
1645
1646 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1647 AllocaPartitioning::iterator PIs[2];
1648 AllocaPartitioning::PartitionUse PUs[2];
1649 for (unsigned i = 0, e = 2; i != e; ++i) {
1650 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1651 if (PIs[i] != P.end()) {
1652 // If the pointer is within the partitioning, remove the select from
1653 // its uses. We'll add in the new loads below.
1654 AllocaPartitioning::use_iterator UI
1655 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1656 PUs[i] = *UI;
1657 // Clear out the use here so that the offsets into the use list remain
1658 // stable but this use is ignored when rewriting.
1659 UI->U = 0;
1660 }
1661 }
1662
1663 Value *TV = SI.getTrueValue();
1664 Value *FV = SI.getFalseValue();
1665 // Replace the loads of the select with a select of two loads.
1666 while (!Loads.empty()) {
1667 LoadInst *LI = Loads.pop_back_val();
1668
1669 IRB.SetInsertPoint(LI);
1670 LoadInst *TL =
1671 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1672 LoadInst *FL =
1673 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1674 NumLoadsSpeculated += 2;
1675
1676 // Transfer alignment and TBAA info if present.
1677 TL->setAlignment(LI->getAlignment());
1678 FL->setAlignment(LI->getAlignment());
1679 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1680 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1681 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1682 }
1683
1684 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1685 LI->getName() + ".sroa.speculated");
1686
1687 LoadInst *Loads[2] = { TL, FL };
1688 for (unsigned i = 0, e = 2; i != e; ++i) {
1689 if (PIs[i] != P.end()) {
1690 Use *LoadUse = &Loads[i]->getOperandUse(0);
1691 assert(PUs[i].U->get() == LoadUse->get());
1692 PUs[i].U = LoadUse;
1693 P.use_push_back(PIs[i], PUs[i]);
1694 }
1695 }
1696
1697 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1698 LI->replaceAllUsesWith(V);
1699 Pass.DeadInsts.push_back(LI);
1700 }
1701 }
1702};
1703}
1704
Chandler Carruth713aa942012-09-14 09:22:59 +00001705/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1706///
1707/// If the provided GEP is all-constant, the total byte offset formed by the
1708/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1709/// operands, the function returns false and the value of Offset is unmodified.
1710static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1711 APInt &Offset) {
1712 APInt GEPOffset(Offset.getBitWidth(), 0);
1713 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1714 GTI != GTE; ++GTI) {
1715 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1716 if (!OpC)
1717 return false;
1718 if (OpC->isZero()) continue;
1719
1720 // Handle a struct index, which adds its field offset to the pointer.
1721 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1722 unsigned ElementIdx = OpC->getZExtValue();
1723 const StructLayout *SL = TD.getStructLayout(STy);
1724 GEPOffset += APInt(Offset.getBitWidth(),
1725 SL->getElementOffset(ElementIdx));
1726 continue;
1727 }
1728
1729 APInt TypeSize(Offset.getBitWidth(),
1730 TD.getTypeAllocSize(GTI.getIndexedType()));
1731 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1732 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1733 "vector element size is not a multiple of 8, cannot GEP over it");
1734 TypeSize = VTy->getScalarSizeInBits() / 8;
1735 }
1736
1737 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1738 }
1739 Offset = GEPOffset;
1740 return true;
1741}
1742
1743/// \brief Build a GEP out of a base pointer and indices.
1744///
1745/// This will return the BasePtr if that is valid, or build a new GEP
1746/// instruction using the IRBuilder if GEP-ing is needed.
1747static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1748 SmallVectorImpl<Value *> &Indices,
1749 const Twine &Prefix) {
1750 if (Indices.empty())
1751 return BasePtr;
1752
1753 // A single zero index is a no-op, so check for this and avoid building a GEP
1754 // in that case.
1755 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1756 return BasePtr;
1757
1758 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1759}
1760
1761/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1762/// TargetTy without changing the offset of the pointer.
1763///
1764/// This routine assumes we've already established a properly offset GEP with
1765/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1766/// zero-indices down through type layers until we find one the same as
1767/// TargetTy. If we can't find one with the same type, we at least try to use
1768/// one with the same size. If none of that works, we just produce the GEP as
1769/// indicated by Indices to have the correct offset.
1770static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1771 Value *BasePtr, Type *Ty, Type *TargetTy,
1772 SmallVectorImpl<Value *> &Indices,
1773 const Twine &Prefix) {
1774 if (Ty == TargetTy)
1775 return buildGEP(IRB, BasePtr, Indices, Prefix);
1776
1777 // See if we can descend into a struct and locate a field with the correct
1778 // type.
1779 unsigned NumLayers = 0;
1780 Type *ElementTy = Ty;
1781 do {
1782 if (ElementTy->isPointerTy())
1783 break;
1784 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1785 ElementTy = SeqTy->getElementType();
1786 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1787 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1788 ElementTy = *STy->element_begin();
1789 Indices.push_back(IRB.getInt32(0));
1790 } else {
1791 break;
1792 }
1793 ++NumLayers;
1794 } while (ElementTy != TargetTy);
1795 if (ElementTy != TargetTy)
1796 Indices.erase(Indices.end() - NumLayers, Indices.end());
1797
1798 return buildGEP(IRB, BasePtr, Indices, Prefix);
1799}
1800
1801/// \brief Recursively compute indices for a natural GEP.
1802///
1803/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1804/// element types adding appropriate indices for the GEP.
1805static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1806 Value *Ptr, Type *Ty, APInt &Offset,
1807 Type *TargetTy,
1808 SmallVectorImpl<Value *> &Indices,
1809 const Twine &Prefix) {
1810 if (Offset == 0)
1811 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1812
1813 // We can't recurse through pointer types.
1814 if (Ty->isPointerTy())
1815 return 0;
1816
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001817 // We try to analyze GEPs over vectors here, but note that these GEPs are
1818 // extremely poorly defined currently. The long-term goal is to remove GEPing
1819 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001820 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1821 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1822 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001823 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001824 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1825 APInt NumSkippedElements = Offset.udiv(ElementSize);
1826 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1827 return 0;
1828 Offset -= NumSkippedElements * ElementSize;
1829 Indices.push_back(IRB.getInt(NumSkippedElements));
1830 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1831 Offset, TargetTy, Indices, Prefix);
1832 }
1833
1834 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1835 Type *ElementTy = ArrTy->getElementType();
1836 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1837 APInt NumSkippedElements = Offset.udiv(ElementSize);
1838 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1839 return 0;
1840
1841 Offset -= NumSkippedElements * ElementSize;
1842 Indices.push_back(IRB.getInt(NumSkippedElements));
1843 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1844 Indices, Prefix);
1845 }
1846
1847 StructType *STy = dyn_cast<StructType>(Ty);
1848 if (!STy)
1849 return 0;
1850
1851 const StructLayout *SL = TD.getStructLayout(STy);
1852 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001853 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001854 return 0;
1855 unsigned Index = SL->getElementContainingOffset(StructOffset);
1856 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1857 Type *ElementTy = STy->getElementType(Index);
1858 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1859 return 0; // The offset points into alignment padding.
1860
1861 Indices.push_back(IRB.getInt32(Index));
1862 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1863 Indices, Prefix);
1864}
1865
1866/// \brief Get a natural GEP from a base pointer to a particular offset and
1867/// resulting in a particular type.
1868///
1869/// The goal is to produce a "natural" looking GEP that works with the existing
1870/// composite types to arrive at the appropriate offset and element type for
1871/// a pointer. TargetTy is the element type the returned GEP should point-to if
1872/// possible. We recurse by decreasing Offset, adding the appropriate index to
1873/// Indices, and setting Ty to the result subtype.
1874///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001875/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth713aa942012-09-14 09:22:59 +00001876static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1877 Value *Ptr, APInt Offset, Type *TargetTy,
1878 SmallVectorImpl<Value *> &Indices,
1879 const Twine &Prefix) {
1880 PointerType *Ty = cast<PointerType>(Ptr->getType());
1881
1882 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1883 // an i8.
1884 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1885 return 0;
1886
1887 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001888 if (!ElementTy->isSized())
1889 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001890 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1891 if (ElementSize == 0)
1892 return 0; // Zero-length arrays can't help us build a natural GEP.
1893 APInt NumSkippedElements = Offset.udiv(ElementSize);
1894
1895 Offset -= NumSkippedElements * ElementSize;
1896 Indices.push_back(IRB.getInt(NumSkippedElements));
1897 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1898 Indices, Prefix);
1899}
1900
1901/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1902/// resulting pointer has PointerTy.
1903///
1904/// This tries very hard to compute a "natural" GEP which arrives at the offset
1905/// and produces the pointer type desired. Where it cannot, it will try to use
1906/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1907/// fails, it will try to use an existing i8* and GEP to the byte offset and
1908/// bitcast to the type.
1909///
1910/// The strategy for finding the more natural GEPs is to peel off layers of the
1911/// pointer, walking back through bit casts and GEPs, searching for a base
1912/// pointer from which we can compute a natural GEP with the desired
1913/// properities. The algorithm tries to fold as many constant indices into
1914/// a single GEP as possible, thus making each GEP more independent of the
1915/// surrounding code.
1916static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1917 Value *Ptr, APInt Offset, Type *PointerTy,
1918 const Twine &Prefix) {
1919 // Even though we don't look through PHI nodes, we could be called on an
1920 // instruction in an unreachable block, which may be on a cycle.
1921 SmallPtrSet<Value *, 4> Visited;
1922 Visited.insert(Ptr);
1923 SmallVector<Value *, 4> Indices;
1924
1925 // We may end up computing an offset pointer that has the wrong type. If we
1926 // never are able to compute one directly that has the correct type, we'll
1927 // fall back to it, so keep it around here.
1928 Value *OffsetPtr = 0;
1929
1930 // Remember any i8 pointer we come across to re-use if we need to do a raw
1931 // byte offset.
1932 Value *Int8Ptr = 0;
1933 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1934
1935 Type *TargetTy = PointerTy->getPointerElementType();
1936
1937 do {
1938 // First fold any existing GEPs into the offset.
1939 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1940 APInt GEPOffset(Offset.getBitWidth(), 0);
1941 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1942 break;
1943 Offset += GEPOffset;
1944 Ptr = GEP->getPointerOperand();
1945 if (!Visited.insert(Ptr))
1946 break;
1947 }
1948
1949 // See if we can perform a natural GEP here.
1950 Indices.clear();
1951 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1952 Indices, Prefix)) {
1953 if (P->getType() == PointerTy) {
1954 // Zap any offset pointer that we ended up computing in previous rounds.
1955 if (OffsetPtr && OffsetPtr->use_empty())
1956 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1957 I->eraseFromParent();
1958 return P;
1959 }
1960 if (!OffsetPtr) {
1961 OffsetPtr = P;
1962 }
1963 }
1964
1965 // Stash this pointer if we've found an i8*.
1966 if (Ptr->getType()->isIntegerTy(8)) {
1967 Int8Ptr = Ptr;
1968 Int8PtrOffset = Offset;
1969 }
1970
1971 // Peel off a layer of the pointer and update the offset appropriately.
1972 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1973 Ptr = cast<Operator>(Ptr)->getOperand(0);
1974 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1975 if (GA->mayBeOverridden())
1976 break;
1977 Ptr = GA->getAliasee();
1978 } else {
1979 break;
1980 }
1981 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1982 } while (Visited.insert(Ptr));
1983
1984 if (!OffsetPtr) {
1985 if (!Int8Ptr) {
1986 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1987 Prefix + ".raw_cast");
1988 Int8PtrOffset = Offset;
1989 }
1990
1991 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1992 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1993 Prefix + ".raw_idx");
1994 }
1995 Ptr = OffsetPtr;
1996
1997 // On the off chance we were targeting i8*, guard the bitcast here.
1998 if (Ptr->getType() != PointerTy)
1999 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2000
2001 return Ptr;
2002}
2003
2004/// \brief Test whether the given alloca partition can be promoted to a vector.
2005///
2006/// This is a quick test to check whether we can rewrite a particular alloca
2007/// partition (and its newly formed alloca) into a vector alloca with only
2008/// whole-vector loads and stores such that it could be promoted to a vector
2009/// SSA value. We only can ensure this for a limited set of operations, and we
2010/// don't want to do the rewrites unless we are confident that the result will
2011/// be promotable, so we have an early test here.
2012static bool isVectorPromotionViable(const TargetData &TD,
2013 Type *AllocaTy,
2014 AllocaPartitioning &P,
2015 uint64_t PartitionBeginOffset,
2016 uint64_t PartitionEndOffset,
2017 AllocaPartitioning::const_use_iterator I,
2018 AllocaPartitioning::const_use_iterator E) {
2019 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2020 if (!Ty)
2021 return false;
2022
2023 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2024 uint64_t ElementSize = Ty->getScalarSizeInBits();
2025
2026 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2027 // that aren't byte sized.
2028 if (ElementSize % 8)
2029 return false;
2030 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2031 VecSize /= 8;
2032 ElementSize /= 8;
2033
2034 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002035 if (!I->U)
2036 continue; // Skip dead use.
2037
Chandler Carruth713aa942012-09-14 09:22:59 +00002038 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2039 uint64_t BeginIndex = BeginOffset / ElementSize;
2040 if (BeginIndex * ElementSize != BeginOffset ||
2041 BeginIndex >= Ty->getNumElements())
2042 return false;
2043 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2044 uint64_t EndIndex = EndOffset / ElementSize;
2045 if (EndIndex * ElementSize != EndOffset ||
2046 EndIndex > Ty->getNumElements())
2047 return false;
2048
2049 // FIXME: We should build shuffle vector instructions to handle
2050 // non-element-sized accesses.
2051 if ((EndOffset - BeginOffset) != ElementSize &&
2052 (EndOffset - BeginOffset) != VecSize)
2053 return false;
2054
Chandler Carruth77c12702012-10-01 01:49:22 +00002055 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002056 if (MI->isVolatile())
2057 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002058 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002059 const AllocaPartitioning::MemTransferOffsets &MTO
2060 = P.getMemTransferOffsets(*MTI);
2061 if (!MTO.IsSplittable)
2062 return false;
2063 }
Chandler Carruth77c12702012-10-01 01:49:22 +00002064 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002065 // Disable vector promotion when there are loads or stores of an FCA.
2066 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002067 } else if (!isa<LoadInst>(I->U->getUser()) &&
2068 !isa<StoreInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002069 return false;
2070 }
2071 }
2072 return true;
2073}
2074
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002075/// \brief Test whether the given alloca partition can be promoted to an int.
2076///
2077/// This is a quick test to check whether we can rewrite a particular alloca
2078/// partition (and its newly formed alloca) into an integer alloca suitable for
2079/// promotion to an SSA value. We only can ensure this for a limited set of
2080/// operations, and we don't want to do the rewrites unless we are confident
2081/// that the result will be promotable, so we have an early test here.
2082static bool isIntegerPromotionViable(const TargetData &TD,
2083 Type *AllocaTy,
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002084 uint64_t AllocBeginOffset,
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002085 AllocaPartitioning &P,
2086 AllocaPartitioning::const_use_iterator I,
2087 AllocaPartitioning::const_use_iterator E) {
2088 IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002089 if (!Ty || 8*TD.getTypeStoreSize(Ty) != Ty->getBitWidth())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002090 return false;
2091
2092 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2093 // Also ensure that the alloca has a covering load or store. We don't want
2094 // promote because of some other unsplittable entry (which we may make
2095 // splittable later) and lose the ability to promote each element access.
2096 bool WholeAllocaOp = false;
2097 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002098 if (!I->U)
2099 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002100
2101 // We can't reasonably handle cases where the load or store extends past
2102 // the end of the aloca's type and into its padding.
2103 if ((I->EndOffset - AllocBeginOffset) > TD.getTypeStoreSize(Ty))
2104 return false;
2105
Chandler Carruth77c12702012-10-01 01:49:22 +00002106 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002107 if (LI->isVolatile() || !LI->getType()->isIntegerTy())
2108 return false;
2109 if (LI->getType() == Ty)
2110 WholeAllocaOp = true;
Chandler Carruth77c12702012-10-01 01:49:22 +00002111 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002112 if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
2113 return false;
2114 if (SI->getValueOperand()->getType() == Ty)
2115 WholeAllocaOp = true;
Chandler Carruth77c12702012-10-01 01:49:22 +00002116 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002117 if (MI->isVolatile())
2118 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002119 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002120 const AllocaPartitioning::MemTransferOffsets &MTO
2121 = P.getMemTransferOffsets(*MTI);
2122 if (!MTO.IsSplittable)
2123 return false;
2124 }
2125 } else {
2126 return false;
2127 }
2128 }
2129 return WholeAllocaOp;
2130}
2131
Chandler Carruth713aa942012-09-14 09:22:59 +00002132namespace {
2133/// \brief Visitor to rewrite instructions using a partition of an alloca to
2134/// use a new alloca.
2135///
2136/// Also implements the rewriting to vector-based accesses when the partition
2137/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2138/// lives here.
2139class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2140 bool> {
2141 // Befriend the base class so it can delegate to private visit methods.
2142 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2143
2144 const TargetData &TD;
2145 AllocaPartitioning &P;
2146 SROA &Pass;
2147 AllocaInst &OldAI, &NewAI;
2148 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2149
2150 // If we are rewriting an alloca partition which can be written as pure
2151 // vector operations, we stash extra information here. When VecTy is
2152 // non-null, we have some strict guarantees about the rewriten alloca:
2153 // - The new alloca is exactly the size of the vector type here.
2154 // - The accesses all either map to the entire vector or to a single
2155 // element.
2156 // - The set of accessing instructions is only one of those handled above
2157 // in isVectorPromotionViable. Generally these are the same access kinds
2158 // which are promotable via mem2reg.
2159 VectorType *VecTy;
2160 Type *ElementTy;
2161 uint64_t ElementSize;
2162
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002163 // This is a convenience and flag variable that will be null unless the new
2164 // alloca has a promotion-targeted integer type due to passing
2165 // isIntegerPromotionViable above. If it is non-null does, the desired
2166 // integer type will be stored here for easy access during rewriting.
2167 IntegerType *IntPromotionTy;
2168
Chandler Carruth713aa942012-09-14 09:22:59 +00002169 // The offset of the partition user currently being rewritten.
2170 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002171 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002172 Instruction *OldPtr;
2173
2174 // The name prefix to use when rewriting instructions for this alloca.
2175 std::string NamePrefix;
2176
2177public:
2178 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
2179 AllocaPartitioning::iterator PI,
2180 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2181 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2182 : TD(TD), P(P), Pass(Pass),
2183 OldAI(OldAI), NewAI(NewAI),
2184 NewAllocaBeginOffset(NewBeginOffset),
2185 NewAllocaEndOffset(NewEndOffset),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002186 VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002187 BeginOffset(), EndOffset() {
2188 }
2189
2190 /// \brief Visit the users of the alloca partition and rewrite them.
2191 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2192 AllocaPartitioning::const_use_iterator E) {
2193 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2194 NewAllocaBeginOffset, NewAllocaEndOffset,
2195 I, E)) {
2196 ++NumVectorized;
2197 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2198 ElementTy = VecTy->getElementType();
2199 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2200 "Only multiple-of-8 sized vector elements are viable");
2201 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002202 } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002203 NewAllocaBeginOffset, P, I, E)) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002204 IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002205 }
2206 bool CanSROA = true;
2207 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002208 if (!I->U)
2209 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002210 BeginOffset = I->BeginOffset;
2211 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002212 OldUse = I->U;
2213 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002214 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002215 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002216 }
2217 if (VecTy) {
2218 assert(CanSROA);
2219 VecTy = 0;
2220 ElementTy = 0;
2221 ElementSize = 0;
2222 }
2223 return CanSROA;
2224 }
2225
2226private:
2227 // Every instruction which can end up as a user must have a rewrite rule.
2228 bool visitInstruction(Instruction &I) {
2229 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2230 llvm_unreachable("No rewrite rule for this instruction!");
2231 }
2232
2233 Twine getName(const Twine &Suffix) {
2234 return NamePrefix + Suffix;
2235 }
2236
2237 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2238 assert(BeginOffset >= NewAllocaBeginOffset);
2239 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2240 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2241 }
2242
Chandler Carruthf710fb12012-10-03 08:14:02 +00002243 /// \brief Compute suitable alignment to access an offset into the new alloca.
2244 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002245 unsigned NewAIAlign = NewAI.getAlignment();
2246 if (!NewAIAlign)
2247 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2248 return MinAlign(NewAIAlign, Offset);
2249 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002250
2251 /// \brief Compute suitable alignment to access this partition of the new
2252 /// alloca.
2253 unsigned getPartitionAlign() {
2254 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002255 }
2256
Chandler Carruthf710fb12012-10-03 08:14:02 +00002257 /// \brief Compute suitable alignment to access a type at an offset of the
2258 /// new alloca.
2259 ///
2260 /// \returns zero if the type's ABI alignment is a suitable alignment,
2261 /// otherwise returns the maximal suitable alignment.
2262 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2263 unsigned Align = getOffsetAlign(Offset);
2264 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2265 }
2266
2267 /// \brief Compute suitable alignment to access a type at the beginning of
2268 /// this partition of the new alloca.
2269 ///
2270 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2271 unsigned getPartitionTypeAlign(Type *Ty) {
2272 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002273 }
2274
Chandler Carruth713aa942012-09-14 09:22:59 +00002275 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2276 assert(VecTy && "Can only call getIndex when rewriting a vector");
2277 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2278 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2279 uint32_t Index = RelOffset / ElementSize;
2280 assert(Index * ElementSize == RelOffset);
2281 return IRB.getInt32(Index);
2282 }
2283
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002284 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
2285 uint64_t Offset) {
2286 assert(IntPromotionTy && "Alloca is not an integer we can extract from");
Chandler Carruth81b001a2012-09-26 10:27:46 +00002287 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2288 getName(".load"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002289 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2290 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002291 assert(TD.getTypeStoreSize(TargetTy) + RelOffset <=
2292 TD.getTypeStoreSize(IntPromotionTy) &&
2293 "Element load outside of alloca store");
2294 uint64_t ShAmt = 8*RelOffset;
2295 if (TD.isBigEndian())
2296 ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) -
2297 TD.getTypeStoreSize(TargetTy) - RelOffset);
2298 if (ShAmt)
2299 V = IRB.CreateLShr(V, ShAmt, getName(".shift"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002300 if (TargetTy != IntPromotionTy) {
2301 assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
2302 "Cannot extract to a larger integer!");
2303 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
2304 }
2305 return V;
2306 }
2307
2308 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
2309 IntegerType *Ty = cast<IntegerType>(V->getType());
2310 if (Ty == IntPromotionTy)
Chandler Carruth81b001a2012-09-26 10:27:46 +00002311 return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002312
2313 assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
2314 "Cannot insert a larger integer!");
2315 V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
2316 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2317 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002318 assert(TD.getTypeStoreSize(Ty) + RelOffset <=
2319 TD.getTypeStoreSize(IntPromotionTy) &&
2320 "Element store outside of alloca store");
2321 uint64_t ShAmt = 8*RelOffset;
2322 if (TD.isBigEndian())
2323 ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) - TD.getTypeStoreSize(Ty)
2324 - RelOffset);
2325 if (ShAmt)
2326 V = IRB.CreateShl(V, ShAmt, getName(".shift"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002327
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002328 APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth()).shl(ShAmt);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002329 Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI,
2330 NewAI.getAlignment(),
2331 getName(".oldload")),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002332 Mask, getName(".mask"));
Chandler Carruth81b001a2012-09-26 10:27:46 +00002333 return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")),
2334 &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002335 }
2336
Chandler Carruth713aa942012-09-14 09:22:59 +00002337 void deleteIfTriviallyDead(Value *V) {
2338 Instruction *I = cast<Instruction>(V);
2339 if (isInstructionTriviallyDead(I))
2340 Pass.DeadInsts.push_back(I);
2341 }
2342
2343 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
2344 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2345 return IRB.CreateIntToPtr(V, Ty);
2346 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2347 return IRB.CreatePtrToInt(V, Ty);
2348
2349 return IRB.CreateBitCast(V, Ty);
2350 }
2351
2352 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2353 Value *Result;
2354 if (LI.getType() == VecTy->getElementType() ||
2355 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002356 Result = IRB.CreateExtractElement(
2357 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2358 getIndex(IRB, BeginOffset), getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002359 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002360 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2361 getName(".load"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002362 }
2363 if (Result->getType() != LI.getType())
2364 Result = getValueCast(IRB, Result, LI.getType());
2365 LI.replaceAllUsesWith(Result);
2366 Pass.DeadInsts.push_back(&LI);
2367
2368 DEBUG(dbgs() << " to: " << *Result << "\n");
2369 return true;
2370 }
2371
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002372 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2373 assert(!LI.isVolatile());
2374 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
2375 BeginOffset);
2376 LI.replaceAllUsesWith(Result);
2377 Pass.DeadInsts.push_back(&LI);
2378 DEBUG(dbgs() << " to: " << *Result << "\n");
2379 return true;
2380 }
2381
Chandler Carruth713aa942012-09-14 09:22:59 +00002382 bool visitLoadInst(LoadInst &LI) {
2383 DEBUG(dbgs() << " original: " << LI << "\n");
2384 Value *OldOp = LI.getOperand(0);
2385 assert(OldOp == OldPtr);
2386 IRBuilder<> IRB(&LI);
2387
2388 if (VecTy)
2389 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002390 if (IntPromotionTy)
2391 return rewriteIntegerLoad(IRB, LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002392
2393 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2394 LI.getPointerOperand()->getType());
2395 LI.setOperand(0, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002396 LI.setAlignment(getPartitionTypeAlign(LI.getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002397 DEBUG(dbgs() << " to: " << LI << "\n");
2398
2399 deleteIfTriviallyDead(OldOp);
2400 return NewPtr == &NewAI && !LI.isVolatile();
2401 }
2402
2403 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2404 Value *OldOp) {
2405 Value *V = SI.getValueOperand();
2406 if (V->getType() == ElementTy ||
2407 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2408 if (V->getType() != ElementTy)
2409 V = getValueCast(IRB, V, ElementTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002410 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2411 getName(".load"));
2412 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002413 getName(".insert"));
2414 } else if (V->getType() != VecTy) {
2415 V = getValueCast(IRB, V, VecTy);
2416 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002417 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002418 Pass.DeadInsts.push_back(&SI);
2419
2420 (void)Store;
2421 DEBUG(dbgs() << " to: " << *Store << "\n");
2422 return true;
2423 }
2424
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002425 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2426 assert(!SI.isVolatile());
2427 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2428 Pass.DeadInsts.push_back(&SI);
2429 (void)Store;
2430 DEBUG(dbgs() << " to: " << *Store << "\n");
2431 return true;
2432 }
2433
Chandler Carruth713aa942012-09-14 09:22:59 +00002434 bool visitStoreInst(StoreInst &SI) {
2435 DEBUG(dbgs() << " original: " << SI << "\n");
2436 Value *OldOp = SI.getOperand(1);
2437 assert(OldOp == OldPtr);
2438 IRBuilder<> IRB(&SI);
2439
2440 if (VecTy)
2441 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002442 if (IntPromotionTy)
2443 return rewriteIntegerStore(IRB, SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002444
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002445 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2446 // alloca that should be re-examined after promoting this alloca.
2447 if (SI.getValueOperand()->getType()->isPointerTy())
2448 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI.getValueOperand()
2449 ->stripInBoundsOffsets()))
2450 Pass.PostPromotionWorklist.insert(AI);
2451
Chandler Carruth713aa942012-09-14 09:22:59 +00002452 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2453 SI.getPointerOperand()->getType());
2454 SI.setOperand(1, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002455 SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002456 DEBUG(dbgs() << " to: " << SI << "\n");
2457
2458 deleteIfTriviallyDead(OldOp);
2459 return NewPtr == &NewAI && !SI.isVolatile();
2460 }
2461
2462 bool visitMemSetInst(MemSetInst &II) {
2463 DEBUG(dbgs() << " original: " << II << "\n");
2464 IRBuilder<> IRB(&II);
2465 assert(II.getRawDest() == OldPtr);
2466
2467 // If the memset has a variable size, it cannot be split, just adjust the
2468 // pointer to the new alloca.
2469 if (!isa<Constant>(II.getLength())) {
2470 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002471 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002472 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002473
Chandler Carruth713aa942012-09-14 09:22:59 +00002474 deleteIfTriviallyDead(OldPtr);
2475 return false;
2476 }
2477
2478 // Record this instruction for deletion.
2479 if (Pass.DeadSplitInsts.insert(&II))
2480 Pass.DeadInsts.push_back(&II);
2481
2482 Type *AllocaTy = NewAI.getAllocatedType();
2483 Type *ScalarTy = AllocaTy->getScalarType();
2484
2485 // If this doesn't map cleanly onto the alloca type, and that type isn't
2486 // a single value type, just emit a memset.
2487 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
2488 EndOffset != NewAllocaEndOffset ||
2489 !AllocaTy->isSingleValueType() ||
2490 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2491 Type *SizeTy = II.getLength()->getType();
2492 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002493 CallInst *New
2494 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2495 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002496 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002497 II.isVolatile());
2498 (void)New;
2499 DEBUG(dbgs() << " to: " << *New << "\n");
2500 return false;
2501 }
2502
2503 // If we can represent this as a simple value, we have to build the actual
2504 // value to store, which requires expanding the byte present in memset to
2505 // a sensible representation for the alloca type. This is essentially
2506 // splatting the byte to a sufficiently wide integer, bitcasting to the
2507 // desired scalar type, and splatting it across any desired vector type.
2508 Value *V = II.getValue();
2509 IntegerType *VTy = cast<IntegerType>(V->getType());
2510 Type *IntTy = Type::getIntNTy(VTy->getContext(),
2511 TD.getTypeSizeInBits(ScalarTy));
2512 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
2513 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
2514 ConstantExpr::getUDiv(
2515 Constant::getAllOnesValue(IntTy),
2516 ConstantExpr::getZExt(
2517 Constant::getAllOnesValue(V->getType()),
2518 IntTy)),
2519 getName(".isplat"));
2520 if (V->getType() != ScalarTy) {
2521 if (ScalarTy->isPointerTy())
2522 V = IRB.CreateIntToPtr(V, ScalarTy);
2523 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
2524 V = IRB.CreateBitCast(V, ScalarTy);
2525 else if (ScalarTy->isIntegerTy())
2526 llvm_unreachable("Computed different integer types with equal widths");
2527 else
2528 llvm_unreachable("Invalid scalar type");
2529 }
2530
2531 // If this is an element-wide memset of a vectorizable alloca, insert it.
2532 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2533 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002534 StoreInst *Store = IRB.CreateAlignedStore(
2535 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2536 NewAI.getAlignment(),
2537 getName(".load")),
2538 V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002539 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002540 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002541 (void)Store;
2542 DEBUG(dbgs() << " to: " << *Store << "\n");
2543 return true;
2544 }
2545
2546 // Splat to a vector if needed.
2547 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2548 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2549 V = IRB.CreateShuffleVector(
2550 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2551 IRB.getInt32(0), getName(".vsplat.insert")),
2552 UndefValue::get(SplatSourceTy),
2553 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2554 getName(".vsplat.shuffle"));
2555 assert(V->getType() == VecTy);
2556 }
2557
Chandler Carruth81b001a2012-09-26 10:27:46 +00002558 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2559 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002560 (void)New;
2561 DEBUG(dbgs() << " to: " << *New << "\n");
2562 return !II.isVolatile();
2563 }
2564
2565 bool visitMemTransferInst(MemTransferInst &II) {
2566 // Rewriting of memory transfer instructions can be a bit tricky. We break
2567 // them into two categories: split intrinsics and unsplit intrinsics.
2568
2569 DEBUG(dbgs() << " original: " << II << "\n");
2570 IRBuilder<> IRB(&II);
2571
2572 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2573 bool IsDest = II.getRawDest() == OldPtr;
2574
2575 const AllocaPartitioning::MemTransferOffsets &MTO
2576 = P.getMemTransferOffsets(II);
2577
Chandler Carruth673850a2012-10-01 12:16:54 +00002578 // Compute the relative offset within the transfer.
2579 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2580 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2581 : MTO.SourceBegin));
2582
2583 unsigned Align = II.getAlignment();
2584 if (Align > 1)
2585 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002586 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002587
Chandler Carruth713aa942012-09-14 09:22:59 +00002588 // For unsplit intrinsics, we simply modify the source and destination
2589 // pointers in place. This isn't just an optimization, it is a matter of
2590 // correctness. With unsplit intrinsics we may be dealing with transfers
2591 // within a single alloca before SROA ran, or with transfers that have
2592 // a variable length. We may also be dealing with memmove instead of
2593 // memcpy, and so simply updating the pointers is the necessary for us to
2594 // update both source and dest of a single call.
2595 if (!MTO.IsSplittable) {
2596 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2597 if (IsDest)
2598 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2599 else
2600 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2601
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002602 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002603 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002604
Chandler Carruth713aa942012-09-14 09:22:59 +00002605 DEBUG(dbgs() << " to: " << II << "\n");
2606 deleteIfTriviallyDead(OldOp);
2607 return false;
2608 }
2609 // For split transfer intrinsics we have an incredibly useful assurance:
2610 // the source and destination do not reside within the same alloca, and at
2611 // least one of them does not escape. This means that we can replace
2612 // memmove with memcpy, and we don't need to worry about all manner of
2613 // downsides to splitting and transforming the operations.
2614
Chandler Carruth713aa942012-09-14 09:22:59 +00002615 // If this doesn't map cleanly onto the alloca type, and that type isn't
2616 // a single value type, just emit a memcpy.
2617 bool EmitMemCpy
2618 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2619 EndOffset != NewAllocaEndOffset ||
2620 !NewAI.getAllocatedType()->isSingleValueType());
2621
2622 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2623 // size hasn't been shrunk based on analysis of the viable range, this is
2624 // a no-op.
2625 if (EmitMemCpy && &OldAI == &NewAI) {
2626 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2627 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2628 // Ensure the start lines up.
2629 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002630 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002631
2632 // Rewrite the size as needed.
2633 if (EndOffset != OrigEnd)
2634 II.setLength(ConstantInt::get(II.getLength()->getType(),
2635 EndOffset - BeginOffset));
2636 return false;
2637 }
2638 // Record this instruction for deletion.
2639 if (Pass.DeadSplitInsts.insert(&II))
2640 Pass.DeadInsts.push_back(&II);
2641
2642 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2643 EndOffset < NewAllocaEndOffset);
2644
2645 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2646 : II.getRawDest()->getType();
2647 if (!EmitMemCpy)
2648 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2649 : NewAI.getType();
2650
2651 // Compute the other pointer, folding as much as possible to produce
2652 // a single, simple GEP in most cases.
2653 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2654 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2655 getName("." + OtherPtr->getName()));
2656
2657 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2658 // alloca that should be re-examined after rewriting this instruction.
2659 if (AllocaInst *AI
2660 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002661 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002662
2663 if (EmitMemCpy) {
2664 Value *OurPtr
2665 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2666 : II.getRawSource()->getType());
2667 Type *SizeTy = II.getLength()->getType();
2668 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2669
2670 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2671 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002672 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002673 (void)New;
2674 DEBUG(dbgs() << " to: " << *New << "\n");
2675 return false;
2676 }
2677
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002678 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2679 // is equivalent to 1, but that isn't true if we end up rewriting this as
2680 // a load or store.
2681 if (!Align)
2682 Align = 1;
2683
Chandler Carruth713aa942012-09-14 09:22:59 +00002684 Value *SrcPtr = OtherPtr;
2685 Value *DstPtr = &NewAI;
2686 if (!IsDest)
2687 std::swap(SrcPtr, DstPtr);
2688
2689 Value *Src;
2690 if (IsVectorElement && !IsDest) {
2691 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002692 Src = IRB.CreateExtractElement(
2693 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2694 getIndex(IRB, BeginOffset),
2695 getName(".copyextract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002696 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002697 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2698 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002699 }
2700
2701 if (IsVectorElement && IsDest) {
2702 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002703 Src = IRB.CreateInsertElement(
2704 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2705 Src, getIndex(IRB, BeginOffset),
2706 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002707 }
2708
Chandler Carruth81b001a2012-09-26 10:27:46 +00002709 StoreInst *Store = cast<StoreInst>(
2710 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2711 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002712 DEBUG(dbgs() << " to: " << *Store << "\n");
2713 return !II.isVolatile();
2714 }
2715
2716 bool visitIntrinsicInst(IntrinsicInst &II) {
2717 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2718 II.getIntrinsicID() == Intrinsic::lifetime_end);
2719 DEBUG(dbgs() << " original: " << II << "\n");
2720 IRBuilder<> IRB(&II);
2721 assert(II.getArgOperand(1) == OldPtr);
2722
2723 // Record this instruction for deletion.
2724 if (Pass.DeadSplitInsts.insert(&II))
2725 Pass.DeadInsts.push_back(&II);
2726
2727 ConstantInt *Size
2728 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2729 EndOffset - BeginOffset);
2730 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2731 Value *New;
2732 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2733 New = IRB.CreateLifetimeStart(Ptr, Size);
2734 else
2735 New = IRB.CreateLifetimeEnd(Ptr, Size);
2736
2737 DEBUG(dbgs() << " to: " << *New << "\n");
2738 return true;
2739 }
2740
Chandler Carruth713aa942012-09-14 09:22:59 +00002741 bool visitPHINode(PHINode &PN) {
2742 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002743
Chandler Carruth713aa942012-09-14 09:22:59 +00002744 // We would like to compute a new pointer in only one place, but have it be
2745 // as local as possible to the PHI. To do that, we re-use the location of
2746 // the old pointer, which necessarily must be in the right position to
2747 // dominate the PHI.
2748 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2749
Chandler Carruth713aa942012-09-14 09:22:59 +00002750 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002751 // Replace the operands which were using the old pointer.
2752 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2753 for (; OI != OE; ++OI)
2754 if (*OI == OldPtr)
2755 *OI = NewPtr;
Chandler Carruth713aa942012-09-14 09:22:59 +00002756
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002757 DEBUG(dbgs() << " to: " << PN << "\n");
2758 deleteIfTriviallyDead(OldPtr);
2759 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002760 }
2761
2762 bool visitSelectInst(SelectInst &SI) {
2763 DEBUG(dbgs() << " original: " << SI << "\n");
2764 IRBuilder<> IRB(&SI);
2765
2766 // Find the operand we need to rewrite here.
2767 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2768 if (IsTrueVal)
2769 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2770 else
2771 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002772
Chandler Carruth713aa942012-09-14 09:22:59 +00002773 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002774 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2775 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00002776 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002777 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002778 }
2779
2780};
2781}
2782
Chandler Carruthc370acd2012-09-18 12:57:43 +00002783namespace {
2784/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2785///
2786/// This pass aggressively rewrites all aggregate loads and stores on
2787/// a particular pointer (or any pointer derived from it which we can identify)
2788/// with scalar loads and stores.
2789class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2790 // Befriend the base class so it can delegate to private visit methods.
2791 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2792
2793 const TargetData &TD;
2794
2795 /// Queue of pointer uses to analyze and potentially rewrite.
2796 SmallVector<Use *, 8> Queue;
2797
2798 /// Set to prevent us from cycling with phi nodes and loops.
2799 SmallPtrSet<User *, 8> Visited;
2800
2801 /// The current pointer use being rewritten. This is used to dig up the used
2802 /// value (as opposed to the user).
2803 Use *U;
2804
2805public:
2806 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2807
2808 /// Rewrite loads and stores through a pointer and all pointers derived from
2809 /// it.
2810 bool rewrite(Instruction &I) {
2811 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2812 enqueueUsers(I);
2813 bool Changed = false;
2814 while (!Queue.empty()) {
2815 U = Queue.pop_back_val();
2816 Changed |= visit(cast<Instruction>(U->getUser()));
2817 }
2818 return Changed;
2819 }
2820
2821private:
2822 /// Enqueue all the users of the given instruction for further processing.
2823 /// This uses a set to de-duplicate users.
2824 void enqueueUsers(Instruction &I) {
2825 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2826 ++UI)
2827 if (Visited.insert(*UI))
2828 Queue.push_back(&UI.getUse());
2829 }
2830
2831 // Conservative default is to not rewrite anything.
2832 bool visitInstruction(Instruction &I) { return false; }
2833
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002834 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002835 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002836 class OpSplitter {
2837 protected:
2838 /// The builder used to form new instructions.
2839 IRBuilder<> IRB;
2840 /// The indices which to be used with insert- or extractvalue to select the
2841 /// appropriate value within the aggregate.
2842 SmallVector<unsigned, 4> Indices;
2843 /// The indices to a GEP instruction which will move Ptr to the correct slot
2844 /// within the aggregate.
2845 SmallVector<Value *, 4> GEPIndices;
2846 /// The base pointer of the original op, used as a base for GEPing the
2847 /// split operations.
2848 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002849
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002850 /// Initialize the splitter with an insertion point, Ptr and start with a
2851 /// single zero GEP index.
2852 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002853 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002854
2855 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002856 /// \brief Generic recursive split emission routine.
2857 ///
2858 /// This method recursively splits an aggregate op (load or store) into
2859 /// scalar or vector ops. It splits recursively until it hits a single value
2860 /// and emits that single value operation via the template argument.
2861 ///
2862 /// The logic of this routine relies on GEPs and insertvalue and
2863 /// extractvalue all operating with the same fundamental index list, merely
2864 /// formatted differently (GEPs need actual values).
2865 ///
2866 /// \param Ty The type being split recursively into smaller ops.
2867 /// \param Agg The aggregate value being built up or stored, depending on
2868 /// whether this is splitting a load or a store respectively.
2869 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2870 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002871 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002872
2873 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2874 unsigned OldSize = Indices.size();
2875 (void)OldSize;
2876 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2877 ++Idx) {
2878 assert(Indices.size() == OldSize && "Did not return to the old size");
2879 Indices.push_back(Idx);
2880 GEPIndices.push_back(IRB.getInt32(Idx));
2881 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2882 GEPIndices.pop_back();
2883 Indices.pop_back();
2884 }
2885 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002886 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00002887
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002888 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2889 unsigned OldSize = Indices.size();
2890 (void)OldSize;
2891 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2892 ++Idx) {
2893 assert(Indices.size() == OldSize && "Did not return to the old size");
2894 Indices.push_back(Idx);
2895 GEPIndices.push_back(IRB.getInt32(Idx));
2896 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2897 GEPIndices.pop_back();
2898 Indices.pop_back();
2899 }
2900 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002901 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002902
2903 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002904 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002905 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002906
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002907 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002908 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002909 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00002910
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002911 /// Emit a leaf load of a single value. This is called at the leaves of the
2912 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002913 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002914 assert(Ty->isSingleValueType());
2915 // Load the single value and insert it using the indices.
2916 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2917 Name + ".gep"),
2918 Name + ".load");
2919 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2920 DEBUG(dbgs() << " to: " << *Load << "\n");
2921 }
2922 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002923
2924 bool visitLoadInst(LoadInst &LI) {
2925 assert(LI.getPointerOperand() == *U);
2926 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2927 return false;
2928
2929 // We have an aggregate being loaded, split it apart.
2930 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002931 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00002932 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002933 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002934 LI.replaceAllUsesWith(V);
2935 LI.eraseFromParent();
2936 return true;
2937 }
2938
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002939 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002940 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002941 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002942
2943 /// Emit a leaf store of a single value. This is called at the leaves of the
2944 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002945 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002946 assert(Ty->isSingleValueType());
2947 // Extract the single value and store it using the indices.
2948 Value *Store = IRB.CreateStore(
2949 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2950 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2951 (void)Store;
2952 DEBUG(dbgs() << " to: " << *Store << "\n");
2953 }
2954 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002955
2956 bool visitStoreInst(StoreInst &SI) {
2957 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2958 return false;
2959 Value *V = SI.getValueOperand();
2960 if (V->getType()->isSingleValueType())
2961 return false;
2962
2963 // We have an aggregate being stored, split it apart.
2964 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002965 StoreOpSplitter Splitter(&SI, *U);
2966 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002967 SI.eraseFromParent();
2968 return true;
2969 }
2970
2971 bool visitBitCastInst(BitCastInst &BC) {
2972 enqueueUsers(BC);
2973 return false;
2974 }
2975
2976 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2977 enqueueUsers(GEPI);
2978 return false;
2979 }
2980
2981 bool visitPHINode(PHINode &PN) {
2982 enqueueUsers(PN);
2983 return false;
2984 }
2985
2986 bool visitSelectInst(SelectInst &SI) {
2987 enqueueUsers(SI);
2988 return false;
2989 }
2990};
2991}
2992
Chandler Carruth713aa942012-09-14 09:22:59 +00002993/// \brief Try to find a partition of the aggregate type passed in for a given
2994/// offset and size.
2995///
2996/// This recurses through the aggregate type and tries to compute a subtype
2997/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00002998/// of an array, it will even compute a new array type for that sub-section,
2999/// and the same for structs.
3000///
3001/// Note that this routine is very strict and tries to find a partition of the
3002/// type which produces the *exact* right offset and size. It is not forgiving
3003/// when the size or offset cause either end of type-based partition to be off.
3004/// Also, this is a best-effort routine. It is reasonable to give up and not
3005/// return a type if necessary.
Chandler Carruth713aa942012-09-14 09:22:59 +00003006static Type *getTypePartition(const TargetData &TD, Type *Ty,
3007 uint64_t Offset, uint64_t Size) {
3008 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
3009 return Ty;
3010
3011 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3012 // We can't partition pointers...
3013 if (SeqTy->isPointerTy())
3014 return 0;
3015
3016 Type *ElementTy = SeqTy->getElementType();
3017 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3018 uint64_t NumSkippedElements = Offset / ElementSize;
3019 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3020 if (NumSkippedElements >= ArrTy->getNumElements())
3021 return 0;
3022 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3023 if (NumSkippedElements >= VecTy->getNumElements())
3024 return 0;
3025 Offset -= NumSkippedElements * ElementSize;
3026
3027 // First check if we need to recurse.
3028 if (Offset > 0 || Size < ElementSize) {
3029 // Bail if the partition ends in a different array element.
3030 if ((Offset + Size) > ElementSize)
3031 return 0;
3032 // Recurse through the element type trying to peel off offset bytes.
3033 return getTypePartition(TD, ElementTy, Offset, Size);
3034 }
3035 assert(Offset == 0);
3036
3037 if (Size == ElementSize)
3038 return ElementTy;
3039 assert(Size > ElementSize);
3040 uint64_t NumElements = Size / ElementSize;
3041 if (NumElements * ElementSize != Size)
3042 return 0;
3043 return ArrayType::get(ElementTy, NumElements);
3044 }
3045
3046 StructType *STy = dyn_cast<StructType>(Ty);
3047 if (!STy)
3048 return 0;
3049
3050 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003051 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00003052 return 0;
3053 uint64_t EndOffset = Offset + Size;
3054 if (EndOffset > SL->getSizeInBytes())
3055 return 0;
3056
3057 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00003058 Offset -= SL->getElementOffset(Index);
3059
3060 Type *ElementTy = STy->getElementType(Index);
3061 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3062 if (Offset >= ElementSize)
3063 return 0; // The offset points into alignment padding.
3064
3065 // See if any partition must be contained by the element.
3066 if (Offset > 0 || Size < ElementSize) {
3067 if ((Offset + Size) > ElementSize)
3068 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003069 return getTypePartition(TD, ElementTy, Offset, Size);
3070 }
3071 assert(Offset == 0);
3072
3073 if (Size == ElementSize)
3074 return ElementTy;
3075
3076 StructType::element_iterator EI = STy->element_begin() + Index,
3077 EE = STy->element_end();
3078 if (EndOffset < SL->getSizeInBytes()) {
3079 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3080 if (Index == EndIndex)
3081 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003082
3083 // Don't try to form "natural" types if the elements don't line up with the
3084 // expected size.
3085 // FIXME: We could potentially recurse down through the last element in the
3086 // sub-struct to find a natural end point.
3087 if (SL->getElementOffset(EndIndex) != EndOffset)
3088 return 0;
3089
Chandler Carruth713aa942012-09-14 09:22:59 +00003090 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003091 EE = STy->element_begin() + EndIndex;
3092 }
3093
3094 // Try to build up a sub-structure.
3095 SmallVector<Type *, 4> ElementTys;
3096 do {
3097 ElementTys.push_back(*EI++);
3098 } while (EI != EE);
3099 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
3100 STy->isPacked());
3101 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003102 if (Size != SubSL->getSizeInBytes())
3103 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003104
Chandler Carruth6b547a22012-09-14 11:08:31 +00003105 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003106}
3107
3108/// \brief Rewrite an alloca partition's users.
3109///
3110/// This routine drives both of the rewriting goals of the SROA pass. It tries
3111/// to rewrite uses of an alloca partition to be conducive for SSA value
3112/// promotion. If the partition needs a new, more refined alloca, this will
3113/// build that new alloca, preserving as much type information as possible, and
3114/// rewrite the uses of the old alloca to point at the new one and have the
3115/// appropriate new offsets. It also evaluates how successful the rewrite was
3116/// at enabling promotion and if it was successful queues the alloca to be
3117/// promoted.
3118bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3119 AllocaPartitioning &P,
3120 AllocaPartitioning::iterator PI) {
3121 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003122 bool IsLive = false;
3123 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3124 UE = P.use_end(PI);
3125 UI != UE && !IsLive; ++UI)
3126 if (UI->U)
3127 IsLive = true;
3128 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003129 return false; // No live uses left of this partition.
3130
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003131 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3132 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3133
3134 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3135 DEBUG(dbgs() << " speculating ");
3136 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003137 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003138
Chandler Carruth713aa942012-09-14 09:22:59 +00003139 // Try to compute a friendly type for this partition of the alloca. This
3140 // won't always succeed, in which case we fall back to a legal integer type
3141 // or an i8 array of an appropriate size.
3142 Type *AllocaTy = 0;
3143 if (Type *PartitionTy = P.getCommonType(PI))
3144 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3145 AllocaTy = PartitionTy;
3146 if (!AllocaTy)
3147 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3148 PI->BeginOffset, AllocaSize))
3149 AllocaTy = PartitionTy;
3150 if ((!AllocaTy ||
3151 (AllocaTy->isArrayTy() &&
3152 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3153 TD->isLegalInteger(AllocaSize * 8))
3154 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3155 if (!AllocaTy)
3156 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003157 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003158
3159 // Check for the case where we're going to rewrite to a new alloca of the
3160 // exact same type as the original, and with the same access offsets. In that
3161 // case, re-use the existing alloca, but still run through the rewriter to
3162 // performe phi and select speculation.
3163 AllocaInst *NewAI;
3164 if (AllocaTy == AI.getAllocatedType()) {
3165 assert(PI->BeginOffset == 0 &&
3166 "Non-zero begin offset but same alloca type");
3167 assert(PI == P.begin() && "Begin offset is zero on later partition");
3168 NewAI = &AI;
3169 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003170 unsigned Alignment = AI.getAlignment();
3171 if (!Alignment) {
3172 // The minimum alignment which users can rely on when the explicit
3173 // alignment is omitted or zero is that required by the ABI for this
3174 // type.
3175 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3176 }
3177 Alignment = MinAlign(Alignment, PI->BeginOffset);
3178 // If we will get at least this much alignment from the type alone, leave
3179 // the alloca's alignment unconstrained.
3180 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3181 Alignment = 0;
3182 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003183 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3184 &AI);
3185 ++NumNewAllocas;
3186 }
3187
3188 DEBUG(dbgs() << "Rewriting alloca partition "
3189 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3190 << *NewAI << "\n");
3191
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003192 // Track the high watermark of the post-promotion worklist. We will reset it
3193 // to this point if the alloca is not in fact scheduled for promotion.
3194 unsigned PPWOldSize = PostPromotionWorklist.size();
3195
Chandler Carruth713aa942012-09-14 09:22:59 +00003196 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3197 PI->BeginOffset, PI->EndOffset);
3198 DEBUG(dbgs() << " rewriting ");
3199 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003200 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3201 if (Promotable) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003202 DEBUG(dbgs() << " and queuing for promotion\n");
3203 PromotableAllocas.push_back(NewAI);
3204 } else if (NewAI != &AI) {
3205 // If we can't promote the alloca, iterate on it to check for new
3206 // refinements exposed by splitting the current alloca. Don't iterate on an
3207 // alloca which didn't actually change and didn't get promoted.
3208 Worklist.insert(NewAI);
3209 }
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003210
3211 // Drop any post-promotion work items if promotion didn't happen.
3212 if (!Promotable)
3213 while (PostPromotionWorklist.size() > PPWOldSize)
3214 PostPromotionWorklist.pop_back();
3215
Chandler Carruth713aa942012-09-14 09:22:59 +00003216 return true;
3217}
3218
3219/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3220bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3221 bool Changed = false;
3222 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3223 ++PI)
3224 Changed |= rewriteAllocaPartition(AI, P, PI);
3225
3226 return Changed;
3227}
3228
3229/// \brief Analyze an alloca for SROA.
3230///
3231/// This analyzes the alloca to ensure we can reason about it, builds
3232/// a partitioning of the alloca, and then hands it off to be split and
3233/// rewritten as needed.
3234bool SROA::runOnAlloca(AllocaInst &AI) {
3235 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3236 ++NumAllocasAnalyzed;
3237
3238 // Special case dead allocas, as they're trivial.
3239 if (AI.use_empty()) {
3240 AI.eraseFromParent();
3241 return true;
3242 }
3243
3244 // Skip alloca forms that this analysis can't handle.
3245 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3246 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3247 return false;
3248
Chandler Carruthc370acd2012-09-18 12:57:43 +00003249 bool Changed = false;
3250
3251 // First, split any FCA loads and stores touching this alloca to promote
3252 // better splitting and promotion opportunities.
3253 AggLoadStoreRewriter AggRewriter(*TD);
3254 Changed |= AggRewriter.rewrite(AI);
3255
Chandler Carruth713aa942012-09-14 09:22:59 +00003256 // Build the partition set using a recursive instruction-visiting builder.
3257 AllocaPartitioning P(*TD, AI);
3258 DEBUG(P.print(dbgs()));
3259 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003260 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003261
Chandler Carruth713aa942012-09-14 09:22:59 +00003262 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003263 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3264 DE = P.dead_user_end();
3265 DI != DE; ++DI) {
3266 Changed = true;
3267 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3268 DeadInsts.push_back(*DI);
3269 }
3270 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3271 DE = P.dead_op_end();
3272 DO != DE; ++DO) {
3273 Value *OldV = **DO;
3274 // Clobber the use with an undef value.
3275 **DO = UndefValue::get(OldV->getType());
3276 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3277 if (isInstructionTriviallyDead(OldI)) {
3278 Changed = true;
3279 DeadInsts.push_back(OldI);
3280 }
3281 }
3282
Chandler Carruthfca3f402012-10-05 01:29:09 +00003283 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3284 if (P.begin() == P.end())
3285 return Changed;
3286
Chandler Carruth713aa942012-09-14 09:22:59 +00003287 return splitAlloca(AI, P) || Changed;
3288}
3289
Chandler Carruth8615cd22012-09-14 10:26:38 +00003290/// \brief Delete the dead instructions accumulated in this run.
3291///
3292/// Recursively deletes the dead instructions we've accumulated. This is done
3293/// at the very end to maximize locality of the recursive delete and to
3294/// minimize the problems of invalidated instruction pointers as such pointers
3295/// are used heavily in the intermediate stages of the algorithm.
3296///
3297/// We also record the alloca instructions deleted here so that they aren't
3298/// subsequently handed to mem2reg to promote.
3299void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003300 DeadSplitInsts.clear();
3301 while (!DeadInsts.empty()) {
3302 Instruction *I = DeadInsts.pop_back_val();
3303 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3304
3305 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3306 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3307 // Zero out the operand and see if it becomes trivially dead.
3308 *OI = 0;
3309 if (isInstructionTriviallyDead(U))
3310 DeadInsts.push_back(U);
3311 }
3312
3313 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3314 DeletedAllocas.insert(AI);
3315
3316 ++NumDeleted;
3317 I->eraseFromParent();
3318 }
3319}
3320
Chandler Carruth1c8db502012-09-15 11:43:14 +00003321/// \brief Promote the allocas, using the best available technique.
3322///
3323/// This attempts to promote whatever allocas have been identified as viable in
3324/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3325/// If there is a domtree available, we attempt to promote using the full power
3326/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3327/// based on the SSAUpdater utilities. This function returns whether any
3328/// promotion occured.
3329bool SROA::promoteAllocas(Function &F) {
3330 if (PromotableAllocas.empty())
3331 return false;
3332
3333 NumPromoted += PromotableAllocas.size();
3334
3335 if (DT && !ForceSSAUpdater) {
3336 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3337 PromoteMemToReg(PromotableAllocas, *DT);
3338 PromotableAllocas.clear();
3339 return true;
3340 }
3341
3342 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3343 SSAUpdater SSA;
3344 DIBuilder DIB(*F.getParent());
3345 SmallVector<Instruction*, 64> Insts;
3346
3347 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3348 AllocaInst *AI = PromotableAllocas[Idx];
3349 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3350 UI != UE;) {
3351 Instruction *I = cast<Instruction>(*UI++);
3352 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3353 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3354 // leading to them) here. Eventually it should use them to optimize the
3355 // scalar values produced.
3356 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3357 assert(onlyUsedByLifetimeMarkers(I) &&
3358 "Found a bitcast used outside of a lifetime marker.");
3359 while (!I->use_empty())
3360 cast<Instruction>(*I->use_begin())->eraseFromParent();
3361 I->eraseFromParent();
3362 continue;
3363 }
3364 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3365 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3366 II->getIntrinsicID() == Intrinsic::lifetime_end);
3367 II->eraseFromParent();
3368 continue;
3369 }
3370
3371 Insts.push_back(I);
3372 }
3373 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3374 Insts.clear();
3375 }
3376
3377 PromotableAllocas.clear();
3378 return true;
3379}
3380
Chandler Carruth713aa942012-09-14 09:22:59 +00003381namespace {
3382 /// \brief A predicate to test whether an alloca belongs to a set.
3383 class IsAllocaInSet {
3384 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3385 const SetType &Set;
3386
3387 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003388 typedef AllocaInst *argument_type;
3389
Chandler Carruth713aa942012-09-14 09:22:59 +00003390 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003391 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003392 };
3393}
3394
3395bool SROA::runOnFunction(Function &F) {
3396 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3397 C = &F.getContext();
3398 TD = getAnalysisIfAvailable<TargetData>();
3399 if (!TD) {
3400 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3401 return false;
3402 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003403 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003404
3405 BasicBlock &EntryBB = F.getEntryBlock();
3406 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3407 I != E; ++I)
3408 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3409 Worklist.insert(AI);
3410
3411 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003412 // A set of deleted alloca instruction pointers which should be removed from
3413 // the list of promotable allocas.
3414 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3415
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003416 do {
3417 while (!Worklist.empty()) {
3418 Changed |= runOnAlloca(*Worklist.pop_back_val());
3419 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003420
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003421 // Remove the deleted allocas from various lists so that we don't try to
3422 // continue processing them.
3423 if (!DeletedAllocas.empty()) {
3424 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3425 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3426 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3427 PromotableAllocas.end(),
3428 IsAllocaInSet(DeletedAllocas)),
3429 PromotableAllocas.end());
3430 DeletedAllocas.clear();
3431 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003432 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003433
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003434 Changed |= promoteAllocas(F);
3435
3436 Worklist = PostPromotionWorklist;
3437 PostPromotionWorklist.clear();
3438 } while (!Worklist.empty());
Chandler Carruth713aa942012-09-14 09:22:59 +00003439
3440 return Changed;
3441}
3442
3443void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003444 if (RequiresDomTree)
3445 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003446 AU.setPreservesCFG();
3447}