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/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/ValueHandle.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetData.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
61 #include "llvm/Transforms/Utils/SSAUpdater.h"
64 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
65 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
67 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
68 STATISTIC(NumDeleted, "Number of instructions deleted");
69 STATISTIC(NumVectorized, "Number of vectorized aggregates");
71 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
72 /// forming SSA values through the SSAUpdater infrastructure.
74 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
77 /// \brief Alloca partitioning representation.
79 /// This class represents a partitioning of an alloca into slices, and
80 /// information about the nature of uses of each slice of the alloca. The goal
81 /// is that this information is sufficient to decide if and how to split the
82 /// alloca apart and replace slices with scalars. It is also intended that this
83 /// structure can capture the relevant information needed both to decide about
84 /// and to enact these transformations.
85 class AllocaPartitioning {
87 /// \brief A common base class for representing a half-open byte range.
89 /// \brief The beginning offset of the range.
92 /// \brief The ending offset, not included in the range.
95 ByteRange() : BeginOffset(), EndOffset() {}
96 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
97 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
99 /// \brief Support for ordering ranges.
101 /// This provides an ordering over ranges such that start offsets are
102 /// always increasing, and within equal start offsets, the end offsets are
103 /// decreasing. Thus the spanning range comes first in a cluster with the
104 /// same start position.
105 bool operator<(const ByteRange &RHS) const {
106 if (BeginOffset < RHS.BeginOffset) return true;
107 if (BeginOffset > RHS.BeginOffset) return false;
108 if (EndOffset > RHS.EndOffset) return true;
112 /// \brief Support comparison with a single offset to allow binary searches.
113 bool operator<(uint64_t RHSOffset) const {
114 return BeginOffset < RHSOffset;
117 bool operator==(const ByteRange &RHS) const {
118 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
120 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
123 /// \brief A partition of an alloca.
125 /// This structure represents a contiguous partition of the alloca. These are
126 /// formed by examining the uses of the alloca. During formation, they may
127 /// overlap but once an AllocaPartitioning is built, the Partitions within it
128 /// are all disjoint.
129 struct Partition : public ByteRange {
130 /// \brief Whether this partition is splittable into smaller partitions.
132 /// We flag partitions as splittable when they are formed entirely due to
133 /// accesses by trivially splittable operations such as memset and memcpy.
135 /// FIXME: At some point we should consider loads and stores of FCAs to be
136 /// splittable and eagerly split them into scalar values.
139 Partition() : ByteRange(), IsSplittable() {}
140 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
141 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
144 /// \brief A particular use of a partition of the alloca.
146 /// This structure is used to associate uses of a partition with it. They
147 /// mark the range of bytes which are referenced by a particular instruction,
148 /// and includes a handle to the user itself and the pointer value in use.
149 /// The bounds of these uses are determined by intersecting the bounds of the
150 /// memory use itself with a particular partition. As a consequence there is
151 /// intentionally overlap between various uses of the same partition.
152 struct PartitionUse : public ByteRange {
153 /// \brief The user of this range of the alloca.
154 AssertingVH<Instruction> User;
156 /// \brief The particular pointer value derived from this alloca in use.
157 AssertingVH<Instruction> Ptr;
159 PartitionUse() : ByteRange(), User(), Ptr() {}
160 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
161 Instruction *User, Instruction *Ptr)
162 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
165 /// \brief Construct a partitioning of a particular alloca.
167 /// Construction does most of the work for partitioning the alloca. This
168 /// performs the necessary walks of users and builds a partitioning from it.
169 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
171 /// \brief Test whether a pointer to the allocation escapes our analysis.
173 /// If this is true, the partitioning is never fully built and should be
175 bool isEscaped() const { return PointerEscapingInstr; }
177 /// \brief Support for iterating over the partitions.
179 typedef SmallVectorImpl<Partition>::iterator iterator;
180 iterator begin() { return Partitions.begin(); }
181 iterator end() { return Partitions.end(); }
183 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
184 const_iterator begin() const { return Partitions.begin(); }
185 const_iterator end() const { return Partitions.end(); }
188 /// \brief Support for iterating over and manipulating a particular
189 /// partition's uses.
191 /// The iteration support provided for uses is more limited, but also
192 /// includes some manipulation routines to support rewriting the uses of
193 /// partitions during SROA.
195 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
196 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
197 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
198 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
199 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
200 void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
201 Uses[Idx].insert(UI, U);
203 void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
204 Uses[I - begin()].insert(UI, U);
206 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
207 void use_erase(const_iterator I, use_iterator UI) {
208 Uses[I - begin()].erase(UI);
211 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
212 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
213 const_use_iterator use_begin(const_iterator I) const {
214 return Uses[I - begin()].begin();
216 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
217 const_use_iterator use_end(const_iterator I) const {
218 return Uses[I - begin()].end();
222 /// \brief Allow iterating the dead users for this alloca.
224 /// These are instructions which will never actually use the alloca as they
225 /// are outside the allocated range. They are safe to replace with undef and
228 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
229 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
230 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
233 /// \brief Allow iterating the dead expressions referring to this alloca.
235 /// These are operands which have cannot actually be used to refer to the
236 /// alloca as they are outside its range and the user doesn't correct for
237 /// that. These mostly consist of PHI node inputs and the like which we just
238 /// need to replace with undef.
240 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
241 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
242 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
245 /// \brief MemTransferInst auxiliary data.
246 /// This struct provides some auxiliary data about memory transfer
247 /// intrinsics such as memcpy and memmove. These intrinsics can use two
248 /// different ranges within the same alloca, and provide other challenges to
249 /// correctly represent. We stash extra data to help us untangle this
250 /// after the partitioning is complete.
251 struct MemTransferOffsets {
252 uint64_t DestBegin, DestEnd;
253 uint64_t SourceBegin, SourceEnd;
256 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
257 return MemTransferInstData.lookup(&II);
260 /// \brief Map from a PHI or select operand back to a partition.
262 /// When manipulating PHI nodes or selects, they can use more than one
263 /// partition of an alloca. We store a special mapping to allow finding the
264 /// partition referenced by each of these operands, if any.
265 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
266 SmallDenseMap<std::pair<Instruction *, Value *>,
267 std::pair<unsigned, unsigned> >::const_iterator MapIt
268 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
269 if (MapIt == PHIOrSelectOpMap.end())
272 return begin() + MapIt->second.first;
275 /// \brief Map from a PHI or select operand back to the specific use of
278 /// Similar to mapping these operands back to the partitions, this maps
279 /// directly to the use structure of that partition.
280 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
282 SmallDenseMap<std::pair<Instruction *, Value *>,
283 std::pair<unsigned, unsigned> >::const_iterator MapIt
284 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
285 assert(MapIt != PHIOrSelectOpMap.end());
286 return Uses[MapIt->second.first].begin() + MapIt->second.second;
289 /// \brief Compute a common type among the uses of a particular partition.
291 /// This routines walks all of the uses of a particular partition and tries
292 /// to find a common type between them. Untyped operations such as memset and
293 /// memcpy are ignored.
294 Type *getCommonType(iterator I) const;
296 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
297 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
298 void printUsers(raw_ostream &OS, const_iterator I,
299 StringRef Indent = " ") const;
300 void print(raw_ostream &OS) const;
301 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
302 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
306 template <typename DerivedT, typename RetT = void> class BuilderBase;
307 class PartitionBuilder;
308 friend class AllocaPartitioning::PartitionBuilder;
310 friend class AllocaPartitioning::UseBuilder;
313 /// \brief Handle to alloca instruction to simplify method interfaces.
317 /// \brief The instruction responsible for this alloca having no partitioning.
319 /// When an instruction (potentially) escapes the pointer to the alloca, we
320 /// store a pointer to that here and abort trying to partition the alloca.
321 /// This will be null if the alloca is partitioned successfully.
322 Instruction *PointerEscapingInstr;
324 /// \brief The partitions of the alloca.
326 /// We store a vector of the partitions over the alloca here. This vector is
327 /// sorted by increasing begin offset, and then by decreasing end offset. See
328 /// the Partition inner class for more details. Initially (during
329 /// construction) there are overlaps, but we form a disjoint sequence of
330 /// partitions while finishing construction and a fully constructed object is
331 /// expected to always have this as a disjoint space.
332 SmallVector<Partition, 8> Partitions;
334 /// \brief The uses of the partitions.
336 /// This is essentially a mapping from each partition to a list of uses of
337 /// that partition. The mapping is done with a Uses vector that has the exact
338 /// same number of entries as the partition vector. Each entry is itself
339 /// a vector of the uses.
340 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
342 /// \brief Instructions which will become dead if we rewrite the alloca.
344 /// Note that these are not separated by partition. This is because we expect
345 /// a partitioned alloca to be completely rewritten or not rewritten at all.
346 /// If rewritten, all these instructions can simply be removed and replaced
347 /// with undef as they come from outside of the allocated space.
348 SmallVector<Instruction *, 8> DeadUsers;
350 /// \brief Operands which will become dead if we rewrite the alloca.
352 /// These are operands that in their particular use can be replaced with
353 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
354 /// to PHI nodes and the like. They aren't entirely dead (there might be
355 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
356 /// want to swap this particular input for undef to simplify the use lists of
358 SmallVector<Use *, 8> DeadOperands;
360 /// \brief The underlying storage for auxiliary memcpy and memset info.
361 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
363 /// \brief A side datastructure used when building up the partitions and uses.
365 /// This mapping is only really used during the initial building of the
366 /// partitioning so that we can retain information about PHI and select nodes
368 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
370 /// \brief Auxiliary information for particular PHI or select operands.
371 SmallDenseMap<std::pair<Instruction *, Value *>,
372 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
374 /// \brief A utility routine called from the constructor.
376 /// This does what it says on the tin. It is the key of the alloca partition
377 /// splitting and merging. After it is called we have the desired disjoint
378 /// collection of partitions.
379 void splitAndMergePartitions();
383 template <typename DerivedT, typename RetT>
384 class AllocaPartitioning::BuilderBase
385 : public InstVisitor<DerivedT, RetT> {
387 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
389 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
395 const TargetData &TD;
396 const uint64_t AllocSize;
397 AllocaPartitioning &P;
403 SmallVector<OffsetUse, 8> Queue;
405 // The active offset and use while visiting.
409 void enqueueUsers(Instruction &I, uint64_t UserOffset) {
410 SmallPtrSet<User *, 8> UserSet;
411 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
413 if (!UserSet.insert(*UI))
416 OffsetUse OU = { &UI.getUse(), UserOffset };
421 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, uint64_t &GEPOffset) {
423 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
425 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
431 // Handle a struct index, which adds its field offset to the pointer.
432 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
433 unsigned ElementIdx = OpC->getZExtValue();
434 const StructLayout *SL = TD.getStructLayout(STy);
435 GEPOffset += SL->getElementOffset(ElementIdx);
440 += OpC->getZExtValue() * TD.getTypeAllocSize(GTI.getIndexedType());
445 Value *foldSelectInst(SelectInst &SI) {
446 // If the condition being selected on is a constant or the same value is
447 // being selected between, fold the select. Yes this does (rarely) happen
449 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
450 return SI.getOperand(1+CI->isZero());
451 if (SI.getOperand(1) == SI.getOperand(2)) {
452 assert(*U == SI.getOperand(1));
453 return SI.getOperand(1);
459 /// \brief Builder for the alloca partitioning.
461 /// This class builds an alloca partitioning by recursively visiting the uses
462 /// of an alloca and splitting the partitions for each load and store at each
464 class AllocaPartitioning::PartitionBuilder
465 : public BuilderBase<PartitionBuilder, bool> {
466 friend class InstVisitor<PartitionBuilder, bool>;
468 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
471 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
472 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
474 /// \brief Run the builder over the allocation.
476 // Note that we have to re-evaluate size on each trip through the loop as
477 // the queue grows at the tail.
478 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
480 Offset = Queue[Idx].Offset;
481 if (!visit(cast<Instruction>(U->getUser())))
488 bool markAsEscaping(Instruction &I) {
489 P.PointerEscapingInstr = &I;
493 void insertUse(Instruction &I, uint64_t Size, bool IsSplittable = false) {
494 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
496 // Completely skip uses which start outside of the allocation.
497 if (BeginOffset >= AllocSize) {
498 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
499 << " which starts past the end of the " << AllocSize
501 << " alloca: " << P.AI << "\n"
502 << " use: " << I << "\n");
506 // Clamp the size to the allocation.
507 if (EndOffset > AllocSize) {
508 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
509 << " to remain within the " << AllocSize << " byte alloca:\n"
510 << " alloca: " << P.AI << "\n"
511 << " use: " << I << "\n");
512 EndOffset = AllocSize;
515 // See if we can just add a user onto the last slot currently occupied.
516 if (!P.Partitions.empty() &&
517 P.Partitions.back().BeginOffset == BeginOffset &&
518 P.Partitions.back().EndOffset == EndOffset) {
519 P.Partitions.back().IsSplittable &= IsSplittable;
523 Partition New(BeginOffset, EndOffset, IsSplittable);
524 P.Partitions.push_back(New);
527 bool handleLoadOrStore(Type *Ty, Instruction &I) {
528 uint64_t Size = TD.getTypeStoreSize(Ty);
530 // If this memory access can be shown to *statically* extend outside the
531 // bounds of of the allocation, it's behavior is undefined, so simply
532 // ignore it. Note that this is more strict than the generic clamping
533 // behavior of insertUse. We also try to handle cases which might run the
535 // FIXME: We should instead consider the pointer to have escaped if this
536 // function is being instrumented for addressing bugs or race conditions.
537 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
538 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
539 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
540 << " which extends past the end of the " << AllocSize
542 << " alloca: " << P.AI << "\n"
543 << " use: " << I << "\n");
551 bool visitBitCastInst(BitCastInst &BC) {
552 enqueueUsers(BC, Offset);
556 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
558 if (!computeConstantGEPOffset(GEPI, GEPOffset))
559 return markAsEscaping(GEPI);
561 enqueueUsers(GEPI, GEPOffset);
565 bool visitLoadInst(LoadInst &LI) {
566 return handleLoadOrStore(LI.getType(), LI);
569 bool visitStoreInst(StoreInst &SI) {
570 if (SI.getOperand(0) == *U)
571 return markAsEscaping(SI);
573 return handleLoadOrStore(SI.getOperand(0)->getType(), SI);
577 bool visitMemSetInst(MemSetInst &II) {
578 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
579 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
580 insertUse(II, Length ? Length->getZExtValue() : AllocSize - Offset, Length);
584 bool visitMemTransferInst(MemTransferInst &II) {
585 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
586 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
588 // Zero-length mem transfer intrinsics can be ignored entirely.
591 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
593 // Only intrinsics with a constant length can be split.
594 Offsets.IsSplittable = Length;
596 if (*U != II.getRawDest()) {
597 assert(*U == II.getRawSource());
598 Offsets.SourceBegin = Offset;
599 Offsets.SourceEnd = Offset + Size;
601 Offsets.DestBegin = Offset;
602 Offsets.DestEnd = Offset + Size;
605 insertUse(II, Size, Offsets.IsSplittable);
606 unsigned NewIdx = P.Partitions.size() - 1;
608 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
609 bool Inserted = false;
610 llvm::tie(PMI, Inserted)
611 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
612 if (!Inserted && Offsets.IsSplittable) {
613 // We've found a memory transfer intrinsic which refers to the alloca as
614 // both a source and dest. We refuse to split these to simplify splitting
615 // logic. If possible, SROA will still split them into separate allocas
616 // and then re-analyze.
617 Offsets.IsSplittable = false;
618 P.Partitions[PMI->second].IsSplittable = false;
619 P.Partitions[NewIdx].IsSplittable = false;
625 // Disable SRoA for any intrinsics except for lifetime invariants.
626 // FIXME: What about debug instrinsics? This matches old behavior, but
627 // doesn't make sense.
628 bool visitIntrinsicInst(IntrinsicInst &II) {
629 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
630 II.getIntrinsicID() == Intrinsic::lifetime_end) {
631 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
632 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
633 insertUse(II, Size, true);
637 return markAsEscaping(II);
640 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
641 // We consider any PHI or select that results in a direct load or store of
642 // the same offset to be a viable use for partitioning purposes. These uses
643 // are considered unsplittable and the size is the maximum loaded or stored
645 SmallPtrSet<Instruction *, 4> Visited;
646 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
647 Visited.insert(Root);
648 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
650 Instruction *I, *UsedI;
651 llvm::tie(UsedI, I) = Uses.pop_back_val();
653 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
654 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
657 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
658 Value *Op = SI->getOperand(0);
661 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
665 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
666 if (!GEP->hasAllZeroIndices())
668 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
669 !isa<SelectInst>(I)) {
673 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
675 if (Visited.insert(cast<Instruction>(*UI)))
676 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
677 } while (!Uses.empty());
682 bool visitPHINode(PHINode &PN) {
683 // See if we already have computed info on this node.
684 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
686 PHIInfo.second = true;
687 insertUse(PN, PHIInfo.first);
691 // Check for an unsafe use of the PHI node.
692 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
693 return markAsEscaping(*EscapingI);
695 insertUse(PN, PHIInfo.first);
699 bool visitSelectInst(SelectInst &SI) {
700 if (Value *Result = foldSelectInst(SI)) {
702 // If the result of the constant fold will be the pointer, recurse
703 // through the select as if we had RAUW'ed it.
704 enqueueUsers(SI, Offset);
709 // See if we already have computed info on this node.
710 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
711 if (SelectInfo.first) {
712 SelectInfo.second = true;
713 insertUse(SI, SelectInfo.first);
717 // Check for an unsafe use of the PHI node.
718 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
719 return markAsEscaping(*EscapingI);
721 insertUse(SI, SelectInfo.first);
725 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
726 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
730 /// \brief Use adder for the alloca partitioning.
732 /// This class adds the uses of an alloca to all of the partitions which they
733 /// use. For splittable partitions, this can end up doing essentially a linear
734 /// walk of the partitions, but the number of steps remains bounded by the
735 /// total result instruction size:
736 /// - The number of partitions is a result of the number unsplittable
737 /// instructions using the alloca.
738 /// - The number of users of each partition is at worst the total number of
739 /// splittable instructions using the alloca.
740 /// Thus we will produce N * M instructions in the end, where N are the number
741 /// of unsplittable uses and M are the number of splittable. This visitor does
742 /// the exact same number of updates to the partitioning.
744 /// In the more common case, this visitor will leverage the fact that the
745 /// partition space is pre-sorted, and do a logarithmic search for the
746 /// partition needed, making the total visit a classical ((N + M) * log(N))
747 /// complexity operation.
748 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
749 friend class InstVisitor<UseBuilder>;
751 /// \brief Set to de-duplicate dead instructions found in the use walk.
752 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
755 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
756 : BuilderBase<UseBuilder>(TD, AI, P) {}
758 /// \brief Run the builder over the allocation.
760 // Note that we have to re-evaluate size on each trip through the loop as
761 // the queue grows at the tail.
762 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
764 Offset = Queue[Idx].Offset;
765 this->visit(cast<Instruction>(U->getUser()));
770 void markAsDead(Instruction &I) {
771 if (VisitedDeadInsts.insert(&I))
772 P.DeadUsers.push_back(&I);
775 void insertUse(uint64_t Size, Instruction &User) {
776 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
778 // If the use extends outside of the allocation, record it as a dead use
779 // for elimination later.
780 if (BeginOffset >= AllocSize || Size == 0)
781 return markAsDead(User);
783 // Bound the use by the size of the allocation.
784 if (EndOffset > AllocSize)
785 EndOffset = AllocSize;
787 // NB: This only works if we have zero overlapping partitions.
788 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
789 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
791 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
793 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
794 std::min(I->EndOffset, EndOffset),
795 &User, cast<Instruction>(*U));
796 P.Uses[I - P.begin()].push_back(NewUse);
797 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
798 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
799 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
803 void handleLoadOrStore(Type *Ty, Instruction &I) {
804 uint64_t Size = TD.getTypeStoreSize(Ty);
806 // If this memory access can be shown to *statically* extend outside the
807 // bounds of of the allocation, it's behavior is undefined, so simply
808 // ignore it. Note that this is more strict than the generic clamping
809 // behavior of insertUse.
810 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
811 return markAsDead(I);
816 void visitBitCastInst(BitCastInst &BC) {
818 return markAsDead(BC);
820 enqueueUsers(BC, Offset);
823 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
824 if (GEPI.use_empty())
825 return markAsDead(GEPI);
828 if (!computeConstantGEPOffset(GEPI, GEPOffset))
829 llvm_unreachable("Unable to compute constant offset for use");
831 enqueueUsers(GEPI, GEPOffset);
834 void visitLoadInst(LoadInst &LI) {
835 handleLoadOrStore(LI.getType(), LI);
838 void visitStoreInst(StoreInst &SI) {
839 handleLoadOrStore(SI.getOperand(0)->getType(), SI);
842 void visitMemSetInst(MemSetInst &II) {
843 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
844 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
847 void visitMemTransferInst(MemTransferInst &II) {
848 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
849 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
852 void visitIntrinsicInst(IntrinsicInst &II) {
853 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
854 II.getIntrinsicID() == Intrinsic::lifetime_end);
856 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
857 insertUse(std::min(AllocSize - Offset, Length->getLimitedValue()), II);
860 void insertPHIOrSelect(Instruction &User) {
861 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
863 // For PHI and select operands outside the alloca, we can't nuke the entire
864 // phi or select -- the other side might still be relevant, so we special
865 // case them here and use a separate structure to track the operands
866 // themselves which should be replaced with undef.
867 if (Offset >= AllocSize) {
868 P.DeadOperands.push_back(U);
872 insertUse(Size, User);
874 void visitPHINode(PHINode &PN) {
876 return markAsDead(PN);
878 insertPHIOrSelect(PN);
880 void visitSelectInst(SelectInst &SI) {
882 return markAsDead(SI);
884 if (Value *Result = foldSelectInst(SI)) {
886 // If the result of the constant fold will be the pointer, recurse
887 // through the select as if we had RAUW'ed it.
888 enqueueUsers(SI, Offset);
893 insertPHIOrSelect(SI);
896 /// \brief Unreachable, we've already visited the alloca once.
897 void visitInstruction(Instruction &I) {
898 llvm_unreachable("Unhandled instruction in use builder.");
902 void AllocaPartitioning::splitAndMergePartitions() {
903 size_t NumDeadPartitions = 0;
905 // Track the range of splittable partitions that we pass when accumulating
906 // overlapping unsplittable partitions.
907 uint64_t SplitEndOffset = 0ull;
909 Partition New(0ull, 0ull, false);
911 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
914 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
915 assert(New.BeginOffset == New.EndOffset);
918 assert(New.IsSplittable);
919 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
921 assert(New.BeginOffset != New.EndOffset);
923 // Scan the overlapping partitions.
924 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
925 // If the new partition we are forming is splittable, stop at the first
926 // unsplittable partition.
927 if (New.IsSplittable && !Partitions[j].IsSplittable)
930 // Grow the new partition to include any equally splittable range. 'j' is
931 // always equally splittable when New is splittable, but when New is not
932 // splittable, we may subsume some (or part of some) splitable partition
933 // without growing the new one.
934 if (New.IsSplittable == Partitions[j].IsSplittable) {
935 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
937 assert(!New.IsSplittable);
938 assert(Partitions[j].IsSplittable);
939 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
942 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
947 // If the new partition is splittable, chop off the end as soon as the
948 // unsplittable subsequent partition starts and ensure we eventually cover
949 // the splittable area.
950 if (j != e && New.IsSplittable) {
951 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
952 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
955 // Add the new partition if it differs from the original one and is
956 // non-empty. We can end up with an empty partition here if it was
957 // splittable but there is an unsplittable one that starts at the same
959 if (New != Partitions[i]) {
960 if (New.BeginOffset != New.EndOffset)
961 Partitions.push_back(New);
962 // Mark the old one for removal.
963 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
967 New.BeginOffset = New.EndOffset;
968 if (!New.IsSplittable) {
969 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
970 if (j != e && !Partitions[j].IsSplittable)
971 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
972 New.IsSplittable = true;
973 // If there is a trailing splittable partition which won't be fused into
974 // the next splittable partition go ahead and add it onto the partitions
976 if (New.BeginOffset < New.EndOffset &&
977 (j == e || !Partitions[j].IsSplittable ||
978 New.EndOffset < Partitions[j].BeginOffset)) {
979 Partitions.push_back(New);
980 New.BeginOffset = New.EndOffset = 0ull;
985 // Re-sort the partitions now that they have been split and merged into
986 // disjoint set of partitions. Also remove any of the dead partitions we've
987 // replaced in the process.
988 std::sort(Partitions.begin(), Partitions.end());
989 if (NumDeadPartitions) {
990 assert(Partitions.back().BeginOffset == UINT64_MAX);
991 assert(Partitions.back().EndOffset == UINT64_MAX);
992 assert((ptrdiff_t)NumDeadPartitions ==
993 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
995 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
998 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
1003 PointerEscapingInstr(0) {
1004 PartitionBuilder PB(TD, AI, *this);
1008 if (Partitions.size() > 1) {
1009 // Sort the uses. This arranges for the offsets to be in ascending order,
1010 // and the sizes to be in descending order.
1011 std::sort(Partitions.begin(), Partitions.end());
1013 // Intersect splittability for all partitions with equal offsets and sizes.
1014 // Then remove all but the first so that we have a sequence of non-equal but
1015 // potentially overlapping partitions.
1016 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1019 while (J != E && *I == *J) {
1020 I->IsSplittable &= J->IsSplittable;
1024 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1027 // Split splittable and merge unsplittable partitions into a disjoint set
1028 // of partitions over the used space of the allocation.
1029 splitAndMergePartitions();
1032 // Now build up the user lists for each of these disjoint partitions by
1033 // re-walking the recursive users of the alloca.
1034 Uses.resize(Partitions.size());
1035 UseBuilder UB(TD, AI, *this);
1037 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1038 std::stable_sort(use_begin(I), use_end(I));
1041 Type *AllocaPartitioning::getCommonType(iterator I) const {
1043 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1044 if (isa<MemIntrinsic>(*UI->User))
1046 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1050 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1051 UserTy = LI->getType();
1052 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1053 UserTy = SI->getValueOperand()->getType();
1054 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1055 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1056 UserTy = PtrTy->getElementType();
1057 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1058 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1059 UserTy = PtrTy->getElementType();
1062 if (Ty && Ty != UserTy)
1070 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1072 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1073 StringRef Indent) const {
1074 OS << Indent << "partition #" << (I - begin())
1075 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1076 << (I->IsSplittable ? " (splittable)" : "")
1077 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1081 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1082 StringRef Indent) const {
1083 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1085 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1086 << "used by: " << *UI->User << "\n";
1087 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1088 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1090 if (!MTO.IsSplittable)
1091 IsDest = UI->BeginOffset == MTO.DestBegin;
1093 IsDest = MTO.DestBegin != 0u;
1094 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1095 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1096 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1101 void AllocaPartitioning::print(raw_ostream &OS) const {
1102 if (PointerEscapingInstr) {
1103 OS << "No partitioning for alloca: " << AI << "\n"
1104 << " A pointer to this alloca escaped by:\n"
1105 << " " << *PointerEscapingInstr << "\n";
1109 OS << "Partitioning of alloca: " << AI << "\n";
1111 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1117 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1118 void AllocaPartitioning::dump() const { print(dbgs()); }
1120 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1124 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1126 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1127 /// the loads and stores of an alloca instruction, as well as updating its
1128 /// debug information. This is used when a domtree is unavailable and thus
1129 /// mem2reg in its full form can't be used to handle promotion of allocas to
1131 class AllocaPromoter : public LoadAndStorePromoter {
1135 SmallVector<DbgDeclareInst *, 4> DDIs;
1136 SmallVector<DbgValueInst *, 4> DVIs;
1139 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1140 AllocaInst &AI, DIBuilder &DIB)
1141 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1143 void run(const SmallVectorImpl<Instruction*> &Insts) {
1144 // Remember which alloca we're promoting (for isInstInList).
1145 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1146 for (Value::use_iterator UI = DebugNode->use_begin(),
1147 UE = DebugNode->use_end();
1149 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1150 DDIs.push_back(DDI);
1151 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1152 DVIs.push_back(DVI);
1155 LoadAndStorePromoter::run(Insts);
1156 AI.eraseFromParent();
1157 while (!DDIs.empty())
1158 DDIs.pop_back_val()->eraseFromParent();
1159 while (!DVIs.empty())
1160 DVIs.pop_back_val()->eraseFromParent();
1163 virtual bool isInstInList(Instruction *I,
1164 const SmallVectorImpl<Instruction*> &Insts) const {
1165 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1166 return LI->getOperand(0) == &AI;
1167 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1170 virtual void updateDebugInfo(Instruction *Inst) const {
1171 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1172 E = DDIs.end(); I != E; ++I) {
1173 DbgDeclareInst *DDI = *I;
1174 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1175 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1176 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1177 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1179 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1180 E = DVIs.end(); I != E; ++I) {
1181 DbgValueInst *DVI = *I;
1183 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1184 // If an argument is zero extended then use argument directly. The ZExt
1185 // may be zapped by an optimization pass in future.
1186 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1187 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1188 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1189 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1191 Arg = SI->getOperand(0);
1192 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1193 Arg = LI->getOperand(0);
1197 Instruction *DbgVal =
1198 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1200 DbgVal->setDebugLoc(DVI->getDebugLoc());
1204 } // end anon namespace
1208 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1210 /// This pass takes allocations which can be completely analyzed (that is, they
1211 /// don't escape) and tries to turn them into scalar SSA values. There are
1212 /// a few steps to this process.
1214 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1215 /// are used to try to split them into smaller allocations, ideally of
1216 /// a single scalar data type. It will split up memcpy and memset accesses
1217 /// as necessary and try to isolate invidual scalar accesses.
1218 /// 2) It will transform accesses into forms which are suitable for SSA value
1219 /// promotion. This can be replacing a memset with a scalar store of an
1220 /// integer value, or it can involve speculating operations on a PHI or
1221 /// select to be a PHI or select of the results.
1222 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1223 /// onto insert and extract operations on a vector value, and convert them to
1224 /// this form. By doing so, it will enable promotion of vector aggregates to
1225 /// SSA vector values.
1226 class SROA : public FunctionPass {
1227 const bool RequiresDomTree;
1230 const TargetData *TD;
1233 /// \brief Worklist of alloca instructions to simplify.
1235 /// Each alloca in the function is added to this. Each new alloca formed gets
1236 /// added to it as well to recursively simplify unless that alloca can be
1237 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1238 /// the one being actively rewritten, we add it back onto the list if not
1239 /// already present to ensure it is re-visited.
1240 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1242 /// \brief A collection of instructions to delete.
1243 /// We try to batch deletions to simplify code and make things a bit more
1245 SmallVector<Instruction *, 8> DeadInsts;
1247 /// \brief A set to prevent repeatedly marking an instruction split into many
1248 /// uses as dead. Only used to guard insertion into DeadInsts.
1249 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1251 /// \brief A collection of alloca instructions we can directly promote.
1252 std::vector<AllocaInst *> PromotableAllocas;
1255 SROA(bool RequiresDomTree = true)
1256 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1257 C(0), TD(0), DT(0) {
1258 initializeSROAPass(*PassRegistry::getPassRegistry());
1260 bool runOnFunction(Function &F);
1261 void getAnalysisUsage(AnalysisUsage &AU) const;
1263 const char *getPassName() const { return "SROA"; }
1267 friend class AllocaPartitionRewriter;
1268 friend class AllocaPartitionVectorRewriter;
1270 bool rewriteAllocaPartition(AllocaInst &AI,
1271 AllocaPartitioning &P,
1272 AllocaPartitioning::iterator PI);
1273 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1274 bool runOnAlloca(AllocaInst &AI);
1275 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1276 bool promoteAllocas(Function &F);
1282 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1283 return new SROA(RequiresDomTree);
1286 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1288 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1289 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1292 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1294 /// If the provided GEP is all-constant, the total byte offset formed by the
1295 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1296 /// operands, the function returns false and the value of Offset is unmodified.
1297 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1299 APInt GEPOffset(Offset.getBitWidth(), 0);
1300 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1301 GTI != GTE; ++GTI) {
1302 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1305 if (OpC->isZero()) continue;
1307 // Handle a struct index, which adds its field offset to the pointer.
1308 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1309 unsigned ElementIdx = OpC->getZExtValue();
1310 const StructLayout *SL = TD.getStructLayout(STy);
1311 GEPOffset += APInt(Offset.getBitWidth(),
1312 SL->getElementOffset(ElementIdx));
1316 APInt TypeSize(Offset.getBitWidth(),
1317 TD.getTypeAllocSize(GTI.getIndexedType()));
1318 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1319 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1320 "vector element size is not a multiple of 8, cannot GEP over it");
1321 TypeSize = VTy->getScalarSizeInBits() / 8;
1324 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1330 /// \brief Build a GEP out of a base pointer and indices.
1332 /// This will return the BasePtr if that is valid, or build a new GEP
1333 /// instruction using the IRBuilder if GEP-ing is needed.
1334 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1335 SmallVectorImpl<Value *> &Indices,
1336 const Twine &Prefix) {
1337 if (Indices.empty())
1340 // A single zero index is a no-op, so check for this and avoid building a GEP
1342 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1345 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1348 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1349 /// TargetTy without changing the offset of the pointer.
1351 /// This routine assumes we've already established a properly offset GEP with
1352 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1353 /// zero-indices down through type layers until we find one the same as
1354 /// TargetTy. If we can't find one with the same type, we at least try to use
1355 /// one with the same size. If none of that works, we just produce the GEP as
1356 /// indicated by Indices to have the correct offset.
1357 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1358 Value *BasePtr, Type *Ty, Type *TargetTy,
1359 SmallVectorImpl<Value *> &Indices,
1360 const Twine &Prefix) {
1362 return buildGEP(IRB, BasePtr, Indices, Prefix);
1364 // See if we can descend into a struct and locate a field with the correct
1366 unsigned NumLayers = 0;
1367 Type *ElementTy = Ty;
1369 if (ElementTy->isPointerTy())
1371 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1372 ElementTy = SeqTy->getElementType();
1373 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1374 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1375 ElementTy = *STy->element_begin();
1376 Indices.push_back(IRB.getInt32(0));
1381 } while (ElementTy != TargetTy);
1382 if (ElementTy != TargetTy)
1383 Indices.erase(Indices.end() - NumLayers, Indices.end());
1385 return buildGEP(IRB, BasePtr, Indices, Prefix);
1388 /// \brief Recursively compute indices for a natural GEP.
1390 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1391 /// element types adding appropriate indices for the GEP.
1392 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1393 Value *Ptr, Type *Ty, APInt &Offset,
1395 SmallVectorImpl<Value *> &Indices,
1396 const Twine &Prefix) {
1398 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1400 // We can't recurse through pointer types.
1401 if (Ty->isPointerTy())
1404 // We try to analyze GEPs over vectors here, but note that these GEPs are
1405 // extremely poorly defined currently. The long-term goal is to remove GEPing
1406 // over a vector from the IR completely.
1407 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1408 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1409 if (ElementSizeInBits % 8)
1410 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1411 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1412 APInt NumSkippedElements = Offset.udiv(ElementSize);
1413 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1415 Offset -= NumSkippedElements * ElementSize;
1416 Indices.push_back(IRB.getInt(NumSkippedElements));
1417 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1418 Offset, TargetTy, Indices, Prefix);
1421 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1422 Type *ElementTy = ArrTy->getElementType();
1423 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1424 APInt NumSkippedElements = Offset.udiv(ElementSize);
1425 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1428 Offset -= NumSkippedElements * ElementSize;
1429 Indices.push_back(IRB.getInt(NumSkippedElements));
1430 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1434 StructType *STy = dyn_cast<StructType>(Ty);
1438 const StructLayout *SL = TD.getStructLayout(STy);
1439 uint64_t StructOffset = Offset.getZExtValue();
1440 if (StructOffset >= SL->getSizeInBytes())
1442 unsigned Index = SL->getElementContainingOffset(StructOffset);
1443 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1444 Type *ElementTy = STy->getElementType(Index);
1445 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1446 return 0; // The offset points into alignment padding.
1448 Indices.push_back(IRB.getInt32(Index));
1449 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1453 /// \brief Get a natural GEP from a base pointer to a particular offset and
1454 /// resulting in a particular type.
1456 /// The goal is to produce a "natural" looking GEP that works with the existing
1457 /// composite types to arrive at the appropriate offset and element type for
1458 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1459 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1460 /// Indices, and setting Ty to the result subtype.
1462 /// If no natural GEP can be constructed, this function returns null.
1463 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1464 Value *Ptr, APInt Offset, Type *TargetTy,
1465 SmallVectorImpl<Value *> &Indices,
1466 const Twine &Prefix) {
1467 PointerType *Ty = cast<PointerType>(Ptr->getType());
1469 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1471 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1474 Type *ElementTy = Ty->getElementType();
1475 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1476 if (ElementSize == 0)
1477 return 0; // Zero-length arrays can't help us build a natural GEP.
1478 APInt NumSkippedElements = Offset.udiv(ElementSize);
1480 Offset -= NumSkippedElements * ElementSize;
1481 Indices.push_back(IRB.getInt(NumSkippedElements));
1482 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1486 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1487 /// resulting pointer has PointerTy.
1489 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1490 /// and produces the pointer type desired. Where it cannot, it will try to use
1491 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1492 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1493 /// bitcast to the type.
1495 /// The strategy for finding the more natural GEPs is to peel off layers of the
1496 /// pointer, walking back through bit casts and GEPs, searching for a base
1497 /// pointer from which we can compute a natural GEP with the desired
1498 /// properities. The algorithm tries to fold as many constant indices into
1499 /// a single GEP as possible, thus making each GEP more independent of the
1500 /// surrounding code.
1501 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1502 Value *Ptr, APInt Offset, Type *PointerTy,
1503 const Twine &Prefix) {
1504 // Even though we don't look through PHI nodes, we could be called on an
1505 // instruction in an unreachable block, which may be on a cycle.
1506 SmallPtrSet<Value *, 4> Visited;
1507 Visited.insert(Ptr);
1508 SmallVector<Value *, 4> Indices;
1510 // We may end up computing an offset pointer that has the wrong type. If we
1511 // never are able to compute one directly that has the correct type, we'll
1512 // fall back to it, so keep it around here.
1513 Value *OffsetPtr = 0;
1515 // Remember any i8 pointer we come across to re-use if we need to do a raw
1518 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1520 Type *TargetTy = PointerTy->getPointerElementType();
1523 // First fold any existing GEPs into the offset.
1524 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1525 APInt GEPOffset(Offset.getBitWidth(), 0);
1526 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1528 Offset += GEPOffset;
1529 Ptr = GEP->getPointerOperand();
1530 if (!Visited.insert(Ptr))
1534 // See if we can perform a natural GEP here.
1536 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1538 if (P->getType() == PointerTy) {
1539 // Zap any offset pointer that we ended up computing in previous rounds.
1540 if (OffsetPtr && OffsetPtr->use_empty())
1541 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1542 I->eraseFromParent();
1550 // Stash this pointer if we've found an i8*.
1551 if (Ptr->getType()->isIntegerTy(8)) {
1553 Int8PtrOffset = Offset;
1556 // Peel off a layer of the pointer and update the offset appropriately.
1557 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1558 Ptr = cast<Operator>(Ptr)->getOperand(0);
1559 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1560 if (GA->mayBeOverridden())
1562 Ptr = GA->getAliasee();
1566 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1567 } while (Visited.insert(Ptr));
1571 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1572 Prefix + ".raw_cast");
1573 Int8PtrOffset = Offset;
1576 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1577 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1578 Prefix + ".raw_idx");
1582 // On the off chance we were targeting i8*, guard the bitcast here.
1583 if (Ptr->getType() != PointerTy)
1584 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1589 /// \brief Test whether the given alloca partition can be promoted to a vector.
1591 /// This is a quick test to check whether we can rewrite a particular alloca
1592 /// partition (and its newly formed alloca) into a vector alloca with only
1593 /// whole-vector loads and stores such that it could be promoted to a vector
1594 /// SSA value. We only can ensure this for a limited set of operations, and we
1595 /// don't want to do the rewrites unless we are confident that the result will
1596 /// be promotable, so we have an early test here.
1597 static bool isVectorPromotionViable(const TargetData &TD,
1599 AllocaPartitioning &P,
1600 uint64_t PartitionBeginOffset,
1601 uint64_t PartitionEndOffset,
1602 AllocaPartitioning::const_use_iterator I,
1603 AllocaPartitioning::const_use_iterator E) {
1604 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1608 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1609 uint64_t ElementSize = Ty->getScalarSizeInBits();
1611 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1612 // that aren't byte sized.
1613 if (ElementSize % 8)
1615 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1619 for (; I != E; ++I) {
1620 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1621 uint64_t BeginIndex = BeginOffset / ElementSize;
1622 if (BeginIndex * ElementSize != BeginOffset ||
1623 BeginIndex >= Ty->getNumElements())
1625 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1626 uint64_t EndIndex = EndOffset / ElementSize;
1627 if (EndIndex * ElementSize != EndOffset ||
1628 EndIndex > Ty->getNumElements())
1631 // FIXME: We should build shuffle vector instructions to handle
1632 // non-element-sized accesses.
1633 if ((EndOffset - BeginOffset) != ElementSize &&
1634 (EndOffset - BeginOffset) != VecSize)
1637 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1638 if (MI->isVolatile())
1640 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1641 const AllocaPartitioning::MemTransferOffsets &MTO
1642 = P.getMemTransferOffsets(*MTI);
1643 if (!MTO.IsSplittable)
1646 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1647 // Disable vector promotion when there are loads or stores of an FCA.
1649 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1657 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1658 /// use a new alloca.
1660 /// Also implements the rewriting to vector-based accesses when the partition
1661 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1663 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1665 // Befriend the base class so it can delegate to private visit methods.
1666 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1668 const TargetData &TD;
1669 AllocaPartitioning &P;
1671 AllocaInst &OldAI, &NewAI;
1672 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1674 // If we are rewriting an alloca partition which can be written as pure
1675 // vector operations, we stash extra information here. When VecTy is
1676 // non-null, we have some strict guarantees about the rewriten alloca:
1677 // - The new alloca is exactly the size of the vector type here.
1678 // - The accesses all either map to the entire vector or to a single
1680 // - The set of accessing instructions is only one of those handled above
1681 // in isVectorPromotionViable. Generally these are the same access kinds
1682 // which are promotable via mem2reg.
1685 uint64_t ElementSize;
1687 // The offset of the partition user currently being rewritten.
1688 uint64_t BeginOffset, EndOffset;
1689 Instruction *OldPtr;
1691 // The name prefix to use when rewriting instructions for this alloca.
1692 std::string NamePrefix;
1695 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1696 AllocaPartitioning::iterator PI,
1697 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1698 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1699 : TD(TD), P(P), Pass(Pass),
1700 OldAI(OldAI), NewAI(NewAI),
1701 NewAllocaBeginOffset(NewBeginOffset),
1702 NewAllocaEndOffset(NewEndOffset),
1703 VecTy(), ElementTy(), ElementSize(),
1704 BeginOffset(), EndOffset() {
1707 /// \brief Visit the users of the alloca partition and rewrite them.
1708 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1709 AllocaPartitioning::const_use_iterator E) {
1710 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1711 NewAllocaBeginOffset, NewAllocaEndOffset,
1714 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1715 ElementTy = VecTy->getElementType();
1716 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1717 "Only multiple-of-8 sized vector elements are viable");
1718 ElementSize = VecTy->getScalarSizeInBits() / 8;
1720 bool CanSROA = true;
1721 for (; I != E; ++I) {
1722 BeginOffset = I->BeginOffset;
1723 EndOffset = I->EndOffset;
1725 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1726 CanSROA &= visit(I->User);
1738 // Every instruction which can end up as a user must have a rewrite rule.
1739 bool visitInstruction(Instruction &I) {
1740 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1741 llvm_unreachable("No rewrite rule for this instruction!");
1744 Twine getName(const Twine &Suffix) {
1745 return NamePrefix + Suffix;
1748 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1749 assert(BeginOffset >= NewAllocaBeginOffset);
1750 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1751 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1754 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1755 assert(VecTy && "Can only call getIndex when rewriting a vector");
1756 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1757 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1758 uint32_t Index = RelOffset / ElementSize;
1759 assert(Index * ElementSize == RelOffset);
1760 return IRB.getInt32(Index);
1763 void deleteIfTriviallyDead(Value *V) {
1764 Instruction *I = cast<Instruction>(V);
1765 if (isInstructionTriviallyDead(I))
1766 Pass.DeadInsts.push_back(I);
1769 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1770 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1771 return IRB.CreateIntToPtr(V, Ty);
1772 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1773 return IRB.CreatePtrToInt(V, Ty);
1775 return IRB.CreateBitCast(V, Ty);
1778 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1780 if (LI.getType() == VecTy->getElementType() ||
1781 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1783 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1784 getIndex(IRB, BeginOffset),
1785 getName(".extract"));
1787 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1789 if (Result->getType() != LI.getType())
1790 Result = getValueCast(IRB, Result, LI.getType());
1791 LI.replaceAllUsesWith(Result);
1792 Pass.DeadInsts.push_back(&LI);
1794 DEBUG(dbgs() << " to: " << *Result << "\n");
1798 bool visitLoadInst(LoadInst &LI) {
1799 DEBUG(dbgs() << " original: " << LI << "\n");
1800 Value *OldOp = LI.getOperand(0);
1801 assert(OldOp == OldPtr);
1802 IRBuilder<> IRB(&LI);
1805 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1807 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1808 LI.getPointerOperand()->getType());
1809 LI.setOperand(0, NewPtr);
1810 DEBUG(dbgs() << " to: " << LI << "\n");
1812 deleteIfTriviallyDead(OldOp);
1813 return NewPtr == &NewAI && !LI.isVolatile();
1816 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1818 Value *V = SI.getValueOperand();
1819 if (V->getType() == ElementTy ||
1820 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1821 if (V->getType() != ElementTy)
1822 V = getValueCast(IRB, V, ElementTy);
1823 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1824 getIndex(IRB, BeginOffset),
1825 getName(".insert"));
1826 } else if (V->getType() != VecTy) {
1827 V = getValueCast(IRB, V, VecTy);
1829 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1830 Pass.DeadInsts.push_back(&SI);
1833 DEBUG(dbgs() << " to: " << *Store << "\n");
1837 bool visitStoreInst(StoreInst &SI) {
1838 DEBUG(dbgs() << " original: " << SI << "\n");
1839 Value *OldOp = SI.getOperand(1);
1840 assert(OldOp == OldPtr);
1841 IRBuilder<> IRB(&SI);
1844 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1846 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1847 SI.getPointerOperand()->getType());
1848 SI.setOperand(1, NewPtr);
1849 DEBUG(dbgs() << " to: " << SI << "\n");
1851 deleteIfTriviallyDead(OldOp);
1852 return NewPtr == &NewAI && !SI.isVolatile();
1855 bool visitMemSetInst(MemSetInst &II) {
1856 DEBUG(dbgs() << " original: " << II << "\n");
1857 IRBuilder<> IRB(&II);
1858 assert(II.getRawDest() == OldPtr);
1860 // If the memset has a variable size, it cannot be split, just adjust the
1861 // pointer to the new alloca.
1862 if (!isa<Constant>(II.getLength())) {
1863 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1864 deleteIfTriviallyDead(OldPtr);
1868 // Record this instruction for deletion.
1869 if (Pass.DeadSplitInsts.insert(&II))
1870 Pass.DeadInsts.push_back(&II);
1872 Type *AllocaTy = NewAI.getAllocatedType();
1873 Type *ScalarTy = AllocaTy->getScalarType();
1875 // If this doesn't map cleanly onto the alloca type, and that type isn't
1876 // a single value type, just emit a memset.
1877 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1878 EndOffset != NewAllocaEndOffset ||
1879 !AllocaTy->isSingleValueType() ||
1880 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1881 Type *SizeTy = II.getLength()->getType();
1882 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1885 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1886 II.getRawDest()->getType()),
1887 II.getValue(), Size, II.getAlignment(),
1890 DEBUG(dbgs() << " to: " << *New << "\n");
1894 // If we can represent this as a simple value, we have to build the actual
1895 // value to store, which requires expanding the byte present in memset to
1896 // a sensible representation for the alloca type. This is essentially
1897 // splatting the byte to a sufficiently wide integer, bitcasting to the
1898 // desired scalar type, and splatting it across any desired vector type.
1899 Value *V = II.getValue();
1900 IntegerType *VTy = cast<IntegerType>(V->getType());
1901 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1902 TD.getTypeSizeInBits(ScalarTy));
1903 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1904 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1905 ConstantExpr::getUDiv(
1906 Constant::getAllOnesValue(IntTy),
1907 ConstantExpr::getZExt(
1908 Constant::getAllOnesValue(V->getType()),
1910 getName(".isplat"));
1911 if (V->getType() != ScalarTy) {
1912 if (ScalarTy->isPointerTy())
1913 V = IRB.CreateIntToPtr(V, ScalarTy);
1914 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1915 V = IRB.CreateBitCast(V, ScalarTy);
1916 else if (ScalarTy->isIntegerTy())
1917 llvm_unreachable("Computed different integer types with equal widths");
1919 llvm_unreachable("Invalid scalar type");
1922 // If this is an element-wide memset of a vectorizable alloca, insert it.
1923 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1924 EndOffset < NewAllocaEndOffset)) {
1925 StoreInst *Store = IRB.CreateStore(
1926 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1927 getIndex(IRB, BeginOffset),
1928 getName(".insert")),
1931 DEBUG(dbgs() << " to: " << *Store << "\n");
1935 // Splat to a vector if needed.
1936 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1937 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1938 V = IRB.CreateShuffleVector(
1939 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1940 IRB.getInt32(0), getName(".vsplat.insert")),
1941 UndefValue::get(SplatSourceTy),
1942 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1943 getName(".vsplat.shuffle"));
1944 assert(V->getType() == VecTy);
1947 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1949 DEBUG(dbgs() << " to: " << *New << "\n");
1950 return !II.isVolatile();
1953 bool visitMemTransferInst(MemTransferInst &II) {
1954 // Rewriting of memory transfer instructions can be a bit tricky. We break
1955 // them into two categories: split intrinsics and unsplit intrinsics.
1957 DEBUG(dbgs() << " original: " << II << "\n");
1958 IRBuilder<> IRB(&II);
1960 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1961 bool IsDest = II.getRawDest() == OldPtr;
1963 const AllocaPartitioning::MemTransferOffsets &MTO
1964 = P.getMemTransferOffsets(II);
1966 // For unsplit intrinsics, we simply modify the source and destination
1967 // pointers in place. This isn't just an optimization, it is a matter of
1968 // correctness. With unsplit intrinsics we may be dealing with transfers
1969 // within a single alloca before SROA ran, or with transfers that have
1970 // a variable length. We may also be dealing with memmove instead of
1971 // memcpy, and so simply updating the pointers is the necessary for us to
1972 // update both source and dest of a single call.
1973 if (!MTO.IsSplittable) {
1974 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1976 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1978 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1980 DEBUG(dbgs() << " to: " << II << "\n");
1981 deleteIfTriviallyDead(OldOp);
1984 // For split transfer intrinsics we have an incredibly useful assurance:
1985 // the source and destination do not reside within the same alloca, and at
1986 // least one of them does not escape. This means that we can replace
1987 // memmove with memcpy, and we don't need to worry about all manner of
1988 // downsides to splitting and transforming the operations.
1990 // Compute the relative offset within the transfer.
1991 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1992 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
1993 : MTO.SourceBegin));
1995 // If this doesn't map cleanly onto the alloca type, and that type isn't
1996 // a single value type, just emit a memcpy.
1998 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
1999 EndOffset != NewAllocaEndOffset ||
2000 !NewAI.getAllocatedType()->isSingleValueType());
2002 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2003 // size hasn't been shrunk based on analysis of the viable range, this is
2005 if (EmitMemCpy && &OldAI == &NewAI) {
2006 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2007 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2008 // Ensure the start lines up.
2009 assert(BeginOffset == OrigBegin);
2012 // Rewrite the size as needed.
2013 if (EndOffset != OrigEnd)
2014 II.setLength(ConstantInt::get(II.getLength()->getType(),
2015 EndOffset - BeginOffset));
2018 // Record this instruction for deletion.
2019 if (Pass.DeadSplitInsts.insert(&II))
2020 Pass.DeadInsts.push_back(&II);
2022 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2023 EndOffset < NewAllocaEndOffset);
2025 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2026 : II.getRawDest()->getType();
2028 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2031 // Compute the other pointer, folding as much as possible to produce
2032 // a single, simple GEP in most cases.
2033 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2034 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2035 getName("." + OtherPtr->getName()));
2037 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2038 // alloca that should be re-examined after rewriting this instruction.
2040 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2041 Pass.Worklist.insert(AI);
2045 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2046 : II.getRawSource()->getType());
2047 Type *SizeTy = II.getLength()->getType();
2048 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2050 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2051 IsDest ? OtherPtr : OurPtr,
2052 Size, II.getAlignment(),
2055 DEBUG(dbgs() << " to: " << *New << "\n");
2059 Value *SrcPtr = OtherPtr;
2060 Value *DstPtr = &NewAI;
2062 std::swap(SrcPtr, DstPtr);
2065 if (IsVectorElement && !IsDest) {
2066 // We have to extract rather than load.
2067 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
2068 getName(".copyload")),
2069 getIndex(IRB, BeginOffset),
2070 getName(".copyextract"));
2072 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
2075 if (IsVectorElement && IsDest) {
2076 // We have to insert into a loaded copy before storing.
2077 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
2078 Src, getIndex(IRB, BeginOffset),
2079 getName(".insert"));
2082 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
2084 DEBUG(dbgs() << " to: " << *Store << "\n");
2085 return !II.isVolatile();
2088 bool visitIntrinsicInst(IntrinsicInst &II) {
2089 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2090 II.getIntrinsicID() == Intrinsic::lifetime_end);
2091 DEBUG(dbgs() << " original: " << II << "\n");
2092 IRBuilder<> IRB(&II);
2093 assert(II.getArgOperand(1) == OldPtr);
2095 // Record this instruction for deletion.
2096 if (Pass.DeadSplitInsts.insert(&II))
2097 Pass.DeadInsts.push_back(&II);
2100 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2101 EndOffset - BeginOffset);
2102 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2104 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2105 New = IRB.CreateLifetimeStart(Ptr, Size);
2107 New = IRB.CreateLifetimeEnd(Ptr, Size);
2109 DEBUG(dbgs() << " to: " << *New << "\n");
2113 /// PHI instructions that use an alloca and are subsequently loaded can be
2114 /// rewritten to load both input pointers in the pred blocks and then PHI the
2115 /// results, allowing the load of the alloca to be promoted.
2117 /// %P2 = phi [i32* %Alloca, i32* %Other]
2118 /// %V = load i32* %P2
2120 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2122 /// %V2 = load i32* %Other
2124 /// %V = phi [i32 %V1, i32 %V2]
2126 /// We can do this to a select if its only uses are loads and if the operand
2127 /// to the select can be loaded unconditionally.
2129 /// FIXME: This should be hoisted into a generic utility, likely in
2130 /// Transforms/Util/Local.h
2131 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2132 // For now, we can only do this promotion if the load is in the same block
2133 // as the PHI, and if there are no stores between the phi and load.
2134 // TODO: Allow recursive phi users.
2135 // TODO: Allow stores.
2136 BasicBlock *BB = PN.getParent();
2137 unsigned MaxAlign = 0;
2138 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2140 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2141 if (LI == 0 || !LI->isSimple()) return false;
2143 // For now we only allow loads in the same block as the PHI. This is
2144 // a common case that happens when instcombine merges two loads through
2146 if (LI->getParent() != BB) return false;
2148 // Ensure that there are no instructions between the PHI and the load that
2150 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2151 if (BBI->mayWriteToMemory())
2154 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2155 Loads.push_back(LI);
2158 // We can only transform this if it is safe to push the loads into the
2159 // predecessor blocks. The only thing to watch out for is that we can't put
2160 // a possibly trapping load in the predecessor if it is a critical edge.
2161 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2163 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2164 Value *InVal = PN.getIncomingValue(Idx);
2166 // If the value is produced by the terminator of the predecessor (an
2167 // invoke) or it has side-effects, there is no valid place to put a load
2168 // in the predecessor.
2169 if (TI == InVal || TI->mayHaveSideEffects())
2172 // If the predecessor has a single successor, then the edge isn't
2174 if (TI->getNumSuccessors() == 1)
2177 // If this pointer is always safe to load, or if we can prove that there
2178 // is already a load in the block, then we can move the load to the pred
2180 if (InVal->isDereferenceablePointer() ||
2181 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2190 bool visitPHINode(PHINode &PN) {
2191 DEBUG(dbgs() << " original: " << PN << "\n");
2192 // We would like to compute a new pointer in only one place, but have it be
2193 // as local as possible to the PHI. To do that, we re-use the location of
2194 // the old pointer, which necessarily must be in the right position to
2195 // dominate the PHI.
2196 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2198 SmallVector<LoadInst *, 4> Loads;
2199 if (!isSafePHIToSpeculate(PN, Loads)) {
2200 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2201 // Replace the operands which were using the old pointer.
2202 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2203 for (; OI != OE; ++OI)
2207 DEBUG(dbgs() << " to: " << PN << "\n");
2208 deleteIfTriviallyDead(OldPtr);
2211 assert(!Loads.empty());
2213 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2214 IRBuilder<> PHIBuilder(&PN);
2215 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2216 NewPN->takeName(&PN);
2218 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2219 // matter which one we get and if any differ, it doesn't matter.
2220 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2221 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2222 unsigned Align = SomeLoad->getAlignment();
2223 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2225 // Rewrite all loads of the PN to use the new PHI.
2227 LoadInst *LI = Loads.pop_back_val();
2228 LI->replaceAllUsesWith(NewPN);
2229 Pass.DeadInsts.push_back(LI);
2230 } while (!Loads.empty());
2232 // Inject loads into all of the pred blocks.
2233 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2234 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2235 TerminatorInst *TI = Pred->getTerminator();
2236 Value *InVal = PN.getIncomingValue(Idx);
2237 IRBuilder<> PredBuilder(TI);
2239 // Map the value to the new alloca pointer if this was the old alloca
2241 bool ThisOperand = InVal == OldPtr;
2246 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2248 ++NumLoadsSpeculated;
2249 Load->setAlignment(Align);
2251 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2252 NewPN->addIncoming(Load, Pred);
2256 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2258 // No uses to rewrite.
2261 // Try to lookup and rewrite any partition uses corresponding to this phi
2263 AllocaPartitioning::iterator PI
2264 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2265 if (PI != P.end()) {
2266 // If the other pointer is within the partitioning, replace the PHI in
2267 // its uses with the load we just speculated, or add another load for
2268 // it to rewrite if we've already replaced the PHI.
2269 AllocaPartitioning::use_iterator UI
2270 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2271 if (isa<PHINode>(*UI->User))
2274 AllocaPartitioning::PartitionUse OtherUse = *UI;
2275 OtherUse.User = Load;
2276 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2281 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2282 return NewPtr == &NewAI;
2285 /// Select instructions that use an alloca and are subsequently loaded can be
2286 /// rewritten to load both input pointers and then select between the result,
2287 /// allowing the load of the alloca to be promoted.
2289 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2290 /// %V = load i32* %P2
2292 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2293 /// %V2 = load i32* %Other
2294 /// %V = select i1 %cond, i32 %V1, i32 %V2
2296 /// We can do this to a select if its only uses are loads and if the operand
2297 /// to the select can be loaded unconditionally.
2298 bool isSafeSelectToSpeculate(SelectInst &SI,
2299 SmallVectorImpl<LoadInst *> &Loads) {
2300 Value *TValue = SI.getTrueValue();
2301 Value *FValue = SI.getFalseValue();
2302 bool TDerefable = TValue->isDereferenceablePointer();
2303 bool FDerefable = FValue->isDereferenceablePointer();
2305 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2307 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2308 if (LI == 0 || !LI->isSimple()) return false;
2310 // Both operands to the select need to be dereferencable, either
2311 // absolutely (e.g. allocas) or at this point because we can see other
2313 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2314 LI->getAlignment(), &TD))
2316 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2317 LI->getAlignment(), &TD))
2319 Loads.push_back(LI);
2325 bool visitSelectInst(SelectInst &SI) {
2326 DEBUG(dbgs() << " original: " << SI << "\n");
2327 IRBuilder<> IRB(&SI);
2329 // Find the operand we need to rewrite here.
2330 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2332 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2334 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2335 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2337 // If the select isn't safe to speculate, just use simple logic to emit it.
2338 SmallVector<LoadInst *, 4> Loads;
2339 if (!isSafeSelectToSpeculate(SI, Loads)) {
2340 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2341 DEBUG(dbgs() << " to: " << SI << "\n");
2342 deleteIfTriviallyDead(OldPtr);
2346 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2347 AllocaPartitioning::iterator PI
2348 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2349 AllocaPartitioning::PartitionUse OtherUse;
2350 if (PI != P.end()) {
2351 // If the other pointer is within the partitioning, remove the select
2352 // from its uses. We'll add in the new loads below.
2353 AllocaPartitioning::use_iterator UI
2354 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2356 P.use_erase(PI, UI);
2359 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2360 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2361 // Replace the loads of the select with a select of two loads.
2362 while (!Loads.empty()) {
2363 LoadInst *LI = Loads.pop_back_val();
2365 IRB.SetInsertPoint(LI);
2367 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2369 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2370 NumLoadsSpeculated += 2;
2371 if (PI != P.end()) {
2372 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2373 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2374 OtherUse.User = OtherLoad;
2375 P.use_insert(PI, P.use_end(PI), OtherUse);
2378 // Transfer alignment and TBAA info if present.
2379 TL->setAlignment(LI->getAlignment());
2380 FL->setAlignment(LI->getAlignment());
2381 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2382 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2383 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2386 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2388 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2389 LI->replaceAllUsesWith(V);
2390 Pass.DeadInsts.push_back(LI);
2393 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2395 deleteIfTriviallyDead(OldPtr);
2396 return NewPtr == &NewAI;
2402 /// \brief Try to find a partition of the aggregate type passed in for a given
2403 /// offset and size.
2405 /// This recurses through the aggregate type and tries to compute a subtype
2406 /// based on the offset and size. When the offset and size span a sub-section
2407 /// of an array, it will even compute a new array type for that sub-section,
2408 /// and the same for structs.
2410 /// Note that this routine is very strict and tries to find a partition of the
2411 /// type which produces the *exact* right offset and size. It is not forgiving
2412 /// when the size or offset cause either end of type-based partition to be off.
2413 /// Also, this is a best-effort routine. It is reasonable to give up and not
2414 /// return a type if necessary.
2415 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2416 uint64_t Offset, uint64_t Size) {
2417 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2420 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2421 // We can't partition pointers...
2422 if (SeqTy->isPointerTy())
2425 Type *ElementTy = SeqTy->getElementType();
2426 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2427 uint64_t NumSkippedElements = Offset / ElementSize;
2428 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2429 if (NumSkippedElements >= ArrTy->getNumElements())
2431 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2432 if (NumSkippedElements >= VecTy->getNumElements())
2434 Offset -= NumSkippedElements * ElementSize;
2436 // First check if we need to recurse.
2437 if (Offset > 0 || Size < ElementSize) {
2438 // Bail if the partition ends in a different array element.
2439 if ((Offset + Size) > ElementSize)
2441 // Recurse through the element type trying to peel off offset bytes.
2442 return getTypePartition(TD, ElementTy, Offset, Size);
2444 assert(Offset == 0);
2446 if (Size == ElementSize)
2448 assert(Size > ElementSize);
2449 uint64_t NumElements = Size / ElementSize;
2450 if (NumElements * ElementSize != Size)
2452 return ArrayType::get(ElementTy, NumElements);
2455 StructType *STy = dyn_cast<StructType>(Ty);
2459 const StructLayout *SL = TD.getStructLayout(STy);
2460 if (Offset >= SL->getSizeInBytes())
2462 uint64_t EndOffset = Offset + Size;
2463 if (EndOffset > SL->getSizeInBytes())
2466 unsigned Index = SL->getElementContainingOffset(Offset);
2467 Offset -= SL->getElementOffset(Index);
2469 Type *ElementTy = STy->getElementType(Index);
2470 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2471 if (Offset >= ElementSize)
2472 return 0; // The offset points into alignment padding.
2474 // See if any partition must be contained by the element.
2475 if (Offset > 0 || Size < ElementSize) {
2476 if ((Offset + Size) > ElementSize)
2478 return getTypePartition(TD, ElementTy, Offset, Size);
2480 assert(Offset == 0);
2482 if (Size == ElementSize)
2485 StructType::element_iterator EI = STy->element_begin() + Index,
2486 EE = STy->element_end();
2487 if (EndOffset < SL->getSizeInBytes()) {
2488 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2489 if (Index == EndIndex)
2490 return 0; // Within a single element and its padding.
2492 // Don't try to form "natural" types if the elements don't line up with the
2494 // FIXME: We could potentially recurse down through the last element in the
2495 // sub-struct to find a natural end point.
2496 if (SL->getElementOffset(EndIndex) != EndOffset)
2499 assert(Index < EndIndex);
2500 EE = STy->element_begin() + EndIndex;
2503 // Try to build up a sub-structure.
2504 SmallVector<Type *, 4> ElementTys;
2506 ElementTys.push_back(*EI++);
2508 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2510 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2511 if (Size != SubSL->getSizeInBytes())
2512 return 0; // The sub-struct doesn't have quite the size needed.
2517 /// \brief Rewrite an alloca partition's users.
2519 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2520 /// to rewrite uses of an alloca partition to be conducive for SSA value
2521 /// promotion. If the partition needs a new, more refined alloca, this will
2522 /// build that new alloca, preserving as much type information as possible, and
2523 /// rewrite the uses of the old alloca to point at the new one and have the
2524 /// appropriate new offsets. It also evaluates how successful the rewrite was
2525 /// at enabling promotion and if it was successful queues the alloca to be
2527 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2528 AllocaPartitioning &P,
2529 AllocaPartitioning::iterator PI) {
2530 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2531 if (P.use_begin(PI) == P.use_end(PI))
2532 return false; // No live uses left of this partition.
2534 // Try to compute a friendly type for this partition of the alloca. This
2535 // won't always succeed, in which case we fall back to a legal integer type
2536 // or an i8 array of an appropriate size.
2538 if (Type *PartitionTy = P.getCommonType(PI))
2539 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2540 AllocaTy = PartitionTy;
2542 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2543 PI->BeginOffset, AllocaSize))
2544 AllocaTy = PartitionTy;
2546 (AllocaTy->isArrayTy() &&
2547 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2548 TD->isLegalInteger(AllocaSize * 8))
2549 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2551 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2552 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
2554 // Check for the case where we're going to rewrite to a new alloca of the
2555 // exact same type as the original, and with the same access offsets. In that
2556 // case, re-use the existing alloca, but still run through the rewriter to
2557 // performe phi and select speculation.
2559 if (AllocaTy == AI.getAllocatedType()) {
2560 assert(PI->BeginOffset == 0 &&
2561 "Non-zero begin offset but same alloca type");
2562 assert(PI == P.begin() && "Begin offset is zero on later partition");
2565 // FIXME: The alignment here is overly conservative -- we could in many
2566 // cases get away with much weaker alignment constraints.
2567 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2568 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2573 DEBUG(dbgs() << "Rewriting alloca partition "
2574 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2577 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2578 PI->BeginOffset, PI->EndOffset);
2579 DEBUG(dbgs() << " rewriting ");
2580 DEBUG(P.print(dbgs(), PI, ""));
2581 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2582 DEBUG(dbgs() << " and queuing for promotion\n");
2583 PromotableAllocas.push_back(NewAI);
2584 } else if (NewAI != &AI) {
2585 // If we can't promote the alloca, iterate on it to check for new
2586 // refinements exposed by splitting the current alloca. Don't iterate on an
2587 // alloca which didn't actually change and didn't get promoted.
2588 Worklist.insert(NewAI);
2593 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2594 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2595 bool Changed = false;
2596 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2598 Changed |= rewriteAllocaPartition(AI, P, PI);
2603 /// \brief Analyze an alloca for SROA.
2605 /// This analyzes the alloca to ensure we can reason about it, builds
2606 /// a partitioning of the alloca, and then hands it off to be split and
2607 /// rewritten as needed.
2608 bool SROA::runOnAlloca(AllocaInst &AI) {
2609 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2610 ++NumAllocasAnalyzed;
2612 // Special case dead allocas, as they're trivial.
2613 if (AI.use_empty()) {
2614 AI.eraseFromParent();
2618 // Skip alloca forms that this analysis can't handle.
2619 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2620 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2623 // First check if this is a non-aggregate type that we should simply promote.
2624 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2625 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2626 PromotableAllocas.push_back(&AI);
2630 // Build the partition set using a recursive instruction-visiting builder.
2631 AllocaPartitioning P(*TD, AI);
2632 DEBUG(P.print(dbgs()));
2636 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2637 if (P.begin() == P.end())
2640 // Delete all the dead users of this alloca before splitting and rewriting it.
2641 bool Changed = false;
2642 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2643 DE = P.dead_user_end();
2646 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2647 DeadInsts.push_back(*DI);
2649 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2650 DE = P.dead_op_end();
2653 // Clobber the use with an undef value.
2654 **DO = UndefValue::get(OldV->getType());
2655 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2656 if (isInstructionTriviallyDead(OldI)) {
2658 DeadInsts.push_back(OldI);
2662 return splitAlloca(AI, P) || Changed;
2665 /// \brief Delete the dead instructions accumulated in this run.
2667 /// Recursively deletes the dead instructions we've accumulated. This is done
2668 /// at the very end to maximize locality of the recursive delete and to
2669 /// minimize the problems of invalidated instruction pointers as such pointers
2670 /// are used heavily in the intermediate stages of the algorithm.
2672 /// We also record the alloca instructions deleted here so that they aren't
2673 /// subsequently handed to mem2reg to promote.
2674 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
2675 DeadSplitInsts.clear();
2676 while (!DeadInsts.empty()) {
2677 Instruction *I = DeadInsts.pop_back_val();
2678 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2680 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2681 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2682 // Zero out the operand and see if it becomes trivially dead.
2684 if (isInstructionTriviallyDead(U))
2685 DeadInsts.push_back(U);
2688 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2689 DeletedAllocas.insert(AI);
2692 I->eraseFromParent();
2696 /// \brief Promote the allocas, using the best available technique.
2698 /// This attempts to promote whatever allocas have been identified as viable in
2699 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
2700 /// If there is a domtree available, we attempt to promote using the full power
2701 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
2702 /// based on the SSAUpdater utilities. This function returns whether any
2703 /// promotion occured.
2704 bool SROA::promoteAllocas(Function &F) {
2705 if (PromotableAllocas.empty())
2708 NumPromoted += PromotableAllocas.size();
2710 if (DT && !ForceSSAUpdater) {
2711 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2712 PromoteMemToReg(PromotableAllocas, *DT);
2713 PromotableAllocas.clear();
2717 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
2719 DIBuilder DIB(*F.getParent());
2720 SmallVector<Instruction*, 64> Insts;
2722 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
2723 AllocaInst *AI = PromotableAllocas[Idx];
2724 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
2726 Instruction *I = cast<Instruction>(*UI++);
2727 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
2728 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
2729 // leading to them) here. Eventually it should use them to optimize the
2730 // scalar values produced.
2731 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
2732 assert(onlyUsedByLifetimeMarkers(I) &&
2733 "Found a bitcast used outside of a lifetime marker.");
2734 while (!I->use_empty())
2735 cast<Instruction>(*I->use_begin())->eraseFromParent();
2736 I->eraseFromParent();
2739 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2740 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
2741 II->getIntrinsicID() == Intrinsic::lifetime_end);
2742 II->eraseFromParent();
2748 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
2752 PromotableAllocas.clear();
2757 /// \brief A predicate to test whether an alloca belongs to a set.
2758 class IsAllocaInSet {
2759 typedef SmallPtrSet<AllocaInst *, 4> SetType;
2763 IsAllocaInSet(const SetType &Set) : Set(Set) {}
2764 bool operator()(AllocaInst *AI) { return Set.count(AI); }
2768 bool SROA::runOnFunction(Function &F) {
2769 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2770 C = &F.getContext();
2771 TD = getAnalysisIfAvailable<TargetData>();
2773 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
2776 DT = getAnalysisIfAvailable<DominatorTree>();
2778 BasicBlock &EntryBB = F.getEntryBlock();
2779 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
2781 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2782 Worklist.insert(AI);
2784 bool Changed = false;
2785 // A set of deleted alloca instruction pointers which should be removed from
2786 // the list of promotable allocas.
2787 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
2789 while (!Worklist.empty()) {
2790 Changed |= runOnAlloca(*Worklist.pop_back_val());
2791 deleteDeadInstructions(DeletedAllocas);
2792 if (!DeletedAllocas.empty()) {
2793 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
2794 PromotableAllocas.end(),
2795 IsAllocaInSet(DeletedAllocas)),
2796 PromotableAllocas.end());
2797 DeletedAllocas.clear();
2801 Changed |= promoteAllocas(F);
2806 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
2807 if (RequiresDomTree)
2808 AU.addRequired<DominatorTree>();
2809 AU.setPreservesCFG();