1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "sroa"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/Constants.h"
36 #include "llvm/DIBuilder.h"
37 #include "llvm/DataLayout.h"
38 #include "llvm/DebugInfo.h"
39 #include "llvm/DerivedTypes.h"
40 #include "llvm/Function.h"
41 #include "llvm/IRBuilder.h"
42 #include "llvm/InstVisitor.h"
43 #include "llvm/Instructions.h"
44 #include "llvm/IntrinsicInst.h"
45 #include "llvm/LLVMContext.h"
46 #include "llvm/Module.h"
47 #include "llvm/Operator.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include "llvm/Transforms/Utils/SSAUpdater.h"
60 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
62 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
63 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
64 STATISTIC(NumDeleted, "Number of instructions deleted");
65 STATISTIC(NumVectorized, "Number of vectorized aggregates");
67 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
68 /// forming SSA values through the SSAUpdater infrastructure.
70 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
73 /// \brief Alloca partitioning representation.
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
79 /// structure can capture the relevant information needed both to decide about
80 /// and to enact these transformations.
81 class AllocaPartitioning {
83 /// \brief A common base class for representing a half-open byte range.
85 /// \brief The beginning offset of the range.
88 /// \brief The ending offset, not included in the range.
91 ByteRange() : BeginOffset(), EndOffset() {}
92 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
93 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
95 /// \brief Support for ordering ranges.
97 /// This provides an ordering over ranges such that start offsets are
98 /// always increasing, and within equal start offsets, the end offsets are
99 /// decreasing. Thus the spanning range comes first in a cluster with the
100 /// 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;
108 /// \brief Support comparison with a single offset to allow binary searches.
109 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
110 return LHS.BeginOffset < RHSOffset;
113 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
114 const ByteRange &RHS) {
115 return LHSOffset < RHS.BeginOffset;
118 bool operator==(const ByteRange &RHS) const {
119 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
121 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
124 /// \brief A partition of an alloca.
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.
133 /// We flag partitions as splittable when they are formed entirely due to
134 /// accesses by trivially splittable operations such as memset and memcpy.
137 /// \brief Test whether a partition has been marked as dead.
138 bool isDead() const {
139 if (BeginOffset == UINT64_MAX) {
140 assert(EndOffset == UINT64_MAX);
146 /// \brief Kill a partition.
147 /// This is accomplished by setting both its beginning and end offset to
148 /// the maximum possible value.
150 assert(!isDead() && "He's Dead, Jim!");
151 BeginOffset = EndOffset = UINT64_MAX;
154 Partition() : ByteRange(), IsSplittable() {}
155 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
156 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
159 /// \brief A particular use of a partition of the alloca.
161 /// This structure is used to associate uses of a partition with it. They
162 /// mark the range of bytes which are referenced by a particular instruction,
163 /// and includes a handle to the user itself and the pointer value in use.
164 /// The bounds of these uses are determined by intersecting the bounds of the
165 /// memory use itself with a particular partition. As a consequence there is
166 /// intentionally overlap between various uses of the same partition.
167 struct PartitionUse : public ByteRange {
168 /// \brief The use in question. Provides access to both user and used value.
170 /// Note that this may be null if the partition use is *dead*, that is, it
171 /// should be ignored.
174 PartitionUse() : ByteRange(), U() {}
175 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
176 : ByteRange(BeginOffset, EndOffset), U(U) {}
179 /// \brief Construct a partitioning of a particular alloca.
181 /// Construction does most of the work for partitioning the alloca. This
182 /// performs the necessary walks of users and builds a partitioning from it.
183 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
185 /// \brief Test whether a pointer to the allocation escapes our analysis.
187 /// If this is true, the partitioning is never fully built and should be
189 bool isEscaped() const { return PointerEscapingInstr; }
191 /// \brief Support for iterating over the partitions.
193 typedef SmallVectorImpl<Partition>::iterator iterator;
194 iterator begin() { return Partitions.begin(); }
195 iterator end() { return Partitions.end(); }
197 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
198 const_iterator begin() const { return Partitions.begin(); }
199 const_iterator end() const { return Partitions.end(); }
202 /// \brief Support for iterating over and manipulating a particular
203 /// partition's uses.
205 /// The iteration support provided for uses is more limited, but also
206 /// includes some manipulation routines to support rewriting the uses of
207 /// partitions during SROA.
209 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
210 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
211 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
212 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
213 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
215 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
216 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
217 const_use_iterator use_begin(const_iterator I) const {
218 return Uses[I - begin()].begin();
220 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
221 const_use_iterator use_end(const_iterator I) const {
222 return Uses[I - begin()].end();
225 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
226 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
227 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
228 return Uses[PIdx][UIdx];
230 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
231 return Uses[I - begin()][UIdx];
234 void use_push_back(unsigned Idx, const PartitionUse &PU) {
235 Uses[Idx].push_back(PU);
237 void use_push_back(const_iterator I, const PartitionUse &PU) {
238 Uses[I - begin()].push_back(PU);
242 /// \brief Allow iterating the dead users for this alloca.
244 /// These are instructions which will never actually use the alloca as they
245 /// are outside the allocated range. They are safe to replace with undef and
248 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
249 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
250 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
253 /// \brief Allow iterating the dead expressions referring to this alloca.
255 /// These are operands which have cannot actually be used to refer to the
256 /// alloca as they are outside its range and the user doesn't correct for
257 /// that. These mostly consist of PHI node inputs and the like which we just
258 /// need to replace with undef.
260 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
261 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
262 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
265 /// \brief MemTransferInst auxiliary data.
266 /// This struct provides some auxiliary data about memory transfer
267 /// intrinsics such as memcpy and memmove. These intrinsics can use two
268 /// different ranges within the same alloca, and provide other challenges to
269 /// correctly represent. We stash extra data to help us untangle this
270 /// after the partitioning is complete.
271 struct MemTransferOffsets {
272 /// The destination begin and end offsets when the destination is within
273 /// this alloca. If the end offset is zero the destination is not within
275 uint64_t DestBegin, DestEnd;
277 /// The source begin and end offsets when the source is within this alloca.
278 /// If the end offset is zero, the source is not within this alloca.
279 uint64_t SourceBegin, SourceEnd;
281 /// Flag for whether an alloca is splittable.
284 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
285 return MemTransferInstData.lookup(&II);
288 /// \brief Map from a PHI or select operand back to a partition.
290 /// When manipulating PHI nodes or selects, they can use more than one
291 /// partition of an alloca. We store a special mapping to allow finding the
292 /// partition referenced by each of these operands, if any.
293 iterator findPartitionForPHIOrSelectOperand(Use *U) {
294 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
295 = PHIOrSelectOpMap.find(U);
296 if (MapIt == PHIOrSelectOpMap.end())
299 return begin() + MapIt->second.first;
302 /// \brief Map from a PHI or select operand back to the specific use of
305 /// Similar to mapping these operands back to the partitions, this maps
306 /// directly to the use structure of that partition.
307 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
308 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
309 = PHIOrSelectOpMap.find(U);
310 assert(MapIt != PHIOrSelectOpMap.end());
311 return Uses[MapIt->second.first].begin() + MapIt->second.second;
314 /// \brief Compute a common type among the uses of a particular partition.
316 /// This routines walks all of the uses of a particular partition and tries
317 /// to find a common type between them. Untyped operations such as memset and
318 /// memcpy are ignored.
319 Type *getCommonType(iterator I) const;
321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
322 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
323 void printUsers(raw_ostream &OS, const_iterator I,
324 StringRef Indent = " ") const;
325 void print(raw_ostream &OS) const;
326 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
327 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
331 template <typename DerivedT, typename RetT = void> class BuilderBase;
332 class PartitionBuilder;
333 friend class AllocaPartitioning::PartitionBuilder;
335 friend class AllocaPartitioning::UseBuilder;
337 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
338 /// \brief Handle to alloca instruction to simplify method interfaces.
342 /// \brief The instruction responsible for this alloca having no partitioning.
344 /// When an instruction (potentially) escapes the pointer to the alloca, we
345 /// store a pointer to that here and abort trying to partition the alloca.
346 /// This will be null if the alloca is partitioned successfully.
347 Instruction *PointerEscapingInstr;
349 /// \brief The partitions of the alloca.
351 /// We store a vector of the partitions over the alloca here. This vector is
352 /// sorted by increasing begin offset, and then by decreasing end offset. See
353 /// the Partition inner class for more details. Initially (during
354 /// construction) there are overlaps, but we form a disjoint sequence of
355 /// partitions while finishing construction and a fully constructed object is
356 /// expected to always have this as a disjoint space.
357 SmallVector<Partition, 8> Partitions;
359 /// \brief The uses of the partitions.
361 /// This is essentially a mapping from each partition to a list of uses of
362 /// that partition. The mapping is done with a Uses vector that has the exact
363 /// same number of entries as the partition vector. Each entry is itself
364 /// a vector of the uses.
365 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
367 /// \brief Instructions which will become dead if we rewrite the alloca.
369 /// Note that these are not separated by partition. This is because we expect
370 /// a partitioned alloca to be completely rewritten or not rewritten at all.
371 /// If rewritten, all these instructions can simply be removed and replaced
372 /// with undef as they come from outside of the allocated space.
373 SmallVector<Instruction *, 8> DeadUsers;
375 /// \brief Operands which will become dead if we rewrite the alloca.
377 /// These are operands that in their particular use can be replaced with
378 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
379 /// to PHI nodes and the like. They aren't entirely dead (there might be
380 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
381 /// want to swap this particular input for undef to simplify the use lists of
383 SmallVector<Use *, 8> DeadOperands;
385 /// \brief The underlying storage for auxiliary memcpy and memset info.
386 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
388 /// \brief A side datastructure used when building up the partitions and uses.
390 /// This mapping is only really used during the initial building of the
391 /// partitioning so that we can retain information about PHI and select nodes
393 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
395 /// \brief Auxiliary information for particular PHI or select operands.
396 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
398 /// \brief A utility routine called from the constructor.
400 /// This does what it says on the tin. It is the key of the alloca partition
401 /// splitting and merging. After it is called we have the desired disjoint
402 /// collection of partitions.
403 void splitAndMergePartitions();
407 template <typename DerivedT, typename RetT>
408 class AllocaPartitioning::BuilderBase
409 : public InstVisitor<DerivedT, RetT> {
411 BuilderBase(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
413 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
419 const DataLayout &TD;
420 const uint64_t AllocSize;
421 AllocaPartitioning &P;
423 SmallPtrSet<Use *, 8> VisitedUses;
429 SmallVector<OffsetUse, 8> Queue;
431 // The active offset and use while visiting.
435 void enqueueUsers(Instruction &I, int64_t UserOffset) {
436 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
438 if (VisitedUses.insert(&UI.getUse())) {
439 OffsetUse OU = { &UI.getUse(), UserOffset };
445 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
447 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
449 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
455 // Handle a struct index, which adds its field offset to the pointer.
456 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
457 unsigned ElementIdx = OpC->getZExtValue();
458 const StructLayout *SL = TD.getStructLayout(STy);
459 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
460 // Check that we can continue to model this GEP in a signed 64-bit offset.
461 if (ElementOffset > INT64_MAX ||
463 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
470 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
472 GEPOffset += ElementOffset;
476 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
477 Index *= APInt(Index.getBitWidth(),
478 TD.getTypeAllocSize(GTI.getIndexedType()));
479 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
481 // Check if the result can be stored in our int64_t offset.
482 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
483 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
484 << "what can be represented in an int64_t!\n"
485 << " alloca: " << P.AI << "\n");
489 GEPOffset = Index.getSExtValue();
494 Value *foldSelectInst(SelectInst &SI) {
495 // If the condition being selected on is a constant or the same value is
496 // being selected between, fold the select. Yes this does (rarely) happen
498 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
499 return SI.getOperand(1+CI->isZero());
500 if (SI.getOperand(1) == SI.getOperand(2)) {
501 assert(*U == SI.getOperand(1));
502 return SI.getOperand(1);
508 /// \brief Builder for the alloca partitioning.
510 /// This class builds an alloca partitioning by recursively visiting the uses
511 /// of an alloca and splitting the partitions for each load and store at each
513 class AllocaPartitioning::PartitionBuilder
514 : public BuilderBase<PartitionBuilder, bool> {
515 friend class InstVisitor<PartitionBuilder, bool>;
517 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
520 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
521 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
523 /// \brief Run the builder over the allocation.
525 while (!Queue.empty()) {
527 Offset = Queue.back().Offset;
529 if (!visit(cast<Instruction>(U->getUser())))
536 bool markAsEscaping(Instruction &I) {
537 P.PointerEscapingInstr = &I;
541 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
542 bool IsSplittable = false) {
543 // Completely skip uses which have a zero size or start either before or
544 // past the end of the allocation.
545 if (Size == 0 || Offset < 0 || (uint64_t)Offset >= AllocSize) {
546 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
547 << " which has zero size or starts outside of the "
548 << AllocSize << " byte alloca:\n"
549 << " alloca: " << P.AI << "\n"
550 << " use: " << I << "\n");
554 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
556 // Clamp the end offset to the end of the allocation. Note that this is
557 // formulated to handle even the case where "BeginOffset + Size" overflows.
558 // NOTE! This may appear superficially to be something we could ignore
559 // entirely, but that is not so! There may be PHI-node uses where some
560 // instructions are dead but not others. We can't completely ignore the
561 // PHI node, and so have to record at least the information here.
562 assert(AllocSize >= BeginOffset); // Established above.
563 if (Size > AllocSize - BeginOffset) {
564 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
565 << " to remain within the " << AllocSize << " byte alloca:\n"
566 << " alloca: " << P.AI << "\n"
567 << " use: " << I << "\n");
568 EndOffset = AllocSize;
571 Partition New(BeginOffset, EndOffset, IsSplittable);
572 P.Partitions.push_back(New);
575 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
577 uint64_t Size = TD.getTypeStoreSize(Ty);
579 // If this memory access can be shown to *statically* extend outside the
580 // bounds of of the allocation, it's behavior is undefined, so simply
581 // ignore it. Note that this is more strict than the generic clamping
582 // behavior of insertUse. We also try to handle cases which might run the
584 // FIXME: We should instead consider the pointer to have escaped if this
585 // function is being instrumented for addressing bugs or race conditions.
586 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
587 Size > (AllocSize - (uint64_t)Offset)) {
588 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
589 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
590 << " which extends past the end of the " << AllocSize
592 << " alloca: " << P.AI << "\n"
593 << " use: " << I << "\n");
597 // We allow splitting of loads and stores where the type is an integer type
598 // and which cover the entire alloca. Such integer loads and stores
599 // often require decomposition into fine grained loads and stores.
600 bool IsSplittable = false;
601 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
602 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
604 insertUse(I, Offset, Size, IsSplittable);
608 bool visitBitCastInst(BitCastInst &BC) {
609 enqueueUsers(BC, Offset);
613 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
615 if (!computeConstantGEPOffset(GEPI, GEPOffset))
616 return markAsEscaping(GEPI);
618 enqueueUsers(GEPI, GEPOffset);
622 bool visitLoadInst(LoadInst &LI) {
623 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
624 "All simple FCA loads should have been pre-split");
625 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
628 bool visitStoreInst(StoreInst &SI) {
629 Value *ValOp = SI.getValueOperand();
631 return markAsEscaping(SI);
633 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
634 "All simple FCA stores should have been pre-split");
635 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
639 bool visitMemSetInst(MemSetInst &II) {
640 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
641 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
642 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
643 insertUse(II, Offset, Size, Length);
647 bool visitMemTransferInst(MemTransferInst &II) {
648 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
649 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
651 // Zero-length mem transfer intrinsics can be ignored entirely.
654 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
656 // Only intrinsics with a constant length can be split.
657 Offsets.IsSplittable = Length;
659 if (*U == II.getRawDest()) {
660 Offsets.DestBegin = Offset;
661 Offsets.DestEnd = Offset + Size;
663 if (*U == II.getRawSource()) {
664 Offsets.SourceBegin = Offset;
665 Offsets.SourceEnd = Offset + Size;
668 // If we have set up end offsets for both the source and the destination,
669 // we have found both sides of this transfer pointing at the same alloca.
670 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
671 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
672 unsigned PrevIdx = MemTransferPartitionMap[&II];
674 // Check if the begin offsets match and this is a non-volatile transfer.
675 // In that case, we can completely elide the transfer.
676 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
677 P.Partitions[PrevIdx].kill();
681 // Otherwise we have an offset transfer within the same alloca. We can't
683 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
684 } else if (SeenBothEnds) {
685 // Handle the case where this exact use provides both ends of the
687 assert(II.getRawDest() == II.getRawSource());
689 // For non-volatile transfers this is a no-op.
690 if (!II.isVolatile())
693 // Otherwise just suppress splitting.
694 Offsets.IsSplittable = false;
698 // Insert the use now that we've fixed up the splittable nature.
699 insertUse(II, Offset, Size, Offsets.IsSplittable);
701 // Setup the mapping from intrinsic to partition of we've not seen both
702 // ends of this transfer.
704 unsigned NewIdx = P.Partitions.size() - 1;
706 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
708 "Already have intrinsic in map but haven't seen both ends");
715 // Disable SRoA for any intrinsics except for lifetime invariants.
716 // FIXME: What about debug instrinsics? This matches old behavior, but
717 // doesn't make sense.
718 bool visitIntrinsicInst(IntrinsicInst &II) {
719 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
720 II.getIntrinsicID() == Intrinsic::lifetime_end) {
721 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
722 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
723 insertUse(II, Offset, Size, true);
727 return markAsEscaping(II);
730 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
731 // We consider any PHI or select that results in a direct load or store of
732 // the same offset to be a viable use for partitioning purposes. These uses
733 // are considered unsplittable and the size is the maximum loaded or stored
735 SmallPtrSet<Instruction *, 4> Visited;
736 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
737 Visited.insert(Root);
738 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
739 // If there are no loads or stores, the access is dead. We mark that as
740 // a size zero access.
743 Instruction *I, *UsedI;
744 llvm::tie(UsedI, I) = Uses.pop_back_val();
746 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
747 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
750 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
751 Value *Op = SI->getOperand(0);
754 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
758 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
759 if (!GEP->hasAllZeroIndices())
761 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
762 !isa<SelectInst>(I)) {
766 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
768 if (Visited.insert(cast<Instruction>(*UI)))
769 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
770 } while (!Uses.empty());
775 bool visitPHINode(PHINode &PN) {
776 // See if we already have computed info on this node.
777 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
779 PHIInfo.second = true;
780 insertUse(PN, Offset, PHIInfo.first);
784 // Check for an unsafe use of the PHI node.
785 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
786 return markAsEscaping(*EscapingI);
788 insertUse(PN, Offset, PHIInfo.first);
792 bool visitSelectInst(SelectInst &SI) {
793 if (Value *Result = foldSelectInst(SI)) {
795 // If the result of the constant fold will be the pointer, recurse
796 // through the select as if we had RAUW'ed it.
797 enqueueUsers(SI, Offset);
802 // See if we already have computed info on this node.
803 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
804 if (SelectInfo.first) {
805 SelectInfo.second = true;
806 insertUse(SI, Offset, SelectInfo.first);
810 // Check for an unsafe use of the PHI node.
811 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
812 return markAsEscaping(*EscapingI);
814 insertUse(SI, Offset, SelectInfo.first);
818 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
819 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
823 /// \brief Use adder for the alloca partitioning.
825 /// This class adds the uses of an alloca to all of the partitions which they
826 /// use. For splittable partitions, this can end up doing essentially a linear
827 /// walk of the partitions, but the number of steps remains bounded by the
828 /// total result instruction size:
829 /// - The number of partitions is a result of the number unsplittable
830 /// instructions using the alloca.
831 /// - The number of users of each partition is at worst the total number of
832 /// splittable instructions using the alloca.
833 /// Thus we will produce N * M instructions in the end, where N are the number
834 /// of unsplittable uses and M are the number of splittable. This visitor does
835 /// the exact same number of updates to the partitioning.
837 /// In the more common case, this visitor will leverage the fact that the
838 /// partition space is pre-sorted, and do a logarithmic search for the
839 /// partition needed, making the total visit a classical ((N + M) * log(N))
840 /// complexity operation.
841 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
842 friend class InstVisitor<UseBuilder>;
844 /// \brief Set to de-duplicate dead instructions found in the use walk.
845 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
848 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
849 : BuilderBase<UseBuilder>(TD, AI, P) {}
851 /// \brief Run the builder over the allocation.
853 while (!Queue.empty()) {
855 Offset = Queue.back().Offset;
857 this->visit(cast<Instruction>(U->getUser()));
862 void markAsDead(Instruction &I) {
863 if (VisitedDeadInsts.insert(&I))
864 P.DeadUsers.push_back(&I);
867 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
868 // If the use has a zero size or extends outside of the allocation, record
869 // it as a dead use for elimination later.
870 if (Size == 0 || Offset < 0 || (uint64_t)Offset >= AllocSize)
871 return markAsDead(User);
873 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
875 // Clamp the end offset to the end of the allocation. Note that this is
876 // formulated to handle even the case where "BeginOffset + Size" overflows.
877 assert(AllocSize >= BeginOffset); // Established above.
878 if (Size > AllocSize - BeginOffset)
879 EndOffset = AllocSize;
881 // NB: This only works if we have zero overlapping partitions.
882 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
883 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
885 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
887 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
888 std::min(I->EndOffset, EndOffset), U);
889 P.use_push_back(I, NewPU);
890 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
891 P.PHIOrSelectOpMap[U]
892 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
896 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
897 uint64_t Size = TD.getTypeStoreSize(Ty);
899 // If this memory access can be shown to *statically* extend outside the
900 // bounds of of the allocation, it's behavior is undefined, so simply
901 // ignore it. Note that this is more strict than the generic clamping
902 // behavior of insertUse.
903 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
904 Size > (AllocSize - (uint64_t)Offset))
905 return markAsDead(I);
907 insertUse(I, Offset, Size);
910 void visitBitCastInst(BitCastInst &BC) {
912 return markAsDead(BC);
914 enqueueUsers(BC, Offset);
917 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
918 if (GEPI.use_empty())
919 return markAsDead(GEPI);
922 if (!computeConstantGEPOffset(GEPI, GEPOffset))
923 llvm_unreachable("Unable to compute constant offset for use");
925 enqueueUsers(GEPI, GEPOffset);
928 void visitLoadInst(LoadInst &LI) {
929 handleLoadOrStore(LI.getType(), LI, Offset);
932 void visitStoreInst(StoreInst &SI) {
933 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
936 void visitMemSetInst(MemSetInst &II) {
937 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
938 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
939 insertUse(II, Offset, Size);
942 void visitMemTransferInst(MemTransferInst &II) {
943 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
944 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
946 return markAsDead(II);
948 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
949 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
950 Offsets.DestBegin == Offsets.SourceBegin)
951 return markAsDead(II); // Skip identity transfers without side-effects.
953 insertUse(II, Offset, Size);
956 void visitIntrinsicInst(IntrinsicInst &II) {
957 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
958 II.getIntrinsicID() == Intrinsic::lifetime_end);
960 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
961 insertUse(II, Offset,
962 std::min(AllocSize - Offset, Length->getLimitedValue()));
965 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
966 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
968 // For PHI and select operands outside the alloca, we can't nuke the entire
969 // phi or select -- the other side might still be relevant, so we special
970 // case them here and use a separate structure to track the operands
971 // themselves which should be replaced with undef.
972 if (Offset >= AllocSize) {
973 P.DeadOperands.push_back(U);
977 insertUse(User, Offset, Size);
979 void visitPHINode(PHINode &PN) {
981 return markAsDead(PN);
983 insertPHIOrSelect(PN, Offset);
985 void visitSelectInst(SelectInst &SI) {
987 return markAsDead(SI);
989 if (Value *Result = foldSelectInst(SI)) {
991 // If the result of the constant fold will be the pointer, recurse
992 // through the select as if we had RAUW'ed it.
993 enqueueUsers(SI, Offset);
995 // Otherwise the operand to the select is dead, and we can replace it
997 P.DeadOperands.push_back(U);
1002 insertPHIOrSelect(SI, Offset);
1005 /// \brief Unreachable, we've already visited the alloca once.
1006 void visitInstruction(Instruction &I) {
1007 llvm_unreachable("Unhandled instruction in use builder.");
1011 void AllocaPartitioning::splitAndMergePartitions() {
1012 size_t NumDeadPartitions = 0;
1014 // Track the range of splittable partitions that we pass when accumulating
1015 // overlapping unsplittable partitions.
1016 uint64_t SplitEndOffset = 0ull;
1018 Partition New(0ull, 0ull, false);
1020 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1023 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1024 assert(New.BeginOffset == New.EndOffset);
1025 New = Partitions[i];
1027 assert(New.IsSplittable);
1028 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1030 assert(New.BeginOffset != New.EndOffset);
1032 // Scan the overlapping partitions.
1033 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1034 // If the new partition we are forming is splittable, stop at the first
1035 // unsplittable partition.
1036 if (New.IsSplittable && !Partitions[j].IsSplittable)
1039 // Grow the new partition to include any equally splittable range. 'j' is
1040 // always equally splittable when New is splittable, but when New is not
1041 // splittable, we may subsume some (or part of some) splitable partition
1042 // without growing the new one.
1043 if (New.IsSplittable == Partitions[j].IsSplittable) {
1044 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1046 assert(!New.IsSplittable);
1047 assert(Partitions[j].IsSplittable);
1048 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1051 Partitions[j].kill();
1052 ++NumDeadPartitions;
1056 // If the new partition is splittable, chop off the end as soon as the
1057 // unsplittable subsequent partition starts and ensure we eventually cover
1058 // the splittable area.
1059 if (j != e && New.IsSplittable) {
1060 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1061 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1064 // Add the new partition if it differs from the original one and is
1065 // non-empty. We can end up with an empty partition here if it was
1066 // splittable but there is an unsplittable one that starts at the same
1068 if (New != Partitions[i]) {
1069 if (New.BeginOffset != New.EndOffset)
1070 Partitions.push_back(New);
1071 // Mark the old one for removal.
1072 Partitions[i].kill();
1073 ++NumDeadPartitions;
1076 New.BeginOffset = New.EndOffset;
1077 if (!New.IsSplittable) {
1078 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1079 if (j != e && !Partitions[j].IsSplittable)
1080 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1081 New.IsSplittable = true;
1082 // If there is a trailing splittable partition which won't be fused into
1083 // the next splittable partition go ahead and add it onto the partitions
1085 if (New.BeginOffset < New.EndOffset &&
1086 (j == e || !Partitions[j].IsSplittable ||
1087 New.EndOffset < Partitions[j].BeginOffset)) {
1088 Partitions.push_back(New);
1089 New.BeginOffset = New.EndOffset = 0ull;
1094 // Re-sort the partitions now that they have been split and merged into
1095 // disjoint set of partitions. Also remove any of the dead partitions we've
1096 // replaced in the process.
1097 std::sort(Partitions.begin(), Partitions.end());
1098 if (NumDeadPartitions) {
1099 assert(Partitions.back().isDead());
1100 assert((ptrdiff_t)NumDeadPartitions ==
1101 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1103 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1106 AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
1108 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1111 PointerEscapingInstr(0) {
1112 PartitionBuilder PB(TD, AI, *this);
1116 // Sort the uses. This arranges for the offsets to be in ascending order,
1117 // and the sizes to be in descending order.
1118 std::sort(Partitions.begin(), Partitions.end());
1120 // Remove any partitions from the back which are marked as dead.
1121 while (!Partitions.empty() && Partitions.back().isDead())
1122 Partitions.pop_back();
1124 if (Partitions.size() > 1) {
1125 // Intersect splittability for all partitions with equal offsets and sizes.
1126 // Then remove all but the first so that we have a sequence of non-equal but
1127 // potentially overlapping partitions.
1128 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1131 while (J != E && *I == *J) {
1132 I->IsSplittable &= J->IsSplittable;
1136 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1139 // Split splittable and merge unsplittable partitions into a disjoint set
1140 // of partitions over the used space of the allocation.
1141 splitAndMergePartitions();
1144 // Now build up the user lists for each of these disjoint partitions by
1145 // re-walking the recursive users of the alloca.
1146 Uses.resize(Partitions.size());
1147 UseBuilder UB(TD, AI, *this);
1151 Type *AllocaPartitioning::getCommonType(iterator I) const {
1153 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1155 continue; // Skip dead uses.
1156 if (isa<IntrinsicInst>(*UI->U->getUser()))
1158 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1162 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
1163 UserTy = LI->getType();
1164 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
1165 UserTy = SI->getValueOperand()->getType();
1167 return 0; // Bail if we have weird uses.
1170 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1171 // If the type is larger than the partition, skip it. We only encounter
1172 // this for split integer operations where we want to use the type of the
1173 // entity causing the split.
1174 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1177 // If we have found an integer type use covering the alloca, use that
1178 // regardless of the other types, as integers are often used for a "bucket
1183 if (Ty && Ty != UserTy)
1191 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1193 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1194 StringRef Indent) const {
1195 OS << Indent << "partition #" << (I - begin())
1196 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1197 << (I->IsSplittable ? " (splittable)" : "")
1198 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1202 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1203 StringRef Indent) const {
1204 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1207 continue; // Skip dead uses.
1208 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1209 << "used by: " << *UI->U->getUser() << "\n";
1210 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
1211 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1213 if (!MTO.IsSplittable)
1214 IsDest = UI->BeginOffset == MTO.DestBegin;
1216 IsDest = MTO.DestBegin != 0u;
1217 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1218 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1219 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1224 void AllocaPartitioning::print(raw_ostream &OS) const {
1225 if (PointerEscapingInstr) {
1226 OS << "No partitioning for alloca: " << AI << "\n"
1227 << " A pointer to this alloca escaped by:\n"
1228 << " " << *PointerEscapingInstr << "\n";
1232 OS << "Partitioning of alloca: " << AI << "\n";
1234 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1240 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1241 void AllocaPartitioning::dump() const { print(dbgs()); }
1243 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1247 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1249 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1250 /// the loads and stores of an alloca instruction, as well as updating its
1251 /// debug information. This is used when a domtree is unavailable and thus
1252 /// mem2reg in its full form can't be used to handle promotion of allocas to
1254 class AllocaPromoter : public LoadAndStorePromoter {
1258 SmallVector<DbgDeclareInst *, 4> DDIs;
1259 SmallVector<DbgValueInst *, 4> DVIs;
1262 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1263 AllocaInst &AI, DIBuilder &DIB)
1264 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1266 void run(const SmallVectorImpl<Instruction*> &Insts) {
1267 // Remember which alloca we're promoting (for isInstInList).
1268 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1269 for (Value::use_iterator UI = DebugNode->use_begin(),
1270 UE = DebugNode->use_end();
1272 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1273 DDIs.push_back(DDI);
1274 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1275 DVIs.push_back(DVI);
1278 LoadAndStorePromoter::run(Insts);
1279 AI.eraseFromParent();
1280 while (!DDIs.empty())
1281 DDIs.pop_back_val()->eraseFromParent();
1282 while (!DVIs.empty())
1283 DVIs.pop_back_val()->eraseFromParent();
1286 virtual bool isInstInList(Instruction *I,
1287 const SmallVectorImpl<Instruction*> &Insts) const {
1288 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1289 return LI->getOperand(0) == &AI;
1290 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1293 virtual void updateDebugInfo(Instruction *Inst) const {
1294 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1295 E = DDIs.end(); I != E; ++I) {
1296 DbgDeclareInst *DDI = *I;
1297 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1298 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1299 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1300 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1302 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1303 E = DVIs.end(); I != E; ++I) {
1304 DbgValueInst *DVI = *I;
1306 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1307 // If an argument is zero extended then use argument directly. The ZExt
1308 // may be zapped by an optimization pass in future.
1309 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1310 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1311 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1312 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1314 Arg = SI->getOperand(0);
1315 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1316 Arg = LI->getOperand(0);
1320 Instruction *DbgVal =
1321 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1323 DbgVal->setDebugLoc(DVI->getDebugLoc());
1327 } // end anon namespace
1331 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1333 /// This pass takes allocations which can be completely analyzed (that is, they
1334 /// don't escape) and tries to turn them into scalar SSA values. There are
1335 /// a few steps to this process.
1337 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1338 /// are used to try to split them into smaller allocations, ideally of
1339 /// a single scalar data type. It will split up memcpy and memset accesses
1340 /// as necessary and try to isolate invidual scalar accesses.
1341 /// 2) It will transform accesses into forms which are suitable for SSA value
1342 /// promotion. This can be replacing a memset with a scalar store of an
1343 /// integer value, or it can involve speculating operations on a PHI or
1344 /// select to be a PHI or select of the results.
1345 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1346 /// onto insert and extract operations on a vector value, and convert them to
1347 /// this form. By doing so, it will enable promotion of vector aggregates to
1348 /// SSA vector values.
1349 class SROA : public FunctionPass {
1350 const bool RequiresDomTree;
1353 const DataLayout *TD;
1356 /// \brief Worklist of alloca instructions to simplify.
1358 /// Each alloca in the function is added to this. Each new alloca formed gets
1359 /// added to it as well to recursively simplify unless that alloca can be
1360 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1361 /// the one being actively rewritten, we add it back onto the list if not
1362 /// already present to ensure it is re-visited.
1363 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1365 /// \brief A collection of instructions to delete.
1366 /// We try to batch deletions to simplify code and make things a bit more
1368 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
1370 /// \brief Post-promotion worklist.
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.
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;
1380 /// \brief A collection of alloca instructions we can directly promote.
1381 std::vector<AllocaInst *> PromotableAllocas;
1384 SROA(bool RequiresDomTree = true)
1385 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1386 C(0), TD(0), DT(0) {
1387 initializeSROAPass(*PassRegistry::getPassRegistry());
1389 bool runOnFunction(Function &F);
1390 void getAnalysisUsage(AnalysisUsage &AU) const;
1392 const char *getPassName() const { return "SROA"; }
1396 friend class PHIOrSelectSpeculator;
1397 friend class AllocaPartitionRewriter;
1398 friend class AllocaPartitionVectorRewriter;
1400 bool rewriteAllocaPartition(AllocaInst &AI,
1401 AllocaPartitioning &P,
1402 AllocaPartitioning::iterator PI);
1403 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1404 bool runOnAlloca(AllocaInst &AI);
1405 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1406 bool promoteAllocas(Function &F);
1412 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1413 return new SROA(RequiresDomTree);
1416 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1418 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1419 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1423 /// \brief Visitor to speculate PHIs and Selects where possible.
1424 class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1425 // Befriend the base class so it can delegate to private visit methods.
1426 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1428 const DataLayout &TD;
1429 AllocaPartitioning &P;
1433 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
1434 : TD(TD), P(P), Pass(Pass) {}
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);
1444 continue; // Skip dead use.
1446 visit(cast<Instruction>(PU.U->getUser()));
1451 // By default, skip this instruction.
1452 void visitInstruction(Instruction &I) {}
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.
1458 /// %P2 = phi [i32* %Alloca, i32* %Other]
1459 /// %V = load i32* %P2
1461 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1463 /// %V2 = load i32* %Other
1465 /// %V = phi [i32 %V1, i32 %V2]
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.
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();
1481 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1482 if (LI == 0 || !LI->isSimple()) return false;
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
1487 if (LI->getParent() != BB) return false;
1489 // Ensure that there are no instructions between the PHI and the load that
1491 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1492 if (BBI->mayWriteToMemory())
1495 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1496 Loads.push_back(LI);
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;
1504 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1505 Value *InVal = PN.getIncomingValue(Idx);
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())
1513 // If the predecessor has a single successor, then the edge isn't
1515 if (TI->getNumSuccessors() == 1)
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
1521 if (InVal->isDereferenceablePointer() ||
1522 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1531 void visitPHINode(PHINode &PN) {
1532 DEBUG(dbgs() << " original: " << PN << "\n");
1534 SmallVector<LoadInst *, 4> Loads;
1535 if (!isSafePHIToSpeculate(PN, Loads))
1538 assert(!Loads.empty());
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");
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();
1551 // Rewrite all loads of the PN to use the new PHI.
1553 LoadInst *LI = Loads.pop_back_val();
1554 LI->replaceAllUsesWith(NewPN);
1555 Pass.DeadInsts.insert(LI);
1556 } while (!Loads.empty());
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);
1567 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1569 ++NumLoadsSpeculated;
1570 Load->setAlignment(Align);
1572 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1573 NewPN->addIncoming(Load, Pred);
1575 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1577 // No uses to rewrite.
1580 // Try to lookup and rewrite any partition uses corresponding to this phi
1582 AllocaPartitioning::iterator PI
1583 = P.findPartitionForPHIOrSelectOperand(InUse);
1587 // Replace the Use in the PartitionUse for this operand with the Use
1589 AllocaPartitioning::use_iterator UI
1590 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1591 assert(isa<PHINode>(*UI->U->getUser()));
1592 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1594 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
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.
1601 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1602 /// %V = load i32* %P2
1604 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1605 /// %V2 = load i32* %Other
1606 /// %V = select i1 %cond, i32 %V1, i32 %V2
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();
1617 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1619 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1620 if (LI == 0 || !LI->isSimple()) return false;
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
1625 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1626 LI->getAlignment(), &TD))
1628 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1629 LI->getAlignment(), &TD))
1631 Loads.push_back(LI);
1637 void visitSelectInst(SelectInst &SI) {
1638 DEBUG(dbgs() << " original: " << SI << "\n");
1639 IRBuilder<> IRB(&SI);
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))
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]);
1657 // Clear out the use here so that the offsets into the use list remain
1658 // stable but this use is ignored when rewriting.
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();
1669 IRB.SetInsertPoint(LI);
1671 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1673 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1674 NumLoadsSpeculated += 2;
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);
1684 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1685 LI->getName() + ".sroa.speculated");
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());
1693 P.use_push_back(PIs[i], PUs[i]);
1697 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1698 LI->replaceAllUsesWith(V);
1699 Pass.DeadInsts.insert(LI);
1705 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
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.
1710 static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
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());
1718 if (OpC->isZero()) continue;
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));
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;
1737 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1743 /// \brief Build a GEP out of a base pointer and indices.
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.
1747 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1748 SmallVectorImpl<Value *> &Indices,
1749 const Twine &Prefix) {
1750 if (Indices.empty())
1753 // A single zero index is a no-op, so check for this and avoid building a GEP
1755 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1758 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1761 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1762 /// TargetTy without changing the offset of the pointer.
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.
1770 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
1771 Value *BasePtr, Type *Ty, Type *TargetTy,
1772 SmallVectorImpl<Value *> &Indices,
1773 const Twine &Prefix) {
1775 return buildGEP(IRB, BasePtr, Indices, Prefix);
1777 // See if we can descend into a struct and locate a field with the correct
1779 unsigned NumLayers = 0;
1780 Type *ElementTy = Ty;
1782 if (ElementTy->isPointerTy())
1784 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1785 ElementTy = SeqTy->getElementType();
1786 // Note that we use the default address space as this index is over an
1787 // array or a vector, not a pointer.
1788 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
1789 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1790 if (STy->element_begin() == STy->element_end())
1791 break; // Nothing left to descend into.
1792 ElementTy = *STy->element_begin();
1793 Indices.push_back(IRB.getInt32(0));
1798 } while (ElementTy != TargetTy);
1799 if (ElementTy != TargetTy)
1800 Indices.erase(Indices.end() - NumLayers, Indices.end());
1802 return buildGEP(IRB, BasePtr, Indices, Prefix);
1805 /// \brief Recursively compute indices for a natural GEP.
1807 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1808 /// element types adding appropriate indices for the GEP.
1809 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
1810 Value *Ptr, Type *Ty, APInt &Offset,
1812 SmallVectorImpl<Value *> &Indices,
1813 const Twine &Prefix) {
1815 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1817 // We can't recurse through pointer types.
1818 if (Ty->isPointerTy())
1821 // We try to analyze GEPs over vectors here, but note that these GEPs are
1822 // extremely poorly defined currently. The long-term goal is to remove GEPing
1823 // over a vector from the IR completely.
1824 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1825 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1826 if (ElementSizeInBits % 8)
1827 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1828 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1829 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1830 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1832 Offset -= NumSkippedElements * ElementSize;
1833 Indices.push_back(IRB.getInt(NumSkippedElements));
1834 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1835 Offset, TargetTy, Indices, Prefix);
1838 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1839 Type *ElementTy = ArrTy->getElementType();
1840 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1841 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1842 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1845 Offset -= NumSkippedElements * ElementSize;
1846 Indices.push_back(IRB.getInt(NumSkippedElements));
1847 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1851 StructType *STy = dyn_cast<StructType>(Ty);
1855 const StructLayout *SL = TD.getStructLayout(STy);
1856 uint64_t StructOffset = Offset.getZExtValue();
1857 if (StructOffset >= SL->getSizeInBytes())
1859 unsigned Index = SL->getElementContainingOffset(StructOffset);
1860 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1861 Type *ElementTy = STy->getElementType(Index);
1862 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1863 return 0; // The offset points into alignment padding.
1865 Indices.push_back(IRB.getInt32(Index));
1866 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1870 /// \brief Get a natural GEP from a base pointer to a particular offset and
1871 /// resulting in a particular type.
1873 /// The goal is to produce a "natural" looking GEP that works with the existing
1874 /// composite types to arrive at the appropriate offset and element type for
1875 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1876 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1877 /// Indices, and setting Ty to the result subtype.
1879 /// If no natural GEP can be constructed, this function returns null.
1880 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
1881 Value *Ptr, APInt Offset, Type *TargetTy,
1882 SmallVectorImpl<Value *> &Indices,
1883 const Twine &Prefix) {
1884 PointerType *Ty = cast<PointerType>(Ptr->getType());
1886 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1888 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1891 Type *ElementTy = Ty->getElementType();
1892 if (!ElementTy->isSized())
1893 return 0; // We can't GEP through an unsized element.
1894 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1895 if (ElementSize == 0)
1896 return 0; // Zero-length arrays can't help us build a natural GEP.
1897 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1899 Offset -= NumSkippedElements * ElementSize;
1900 Indices.push_back(IRB.getInt(NumSkippedElements));
1901 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1905 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1906 /// resulting pointer has PointerTy.
1908 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1909 /// and produces the pointer type desired. Where it cannot, it will try to use
1910 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1911 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1912 /// bitcast to the type.
1914 /// The strategy for finding the more natural GEPs is to peel off layers of the
1915 /// pointer, walking back through bit casts and GEPs, searching for a base
1916 /// pointer from which we can compute a natural GEP with the desired
1917 /// properities. The algorithm tries to fold as many constant indices into
1918 /// a single GEP as possible, thus making each GEP more independent of the
1919 /// surrounding code.
1920 static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
1921 Value *Ptr, APInt Offset, Type *PointerTy,
1922 const Twine &Prefix) {
1923 // Even though we don't look through PHI nodes, we could be called on an
1924 // instruction in an unreachable block, which may be on a cycle.
1925 SmallPtrSet<Value *, 4> Visited;
1926 Visited.insert(Ptr);
1927 SmallVector<Value *, 4> Indices;
1929 // We may end up computing an offset pointer that has the wrong type. If we
1930 // never are able to compute one directly that has the correct type, we'll
1931 // fall back to it, so keep it around here.
1932 Value *OffsetPtr = 0;
1934 // Remember any i8 pointer we come across to re-use if we need to do a raw
1937 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1939 Type *TargetTy = PointerTy->getPointerElementType();
1942 // First fold any existing GEPs into the offset.
1943 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1944 APInt GEPOffset(Offset.getBitWidth(), 0);
1945 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1947 Offset += GEPOffset;
1948 Ptr = GEP->getPointerOperand();
1949 if (!Visited.insert(Ptr))
1953 // See if we can perform a natural GEP here.
1955 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1957 if (P->getType() == PointerTy) {
1958 // Zap any offset pointer that we ended up computing in previous rounds.
1959 if (OffsetPtr && OffsetPtr->use_empty())
1960 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1961 I->eraseFromParent();
1969 // Stash this pointer if we've found an i8*.
1970 if (Ptr->getType()->isIntegerTy(8)) {
1972 Int8PtrOffset = Offset;
1975 // Peel off a layer of the pointer and update the offset appropriately.
1976 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1977 Ptr = cast<Operator>(Ptr)->getOperand(0);
1978 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1979 if (GA->mayBeOverridden())
1981 Ptr = GA->getAliasee();
1985 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1986 } while (Visited.insert(Ptr));
1990 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1991 Prefix + ".raw_cast");
1992 Int8PtrOffset = Offset;
1995 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1996 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1997 Prefix + ".raw_idx");
2001 // On the off chance we were targeting i8*, guard the bitcast here.
2002 if (Ptr->getType() != PointerTy)
2003 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2008 /// \brief Test whether we can convert a value from the old to the new type.
2010 /// This predicate should be used to guard calls to convertValue in order to
2011 /// ensure that we only try to convert viable values. The strategy is that we
2012 /// will peel off single element struct and array wrappings to get to an
2013 /// underlying value, and convert that value.
2014 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2017 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2019 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2022 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2023 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2025 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2033 /// \brief Generic routine to convert an SSA value to a value of a different
2036 /// This will try various different casting techniques, such as bitcasts,
2037 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2038 /// two types for viability with this routine.
2039 static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2041 assert(canConvertValue(DL, V->getType(), Ty) &&
2042 "Value not convertable to type");
2043 if (V->getType() == Ty)
2045 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2046 return IRB.CreateIntToPtr(V, Ty);
2047 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2048 return IRB.CreatePtrToInt(V, Ty);
2050 return IRB.CreateBitCast(V, Ty);
2053 /// \brief Test whether the given alloca partition can be promoted to a vector.
2055 /// This is a quick test to check whether we can rewrite a particular alloca
2056 /// partition (and its newly formed alloca) into a vector alloca with only
2057 /// whole-vector loads and stores such that it could be promoted to a vector
2058 /// SSA value. We only can ensure this for a limited set of operations, and we
2059 /// don't want to do the rewrites unless we are confident that the result will
2060 /// be promotable, so we have an early test here.
2061 static bool isVectorPromotionViable(const DataLayout &TD,
2063 AllocaPartitioning &P,
2064 uint64_t PartitionBeginOffset,
2065 uint64_t PartitionEndOffset,
2066 AllocaPartitioning::const_use_iterator I,
2067 AllocaPartitioning::const_use_iterator E) {
2068 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2072 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2073 uint64_t ElementSize = Ty->getScalarSizeInBits();
2075 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2076 // that aren't byte sized.
2077 if (ElementSize % 8)
2079 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2083 for (; I != E; ++I) {
2085 continue; // Skip dead use.
2087 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2088 uint64_t BeginIndex = BeginOffset / ElementSize;
2089 if (BeginIndex * ElementSize != BeginOffset ||
2090 BeginIndex >= Ty->getNumElements())
2092 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2093 uint64_t EndIndex = EndOffset / ElementSize;
2094 if (EndIndex * ElementSize != EndOffset ||
2095 EndIndex > Ty->getNumElements())
2098 assert(EndIndex > BeginIndex && "Empty vector!");
2099 uint64_t NumElements = EndIndex - BeginIndex;
2101 = (NumElements == 1) ? Ty->getElementType()
2102 : VectorType::get(Ty->getElementType(), NumElements);
2104 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2105 if (MI->isVolatile())
2107 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2108 const AllocaPartitioning::MemTransferOffsets &MTO
2109 = P.getMemTransferOffsets(*MTI);
2110 if (!MTO.IsSplittable)
2113 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
2114 // Disable vector promotion when there are loads or stores of an FCA.
2116 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2117 if (LI->isVolatile())
2119 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2121 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2122 if (SI->isVolatile())
2124 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2133 /// \brief Test whether the given alloca partition's integer operations can be
2134 /// widened to promotable ones.
2136 /// This is a quick test to check whether we can rewrite the integer loads and
2137 /// stores to a particular alloca into wider loads and stores and be able to
2138 /// promote the resulting alloca.
2139 static bool isIntegerWideningViable(const DataLayout &TD,
2141 uint64_t AllocBeginOffset,
2142 AllocaPartitioning &P,
2143 AllocaPartitioning::const_use_iterator I,
2144 AllocaPartitioning::const_use_iterator E) {
2145 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2146 // Don't create integer types larger than the maximum bitwidth.
2147 if (SizeInBits > IntegerType::MAX_INT_BITS)
2150 // Don't try to handle allocas with bit-padding.
2151 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
2154 // We need to ensure that an integer type with the appropriate bitwidth can
2155 // be converted to the alloca type, whatever that is. We don't want to force
2156 // the alloca itself to have an integer type if there is a more suitable one.
2157 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2158 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2159 !canConvertValue(TD, IntTy, AllocaTy))
2162 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2164 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2165 // Also ensure that the alloca has a covering load or store. We don't want
2166 // to widen the integer operotains only to fail to promote due to some other
2167 // unsplittable entry (which we may make splittable later).
2168 bool WholeAllocaOp = false;
2169 for (; I != E; ++I) {
2171 continue; // Skip dead use.
2173 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2174 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2176 // We can't reasonably handle cases where the load or store extends past
2177 // the end of the aloca's type and into its padding.
2181 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2182 if (LI->isVolatile())
2184 if (RelBegin == 0 && RelEnd == Size)
2185 WholeAllocaOp = true;
2186 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2187 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
2191 // Non-integer loads need to be convertible from the alloca type so that
2192 // they are promotable.
2193 if (RelBegin != 0 || RelEnd != Size ||
2194 !canConvertValue(TD, AllocaTy, LI->getType()))
2196 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2197 Type *ValueTy = SI->getValueOperand()->getType();
2198 if (SI->isVolatile())
2200 if (RelBegin == 0 && RelEnd == Size)
2201 WholeAllocaOp = true;
2202 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2203 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
2207 // Non-integer stores need to be convertible to the alloca type so that
2208 // they are promotable.
2209 if (RelBegin != 0 || RelEnd != Size ||
2210 !canConvertValue(TD, ValueTy, AllocaTy))
2212 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
2213 if (MI->isVolatile())
2215 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
2216 const AllocaPartitioning::MemTransferOffsets &MTO
2217 = P.getMemTransferOffsets(*MTI);
2218 if (!MTO.IsSplittable)
2221 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2222 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2223 II->getIntrinsicID() != Intrinsic::lifetime_end)
2229 return WholeAllocaOp;
2232 static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2233 IntegerType *Ty, uint64_t Offset,
2234 const Twine &Name) {
2235 DEBUG(dbgs() << " start: " << *V << "\n");
2236 IntegerType *IntTy = cast<IntegerType>(V->getType());
2237 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2238 "Element extends past full value");
2239 uint64_t ShAmt = 8*Offset;
2240 if (DL.isBigEndian())
2241 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2243 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2244 DEBUG(dbgs() << " shifted: " << *V << "\n");
2246 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2247 "Cannot extract to a larger integer!");
2249 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2250 DEBUG(dbgs() << " trunced: " << *V << "\n");
2255 static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2256 Value *V, uint64_t Offset, const Twine &Name) {
2257 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2258 IntegerType *Ty = cast<IntegerType>(V->getType());
2259 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2260 "Cannot insert a larger integer!");
2261 DEBUG(dbgs() << " start: " << *V << "\n");
2263 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2264 DEBUG(dbgs() << " extended: " << *V << "\n");
2266 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2267 "Element store outside of alloca store");
2268 uint64_t ShAmt = 8*Offset;
2269 if (DL.isBigEndian())
2270 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2272 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2273 DEBUG(dbgs() << " shifted: " << *V << "\n");
2276 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2277 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2278 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2279 DEBUG(dbgs() << " masked: " << *Old << "\n");
2280 V = IRB.CreateOr(Old, V, Name + ".insert");
2281 DEBUG(dbgs() << " inserted: " << *V << "\n");
2287 /// \brief Visitor to rewrite instructions using a partition of an alloca to
2288 /// use a new alloca.
2290 /// Also implements the rewriting to vector-based accesses when the partition
2291 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2293 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2295 // Befriend the base class so it can delegate to private visit methods.
2296 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2298 const DataLayout &TD;
2299 AllocaPartitioning &P;
2301 AllocaInst &OldAI, &NewAI;
2302 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2305 // If we are rewriting an alloca partition which can be written as pure
2306 // vector operations, we stash extra information here. When VecTy is
2307 // non-null, we have some strict guarantees about the rewriten alloca:
2308 // - The new alloca is exactly the size of the vector type here.
2309 // - The accesses all either map to the entire vector or to a single
2311 // - The set of accessing instructions is only one of those handled above
2312 // in isVectorPromotionViable. Generally these are the same access kinds
2313 // which are promotable via mem2reg.
2316 uint64_t ElementSize;
2318 // This is a convenience and flag variable that will be null unless the new
2319 // alloca's integer operations should be widened to this integer type due to
2320 // passing isIntegerWideningViable above. If it is non-null, the desired
2321 // integer type will be stored here for easy access during rewriting.
2324 // The offset of the partition user currently being rewritten.
2325 uint64_t BeginOffset, EndOffset;
2327 Instruction *OldPtr;
2329 // The name prefix to use when rewriting instructions for this alloca.
2330 std::string NamePrefix;
2333 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
2334 AllocaPartitioning::iterator PI,
2335 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2336 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2337 : TD(TD), P(P), Pass(Pass),
2338 OldAI(OldAI), NewAI(NewAI),
2339 NewAllocaBeginOffset(NewBeginOffset),
2340 NewAllocaEndOffset(NewEndOffset),
2341 NewAllocaTy(NewAI.getAllocatedType()),
2342 VecTy(), ElementTy(), ElementSize(), IntTy(),
2343 BeginOffset(), EndOffset() {
2346 /// \brief Visit the users of the alloca partition and rewrite them.
2347 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2348 AllocaPartitioning::const_use_iterator E) {
2349 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2350 NewAllocaBeginOffset, NewAllocaEndOffset,
2353 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2354 ElementTy = VecTy->getElementType();
2355 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2356 "Only multiple-of-8 sized vector elements are viable");
2357 ElementSize = VecTy->getScalarSizeInBits() / 8;
2358 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2359 NewAllocaBeginOffset, P, I, E)) {
2360 IntTy = Type::getIntNTy(NewAI.getContext(),
2361 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
2363 bool CanSROA = true;
2364 for (; I != E; ++I) {
2366 continue; // Skip dead uses.
2367 BeginOffset = I->BeginOffset;
2368 EndOffset = I->EndOffset;
2370 OldPtr = cast<Instruction>(I->U->get());
2371 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
2372 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
2388 // Every instruction which can end up as a user must have a rewrite rule.
2389 bool visitInstruction(Instruction &I) {
2390 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2391 llvm_unreachable("No rewrite rule for this instruction!");
2394 Twine getName(const Twine &Suffix) {
2395 return NamePrefix + Suffix;
2398 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2399 assert(BeginOffset >= NewAllocaBeginOffset);
2400 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2401 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2404 /// \brief Compute suitable alignment to access an offset into the new alloca.
2405 unsigned getOffsetAlign(uint64_t Offset) {
2406 unsigned NewAIAlign = NewAI.getAlignment();
2408 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2409 return MinAlign(NewAIAlign, Offset);
2412 /// \brief Compute suitable alignment to access this partition of the new
2414 unsigned getPartitionAlign() {
2415 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
2418 /// \brief Compute suitable alignment to access a type at an offset of the
2421 /// \returns zero if the type's ABI alignment is a suitable alignment,
2422 /// otherwise returns the maximal suitable alignment.
2423 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2424 unsigned Align = getOffsetAlign(Offset);
2425 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2428 /// \brief Compute suitable alignment to access a type at the beginning of
2429 /// this partition of the new alloca.
2431 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2432 unsigned getPartitionTypeAlign(Type *Ty) {
2433 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
2436 unsigned getIndex(uint64_t Offset) {
2437 assert(VecTy && "Can only call getIndex when rewriting a vector");
2438 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2439 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2440 uint32_t Index = RelOffset / ElementSize;
2441 assert(Index * ElementSize == RelOffset);
2445 void deleteIfTriviallyDead(Value *V) {
2446 Instruction *I = cast<Instruction>(V);
2447 if (isInstructionTriviallyDead(I))
2448 Pass.DeadInsts.insert(I);
2451 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2452 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2454 unsigned BeginIndex = getIndex(BeginOffset);
2455 unsigned EndIndex = getIndex(EndOffset);
2456 assert(EndIndex > BeginIndex && "Empty vector!");
2457 unsigned NumElements = EndIndex - BeginIndex;
2458 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2459 if (NumElements == 1) {
2460 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2461 getName(".extract"));
2462 DEBUG(dbgs() << " extract: " << *V << "\n");
2463 } else if (NumElements < VecTy->getNumElements()) {
2464 SmallVector<Constant*, 8> Mask;
2465 Mask.reserve(NumElements);
2466 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2467 Mask.push_back(IRB.getInt32(i));
2468 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2469 ConstantVector::get(Mask),
2470 getName(".extract"));
2471 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2476 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2477 assert(IntTy && "We cannot insert an integer to the alloca");
2478 assert(!LI.isVolatile());
2479 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2481 V = convertValue(TD, IRB, V, IntTy);
2482 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2483 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2484 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2485 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2486 getName(".extract"));
2490 bool visitLoadInst(LoadInst &LI) {
2491 DEBUG(dbgs() << " original: " << LI << "\n");
2492 Value *OldOp = LI.getOperand(0);
2493 assert(OldOp == OldPtr);
2494 IRBuilder<> IRB(&LI);
2496 uint64_t Size = EndOffset - BeginOffset;
2497 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
2499 // If this memory access can be shown to *statically* extend outside the
2500 // bounds of the original allocation it's behavior is undefined. Rather
2501 // than trying to transform it, just replace it with undef.
2502 // FIXME: We should do something more clever for functions being
2503 // instrumented by asan.
2504 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2505 // should be transformed to a load of null making it unreachable.
2506 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2507 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2508 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2509 Pass.DeadInsts.insert(&LI);
2510 deleteIfTriviallyDead(OldOp);
2511 DEBUG(dbgs() << " to: undef!!\n");
2515 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2517 bool IsPtrAdjusted = false;
2520 V = rewriteVectorizedLoadInst(IRB, LI, OldOp);
2521 } else if (IntTy && LI.getType()->isIntegerTy()) {
2522 V = rewriteIntegerLoad(IRB, LI);
2523 } else if (BeginOffset == NewAllocaBeginOffset &&
2524 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2525 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2526 LI.isVolatile(), getName(".load"));
2528 Type *LTy = TargetTy->getPointerTo();
2529 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2530 getPartitionTypeAlign(TargetTy),
2531 LI.isVolatile(), getName(".load"));
2532 IsPtrAdjusted = true;
2534 V = convertValue(TD, IRB, V, TargetTy);
2536 if (IsSplitIntLoad) {
2537 assert(!LI.isVolatile());
2538 assert(LI.getType()->isIntegerTy() &&
2539 "Only integer type loads and stores are split");
2540 assert(LI.getType()->getIntegerBitWidth() ==
2541 TD.getTypeStoreSizeInBits(LI.getType()) &&
2542 "Non-byte-multiple bit width");
2543 assert(LI.getType()->getIntegerBitWidth() ==
2544 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
2545 "Only alloca-wide loads can be split and recomposed");
2546 // Move the insertion point just past the load so that we can refer to it.
2547 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2548 // Create a placeholder value with the same type as LI to use as the
2549 // basis for the new value. This allows us to replace the uses of LI with
2550 // the computed value, and then replace the placeholder with LI, leaving
2551 // LI only used for this computation.
2553 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2554 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2555 getName(".insert"));
2556 LI.replaceAllUsesWith(V);
2557 Placeholder->replaceAllUsesWith(&LI);
2560 LI.replaceAllUsesWith(V);
2563 Pass.DeadInsts.insert(&LI);
2564 deleteIfTriviallyDead(OldOp);
2565 DEBUG(dbgs() << " to: " << *V << "\n");
2566 return !LI.isVolatile() && !IsPtrAdjusted;
2569 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2570 StoreInst &SI, Value *OldOp) {
2571 unsigned BeginIndex = getIndex(BeginOffset);
2572 unsigned EndIndex = getIndex(EndOffset);
2573 assert(EndIndex > BeginIndex && "Empty vector!");
2574 unsigned NumElements = EndIndex - BeginIndex;
2575 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2577 = (NumElements == 1) ? ElementTy
2578 : VectorType::get(ElementTy, NumElements);
2579 if (V->getType() != PartitionTy)
2580 V = convertValue(TD, IRB, V, PartitionTy);
2581 if (NumElements < VecTy->getNumElements()) {
2582 // We need to mix in the existing elements.
2583 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2585 if (NumElements == 1) {
2586 V = IRB.CreateInsertElement(LI, V, IRB.getInt32(BeginIndex),
2587 getName(".insert"));
2588 DEBUG(dbgs() << " insert: " << *V << "\n");
2590 // When inserting a smaller vector into the larger to store, we first
2591 // use a shuffle vector to widen it with undef elements, and then
2592 // a second shuffle vector to select between the loaded vector and the
2594 SmallVector<Constant*, 8> Mask;
2595 Mask.reserve(VecTy->getNumElements());
2596 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2597 if (i >= BeginIndex && i < EndIndex)
2598 Mask.push_back(IRB.getInt32(i - BeginIndex));
2600 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2601 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2602 ConstantVector::get(Mask),
2603 getName(".expand"));
2604 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2607 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2608 if (i >= BeginIndex && i < EndIndex)
2609 Mask.push_back(IRB.getInt32(i));
2611 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2612 V = IRB.CreateShuffleVector(V, LI, ConstantVector::get(Mask),
2614 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2617 V = convertValue(TD, IRB, V, VecTy);
2619 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2620 Pass.DeadInsts.insert(&SI);
2623 DEBUG(dbgs() << " to: " << *Store << "\n");
2627 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
2628 assert(IntTy && "We cannot extract an integer from the alloca");
2629 assert(!SI.isVolatile());
2630 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2631 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2632 getName(".oldload"));
2633 Old = convertValue(TD, IRB, Old, IntTy);
2634 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2635 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2636 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2637 getName(".insert"));
2639 V = convertValue(TD, IRB, V, NewAllocaTy);
2640 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2641 Pass.DeadInsts.insert(&SI);
2643 DEBUG(dbgs() << " to: " << *Store << "\n");
2647 bool visitStoreInst(StoreInst &SI) {
2648 DEBUG(dbgs() << " original: " << SI << "\n");
2649 Value *OldOp = SI.getOperand(1);
2650 assert(OldOp == OldPtr);
2651 IRBuilder<> IRB(&SI);
2653 Value *V = SI.getValueOperand();
2655 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2656 // alloca that should be re-examined after promoting this alloca.
2657 if (V->getType()->isPointerTy())
2658 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2659 Pass.PostPromotionWorklist.insert(AI);
2661 uint64_t Size = EndOffset - BeginOffset;
2662 if (Size < TD.getTypeStoreSize(V->getType())) {
2663 assert(!SI.isVolatile());
2664 assert(V->getType()->isIntegerTy() &&
2665 "Only integer type loads and stores are split");
2666 assert(V->getType()->getIntegerBitWidth() ==
2667 TD.getTypeStoreSizeInBits(V->getType()) &&
2668 "Non-byte-multiple bit width");
2669 assert(V->getType()->getIntegerBitWidth() ==
2670 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2671 "Only alloca-wide stores can be split and recomposed");
2672 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2673 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2674 getName(".extract"));
2678 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2679 if (IntTy && V->getType()->isIntegerTy())
2680 return rewriteIntegerStore(IRB, V, SI);
2683 if (BeginOffset == NewAllocaBeginOffset &&
2684 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2685 V = convertValue(TD, IRB, V, NewAllocaTy);
2686 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2689 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2690 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2691 getPartitionTypeAlign(V->getType()),
2695 Pass.DeadInsts.insert(&SI);
2696 deleteIfTriviallyDead(OldOp);
2698 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2699 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2702 bool visitMemSetInst(MemSetInst &II) {
2703 DEBUG(dbgs() << " original: " << II << "\n");
2704 IRBuilder<> IRB(&II);
2705 assert(II.getRawDest() == OldPtr);
2707 // If the memset has a variable size, it cannot be split, just adjust the
2708 // pointer to the new alloca.
2709 if (!isa<Constant>(II.getLength())) {
2710 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2711 Type *CstTy = II.getAlignmentCst()->getType();
2712 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
2714 deleteIfTriviallyDead(OldPtr);
2718 // Record this instruction for deletion.
2719 Pass.DeadInsts.insert(&II);
2721 Type *AllocaTy = NewAI.getAllocatedType();
2722 Type *ScalarTy = AllocaTy->getScalarType();
2724 // If this doesn't map cleanly onto the alloca type, and that type isn't
2725 // a single value type, just emit a memset.
2726 if (!VecTy && !IntTy &&
2727 (BeginOffset != NewAllocaBeginOffset ||
2728 EndOffset != NewAllocaEndOffset ||
2729 !AllocaTy->isSingleValueType() ||
2730 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2731 Type *SizeTy = II.getLength()->getType();
2732 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2734 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2735 II.getRawDest()->getType()),
2736 II.getValue(), Size, getPartitionAlign(),
2739 DEBUG(dbgs() << " to: " << *New << "\n");
2743 // If we can represent this as a simple value, we have to build the actual
2744 // value to store, which requires expanding the byte present in memset to
2745 // a sensible representation for the alloca type. This is essentially
2746 // splatting the byte to a sufficiently wide integer, bitcasting to the
2747 // desired scalar type, and splatting it across any desired vector type.
2748 uint64_t Size = EndOffset - BeginOffset;
2749 Value *V = II.getValue();
2750 IntegerType *VTy = cast<IntegerType>(V->getType());
2751 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2752 if (Size*8 > VTy->getBitWidth())
2753 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
2754 ConstantExpr::getUDiv(
2755 Constant::getAllOnesValue(SplatIntTy),
2756 ConstantExpr::getZExt(
2757 Constant::getAllOnesValue(V->getType()),
2759 getName(".isplat"));
2761 // If this is an element-wide memset of a vectorizable alloca, insert it.
2762 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2763 EndOffset < NewAllocaEndOffset)) {
2764 if (V->getType() != ScalarTy)
2765 V = convertValue(TD, IRB, V, ScalarTy);
2766 StoreInst *Store = IRB.CreateAlignedStore(
2767 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2768 NewAI.getAlignment(),
2770 V, IRB.getInt32(getIndex(BeginOffset)),
2771 getName(".insert")),
2772 &NewAI, NewAI.getAlignment());
2774 DEBUG(dbgs() << " to: " << *Store << "\n");
2778 // If this is a memset on an alloca where we can widen stores, insert the
2780 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2781 EndOffset < NewAllocaEndOffset)) {
2782 assert(!II.isVolatile());
2783 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2784 getName(".oldload"));
2785 Old = convertValue(TD, IRB, Old, IntTy);
2786 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2787 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2788 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
2791 if (V->getType() != AllocaTy)
2792 V = convertValue(TD, IRB, V, AllocaTy);
2794 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2797 DEBUG(dbgs() << " to: " << *New << "\n");
2798 return !II.isVolatile();
2801 bool visitMemTransferInst(MemTransferInst &II) {
2802 // Rewriting of memory transfer instructions can be a bit tricky. We break
2803 // them into two categories: split intrinsics and unsplit intrinsics.
2805 DEBUG(dbgs() << " original: " << II << "\n");
2806 IRBuilder<> IRB(&II);
2808 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2809 bool IsDest = II.getRawDest() == OldPtr;
2811 const AllocaPartitioning::MemTransferOffsets &MTO
2812 = P.getMemTransferOffsets(II);
2814 // Compute the relative offset within the transfer.
2815 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2816 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2817 : MTO.SourceBegin));
2819 unsigned Align = II.getAlignment();
2821 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2822 MinAlign(II.getAlignment(), getPartitionAlign()));
2824 // For unsplit intrinsics, we simply modify the source and destination
2825 // pointers in place. This isn't just an optimization, it is a matter of
2826 // correctness. With unsplit intrinsics we may be dealing with transfers
2827 // within a single alloca before SROA ran, or with transfers that have
2828 // a variable length. We may also be dealing with memmove instead of
2829 // memcpy, and so simply updating the pointers is the necessary for us to
2830 // update both source and dest of a single call.
2831 if (!MTO.IsSplittable) {
2832 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2834 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2836 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2838 Type *CstTy = II.getAlignmentCst()->getType();
2839 II.setAlignment(ConstantInt::get(CstTy, Align));
2841 DEBUG(dbgs() << " to: " << II << "\n");
2842 deleteIfTriviallyDead(OldOp);
2845 // For split transfer intrinsics we have an incredibly useful assurance:
2846 // the source and destination do not reside within the same alloca, and at
2847 // least one of them does not escape. This means that we can replace
2848 // memmove with memcpy, and we don't need to worry about all manner of
2849 // downsides to splitting and transforming the operations.
2851 // If this doesn't map cleanly onto the alloca type, and that type isn't
2852 // a single value type, just emit a memcpy.
2854 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2855 EndOffset != NewAllocaEndOffset ||
2856 !NewAI.getAllocatedType()->isSingleValueType());
2858 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2859 // size hasn't been shrunk based on analysis of the viable range, this is
2861 if (EmitMemCpy && &OldAI == &NewAI) {
2862 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2863 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2864 // Ensure the start lines up.
2865 assert(BeginOffset == OrigBegin);
2868 // Rewrite the size as needed.
2869 if (EndOffset != OrigEnd)
2870 II.setLength(ConstantInt::get(II.getLength()->getType(),
2871 EndOffset - BeginOffset));
2874 // Record this instruction for deletion.
2875 Pass.DeadInsts.insert(&II);
2877 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2878 EndOffset == NewAllocaEndOffset;
2879 bool IsVectorElement = VecTy && !IsWholeAlloca;
2880 uint64_t Size = EndOffset - BeginOffset;
2881 IntegerType *SubIntTy
2882 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2884 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2885 : II.getRawDest()->getType();
2887 if (IsVectorElement)
2888 OtherPtrTy = VecTy->getElementType()->getPointerTo();
2889 else if (IntTy && !IsWholeAlloca)
2890 OtherPtrTy = SubIntTy->getPointerTo();
2892 OtherPtrTy = NewAI.getType();
2895 // Compute the other pointer, folding as much as possible to produce
2896 // a single, simple GEP in most cases.
2897 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2898 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2899 getName("." + OtherPtr->getName()));
2901 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2902 // alloca that should be re-examined after rewriting this instruction.
2904 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2905 Pass.Worklist.insert(AI);
2909 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2910 : II.getRawSource()->getType());
2911 Type *SizeTy = II.getLength()->getType();
2912 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2914 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2915 IsDest ? OtherPtr : OurPtr,
2916 Size, Align, II.isVolatile());
2918 DEBUG(dbgs() << " to: " << *New << "\n");
2922 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2923 // is equivalent to 1, but that isn't true if we end up rewriting this as
2928 Value *SrcPtr = OtherPtr;
2929 Value *DstPtr = &NewAI;
2931 std::swap(SrcPtr, DstPtr);
2934 if (IsVectorElement && !IsDest) {
2935 // We have to extract rather than load.
2936 Src = IRB.CreateExtractElement(
2937 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2938 IRB.getInt32(getIndex(BeginOffset)),
2939 getName(".copyextract"));
2940 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2941 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2943 Src = convertValue(TD, IRB, Src, IntTy);
2944 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2945 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2946 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
2948 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2949 getName(".copyload"));
2952 if (IntTy && !IsWholeAlloca && IsDest) {
2953 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2954 getName(".oldload"));
2955 Old = convertValue(TD, IRB, Old, IntTy);
2956 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2957 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2958 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2959 Src = convertValue(TD, IRB, Src, NewAllocaTy);
2962 if (IsVectorElement && IsDest) {
2963 // We have to insert into a loaded copy before storing.
2964 Src = IRB.CreateInsertElement(
2965 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2966 Src, IRB.getInt32(getIndex(BeginOffset)),
2967 getName(".insert"));
2970 StoreInst *Store = cast<StoreInst>(
2971 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2973 DEBUG(dbgs() << " to: " << *Store << "\n");
2974 return !II.isVolatile();
2977 bool visitIntrinsicInst(IntrinsicInst &II) {
2978 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2979 II.getIntrinsicID() == Intrinsic::lifetime_end);
2980 DEBUG(dbgs() << " original: " << II << "\n");
2981 IRBuilder<> IRB(&II);
2982 assert(II.getArgOperand(1) == OldPtr);
2984 // Record this instruction for deletion.
2985 Pass.DeadInsts.insert(&II);
2988 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2989 EndOffset - BeginOffset);
2990 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2992 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2993 New = IRB.CreateLifetimeStart(Ptr, Size);
2995 New = IRB.CreateLifetimeEnd(Ptr, Size);
2997 DEBUG(dbgs() << " to: " << *New << "\n");
3001 bool visitPHINode(PHINode &PN) {
3002 DEBUG(dbgs() << " original: " << PN << "\n");
3004 // We would like to compute a new pointer in only one place, but have it be
3005 // as local as possible to the PHI. To do that, we re-use the location of
3006 // the old pointer, which necessarily must be in the right position to
3007 // dominate the PHI.
3008 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
3010 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
3011 // Replace the operands which were using the old pointer.
3012 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3014 DEBUG(dbgs() << " to: " << PN << "\n");
3015 deleteIfTriviallyDead(OldPtr);
3019 bool visitSelectInst(SelectInst &SI) {
3020 DEBUG(dbgs() << " original: " << SI << "\n");
3021 IRBuilder<> IRB(&SI);
3023 // Find the operand we need to rewrite here.
3024 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3026 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3028 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
3030 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
3031 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3032 DEBUG(dbgs() << " to: " << SI << "\n");
3033 deleteIfTriviallyDead(OldPtr);
3041 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
3043 /// This pass aggressively rewrites all aggregate loads and stores on
3044 /// a particular pointer (or any pointer derived from it which we can identify)
3045 /// with scalar loads and stores.
3046 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3047 // Befriend the base class so it can delegate to private visit methods.
3048 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3050 const DataLayout &TD;
3052 /// Queue of pointer uses to analyze and potentially rewrite.
3053 SmallVector<Use *, 8> Queue;
3055 /// Set to prevent us from cycling with phi nodes and loops.
3056 SmallPtrSet<User *, 8> Visited;
3058 /// The current pointer use being rewritten. This is used to dig up the used
3059 /// value (as opposed to the user).
3063 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
3065 /// Rewrite loads and stores through a pointer and all pointers derived from
3067 bool rewrite(Instruction &I) {
3068 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3070 bool Changed = false;
3071 while (!Queue.empty()) {
3072 U = Queue.pop_back_val();
3073 Changed |= visit(cast<Instruction>(U->getUser()));
3079 /// Enqueue all the users of the given instruction for further processing.
3080 /// This uses a set to de-duplicate users.
3081 void enqueueUsers(Instruction &I) {
3082 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3084 if (Visited.insert(*UI))
3085 Queue.push_back(&UI.getUse());
3088 // Conservative default is to not rewrite anything.
3089 bool visitInstruction(Instruction &I) { return false; }
3091 /// \brief Generic recursive split emission class.
3092 template <typename Derived>
3095 /// The builder used to form new instructions.
3097 /// The indices which to be used with insert- or extractvalue to select the
3098 /// appropriate value within the aggregate.
3099 SmallVector<unsigned, 4> Indices;
3100 /// The indices to a GEP instruction which will move Ptr to the correct slot
3101 /// within the aggregate.
3102 SmallVector<Value *, 4> GEPIndices;
3103 /// The base pointer of the original op, used as a base for GEPing the
3104 /// split operations.
3107 /// Initialize the splitter with an insertion point, Ptr and start with a
3108 /// single zero GEP index.
3109 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3110 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3113 /// \brief Generic recursive split emission routine.
3115 /// This method recursively splits an aggregate op (load or store) into
3116 /// scalar or vector ops. It splits recursively until it hits a single value
3117 /// and emits that single value operation via the template argument.
3119 /// The logic of this routine relies on GEPs and insertvalue and
3120 /// extractvalue all operating with the same fundamental index list, merely
3121 /// formatted differently (GEPs need actual values).
3123 /// \param Ty The type being split recursively into smaller ops.
3124 /// \param Agg The aggregate value being built up or stored, depending on
3125 /// whether this is splitting a load or a store respectively.
3126 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3127 if (Ty->isSingleValueType())
3128 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3130 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3131 unsigned OldSize = Indices.size();
3133 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3135 assert(Indices.size() == OldSize && "Did not return to the old size");
3136 Indices.push_back(Idx);
3137 GEPIndices.push_back(IRB.getInt32(Idx));
3138 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3139 GEPIndices.pop_back();
3145 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3146 unsigned OldSize = Indices.size();
3148 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3150 assert(Indices.size() == OldSize && "Did not return to the old size");
3151 Indices.push_back(Idx);
3152 GEPIndices.push_back(IRB.getInt32(Idx));
3153 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3154 GEPIndices.pop_back();
3160 llvm_unreachable("Only arrays and structs are aggregate loadable types");
3164 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3165 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3166 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3168 /// Emit a leaf load of a single value. This is called at the leaves of the
3169 /// recursive emission to actually load values.
3170 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3171 assert(Ty->isSingleValueType());
3172 // Load the single value and insert it using the indices.
3173 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3176 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3177 DEBUG(dbgs() << " to: " << *Load << "\n");
3181 bool visitLoadInst(LoadInst &LI) {
3182 assert(LI.getPointerOperand() == *U);
3183 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3186 // We have an aggregate being loaded, split it apart.
3187 DEBUG(dbgs() << " original: " << LI << "\n");
3188 LoadOpSplitter Splitter(&LI, *U);
3189 Value *V = UndefValue::get(LI.getType());
3190 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3191 LI.replaceAllUsesWith(V);
3192 LI.eraseFromParent();
3196 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3197 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3198 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3200 /// Emit a leaf store of a single value. This is called at the leaves of the
3201 /// recursive emission to actually produce stores.
3202 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3203 assert(Ty->isSingleValueType());
3204 // Extract the single value and store it using the indices.
3205 Value *Store = IRB.CreateStore(
3206 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3207 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3209 DEBUG(dbgs() << " to: " << *Store << "\n");
3213 bool visitStoreInst(StoreInst &SI) {
3214 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3216 Value *V = SI.getValueOperand();
3217 if (V->getType()->isSingleValueType())
3220 // We have an aggregate being stored, split it apart.
3221 DEBUG(dbgs() << " original: " << SI << "\n");
3222 StoreOpSplitter Splitter(&SI, *U);
3223 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3224 SI.eraseFromParent();
3228 bool visitBitCastInst(BitCastInst &BC) {
3233 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3238 bool visitPHINode(PHINode &PN) {
3243 bool visitSelectInst(SelectInst &SI) {
3250 /// \brief Strip aggregate type wrapping.
3252 /// This removes no-op aggregate types wrapping an underlying type. It will
3253 /// strip as many layers of types as it can without changing either the type
3254 /// size or the allocated size.
3255 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3256 if (Ty->isSingleValueType())
3259 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3260 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3263 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3264 InnerTy = ArrTy->getElementType();
3265 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3266 const StructLayout *SL = DL.getStructLayout(STy);
3267 unsigned Index = SL->getElementContainingOffset(0);
3268 InnerTy = STy->getElementType(Index);
3273 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3274 TypeSize > DL.getTypeSizeInBits(InnerTy))
3277 return stripAggregateTypeWrapping(DL, InnerTy);
3280 /// \brief Try to find a partition of the aggregate type passed in for a given
3281 /// offset and size.
3283 /// This recurses through the aggregate type and tries to compute a subtype
3284 /// based on the offset and size. When the offset and size span a sub-section
3285 /// of an array, it will even compute a new array type for that sub-section,
3286 /// and the same for structs.
3288 /// Note that this routine is very strict and tries to find a partition of the
3289 /// type which produces the *exact* right offset and size. It is not forgiving
3290 /// when the size or offset cause either end of type-based partition to be off.
3291 /// Also, this is a best-effort routine. It is reasonable to give up and not
3292 /// return a type if necessary.
3293 static Type *getTypePartition(const DataLayout &TD, Type *Ty,
3294 uint64_t Offset, uint64_t Size) {
3295 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
3296 return stripAggregateTypeWrapping(TD, Ty);
3297 if (Offset > TD.getTypeAllocSize(Ty) ||
3298 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3301 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3302 // We can't partition pointers...
3303 if (SeqTy->isPointerTy())
3306 Type *ElementTy = SeqTy->getElementType();
3307 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3308 uint64_t NumSkippedElements = Offset / ElementSize;
3309 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3310 if (NumSkippedElements >= ArrTy->getNumElements())
3312 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3313 if (NumSkippedElements >= VecTy->getNumElements())
3315 Offset -= NumSkippedElements * ElementSize;
3317 // First check if we need to recurse.
3318 if (Offset > 0 || Size < ElementSize) {
3319 // Bail if the partition ends in a different array element.
3320 if ((Offset + Size) > ElementSize)
3322 // Recurse through the element type trying to peel off offset bytes.
3323 return getTypePartition(TD, ElementTy, Offset, Size);
3325 assert(Offset == 0);
3327 if (Size == ElementSize)
3328 return stripAggregateTypeWrapping(TD, ElementTy);
3329 assert(Size > ElementSize);
3330 uint64_t NumElements = Size / ElementSize;
3331 if (NumElements * ElementSize != Size)
3333 return ArrayType::get(ElementTy, NumElements);
3336 StructType *STy = dyn_cast<StructType>(Ty);
3340 const StructLayout *SL = TD.getStructLayout(STy);
3341 if (Offset >= SL->getSizeInBytes())
3343 uint64_t EndOffset = Offset + Size;
3344 if (EndOffset > SL->getSizeInBytes())
3347 unsigned Index = SL->getElementContainingOffset(Offset);
3348 Offset -= SL->getElementOffset(Index);
3350 Type *ElementTy = STy->getElementType(Index);
3351 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3352 if (Offset >= ElementSize)
3353 return 0; // The offset points into alignment padding.
3355 // See if any partition must be contained by the element.
3356 if (Offset > 0 || Size < ElementSize) {
3357 if ((Offset + Size) > ElementSize)
3359 return getTypePartition(TD, ElementTy, Offset, Size);
3361 assert(Offset == 0);
3363 if (Size == ElementSize)
3364 return stripAggregateTypeWrapping(TD, ElementTy);
3366 StructType::element_iterator EI = STy->element_begin() + Index,
3367 EE = STy->element_end();
3368 if (EndOffset < SL->getSizeInBytes()) {
3369 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3370 if (Index == EndIndex)
3371 return 0; // Within a single element and its padding.
3373 // Don't try to form "natural" types if the elements don't line up with the
3375 // FIXME: We could potentially recurse down through the last element in the
3376 // sub-struct to find a natural end point.
3377 if (SL->getElementOffset(EndIndex) != EndOffset)
3380 assert(Index < EndIndex);
3381 EE = STy->element_begin() + EndIndex;
3384 // Try to build up a sub-structure.
3385 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3387 const StructLayout *SubSL = TD.getStructLayout(SubTy);
3388 if (Size != SubSL->getSizeInBytes())
3389 return 0; // The sub-struct doesn't have quite the size needed.
3394 /// \brief Rewrite an alloca partition's users.
3396 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3397 /// to rewrite uses of an alloca partition to be conducive for SSA value
3398 /// promotion. If the partition needs a new, more refined alloca, this will
3399 /// build that new alloca, preserving as much type information as possible, and
3400 /// rewrite the uses of the old alloca to point at the new one and have the
3401 /// appropriate new offsets. It also evaluates how successful the rewrite was
3402 /// at enabling promotion and if it was successful queues the alloca to be
3404 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3405 AllocaPartitioning &P,
3406 AllocaPartitioning::iterator PI) {
3407 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
3408 bool IsLive = false;
3409 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3411 UI != UE && !IsLive; ++UI)
3415 return false; // No live uses left of this partition.
3417 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3418 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3420 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3421 DEBUG(dbgs() << " speculating ");
3422 DEBUG(P.print(dbgs(), PI, ""));
3423 Speculator.visitUsers(PI);
3425 // Try to compute a friendly type for this partition of the alloca. This
3426 // won't always succeed, in which case we fall back to a legal integer type
3427 // or an i8 array of an appropriate size.
3429 if (Type *PartitionTy = P.getCommonType(PI))
3430 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3431 AllocaTy = PartitionTy;
3433 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3434 PI->BeginOffset, AllocaSize))
3435 AllocaTy = PartitionTy;
3437 (AllocaTy->isArrayTy() &&
3438 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3439 TD->isLegalInteger(AllocaSize * 8))
3440 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3442 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
3443 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
3445 // Check for the case where we're going to rewrite to a new alloca of the
3446 // exact same type as the original, and with the same access offsets. In that
3447 // case, re-use the existing alloca, but still run through the rewriter to
3448 // performe phi and select speculation.
3450 if (AllocaTy == AI.getAllocatedType()) {
3451 assert(PI->BeginOffset == 0 &&
3452 "Non-zero begin offset but same alloca type");
3453 assert(PI == P.begin() && "Begin offset is zero on later partition");
3456 unsigned Alignment = AI.getAlignment();
3458 // The minimum alignment which users can rely on when the explicit
3459 // alignment is omitted or zero is that required by the ABI for this
3461 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3463 Alignment = MinAlign(Alignment, PI->BeginOffset);
3464 // If we will get at least this much alignment from the type alone, leave
3465 // the alloca's alignment unconstrained.
3466 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3468 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
3469 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3474 DEBUG(dbgs() << "Rewriting alloca partition "
3475 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3478 // Track the high watermark of the post-promotion worklist. We will reset it
3479 // to this point if the alloca is not in fact scheduled for promotion.
3480 unsigned PPWOldSize = PostPromotionWorklist.size();
3482 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3483 PI->BeginOffset, PI->EndOffset);
3484 DEBUG(dbgs() << " rewriting ");
3485 DEBUG(P.print(dbgs(), PI, ""));
3486 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3488 DEBUG(dbgs() << " and queuing for promotion\n");
3489 PromotableAllocas.push_back(NewAI);
3490 } else if (NewAI != &AI) {
3491 // If we can't promote the alloca, iterate on it to check for new
3492 // refinements exposed by splitting the current alloca. Don't iterate on an
3493 // alloca which didn't actually change and didn't get promoted.
3494 Worklist.insert(NewAI);
3497 // Drop any post-promotion work items if promotion didn't happen.
3499 while (PostPromotionWorklist.size() > PPWOldSize)
3500 PostPromotionWorklist.pop_back();
3505 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3506 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3507 bool Changed = false;
3508 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3510 Changed |= rewriteAllocaPartition(AI, P, PI);
3515 /// \brief Analyze an alloca for SROA.
3517 /// This analyzes the alloca to ensure we can reason about it, builds
3518 /// a partitioning of the alloca, and then hands it off to be split and
3519 /// rewritten as needed.
3520 bool SROA::runOnAlloca(AllocaInst &AI) {
3521 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3522 ++NumAllocasAnalyzed;
3524 // Special case dead allocas, as they're trivial.
3525 if (AI.use_empty()) {
3526 AI.eraseFromParent();
3530 // Skip alloca forms that this analysis can't handle.
3531 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3532 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3535 bool Changed = false;
3537 // First, split any FCA loads and stores touching this alloca to promote
3538 // better splitting and promotion opportunities.
3539 AggLoadStoreRewriter AggRewriter(*TD);
3540 Changed |= AggRewriter.rewrite(AI);
3542 // Build the partition set using a recursive instruction-visiting builder.
3543 AllocaPartitioning P(*TD, AI);
3544 DEBUG(P.print(dbgs()));
3548 // Delete all the dead users of this alloca before splitting and rewriting it.
3549 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3550 DE = P.dead_user_end();
3553 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3554 DeadInsts.insert(*DI);
3556 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3557 DE = P.dead_op_end();
3560 // Clobber the use with an undef value.
3561 **DO = UndefValue::get(OldV->getType());
3562 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3563 if (isInstructionTriviallyDead(OldI)) {
3565 DeadInsts.insert(OldI);
3569 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3570 if (P.begin() == P.end())
3573 return splitAlloca(AI, P) || Changed;
3576 /// \brief Delete the dead instructions accumulated in this run.
3578 /// Recursively deletes the dead instructions we've accumulated. This is done
3579 /// at the very end to maximize locality of the recursive delete and to
3580 /// minimize the problems of invalidated instruction pointers as such pointers
3581 /// are used heavily in the intermediate stages of the algorithm.
3583 /// We also record the alloca instructions deleted here so that they aren't
3584 /// subsequently handed to mem2reg to promote.
3585 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3586 while (!DeadInsts.empty()) {
3587 Instruction *I = DeadInsts.pop_back_val();
3588 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3590 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3592 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3593 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3594 // Zero out the operand and see if it becomes trivially dead.
3596 if (isInstructionTriviallyDead(U))
3597 DeadInsts.insert(U);
3600 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3601 DeletedAllocas.insert(AI);
3604 I->eraseFromParent();
3608 /// \brief Promote the allocas, using the best available technique.
3610 /// This attempts to promote whatever allocas have been identified as viable in
3611 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3612 /// If there is a domtree available, we attempt to promote using the full power
3613 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3614 /// based on the SSAUpdater utilities. This function returns whether any
3615 /// promotion occured.
3616 bool SROA::promoteAllocas(Function &F) {
3617 if (PromotableAllocas.empty())
3620 NumPromoted += PromotableAllocas.size();
3622 if (DT && !ForceSSAUpdater) {
3623 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3624 PromoteMemToReg(PromotableAllocas, *DT);
3625 PromotableAllocas.clear();
3629 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3631 DIBuilder DIB(*F.getParent());
3632 SmallVector<Instruction*, 64> Insts;
3634 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3635 AllocaInst *AI = PromotableAllocas[Idx];
3636 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3638 Instruction *I = cast<Instruction>(*UI++);
3639 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3640 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3641 // leading to them) here. Eventually it should use them to optimize the
3642 // scalar values produced.
3643 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3644 assert(onlyUsedByLifetimeMarkers(I) &&
3645 "Found a bitcast used outside of a lifetime marker.");
3646 while (!I->use_empty())
3647 cast<Instruction>(*I->use_begin())->eraseFromParent();
3648 I->eraseFromParent();
3651 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3652 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3653 II->getIntrinsicID() == Intrinsic::lifetime_end);
3654 II->eraseFromParent();
3660 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3664 PromotableAllocas.clear();
3669 /// \brief A predicate to test whether an alloca belongs to a set.
3670 class IsAllocaInSet {
3671 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3675 typedef AllocaInst *argument_type;
3677 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3678 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3682 bool SROA::runOnFunction(Function &F) {
3683 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3684 C = &F.getContext();
3685 TD = getAnalysisIfAvailable<DataLayout>();
3687 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3690 DT = getAnalysisIfAvailable<DominatorTree>();
3692 BasicBlock &EntryBB = F.getEntryBlock();
3693 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3695 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3696 Worklist.insert(AI);
3698 bool Changed = false;
3699 // A set of deleted alloca instruction pointers which should be removed from
3700 // the list of promotable allocas.
3701 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3704 while (!Worklist.empty()) {
3705 Changed |= runOnAlloca(*Worklist.pop_back_val());
3706 deleteDeadInstructions(DeletedAllocas);
3708 // Remove the deleted allocas from various lists so that we don't try to
3709 // continue processing them.
3710 if (!DeletedAllocas.empty()) {
3711 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3712 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3713 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3714 PromotableAllocas.end(),
3715 IsAllocaInSet(DeletedAllocas)),
3716 PromotableAllocas.end());
3717 DeletedAllocas.clear();
3721 Changed |= promoteAllocas(F);
3723 Worklist = PostPromotionWorklist;
3724 PostPromotionWorklist.clear();
3725 } while (!Worklist.empty());
3730 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3731 if (RequiresDomTree)
3732 AU.addRequired<DominatorTree>();
3733 AU.setPreservesCFG();