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/Constants.h"
29 #include "llvm/DIBuilder.h"
30 #include "llvm/DebugInfo.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Function.h"
33 #include "llvm/GlobalVariable.h"
34 #include "llvm/IRBuilder.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/LLVMContext.h"
38 #include "llvm/Module.h"
39 #include "llvm/Operator.h"
40 #include "llvm/Pass.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/TinyPtrVector.h"
46 #include "llvm/Analysis/Dominators.h"
47 #include "llvm/Analysis/Loads.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/ValueHandle.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetData.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
60 #include "llvm/Transforms/Utils/SSAUpdater.h"
63 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
64 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
65 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
66 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
67 STATISTIC(NumDeleted, "Number of instructions deleted");
68 STATISTIC(NumVectorized, "Number of vectorized aggregates");
71 /// \brief Alloca partitioning representation.
73 /// This class represents a partitioning of an alloca into slices, and
74 /// information about the nature of uses of each slice of the alloca. The goal
75 /// is that this information is sufficient to decide if and how to split the
76 /// alloca apart and replace slices with scalars. It is also intended that this
77 /// structure can capture the relevant information needed both to decide about
78 /// and to enact these transformations.
79 class AllocaPartitioning {
81 /// \brief A common base class for representing a half-open byte range.
83 /// \brief The beginning offset of the range.
86 /// \brief The ending offset, not included in the range.
89 ByteRange() : BeginOffset(), EndOffset() {}
90 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
91 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
93 /// \brief Support for ordering ranges.
95 /// This provides an ordering over ranges such that start offsets are
96 /// always increasing, and within equal start offsets, the end offsets are
97 /// decreasing. Thus the spanning range comes first in a cluster with the
98 /// same start position.
99 bool operator<(const ByteRange &RHS) const {
100 if (BeginOffset < RHS.BeginOffset) return true;
101 if (BeginOffset > RHS.BeginOffset) return false;
102 if (EndOffset > RHS.EndOffset) return true;
106 /// \brief Support comparison with a single offset to allow binary searches.
107 bool operator<(uint64_t RHSOffset) const {
108 return BeginOffset < RHSOffset;
111 bool operator==(const ByteRange &RHS) const {
112 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
114 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
117 /// \brief A partition of an alloca.
119 /// This structure represents a contiguous partition of the alloca. These are
120 /// formed by examining the uses of the alloca. During formation, they may
121 /// overlap but once an AllocaPartitioning is built, the Partitions within it
122 /// are all disjoint.
123 struct Partition : public ByteRange {
124 /// \brief Whether this partition is splittable into smaller partitions.
126 /// We flag partitions as splittable when they are formed entirely due to
127 /// accesses by trivially splittable operations such as memset and memcpy.
129 /// FIXME: At some point we should consider loads and stores of FCAs to be
130 /// splittable and eagerly split them into scalar values.
133 Partition() : ByteRange(), IsSplittable() {}
134 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
135 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
138 /// \brief A particular use of a partition of the alloca.
140 /// This structure is used to associate uses of a partition with it. They
141 /// mark the range of bytes which are referenced by a particular instruction,
142 /// and includes a handle to the user itself and the pointer value in use.
143 /// The bounds of these uses are determined by intersecting the bounds of the
144 /// memory use itself with a particular partition. As a consequence there is
145 /// intentionally overlap between various uses of the same partition.
146 struct PartitionUse : public ByteRange {
147 /// \brief The user of this range of the alloca.
148 AssertingVH<Instruction> User;
150 /// \brief The particular pointer value derived from this alloca in use.
151 AssertingVH<Instruction> Ptr;
153 PartitionUse() : ByteRange(), User(), Ptr() {}
154 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
155 Instruction *User, Instruction *Ptr)
156 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
159 /// \brief Construct a partitioning of a particular alloca.
161 /// Construction does most of the work for partitioning the alloca. This
162 /// performs the necessary walks of users and builds a partitioning from it.
163 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
165 /// \brief Test whether a pointer to the allocation escapes our analysis.
167 /// If this is true, the partitioning is never fully built and should be
169 bool isEscaped() const { return PointerEscapingInstr; }
171 /// \brief Support for iterating over the partitions.
173 typedef SmallVectorImpl<Partition>::iterator iterator;
174 iterator begin() { return Partitions.begin(); }
175 iterator end() { return Partitions.end(); }
177 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
178 const_iterator begin() const { return Partitions.begin(); }
179 const_iterator end() const { return Partitions.end(); }
182 /// \brief Support for iterating over and manipulating a particular
183 /// partition's uses.
185 /// The iteration support provided for uses is more limited, but also
186 /// includes some manipulation routines to support rewriting the uses of
187 /// partitions during SROA.
189 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
190 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
191 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
192 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
193 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
194 void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
195 Uses[Idx].insert(UI, U);
197 void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
198 Uses[I - begin()].insert(UI, U);
200 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
201 void use_erase(const_iterator I, use_iterator UI) {
202 Uses[I - begin()].erase(UI);
205 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
206 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
207 const_use_iterator use_begin(const_iterator I) const {
208 return Uses[I - begin()].begin();
210 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
211 const_use_iterator use_end(const_iterator I) const {
212 return Uses[I - begin()].end();
216 /// \brief Allow iterating the dead users for this alloca.
218 /// These are instructions which will never actually use the alloca as they
219 /// are outside the allocated range. They are safe to replace with undef and
222 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
223 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
224 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
227 /// \brief Allow iterating the dead expressions referring to this alloca.
229 /// These are operands which have cannot actually be used to refer to the
230 /// alloca as they are outside its range and the user doesn't correct for
231 /// that. These mostly consist of PHI node inputs and the like which we just
232 /// need to replace with undef.
234 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
235 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
236 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
239 /// \brief MemTransferInst auxiliary data.
240 /// This struct provides some auxiliary data about memory transfer
241 /// intrinsics such as memcpy and memmove. These intrinsics can use two
242 /// different ranges within the same alloca, and provide other challenges to
243 /// correctly represent. We stash extra data to help us untangle this
244 /// after the partitioning is complete.
245 struct MemTransferOffsets {
246 uint64_t DestBegin, DestEnd;
247 uint64_t SourceBegin, SourceEnd;
250 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
251 return MemTransferInstData.lookup(&II);
254 /// \brief Map from a PHI or select operand back to a partition.
256 /// When manipulating PHI nodes or selects, they can use more than one
257 /// partition of an alloca. We store a special mapping to allow finding the
258 /// partition referenced by each of these operands, if any.
259 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
260 SmallDenseMap<std::pair<Instruction *, Value *>,
261 std::pair<unsigned, unsigned> >::const_iterator MapIt
262 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
263 if (MapIt == PHIOrSelectOpMap.end())
266 return begin() + MapIt->second.first;
269 /// \brief Map from a PHI or select operand back to the specific use of
272 /// Similar to mapping these operands back to the partitions, this maps
273 /// directly to the use structure of that partition.
274 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
276 SmallDenseMap<std::pair<Instruction *, Value *>,
277 std::pair<unsigned, unsigned> >::const_iterator MapIt
278 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
279 assert(MapIt != PHIOrSelectOpMap.end());
280 return Uses[MapIt->second.first].begin() + MapIt->second.second;
283 /// \brief Compute a common type among the uses of a particular partition.
285 /// This routines walks all of the uses of a particular partition and tries
286 /// to find a common type between them. Untyped operations such as memset and
287 /// memcpy are ignored.
288 Type *getCommonType(iterator I) const;
290 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
291 void printUsers(raw_ostream &OS, const_iterator I,
292 StringRef Indent = " ") const;
293 void print(raw_ostream &OS) const;
294 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
295 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
298 template <typename DerivedT, typename RetT = void> class BuilderBase;
299 class PartitionBuilder;
300 friend class AllocaPartitioning::PartitionBuilder;
302 friend class AllocaPartitioning::UseBuilder;
304 /// \brief Handle to alloca instruction to simplify method interfaces.
307 /// \brief The instruction responsible for this alloca having no partitioning.
309 /// When an instruction (potentially) escapes the pointer to the alloca, we
310 /// store a pointer to that here and abort trying to partition the alloca.
311 /// This will be null if the alloca is partitioned successfully.
312 Instruction *PointerEscapingInstr;
314 /// \brief The partitions of the alloca.
316 /// We store a vector of the partitions over the alloca here. This vector is
317 /// sorted by increasing begin offset, and then by decreasing end offset. See
318 /// the Partition inner class for more details. Initially (during
319 /// construction) there are overlaps, but we form a disjoint sequence of
320 /// partitions while finishing construction and a fully constructed object is
321 /// expected to always have this as a disjoint space.
322 SmallVector<Partition, 8> Partitions;
324 /// \brief The uses of the partitions.
326 /// This is essentially a mapping from each partition to a list of uses of
327 /// that partition. The mapping is done with a Uses vector that has the exact
328 /// same number of entries as the partition vector. Each entry is itself
329 /// a vector of the uses.
330 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
332 /// \brief Instructions which will become dead if we rewrite the alloca.
334 /// Note that these are not separated by partition. This is because we expect
335 /// a partitioned alloca to be completely rewritten or not rewritten at all.
336 /// If rewritten, all these instructions can simply be removed and replaced
337 /// with undef as they come from outside of the allocated space.
338 SmallVector<Instruction *, 8> DeadUsers;
340 /// \brief Operands which will become dead if we rewrite the alloca.
342 /// These are operands that in their particular use can be replaced with
343 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
344 /// to PHI nodes and the like. They aren't entirely dead (there might be
345 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
346 /// want to swap this particular input for undef to simplify the use lists of
348 SmallVector<Use *, 8> DeadOperands;
350 /// \brief The underlying storage for auxiliary memcpy and memset info.
351 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
353 /// \brief A side datastructure used when building up the partitions and uses.
355 /// This mapping is only really used during the initial building of the
356 /// partitioning so that we can retain information about PHI and select nodes
358 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
360 /// \brief Auxiliary information for particular PHI or select operands.
361 SmallDenseMap<std::pair<Instruction *, Value *>,
362 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
364 /// \brief A utility routine called from the constructor.
366 /// This does what it says on the tin. It is the key of the alloca partition
367 /// splitting and merging. After it is called we have the desired disjoint
368 /// collection of partitions.
369 void splitAndMergePartitions();
373 template <typename DerivedT, typename RetT>
374 class AllocaPartitioning::BuilderBase
375 : public InstVisitor<DerivedT, RetT> {
377 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
379 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
385 const TargetData &TD;
386 const uint64_t AllocSize;
387 AllocaPartitioning &P;
393 SmallVector<OffsetUse, 8> Queue;
395 // The active offset and use while visiting.
399 void enqueueUsers(Instruction &I, uint64_t UserOffset) {
400 SmallPtrSet<User *, 8> UserSet;
401 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
403 if (!UserSet.insert(*UI))
406 OffsetUse OU = { &UI.getUse(), UserOffset };
411 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, uint64_t &GEPOffset) {
413 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
415 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
421 // Handle a struct index, which adds its field offset to the pointer.
422 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
423 unsigned ElementIdx = OpC->getZExtValue();
424 const StructLayout *SL = TD.getStructLayout(STy);
425 GEPOffset += SL->getElementOffset(ElementIdx);
430 += OpC->getZExtValue() * TD.getTypeAllocSize(GTI.getIndexedType());
435 Value *foldSelectInst(SelectInst &SI) {
436 // If the condition being selected on is a constant or the same value is
437 // being selected between, fold the select. Yes this does (rarely) happen
439 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
440 return SI.getOperand(1+CI->isZero());
441 if (SI.getOperand(1) == SI.getOperand(2)) {
442 assert(*U == SI.getOperand(1));
443 return SI.getOperand(1);
449 /// \brief Builder for the alloca partitioning.
451 /// This class builds an alloca partitioning by recursively visiting the uses
452 /// of an alloca and splitting the partitions for each load and store at each
454 class AllocaPartitioning::PartitionBuilder
455 : public BuilderBase<PartitionBuilder, bool> {
456 friend class InstVisitor<PartitionBuilder, bool>;
458 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
461 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
462 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
464 /// \brief Run the builder over the allocation.
466 // Note that we have to re-evaluate size on each trip through the loop as
467 // the queue grows at the tail.
468 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
470 Offset = Queue[Idx].Offset;
471 if (!visit(cast<Instruction>(U->getUser())))
478 bool markAsEscaping(Instruction &I) {
479 P.PointerEscapingInstr = &I;
483 void insertUse(Instruction &I, uint64_t Size, bool IsSplittable = false) {
484 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
486 // Completely skip uses which start outside of the allocation.
487 if (BeginOffset >= AllocSize) {
488 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
489 << " which starts past the end of the " << AllocSize
491 << " alloca: " << P.AI << "\n"
492 << " use: " << I << "\n");
496 // Clamp the size to the allocation.
497 if (EndOffset > AllocSize) {
498 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
499 << " to remain within the " << AllocSize << " byte alloca:\n"
500 << " alloca: " << P.AI << "\n"
501 << " use: " << I << "\n");
502 EndOffset = AllocSize;
505 // See if we can just add a user onto the last slot currently occupied.
506 if (!P.Partitions.empty() &&
507 P.Partitions.back().BeginOffset == BeginOffset &&
508 P.Partitions.back().EndOffset == EndOffset) {
509 P.Partitions.back().IsSplittable &= IsSplittable;
513 Partition New(BeginOffset, EndOffset, IsSplittable);
514 P.Partitions.push_back(New);
517 bool handleLoadOrStore(Type *Ty, Instruction &I) {
518 uint64_t Size = TD.getTypeStoreSize(Ty);
520 // If this memory access can be shown to *statically* extend outside the
521 // bounds of of the allocation, it's behavior is undefined, so simply
522 // ignore it. Note that this is more strict than the generic clamping
523 // behavior of insertUse. We also try to handle cases which might run the
525 // FIXME: We should instead consider the pointer to have escaped if this
526 // function is being instrumented for addressing bugs or race conditions.
527 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
528 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
529 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
530 << " which extends past the end of the " << AllocSize
532 << " alloca: " << P.AI << "\n"
533 << " use: " << I << "\n");
541 bool visitBitCastInst(BitCastInst &BC) {
542 enqueueUsers(BC, Offset);
546 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
547 //unsigned IntPtrWidth = TD->getPointerSizeInBits();
548 //assert(IntPtrWidth == Offset.getBitWidth());
550 if (!computeConstantGEPOffset(GEPI, GEPOffset))
551 return markAsEscaping(GEPI);
553 enqueueUsers(GEPI, GEPOffset);
557 bool visitLoadInst(LoadInst &LI) {
558 return handleLoadOrStore(LI.getType(), LI);
561 bool visitStoreInst(StoreInst &SI) {
562 if (SI.getOperand(0) == *U)
563 return markAsEscaping(SI);
565 return handleLoadOrStore(SI.getOperand(0)->getType(), SI);
569 bool visitMemSetInst(MemSetInst &II) {
570 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
571 insertUse(II, Length ? Length->getZExtValue() : AllocSize - Offset, Length);
575 bool visitMemTransferInst(MemTransferInst &II) {
576 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
577 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
579 // Zero-length mem transfer intrinsics can be ignored entirely.
582 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
584 // Only intrinsics with a constant length can be split.
585 Offsets.IsSplittable = Length;
587 if (*U != II.getRawDest()) {
588 assert(*U == II.getRawSource());
589 Offsets.SourceBegin = Offset;
590 Offsets.SourceEnd = Offset + Size;
592 Offsets.DestBegin = Offset;
593 Offsets.DestEnd = Offset + Size;
596 insertUse(II, Size, Offsets.IsSplittable);
597 unsigned NewIdx = P.Partitions.size() - 1;
599 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
600 bool Inserted = false;
601 llvm::tie(PMI, Inserted)
602 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
603 if (!Inserted && Offsets.IsSplittable) {
604 // We've found a memory transfer intrinsic which refers to the alloca as
605 // both a source and dest. We refuse to split these to simplify splitting
606 // logic. If possible, SROA will still split them into separate allocas
607 // and then re-analyze.
608 Offsets.IsSplittable = false;
609 P.Partitions[PMI->second].IsSplittable = false;
610 P.Partitions[NewIdx].IsSplittable = false;
616 // Disable SRoA for any intrinsics except for lifetime invariants.
617 bool visitIntrinsicInst(IntrinsicInst &II) {
618 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
619 II.getIntrinsicID() == Intrinsic::lifetime_end) {
620 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
621 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
622 insertUse(II, Size, true);
626 return markAsEscaping(II);
629 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
630 // We consider any PHI or select that results in a direct load or store of
631 // the same offset to be a viable use for partitioning purposes. These uses
632 // are considered unsplittable and the size is the maximum loaded or stored
634 SmallPtrSet<Instruction *, 4> Visited;
635 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
636 Visited.insert(Root);
637 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
639 Instruction *I, *UsedI;
640 llvm::tie(UsedI, I) = Uses.pop_back_val();
642 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
643 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
646 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
647 Value *Op = SI->getOperand(0);
650 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
654 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
655 if (!GEP->hasAllZeroIndices())
657 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
658 !isa<SelectInst>(I)) {
662 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
664 if (Visited.insert(cast<Instruction>(*UI)))
665 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
666 } while (!Uses.empty());
671 bool visitPHINode(PHINode &PN) {
672 // See if we already have computed info on this node.
673 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
675 PHIInfo.second = true;
676 insertUse(PN, PHIInfo.first);
680 // Check for an unsafe use of the PHI node.
681 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
682 return markAsEscaping(*EscapingI);
684 insertUse(PN, PHIInfo.first);
688 bool visitSelectInst(SelectInst &SI) {
689 if (Value *Result = foldSelectInst(SI)) {
691 // If the result of the constant fold will be the pointer, recurse
692 // through the select as if we had RAUW'ed it.
693 enqueueUsers(SI, Offset);
698 // See if we already have computed info on this node.
699 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
700 if (SelectInfo.first) {
701 SelectInfo.second = true;
702 insertUse(SI, SelectInfo.first);
706 // Check for an unsafe use of the PHI node.
707 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
708 return markAsEscaping(*EscapingI);
710 insertUse(SI, SelectInfo.first);
714 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
715 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
719 /// \brief Use adder for the alloca partitioning.
721 /// This class adds the uses of an alloca to all of the partitions which they
722 /// use. For splittable partitions, this can end up doing essentially a linear
723 /// walk of the partitions, but the number of steps remains bounded by the
724 /// total result instruction size:
725 /// - The number of partitions is a result of the number unsplittable
726 /// instructions using the alloca.
727 /// - The number of users of each partition is at worst the total number of
728 /// splittable instructions using the alloca.
729 /// Thus we will produce N * M instructions in the end, where N are the number
730 /// of unsplittable uses and M are the number of splittable. This visitor does
731 /// the exact same number of updates to the partitioning.
733 /// In the more common case, this visitor will leverage the fact that the
734 /// partition space is pre-sorted, and do a logarithmic search for the
735 /// partition needed, making the total visit a classical ((N + M) * log(N))
736 /// complexity operation.
737 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
738 friend class InstVisitor<UseBuilder>;
740 /// \brief Set to de-duplicate dead instructions found in the use walk.
741 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
744 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
745 : BuilderBase<UseBuilder>(TD, AI, P) {}
747 /// \brief Run the builder over the allocation.
749 // Note that we have to re-evaluate size on each trip through the loop as
750 // the queue grows at the tail.
751 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
753 Offset = Queue[Idx].Offset;
754 this->visit(cast<Instruction>(U->getUser()));
759 void markAsDead(Instruction &I) {
760 if (VisitedDeadInsts.insert(&I))
761 P.DeadUsers.push_back(&I);
764 void insertUse(uint64_t Size, Instruction &User) {
765 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
767 // If the use extends outside of the allocation, record it as a dead use
768 // for elimination later.
769 if (BeginOffset >= AllocSize || Size == 0)
770 return markAsDead(User);
772 // Bound the use by the size of the allocation.
773 if (EndOffset > AllocSize)
774 EndOffset = AllocSize;
776 // NB: This only works if we have zero overlapping partitions.
777 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
778 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
780 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
782 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
783 std::min(I->EndOffset, EndOffset),
784 &User, cast<Instruction>(*U));
785 P.Uses[I - P.begin()].push_back(NewUse);
786 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
787 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
788 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
792 void handleLoadOrStore(Type *Ty, Instruction &I) {
793 uint64_t Size = TD.getTypeStoreSize(Ty);
795 // If this memory access can be shown to *statically* extend outside the
796 // bounds of of the allocation, it's behavior is undefined, so simply
797 // ignore it. Note that this is more strict than the generic clamping
798 // behavior of insertUse.
799 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
800 return markAsDead(I);
805 void visitBitCastInst(BitCastInst &BC) {
807 return markAsDead(BC);
809 enqueueUsers(BC, Offset);
812 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
813 if (GEPI.use_empty())
814 return markAsDead(GEPI);
816 //unsigned IntPtrWidth = TD->getPointerSizeInBits();
817 //assert(IntPtrWidth == Offset.getBitWidth());
819 if (!computeConstantGEPOffset(GEPI, GEPOffset))
820 llvm_unreachable("Unable to compute constant offset for use");
822 enqueueUsers(GEPI, GEPOffset);
825 void visitLoadInst(LoadInst &LI) {
826 handleLoadOrStore(LI.getType(), LI);
829 void visitStoreInst(StoreInst &SI) {
830 handleLoadOrStore(SI.getOperand(0)->getType(), SI);
833 void visitMemSetInst(MemSetInst &II) {
834 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
835 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
838 void visitMemTransferInst(MemTransferInst &II) {
839 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
840 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
843 void visitIntrinsicInst(IntrinsicInst &II) {
844 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
845 II.getIntrinsicID() == Intrinsic::lifetime_end);
847 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
848 insertUse(std::min(AllocSize - Offset, Length->getLimitedValue()), II);
851 void insertPHIOrSelect(Instruction &User) {
852 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
854 // For PHI and select operands outside the alloca, we can't nuke the entire
855 // phi or select -- the other side might still be relevant, so we special
856 // case them here and use a separate structure to track the operands
857 // themselves which should be replaced with undef.
858 if (Offset >= AllocSize) {
859 P.DeadOperands.push_back(U);
863 insertUse(Size, User);
865 void visitPHINode(PHINode &PN) {
867 return markAsDead(PN);
869 insertPHIOrSelect(PN);
871 void visitSelectInst(SelectInst &SI) {
873 return markAsDead(SI);
875 if (Value *Result = foldSelectInst(SI)) {
877 // If the result of the constant fold will be the pointer, recurse
878 // through the select as if we had RAUW'ed it.
879 enqueueUsers(SI, Offset);
884 insertPHIOrSelect(SI);
887 /// \brief Unreachable, we've already visited the alloca once.
888 void visitInstruction(Instruction &I) {
889 llvm_unreachable("Unhandled instruction in use builder.");
893 void AllocaPartitioning::splitAndMergePartitions() {
894 size_t NumDeadPartitions = 0;
896 // Track the range of splittable partitions that we pass when accumulating
897 // overlapping unsplittable partitions.
898 uint64_t SplitEndOffset = 0ull;
900 Partition New(0ull, 0ull, false);
902 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
905 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
906 assert(New.BeginOffset == New.EndOffset);
909 assert(New.IsSplittable);
910 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
912 assert(New.BeginOffset != New.EndOffset);
914 // Scan the overlapping partitions.
915 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
916 // If the new partition we are forming is splittable, stop at the first
917 // unsplittable partition.
918 if (New.IsSplittable && !Partitions[j].IsSplittable)
921 // Grow the new partition to include any equally splittable range. 'j' is
922 // always equally splittable when New is splittable, but when New is not
923 // splittable, we may subsume some (or part of some) splitable partition
924 // without growing the new one.
925 if (New.IsSplittable == Partitions[j].IsSplittable) {
926 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
928 assert(!New.IsSplittable);
929 assert(Partitions[j].IsSplittable);
930 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
933 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
938 // If the new partition is splittable, chop off the end as soon as the
939 // unsplittable subsequent partition starts and ensure we eventually cover
940 // the splittable area.
941 if (j != e && New.IsSplittable) {
942 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
943 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
946 // Add the new partition if it differs from the original one and is
947 // non-empty. We can end up with an empty partition here if it was
948 // splittable but there is an unsplittable one that starts at the same
950 if (New != Partitions[i]) {
951 if (New.BeginOffset != New.EndOffset)
952 Partitions.push_back(New);
953 // Mark the old one for removal.
954 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
958 New.BeginOffset = New.EndOffset;
959 if (!New.IsSplittable) {
960 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
961 if (j != e && !Partitions[j].IsSplittable)
962 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
963 New.IsSplittable = true;
964 // If there is a trailing splittable partition which won't be fused into
965 // the next splittable partition go ahead and add it onto the partitions
967 if (New.BeginOffset < New.EndOffset &&
968 (j == e || !Partitions[j].IsSplittable ||
969 New.EndOffset < Partitions[j].BeginOffset)) {
970 Partitions.push_back(New);
971 New.BeginOffset = New.EndOffset = 0ull;
976 // Re-sort the partitions now that they have been split and merged into
977 // disjoint set of partitions. Also remove any of the dead partitions we've
978 // replaced in the process.
979 std::sort(Partitions.begin(), Partitions.end());
980 if (NumDeadPartitions) {
981 assert(Partitions.back().BeginOffset == UINT64_MAX);
982 assert(Partitions.back().EndOffset == UINT64_MAX);
983 assert((ptrdiff_t)NumDeadPartitions ==
984 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
986 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
989 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
990 : AI(AI), PointerEscapingInstr(0) {
991 PartitionBuilder PB(TD, AI, *this);
995 if (Partitions.size() > 1) {
996 // Sort the uses. This arranges for the offsets to be in ascending order,
997 // and the sizes to be in descending order.
998 std::sort(Partitions.begin(), Partitions.end());
1000 // Intersect splittability for all partitions with equal offsets and sizes.
1001 // Then remove all but the first so that we have a sequence of non-equal but
1002 // potentially overlapping partitions.
1003 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1006 while (J != E && *I == *J) {
1007 I->IsSplittable &= J->IsSplittable;
1011 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1014 // Split splittable and merge unsplittable partitions into a disjoint set
1015 // of partitions over the used space of the allocation.
1016 splitAndMergePartitions();
1019 // Now build up the user lists for each of these disjoint partitions by
1020 // re-walking the recursive users of the alloca.
1021 Uses.resize(Partitions.size());
1022 UseBuilder UB(TD, AI, *this);
1024 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1025 std::stable_sort(use_begin(I), use_end(I));
1028 Type *AllocaPartitioning::getCommonType(iterator I) const {
1030 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1031 if (isa<MemIntrinsic>(*UI->User))
1033 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1037 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1038 UserTy = LI->getType();
1039 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1040 UserTy = SI->getValueOperand()->getType();
1041 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1042 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1043 UserTy = PtrTy->getElementType();
1044 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1045 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1046 UserTy = PtrTy->getElementType();
1049 if (Ty && Ty != UserTy)
1057 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1058 StringRef Indent) const {
1059 OS << Indent << "partition #" << (I - begin())
1060 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1061 << (I->IsSplittable ? " (splittable)" : "")
1062 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1066 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1067 StringRef Indent) const {
1068 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1070 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1071 << "used by: " << *UI->User << "\n";
1072 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1073 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1075 if (!MTO.IsSplittable)
1076 IsDest = UI->BeginOffset == MTO.DestBegin;
1078 IsDest = MTO.DestBegin != 0u;
1079 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1080 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1081 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1086 void AllocaPartitioning::print(raw_ostream &OS) const {
1087 if (PointerEscapingInstr) {
1088 OS << "No partitioning for alloca: " << AI << "\n"
1089 << " A pointer to this alloca escaped by:\n"
1090 << " " << *PointerEscapingInstr << "\n";
1094 OS << "Partitioning of alloca: " << AI << "\n";
1096 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1102 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1103 void AllocaPartitioning::dump() const { print(dbgs()); }
1107 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1109 /// This pass takes allocations which can be completely analyzed (that is, they
1110 /// don't escape) and tries to turn them into scalar SSA values. There are
1111 /// a few steps to this process.
1113 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1114 /// are used to try to split them into smaller allocations, ideally of
1115 /// a single scalar data type. It will split up memcpy and memset accesses
1116 /// as necessary and try to isolate invidual scalar accesses.
1117 /// 2) It will transform accesses into forms which are suitable for SSA value
1118 /// promotion. This can be replacing a memset with a scalar store of an
1119 /// integer value, or it can involve speculating operations on a PHI or
1120 /// select to be a PHI or select of the results.
1121 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1122 /// onto insert and extract operations on a vector value, and convert them to
1123 /// this form. By doing so, it will enable promotion of vector aggregates to
1124 /// SSA vector values.
1125 class SROA : public FunctionPass {
1127 const TargetData *TD;
1130 /// \brief Worklist of alloca instructions to simplify.
1132 /// Each alloca in the function is added to this. Each new alloca formed gets
1133 /// added to it as well to recursively simplify unless that alloca can be
1134 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1135 /// the one being actively rewritten, we add it back onto the list if not
1136 /// already present to ensure it is re-visited.
1137 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1139 /// \brief A collection of instructions to delete.
1140 /// We try to batch deletions to simplify code and make things a bit more
1142 SmallVector<Instruction *, 8> DeadInsts;
1144 /// \brief A set to prevent repeatedly marking an instruction split into many
1145 /// uses as dead. Only used to guard insertion into DeadInsts.
1146 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1148 /// \brief A set of deleted alloca instructions.
1150 /// These pointers are *no longer valid* as they have been deleted. They are
1151 /// used to remove deleted allocas from the list of promotable allocas.
1152 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
1154 /// \brief A collection of alloca instructions we can directly promote.
1155 std::vector<AllocaInst *> PromotableAllocas;
1158 SROA() : FunctionPass(ID), C(0), TD(0), DT(0) {
1159 initializeSROAPass(*PassRegistry::getPassRegistry());
1161 bool runOnFunction(Function &F);
1162 void getAnalysisUsage(AnalysisUsage &AU) const;
1164 const char *getPassName() const { return "SROA"; }
1168 friend class AllocaPartitionRewriter;
1169 friend class AllocaPartitionVectorRewriter;
1171 bool rewriteAllocaPartition(AllocaInst &AI,
1172 AllocaPartitioning &P,
1173 AllocaPartitioning::iterator PI);
1174 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1175 bool runOnAlloca(AllocaInst &AI);
1176 void deleteDeadInstructions();
1182 FunctionPass *llvm::createSROAPass() {
1186 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1188 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1189 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1192 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1194 /// If the provided GEP is all-constant, the total byte offset formed by the
1195 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1196 /// operands, the function returns false and the value of Offset is unmodified.
1197 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1199 APInt GEPOffset(Offset.getBitWidth(), 0);
1200 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1201 GTI != GTE; ++GTI) {
1202 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1205 if (OpC->isZero()) continue;
1207 // Handle a struct index, which adds its field offset to the pointer.
1208 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1209 unsigned ElementIdx = OpC->getZExtValue();
1210 const StructLayout *SL = TD.getStructLayout(STy);
1211 GEPOffset += APInt(Offset.getBitWidth(),
1212 SL->getElementOffset(ElementIdx));
1216 APInt TypeSize(Offset.getBitWidth(),
1217 TD.getTypeAllocSize(GTI.getIndexedType()));
1218 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1219 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1220 "vector element size is not a multiple of 8, cannot GEP over it");
1221 TypeSize = VTy->getScalarSizeInBits() / 8;
1224 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1230 /// \brief Build a GEP out of a base pointer and indices.
1232 /// This will return the BasePtr if that is valid, or build a new GEP
1233 /// instruction using the IRBuilder if GEP-ing is needed.
1234 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1235 SmallVectorImpl<Value *> &Indices,
1236 const Twine &Prefix) {
1237 if (Indices.empty())
1240 // A single zero index is a no-op, so check for this and avoid building a GEP
1242 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1245 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1248 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1249 /// TargetTy without changing the offset of the pointer.
1251 /// This routine assumes we've already established a properly offset GEP with
1252 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1253 /// zero-indices down through type layers until we find one the same as
1254 /// TargetTy. If we can't find one with the same type, we at least try to use
1255 /// one with the same size. If none of that works, we just produce the GEP as
1256 /// indicated by Indices to have the correct offset.
1257 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1258 Value *BasePtr, Type *Ty, Type *TargetTy,
1259 SmallVectorImpl<Value *> &Indices,
1260 const Twine &Prefix) {
1262 return buildGEP(IRB, BasePtr, Indices, Prefix);
1264 // See if we can descend into a struct and locate a field with the correct
1266 unsigned NumLayers = 0;
1267 Type *ElementTy = Ty;
1269 if (ElementTy->isPointerTy())
1271 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1272 ElementTy = SeqTy->getElementType();
1273 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1274 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1275 ElementTy = *STy->element_begin();
1276 Indices.push_back(IRB.getInt32(0));
1281 } while (ElementTy != TargetTy);
1282 if (ElementTy != TargetTy)
1283 Indices.erase(Indices.end() - NumLayers, Indices.end());
1285 return buildGEP(IRB, BasePtr, Indices, Prefix);
1288 /// \brief Recursively compute indices for a natural GEP.
1290 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1291 /// element types adding appropriate indices for the GEP.
1292 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1293 Value *Ptr, Type *Ty, APInt &Offset,
1295 SmallVectorImpl<Value *> &Indices,
1296 const Twine &Prefix) {
1298 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1300 // We can't recurse through pointer types.
1301 if (Ty->isPointerTy())
1304 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1305 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1306 if (ElementSizeInBits % 8)
1307 return 0; // GEPs over multiple of 8 size vector elements are invalid.
1308 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1309 APInt NumSkippedElements = Offset.udiv(ElementSize);
1310 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1312 Offset -= NumSkippedElements * ElementSize;
1313 Indices.push_back(IRB.getInt(NumSkippedElements));
1314 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1315 Offset, TargetTy, Indices, Prefix);
1318 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1319 Type *ElementTy = ArrTy->getElementType();
1320 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1321 APInt NumSkippedElements = Offset.udiv(ElementSize);
1322 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1325 Offset -= NumSkippedElements * ElementSize;
1326 Indices.push_back(IRB.getInt(NumSkippedElements));
1327 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1331 StructType *STy = dyn_cast<StructType>(Ty);
1335 const StructLayout *SL = TD.getStructLayout(STy);
1336 uint64_t StructOffset = Offset.getZExtValue();
1337 if (StructOffset > SL->getSizeInBytes())
1339 unsigned Index = SL->getElementContainingOffset(StructOffset);
1340 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1341 Type *ElementTy = STy->getElementType(Index);
1342 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1343 return 0; // The offset points into alignment padding.
1345 Indices.push_back(IRB.getInt32(Index));
1346 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1350 /// \brief Get a natural GEP from a base pointer to a particular offset and
1351 /// resulting in a particular type.
1353 /// The goal is to produce a "natural" looking GEP that works with the existing
1354 /// composite types to arrive at the appropriate offset and element type for
1355 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1356 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1357 /// Indices, and setting Ty to the result subtype.
1359 /// If no natural GEP can be constructed, this function returns null.
1360 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1361 Value *Ptr, APInt Offset, Type *TargetTy,
1362 SmallVectorImpl<Value *> &Indices,
1363 const Twine &Prefix) {
1364 PointerType *Ty = cast<PointerType>(Ptr->getType());
1366 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1368 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1371 Type *ElementTy = Ty->getElementType();
1372 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1373 if (ElementSize == 0)
1374 return 0; // Zero-length arrays can't help us build a natural GEP.
1375 APInt NumSkippedElements = Offset.udiv(ElementSize);
1377 Offset -= NumSkippedElements * ElementSize;
1378 Indices.push_back(IRB.getInt(NumSkippedElements));
1379 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1383 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1384 /// resulting pointer has PointerTy.
1386 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1387 /// and produces the pointer type desired. Where it cannot, it will try to use
1388 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1389 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1390 /// bitcast to the type.
1392 /// The strategy for finding the more natural GEPs is to peel off layers of the
1393 /// pointer, walking back through bit casts and GEPs, searching for a base
1394 /// pointer from which we can compute a natural GEP with the desired
1395 /// properities. The algorithm tries to fold as many constant indices into
1396 /// a single GEP as possible, thus making each GEP more independent of the
1397 /// surrounding code.
1398 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1399 Value *Ptr, APInt Offset, Type *PointerTy,
1400 const Twine &Prefix) {
1401 // Even though we don't look through PHI nodes, we could be called on an
1402 // instruction in an unreachable block, which may be on a cycle.
1403 SmallPtrSet<Value *, 4> Visited;
1404 Visited.insert(Ptr);
1405 SmallVector<Value *, 4> Indices;
1407 // We may end up computing an offset pointer that has the wrong type. If we
1408 // never are able to compute one directly that has the correct type, we'll
1409 // fall back to it, so keep it around here.
1410 Value *OffsetPtr = 0;
1412 // Remember any i8 pointer we come across to re-use if we need to do a raw
1415 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1417 Type *TargetTy = PointerTy->getPointerElementType();
1420 // First fold any existing GEPs into the offset.
1421 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1422 APInt GEPOffset(Offset.getBitWidth(), 0);
1423 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1425 Offset += GEPOffset;
1426 Ptr = GEP->getPointerOperand();
1427 if (!Visited.insert(Ptr))
1431 // See if we can perform a natural GEP here.
1433 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1435 if (P->getType() == PointerTy) {
1436 // Zap any offset pointer that we ended up computing in previous rounds.
1437 if (OffsetPtr && OffsetPtr->use_empty())
1438 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1439 I->eraseFromParent();
1447 // Stash this pointer if we've found an i8*.
1448 if (Ptr->getType()->isIntegerTy(8)) {
1450 Int8PtrOffset = Offset;
1453 // Peel off a layer of the pointer and update the offset appropriately.
1454 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1455 Ptr = cast<Operator>(Ptr)->getOperand(0);
1456 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1457 if (GA->mayBeOverridden())
1459 Ptr = GA->getAliasee();
1463 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1464 } while (Visited.insert(Ptr));
1468 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1469 Prefix + ".raw_cast");
1470 Int8PtrOffset = Offset;
1473 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1474 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1475 Prefix + ".raw_idx");
1479 // On the off chance we were targeting i8*, guard the bitcast here.
1480 if (Ptr->getType() != PointerTy)
1481 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1486 /// \brief Test whether the given alloca partition can be promoted to a vector.
1488 /// This is a quick test to check whether we can rewrite a particular alloca
1489 /// partition (and its newly formed alloca) into a vector alloca with only
1490 /// whole-vector loads and stores such that it could be promoted to a vector
1491 /// SSA value. We only can ensure this for a limited set of operations, and we
1492 /// don't want to do the rewrites unless we are confident that the result will
1493 /// be promotable, so we have an early test here.
1494 static bool isVectorPromotionViable(const TargetData &TD,
1496 AllocaPartitioning &P,
1497 uint64_t PartitionBeginOffset,
1498 uint64_t PartitionEndOffset,
1499 AllocaPartitioning::const_use_iterator I,
1500 AllocaPartitioning::const_use_iterator E) {
1501 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1505 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1506 uint64_t ElementSize = Ty->getScalarSizeInBits();
1508 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1509 // that aren't byte sized.
1510 if (ElementSize % 8)
1512 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1516 for (; I != E; ++I) {
1517 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1518 uint64_t BeginIndex = BeginOffset / ElementSize;
1519 if (BeginIndex * ElementSize != BeginOffset ||
1520 BeginIndex >= Ty->getNumElements())
1522 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1523 uint64_t EndIndex = EndOffset / ElementSize;
1524 if (EndIndex * ElementSize != EndOffset ||
1525 EndIndex > Ty->getNumElements())
1528 // FIXME: We should build shuffle vector instructions to handle
1529 // non-element-sized accesses.
1530 if ((EndOffset - BeginOffset) != ElementSize &&
1531 (EndOffset - BeginOffset) != VecSize)
1534 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1535 if (MI->isVolatile())
1537 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1538 const AllocaPartitioning::MemTransferOffsets &MTO
1539 = P.getMemTransferOffsets(*MTI);
1540 if (!MTO.IsSplittable)
1543 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1544 // Disable vector promotion when there are loads or stores of an FCA.
1546 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1554 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1555 /// use a new alloca.
1557 /// Also implements the rewriting to vector-based accesses when the partition
1558 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1560 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1562 // Befriend the base class so it can delegate to private visit methods.
1563 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1565 const TargetData &TD;
1566 AllocaPartitioning &P;
1568 AllocaInst &OldAI, &NewAI;
1569 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1571 // If we are rewriting an alloca partition which can be written as pure
1572 // vector operations, we stash extra information here. When VecTy is
1573 // non-null, we have some strict guarantees about the rewriten alloca:
1574 // - The new alloca is exactly the size of the vector type here.
1575 // - The accesses all either map to the entire vector or to a single
1577 // - The set of accessing instructions is only one of those handled above
1578 // in isVectorPromotionViable. Generally these are the same access kinds
1579 // which are promotable via mem2reg.
1582 uint64_t ElementSize;
1584 // The offset of the partition user currently being rewritten.
1585 uint64_t BeginOffset, EndOffset;
1586 Instruction *OldPtr;
1588 // The name prefix to use when rewriting instructions for this alloca.
1589 std::string NamePrefix;
1592 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1593 AllocaPartitioning::iterator PI,
1594 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1595 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1596 : TD(TD), P(P), Pass(Pass),
1597 OldAI(OldAI), NewAI(NewAI),
1598 NewAllocaBeginOffset(NewBeginOffset),
1599 NewAllocaEndOffset(NewEndOffset),
1600 VecTy(), ElementTy(), ElementSize(),
1601 BeginOffset(), EndOffset() {
1604 /// \brief Visit the users of the alloca partition and rewrite them.
1605 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1606 AllocaPartitioning::const_use_iterator E) {
1607 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1608 NewAllocaBeginOffset, NewAllocaEndOffset,
1611 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1612 ElementTy = VecTy->getElementType();
1613 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1614 "Only multiple-of-8 sized vector elements are viable");
1615 ElementSize = VecTy->getScalarSizeInBits() / 8;
1617 bool CanSROA = true;
1618 for (; I != E; ++I) {
1619 BeginOffset = I->BeginOffset;
1620 EndOffset = I->EndOffset;
1622 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1623 CanSROA &= visit(I->User);
1635 // Every instruction which can end up as a user must have a rewrite rule.
1636 bool visitInstruction(Instruction &I) {
1637 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1638 llvm_unreachable("No rewrite rule for this instruction!");
1641 Twine getName(const Twine &Suffix) {
1642 return NamePrefix + Suffix;
1645 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1646 assert(BeginOffset >= NewAllocaBeginOffset);
1647 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1648 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1651 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1652 assert(VecTy && "Can only call getIndex when rewriting a vector");
1653 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1654 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1655 uint32_t Index = RelOffset / ElementSize;
1656 assert(Index * ElementSize == RelOffset);
1657 return IRB.getInt32(Index);
1660 void deleteIfTriviallyDead(Value *V) {
1661 Instruction *I = cast<Instruction>(V);
1662 if (isInstructionTriviallyDead(I))
1663 Pass.DeadInsts.push_back(I);
1666 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1667 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1668 return IRB.CreateIntToPtr(V, Ty);
1669 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1670 return IRB.CreatePtrToInt(V, Ty);
1672 return IRB.CreateBitCast(V, Ty);
1675 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1677 if (LI.getType() == VecTy->getElementType() ||
1678 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1680 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1681 getIndex(IRB, BeginOffset),
1682 getName(".extract"));
1684 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1686 if (Result->getType() != LI.getType())
1687 Result = getValueCast(IRB, Result, LI.getType());
1688 LI.replaceAllUsesWith(Result);
1689 Pass.DeadInsts.push_back(&LI);
1691 DEBUG(dbgs() << " to: " << *Result << "\n");
1695 bool visitLoadInst(LoadInst &LI) {
1696 DEBUG(dbgs() << " original: " << LI << "\n");
1697 Value *OldOp = LI.getOperand(0);
1698 assert(OldOp == OldPtr);
1699 IRBuilder<> IRB(&LI);
1702 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1704 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1705 LI.getPointerOperand()->getType());
1706 LI.setOperand(0, NewPtr);
1707 DEBUG(dbgs() << " to: " << LI << "\n");
1709 deleteIfTriviallyDead(OldOp);
1710 return NewPtr == &NewAI && !LI.isVolatile();
1713 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1715 Value *V = SI.getValueOperand();
1716 if (V->getType() == ElementTy ||
1717 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1718 if (V->getType() != ElementTy)
1719 V = getValueCast(IRB, V, ElementTy);
1720 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1721 getIndex(IRB, BeginOffset),
1722 getName(".insert"));
1723 } else if (V->getType() != VecTy) {
1724 V = getValueCast(IRB, V, VecTy);
1726 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1727 Pass.DeadInsts.push_back(&SI);
1730 DEBUG(dbgs() << " to: " << *Store << "\n");
1734 bool visitStoreInst(StoreInst &SI) {
1735 DEBUG(dbgs() << " original: " << SI << "\n");
1736 Value *OldOp = SI.getOperand(1);
1737 assert(OldOp == OldPtr);
1738 IRBuilder<> IRB(&SI);
1741 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1743 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1744 SI.getPointerOperand()->getType());
1745 SI.setOperand(1, NewPtr);
1746 DEBUG(dbgs() << " to: " << SI << "\n");
1748 deleteIfTriviallyDead(OldOp);
1749 return NewPtr == &NewAI && !SI.isVolatile();
1752 bool visitMemSetInst(MemSetInst &II) {
1753 DEBUG(dbgs() << " original: " << II << "\n");
1754 IRBuilder<> IRB(&II);
1755 assert(II.getRawDest() == OldPtr);
1757 // If the memset has a variable size, it cannot be split, just adjust the
1758 // pointer to the new alloca.
1759 if (!isa<Constant>(II.getLength())) {
1760 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1761 deleteIfTriviallyDead(OldPtr);
1765 // Record this instruction for deletion.
1766 if (Pass.DeadSplitInsts.insert(&II))
1767 Pass.DeadInsts.push_back(&II);
1769 Type *AllocaTy = NewAI.getAllocatedType();
1770 Type *ScalarTy = AllocaTy->getScalarType();
1772 // If this doesn't map cleanly onto the alloca type, and that type isn't
1773 // a single value type, just emit a memset.
1774 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1775 EndOffset != NewAllocaEndOffset ||
1776 !AllocaTy->isSingleValueType() ||
1777 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1778 Type *SizeTy = II.getLength()->getType();
1779 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1782 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1783 II.getRawDest()->getType()),
1784 II.getValue(), Size, II.getAlignment(),
1787 DEBUG(dbgs() << " to: " << *New << "\n");
1791 // If we can represent this as a simple value, we have to build the actual
1792 // value to store, which requires expanding the byte present in memset to
1793 // a sensible representation for the alloca type. This is essentially
1794 // splatting the byte to a sufficiently wide integer, bitcasting to the
1795 // desired scalar type, and splatting it across any desired vector type.
1796 Value *V = II.getValue();
1797 IntegerType *VTy = cast<IntegerType>(V->getType());
1798 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1799 TD.getTypeSizeInBits(ScalarTy));
1800 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1801 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1802 ConstantExpr::getUDiv(
1803 Constant::getAllOnesValue(IntTy),
1804 ConstantExpr::getZExt(
1805 Constant::getAllOnesValue(V->getType()),
1807 getName(".isplat"));
1808 if (V->getType() != ScalarTy) {
1809 if (ScalarTy->isPointerTy())
1810 V = IRB.CreateIntToPtr(V, ScalarTy);
1811 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1812 V = IRB.CreateBitCast(V, ScalarTy);
1813 else if (ScalarTy->isIntegerTy())
1814 llvm_unreachable("Computed different integer types with equal widths");
1816 llvm_unreachable("Invalid scalar type");
1819 // If this is an element-wide memset of a vectorizable alloca, insert it.
1820 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1821 EndOffset < NewAllocaEndOffset)) {
1822 StoreInst *Store = IRB.CreateStore(
1823 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1824 getIndex(IRB, BeginOffset),
1825 getName(".insert")),
1828 DEBUG(dbgs() << " to: " << *Store << "\n");
1832 // Splat to a vector if needed.
1833 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1834 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1835 V = IRB.CreateShuffleVector(
1836 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1837 IRB.getInt32(0), getName(".vsplat.insert")),
1838 UndefValue::get(SplatSourceTy),
1839 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1840 getName(".vsplat.shuffle"));
1841 assert(V->getType() == VecTy);
1844 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1846 DEBUG(dbgs() << " to: " << *New << "\n");
1847 return !II.isVolatile();
1850 bool visitMemTransferInst(MemTransferInst &II) {
1851 // Rewriting of memory transfer instructions can be a bit tricky. We break
1852 // them into two categories: split intrinsics and unsplit intrinsics.
1854 DEBUG(dbgs() << " original: " << II << "\n");
1855 IRBuilder<> IRB(&II);
1857 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1858 bool IsDest = II.getRawDest() == OldPtr;
1860 const AllocaPartitioning::MemTransferOffsets &MTO
1861 = P.getMemTransferOffsets(II);
1863 // For unsplit intrinsics, we simply modify the source and destination
1864 // pointers in place. This isn't just an optimization, it is a matter of
1865 // correctness. With unsplit intrinsics we may be dealing with transfers
1866 // within a single alloca before SROA ran, or with transfers that have
1867 // a variable length. We may also be dealing with memmove instead of
1868 // memcpy, and so simply updating the pointers is the necessary for us to
1869 // update both source and dest of a single call.
1870 if (!MTO.IsSplittable) {
1871 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1873 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1875 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1877 DEBUG(dbgs() << " to: " << II << "\n");
1878 deleteIfTriviallyDead(OldOp);
1881 // For split transfer intrinsics we have an incredibly useful assurance:
1882 // the source and destination do not reside within the same alloca, and at
1883 // least one of them does not escape. This means that we can replace
1884 // memmove with memcpy, and we don't need to worry about all manner of
1885 // downsides to splitting and transforming the operations.
1887 // Compute the relative offset within the transfer.
1888 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1889 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
1890 : MTO.SourceBegin));
1892 // If this doesn't map cleanly onto the alloca type, and that type isn't
1893 // a single value type, just emit a memcpy.
1895 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
1896 EndOffset != NewAllocaEndOffset ||
1897 !NewAI.getAllocatedType()->isSingleValueType());
1899 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
1900 // size hasn't been shrunk based on analysis of the viable range, this is
1902 if (EmitMemCpy && &OldAI == &NewAI) {
1903 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
1904 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
1905 // Ensure the start lines up.
1906 assert(BeginOffset == OrigBegin);
1908 // Rewrite the size as needed.
1909 if (EndOffset != OrigEnd)
1910 II.setLength(ConstantInt::get(II.getLength()->getType(),
1911 EndOffset - BeginOffset));
1914 // Record this instruction for deletion.
1915 if (Pass.DeadSplitInsts.insert(&II))
1916 Pass.DeadInsts.push_back(&II);
1918 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
1919 EndOffset < NewAllocaEndOffset);
1921 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
1922 : II.getRawDest()->getType();
1924 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
1927 // Compute the other pointer, folding as much as possible to produce
1928 // a single, simple GEP in most cases.
1929 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
1930 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
1931 getName("." + OtherPtr->getName()));
1933 // Strip all inbounds GEPs and pointer casts to try to dig out any root
1934 // alloca that should be re-examined after rewriting this instruction.
1936 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
1937 Pass.Worklist.insert(AI);
1941 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
1942 : II.getRawSource()->getType());
1943 Type *SizeTy = II.getLength()->getType();
1944 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1946 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
1947 IsDest ? OtherPtr : OurPtr,
1948 Size, II.getAlignment(),
1951 DEBUG(dbgs() << " to: " << *New << "\n");
1955 Value *SrcPtr = OtherPtr;
1956 Value *DstPtr = &NewAI;
1958 std::swap(SrcPtr, DstPtr);
1961 if (IsVectorElement && !IsDest) {
1962 // We have to extract rather than load.
1963 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
1964 getName(".copyload")),
1965 getIndex(IRB, BeginOffset),
1966 getName(".copyextract"));
1968 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
1971 if (IsVectorElement && IsDest) {
1972 // We have to insert into a loaded copy before storing.
1973 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
1974 Src, getIndex(IRB, BeginOffset),
1975 getName(".insert"));
1978 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
1980 DEBUG(dbgs() << " to: " << *Store << "\n");
1981 return !II.isVolatile();
1984 bool visitIntrinsicInst(IntrinsicInst &II) {
1985 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
1986 II.getIntrinsicID() == Intrinsic::lifetime_end);
1987 DEBUG(dbgs() << " original: " << II << "\n");
1988 IRBuilder<> IRB(&II);
1989 assert(II.getArgOperand(1) == OldPtr);
1991 // Record this instruction for deletion.
1992 if (Pass.DeadSplitInsts.insert(&II))
1993 Pass.DeadInsts.push_back(&II);
1996 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
1997 EndOffset - BeginOffset);
1998 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2000 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2001 New = IRB.CreateLifetimeStart(Ptr, Size);
2003 New = IRB.CreateLifetimeEnd(Ptr, Size);
2005 DEBUG(dbgs() << " to: " << *New << "\n");
2009 /// PHI instructions that use an alloca and are subsequently loaded can be
2010 /// rewritten to load both input pointers in the pred blocks and then PHI the
2011 /// results, allowing the load of the alloca to be promoted.
2013 /// %P2 = phi [i32* %Alloca, i32* %Other]
2014 /// %V = load i32* %P2
2016 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2018 /// %V2 = load i32* %Other
2020 /// %V = phi [i32 %V1, i32 %V2]
2022 /// We can do this to a select if its only uses are loads and if the operand
2023 /// to the select can be loaded unconditionally.
2025 /// FIXME: This should be hoisted into a generic utility, likely in
2026 /// Transforms/Util/Local.h
2027 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2028 // For now, we can only do this promotion if the load is in the same block
2029 // as the PHI, and if there are no stores between the phi and load.
2030 // TODO: Allow recursive phi users.
2031 // TODO: Allow stores.
2032 BasicBlock *BB = PN.getParent();
2033 unsigned MaxAlign = 0;
2034 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2036 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2037 if (LI == 0 || !LI->isSimple()) return false;
2039 // For now we only allow loads in the same block as the PHI. This is
2040 // a common case that happens when instcombine merges two loads through
2042 if (LI->getParent() != BB) return false;
2044 // Ensure that there are no instructions between the PHI and the load that
2046 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2047 if (BBI->mayWriteToMemory())
2050 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2051 Loads.push_back(LI);
2054 // We can only transform this if it is safe to push the loads into the
2055 // predecessor blocks. The only thing to watch out for is that we can't put
2056 // a possibly trapping load in the predecessor if it is a critical edge.
2057 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2059 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2060 Value *InVal = PN.getIncomingValue(Idx);
2062 // If the value is produced by the terminator of the predecessor (an
2063 // invoke) or it has side-effects, there is no valid place to put a load
2064 // in the predecessor.
2065 if (TI == InVal || TI->mayHaveSideEffects())
2068 // If the predecessor has a single successor, then the edge isn't
2070 if (TI->getNumSuccessors() == 1)
2073 // If this pointer is always safe to load, or if we can prove that there
2074 // is already a load in the block, then we can move the load to the pred
2076 if (InVal->isDereferenceablePointer() ||
2077 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2086 bool visitPHINode(PHINode &PN) {
2087 DEBUG(dbgs() << " original: " << PN << "\n");
2088 // We would like to compute a new pointer in only one place, but have it be
2089 // as local as possible to the PHI. To do that, we re-use the location of
2090 // the old pointer, which necessarily must be in the right position to
2091 // dominate the PHI.
2092 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2094 SmallVector<LoadInst *, 4> Loads;
2095 if (!isSafePHIToSpeculate(PN, Loads)) {
2096 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2097 // Replace the operands which were using the old pointer.
2098 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2099 for (; OI != OE; ++OI)
2103 DEBUG(dbgs() << " to: " << PN << "\n");
2104 deleteIfTriviallyDead(OldPtr);
2107 assert(!Loads.empty());
2109 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2110 IRBuilder<> PHIBuilder(&PN);
2111 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2112 NewPN->takeName(&PN);
2114 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2115 // matter which one we get and if any differ, it doesn't matter.
2116 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2117 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2118 unsigned Align = SomeLoad->getAlignment();
2119 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2121 // Rewrite all loads of the PN to use the new PHI.
2123 LoadInst *LI = Loads.pop_back_val();
2124 LI->replaceAllUsesWith(NewPN);
2125 Pass.DeadInsts.push_back(LI);
2126 } while (!Loads.empty());
2128 // Inject loads into all of the pred blocks.
2129 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2130 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2131 TerminatorInst *TI = Pred->getTerminator();
2132 Value *InVal = PN.getIncomingValue(Idx);
2133 IRBuilder<> PredBuilder(TI);
2135 // Map the value to the new alloca pointer if this was the old alloca
2137 bool ThisOperand = InVal == OldPtr;
2142 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2144 ++NumLoadsSpeculated;
2145 Load->setAlignment(Align);
2147 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2148 NewPN->addIncoming(Load, Pred);
2152 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2154 // No uses to rewrite.
2157 // Try to lookup and rewrite any partition uses corresponding to this phi
2159 AllocaPartitioning::iterator PI
2160 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2161 if (PI != P.end()) {
2162 // If the other pointer is within the partitioning, replace the PHI in
2163 // its uses with the load we just speculated, or add another load for
2164 // it to rewrite if we've already replaced the PHI.
2165 AllocaPartitioning::use_iterator UI
2166 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2167 if (isa<PHINode>(*UI->User))
2170 AllocaPartitioning::PartitionUse OtherUse = *UI;
2171 OtherUse.User = Load;
2172 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2177 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2178 return NewPtr == &NewAI;
2181 /// Select instructions that use an alloca and are subsequently loaded can be
2182 /// rewritten to load both input pointers and then select between the result,
2183 /// allowing the load of the alloca to be promoted.
2185 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2186 /// %V = load i32* %P2
2188 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2189 /// %V2 = load i32* %Other
2190 /// %V = select i1 %cond, i32 %V1, i32 %V2
2192 /// We can do this to a select if its only uses are loads and if the operand
2193 /// to the select can be loaded unconditionally.
2194 bool isSafeSelectToSpeculate(SelectInst &SI,
2195 SmallVectorImpl<LoadInst *> &Loads) {
2196 Value *TValue = SI.getTrueValue();
2197 Value *FValue = SI.getFalseValue();
2198 bool TDerefable = TValue->isDereferenceablePointer();
2199 bool FDerefable = FValue->isDereferenceablePointer();
2201 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2203 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2204 if (LI == 0 || !LI->isSimple()) return false;
2206 // Both operands to the select need to be dereferencable, either
2207 // absolutely (e.g. allocas) or at this point because we can see other
2209 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2210 LI->getAlignment(), &TD))
2212 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2213 LI->getAlignment(), &TD))
2215 Loads.push_back(LI);
2221 bool visitSelectInst(SelectInst &SI) {
2222 DEBUG(dbgs() << " original: " << SI << "\n");
2223 IRBuilder<> IRB(&SI);
2225 // Find the operand we need to rewrite here.
2226 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2228 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2230 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2231 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2233 // If the select isn't safe to speculate, just use simple logic to emit it.
2234 SmallVector<LoadInst *, 4> Loads;
2235 if (!isSafeSelectToSpeculate(SI, Loads)) {
2236 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2237 DEBUG(dbgs() << " to: " << SI << "\n");
2238 deleteIfTriviallyDead(OldPtr);
2242 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2243 AllocaPartitioning::iterator PI
2244 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2245 AllocaPartitioning::PartitionUse OtherUse;
2246 if (PI != P.end()) {
2247 // If the other pointer is within the partitioning, remove the select
2248 // from its uses. We'll add in the new loads below.
2249 AllocaPartitioning::use_iterator UI
2250 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2252 P.use_erase(PI, UI);
2255 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2256 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2257 // Replace the loads of the select with a select of two loads.
2258 while (!Loads.empty()) {
2259 LoadInst *LI = Loads.pop_back_val();
2261 IRB.SetInsertPoint(LI);
2263 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2265 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2266 NumLoadsSpeculated += 2;
2267 if (PI != P.end()) {
2268 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2269 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2270 OtherUse.User = OtherLoad;
2271 P.use_insert(PI, P.use_end(PI), OtherUse);
2274 // Transfer alignment and TBAA info if present.
2275 TL->setAlignment(LI->getAlignment());
2276 FL->setAlignment(LI->getAlignment());
2277 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2278 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2279 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2282 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2284 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2285 LI->replaceAllUsesWith(V);
2286 Pass.DeadInsts.push_back(LI);
2289 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2291 deleteIfTriviallyDead(OldPtr);
2292 return NewPtr == &NewAI;
2298 /// \brief Try to find a partition of the aggregate type passed in for a given
2299 /// offset and size.
2301 /// This recurses through the aggregate type and tries to compute a subtype
2302 /// based on the offset and size. When the offset and size span a sub-section
2303 /// of an array, it will even compute a new array type for that sub-section.
2304 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2305 uint64_t Offset, uint64_t Size) {
2306 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2309 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2310 // We can't partition pointers...
2311 if (SeqTy->isPointerTy())
2314 Type *ElementTy = SeqTy->getElementType();
2315 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2316 uint64_t NumSkippedElements = Offset / ElementSize;
2317 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2318 if (NumSkippedElements >= ArrTy->getNumElements())
2320 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2321 if (NumSkippedElements >= VecTy->getNumElements())
2323 Offset -= NumSkippedElements * ElementSize;
2325 // First check if we need to recurse.
2326 if (Offset > 0 || Size < ElementSize) {
2327 // Bail if the partition ends in a different array element.
2328 if ((Offset + Size) > ElementSize)
2330 // Recurse through the element type trying to peel off offset bytes.
2331 return getTypePartition(TD, ElementTy, Offset, Size);
2333 assert(Offset == 0);
2335 if (Size == ElementSize)
2337 assert(Size > ElementSize);
2338 uint64_t NumElements = Size / ElementSize;
2339 if (NumElements * ElementSize != Size)
2341 return ArrayType::get(ElementTy, NumElements);
2344 StructType *STy = dyn_cast<StructType>(Ty);
2348 const StructLayout *SL = TD.getStructLayout(STy);
2349 if (Offset > SL->getSizeInBytes())
2351 uint64_t EndOffset = Offset + Size;
2352 if (EndOffset > SL->getSizeInBytes())
2355 unsigned Index = SL->getElementContainingOffset(Offset);
2356 if (SL->getElementOffset(Index) != Offset)
2357 return 0; // Inside of padding.
2358 Offset -= SL->getElementOffset(Index);
2360 Type *ElementTy = STy->getElementType(Index);
2361 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2362 if (Offset >= ElementSize)
2363 return 0; // The offset points into alignment padding.
2365 // See if any partition must be contained by the element.
2366 if (Offset > 0 || Size < ElementSize) {
2367 if ((Offset + Size) > ElementSize)
2369 // Bail if this is a poniter element, we can't recurse through them.
2370 if (ElementTy->isPointerTy())
2372 return getTypePartition(TD, ElementTy, Offset, Size);
2374 assert(Offset == 0);
2376 if (Size == ElementSize)
2379 StructType::element_iterator EI = STy->element_begin() + Index,
2380 EE = STy->element_end();
2381 if (EndOffset < SL->getSizeInBytes()) {
2382 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2383 if (Index == EndIndex)
2384 return 0; // Within a single element and its padding.
2385 assert(Index < EndIndex);
2386 assert(Index + EndIndex <= STy->getNumElements());
2387 EE = STy->element_begin() + EndIndex;
2390 // Try to build up a sub-structure.
2391 SmallVector<Type *, 4> ElementTys;
2393 ElementTys.push_back(*EI++);
2395 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2397 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2398 if (Size == SubSL->getSizeInBytes())
2401 // FIXME: We could potentially recurse down through the last element in the
2402 // sub-struct to find a natural end point.
2406 /// \brief Rewrite an alloca partition's users.
2408 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2409 /// to rewrite uses of an alloca partition to be conducive for SSA value
2410 /// promotion. If the partition needs a new, more refined alloca, this will
2411 /// build that new alloca, preserving as much type information as possible, and
2412 /// rewrite the uses of the old alloca to point at the new one and have the
2413 /// appropriate new offsets. It also evaluates how successful the rewrite was
2414 /// at enabling promotion and if it was successful queues the alloca to be
2416 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2417 AllocaPartitioning &P,
2418 AllocaPartitioning::iterator PI) {
2419 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2420 if (P.use_begin(PI) == P.use_end(PI))
2421 return false; // No live uses left of this partition.
2423 // Try to compute a friendly type for this partition of the alloca. This
2424 // won't always succeed, in which case we fall back to a legal integer type
2425 // or an i8 array of an appropriate size.
2427 if (Type *PartitionTy = P.getCommonType(PI))
2428 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2429 AllocaTy = PartitionTy;
2431 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2432 PI->BeginOffset, AllocaSize))
2433 AllocaTy = PartitionTy;
2435 (AllocaTy->isArrayTy() &&
2436 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2437 TD->isLegalInteger(AllocaSize * 8))
2438 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2440 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2442 // Check for the case where we're going to rewrite to a new alloca of the
2443 // exact same type as the original, and with the same access offsets. In that
2444 // case, re-use the existing alloca, but still run through the rewriter to
2445 // performe phi and select speculation.
2447 if (AllocaTy == AI.getAllocatedType()) {
2448 assert(PI->BeginOffset == 0 &&
2449 "Non-zero begin offset but same alloca type");
2450 assert(PI == P.begin() && "Begin offset is zero on later partition");
2453 // FIXME: The alignment here is overly conservative -- we could in many
2454 // cases get away with much weaker alignment constraints.
2455 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2456 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2461 DEBUG(dbgs() << "Rewriting alloca partition "
2462 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2465 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2466 PI->BeginOffset, PI->EndOffset);
2467 DEBUG(dbgs() << " rewriting ");
2468 DEBUG(P.print(dbgs(), PI, ""));
2469 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2470 DEBUG(dbgs() << " and queuing for promotion\n");
2471 PromotableAllocas.push_back(NewAI);
2472 } else if (NewAI != &AI) {
2473 // If we can't promote the alloca, iterate on it to check for new
2474 // refinements exposed by splitting the current alloca. Don't iterate on an
2475 // alloca which didn't actually change and didn't get promoted.
2476 Worklist.insert(NewAI);
2481 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2482 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2483 bool Changed = false;
2484 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2486 Changed |= rewriteAllocaPartition(AI, P, PI);
2491 /// \brief Analyze an alloca for SROA.
2493 /// This analyzes the alloca to ensure we can reason about it, builds
2494 /// a partitioning of the alloca, and then hands it off to be split and
2495 /// rewritten as needed.
2496 bool SROA::runOnAlloca(AllocaInst &AI) {
2497 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2498 ++NumAllocasAnalyzed;
2500 // Special case dead allocas, as they're trivial.
2501 if (AI.use_empty()) {
2502 AI.eraseFromParent();
2506 // Skip alloca forms that this analysis can't handle.
2507 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2508 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2511 // First check if this is a non-aggregate type that we should simply promote.
2512 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2513 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2514 PromotableAllocas.push_back(&AI);
2518 // Build the partition set using a recursive instruction-visiting builder.
2519 AllocaPartitioning P(*TD, AI);
2520 DEBUG(P.print(dbgs()));
2524 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2525 if (P.begin() == P.end())
2528 // Delete all the dead users of this alloca before splitting and rewriting it.
2529 bool Changed = false;
2530 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2531 DE = P.dead_user_end();
2534 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2535 DeadInsts.push_back(*DI);
2537 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2538 DE = P.dead_op_end();
2541 // Clobber the use with an undef value.
2542 **DO = UndefValue::get(OldV->getType());
2543 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2544 if (isInstructionTriviallyDead(OldI)) {
2546 DeadInsts.push_back(OldI);
2550 return splitAlloca(AI, P) || Changed;
2553 void SROA::deleteDeadInstructions() {
2554 DeadSplitInsts.clear();
2555 while (!DeadInsts.empty()) {
2556 Instruction *I = DeadInsts.pop_back_val();
2557 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2559 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2560 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2561 // Zero out the operand and see if it becomes trivially dead.
2563 if (isInstructionTriviallyDead(U))
2564 DeadInsts.push_back(U);
2567 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2568 DeletedAllocas.insert(AI);
2571 I->eraseFromParent();
2576 /// \brief A predicate to test whether an alloca belongs to a set.
2577 class IsAllocaInSet {
2578 typedef SmallPtrSet<AllocaInst *, 4> SetType;
2582 IsAllocaInSet(const SetType &Set) : Set(Set) {}
2583 bool operator()(AllocaInst *AI) { return Set.count(AI); }
2587 bool SROA::runOnFunction(Function &F) {
2588 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2589 C = &F.getContext();
2590 TD = getAnalysisIfAvailable<TargetData>();
2592 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
2595 DT = &getAnalysis<DominatorTree>();
2597 BasicBlock &EntryBB = F.getEntryBlock();
2598 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
2600 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2601 Worklist.insert(AI);
2603 bool Changed = false;
2604 while (!Worklist.empty()) {
2605 Changed |= runOnAlloca(*Worklist.pop_back_val());
2606 deleteDeadInstructions();
2607 if (!DeletedAllocas.empty()) {
2608 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
2609 PromotableAllocas.end(),
2610 IsAllocaInSet(DeletedAllocas)),
2611 PromotableAllocas.end());
2612 DeletedAllocas.clear();
2616 if (!PromotableAllocas.empty()) {
2617 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2618 PromoteMemToReg(PromotableAllocas, *DT);
2620 NumPromoted += PromotableAllocas.size();
2621 PromotableAllocas.clear();
2627 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
2628 AU.addRequired<DominatorTree>();
2629 AU.setPreservesCFG();