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 Offset, uint64_t Size,
494 bool IsSplittable = false) {
495 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
497 // Completely skip uses which start outside of the allocation.
498 if (BeginOffset >= AllocSize) {
499 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
500 << " which starts past the end of the " << AllocSize
502 << " alloca: " << P.AI << "\n"
503 << " use: " << I << "\n");
507 // Clamp the size to the allocation.
508 if (EndOffset > AllocSize) {
509 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
510 << " to remain within the " << AllocSize << " byte alloca:\n"
511 << " alloca: " << P.AI << "\n"
512 << " use: " << I << "\n");
513 EndOffset = AllocSize;
516 // See if we can just add a user onto the last slot currently occupied.
517 if (!P.Partitions.empty() &&
518 P.Partitions.back().BeginOffset == BeginOffset &&
519 P.Partitions.back().EndOffset == EndOffset) {
520 P.Partitions.back().IsSplittable &= IsSplittable;
524 Partition New(BeginOffset, EndOffset, IsSplittable);
525 P.Partitions.push_back(New);
528 bool handleLoadOrStore(Type *Ty, Instruction &I, uint64_t Offset) {
529 uint64_t Size = TD.getTypeStoreSize(Ty);
531 // If this memory access can be shown to *statically* extend outside the
532 // bounds of of the allocation, it's behavior is undefined, so simply
533 // ignore it. Note that this is more strict than the generic clamping
534 // behavior of insertUse. We also try to handle cases which might run the
536 // FIXME: We should instead consider the pointer to have escaped if this
537 // function is being instrumented for addressing bugs or race conditions.
538 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
539 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
540 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
541 << " which extends past the end of the " << AllocSize
543 << " alloca: " << P.AI << "\n"
544 << " use: " << I << "\n");
548 insertUse(I, Offset, Size);
552 bool visitBitCastInst(BitCastInst &BC) {
553 enqueueUsers(BC, Offset);
557 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
559 if (!computeConstantGEPOffset(GEPI, GEPOffset))
560 return markAsEscaping(GEPI);
562 enqueueUsers(GEPI, GEPOffset);
566 bool visitLoadInst(LoadInst &LI) {
567 return handleLoadOrStore(LI.getType(), LI, Offset);
570 bool visitStoreInst(StoreInst &SI) {
571 if (SI.getOperand(0) == *U)
572 return markAsEscaping(SI);
574 return handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
578 bool visitMemSetInst(MemSetInst &II) {
579 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
580 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
581 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
582 insertUse(II, Offset, Size, Length);
586 bool visitMemTransferInst(MemTransferInst &II) {
587 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
588 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
590 // Zero-length mem transfer intrinsics can be ignored entirely.
593 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
595 // Only intrinsics with a constant length can be split.
596 Offsets.IsSplittable = Length;
598 if (*U != II.getRawDest()) {
599 assert(*U == II.getRawSource());
600 Offsets.SourceBegin = Offset;
601 Offsets.SourceEnd = Offset + Size;
603 Offsets.DestBegin = Offset;
604 Offsets.DestEnd = Offset + Size;
607 insertUse(II, Offset, Size, Offsets.IsSplittable);
608 unsigned NewIdx = P.Partitions.size() - 1;
610 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
611 bool Inserted = false;
612 llvm::tie(PMI, Inserted)
613 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
614 if (!Inserted && Offsets.IsSplittable) {
615 // We've found a memory transfer intrinsic which refers to the alloca as
616 // both a source and dest. We refuse to split these to simplify splitting
617 // logic. If possible, SROA will still split them into separate allocas
618 // and then re-analyze.
619 Offsets.IsSplittable = false;
620 P.Partitions[PMI->second].IsSplittable = false;
621 P.Partitions[NewIdx].IsSplittable = false;
627 // Disable SRoA for any intrinsics except for lifetime invariants.
628 // FIXME: What about debug instrinsics? This matches old behavior, but
629 // doesn't make sense.
630 bool visitIntrinsicInst(IntrinsicInst &II) {
631 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
632 II.getIntrinsicID() == Intrinsic::lifetime_end) {
633 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
634 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
635 insertUse(II, Offset, Size, true);
639 return markAsEscaping(II);
642 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
643 // We consider any PHI or select that results in a direct load or store of
644 // the same offset to be a viable use for partitioning purposes. These uses
645 // are considered unsplittable and the size is the maximum loaded or stored
647 SmallPtrSet<Instruction *, 4> Visited;
648 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
649 Visited.insert(Root);
650 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
652 Instruction *I, *UsedI;
653 llvm::tie(UsedI, I) = Uses.pop_back_val();
655 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
656 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
659 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
660 Value *Op = SI->getOperand(0);
663 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
667 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
668 if (!GEP->hasAllZeroIndices())
670 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
671 !isa<SelectInst>(I)) {
675 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
677 if (Visited.insert(cast<Instruction>(*UI)))
678 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
679 } while (!Uses.empty());
684 bool visitPHINode(PHINode &PN) {
685 // See if we already have computed info on this node.
686 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
688 PHIInfo.second = true;
689 insertUse(PN, Offset, PHIInfo.first);
693 // Check for an unsafe use of the PHI node.
694 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
695 return markAsEscaping(*EscapingI);
697 insertUse(PN, Offset, PHIInfo.first);
701 bool visitSelectInst(SelectInst &SI) {
702 if (Value *Result = foldSelectInst(SI)) {
704 // If the result of the constant fold will be the pointer, recurse
705 // through the select as if we had RAUW'ed it.
706 enqueueUsers(SI, Offset);
711 // See if we already have computed info on this node.
712 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
713 if (SelectInfo.first) {
714 SelectInfo.second = true;
715 insertUse(SI, Offset, SelectInfo.first);
719 // Check for an unsafe use of the PHI node.
720 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
721 return markAsEscaping(*EscapingI);
723 insertUse(SI, Offset, SelectInfo.first);
727 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
728 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
732 /// \brief Use adder for the alloca partitioning.
734 /// This class adds the uses of an alloca to all of the partitions which they
735 /// use. For splittable partitions, this can end up doing essentially a linear
736 /// walk of the partitions, but the number of steps remains bounded by the
737 /// total result instruction size:
738 /// - The number of partitions is a result of the number unsplittable
739 /// instructions using the alloca.
740 /// - The number of users of each partition is at worst the total number of
741 /// splittable instructions using the alloca.
742 /// Thus we will produce N * M instructions in the end, where N are the number
743 /// of unsplittable uses and M are the number of splittable. This visitor does
744 /// the exact same number of updates to the partitioning.
746 /// In the more common case, this visitor will leverage the fact that the
747 /// partition space is pre-sorted, and do a logarithmic search for the
748 /// partition needed, making the total visit a classical ((N + M) * log(N))
749 /// complexity operation.
750 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
751 friend class InstVisitor<UseBuilder>;
753 /// \brief Set to de-duplicate dead instructions found in the use walk.
754 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
757 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
758 : BuilderBase<UseBuilder>(TD, AI, P) {}
760 /// \brief Run the builder over the allocation.
762 // Note that we have to re-evaluate size on each trip through the loop as
763 // the queue grows at the tail.
764 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
766 Offset = Queue[Idx].Offset;
767 this->visit(cast<Instruction>(U->getUser()));
772 void markAsDead(Instruction &I) {
773 if (VisitedDeadInsts.insert(&I))
774 P.DeadUsers.push_back(&I);
777 void insertUse(Instruction &User, uint64_t Offset, uint64_t Size) {
778 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
780 // If the use extends outside of the allocation, record it as a dead use
781 // for elimination later.
782 if (BeginOffset >= AllocSize || Size == 0)
783 return markAsDead(User);
785 // Bound the use by the size of the allocation.
786 if (EndOffset > AllocSize)
787 EndOffset = AllocSize;
789 // NB: This only works if we have zero overlapping partitions.
790 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
791 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
793 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
795 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
796 std::min(I->EndOffset, EndOffset),
797 &User, cast<Instruction>(*U));
798 P.Uses[I - P.begin()].push_back(NewUse);
799 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
800 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
801 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
805 void handleLoadOrStore(Type *Ty, Instruction &I, uint64_t Offset) {
806 uint64_t Size = TD.getTypeStoreSize(Ty);
808 // If this memory access can be shown to *statically* extend outside the
809 // bounds of of the allocation, it's behavior is undefined, so simply
810 // ignore it. Note that this is more strict than the generic clamping
811 // behavior of insertUse.
812 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
813 return markAsDead(I);
815 insertUse(I, Offset, Size);
818 void visitBitCastInst(BitCastInst &BC) {
820 return markAsDead(BC);
822 enqueueUsers(BC, Offset);
825 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
826 if (GEPI.use_empty())
827 return markAsDead(GEPI);
830 if (!computeConstantGEPOffset(GEPI, GEPOffset))
831 llvm_unreachable("Unable to compute constant offset for use");
833 enqueueUsers(GEPI, GEPOffset);
836 void visitLoadInst(LoadInst &LI) {
837 handleLoadOrStore(LI.getType(), LI, Offset);
840 void visitStoreInst(StoreInst &SI) {
841 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
844 void visitMemSetInst(MemSetInst &II) {
845 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
846 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
847 insertUse(II, Offset, Size);
850 void visitMemTransferInst(MemTransferInst &II) {
851 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
852 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
853 insertUse(II, Offset, Size);
856 void visitIntrinsicInst(IntrinsicInst &II) {
857 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
858 II.getIntrinsicID() == Intrinsic::lifetime_end);
860 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
861 insertUse(II, Offset,
862 std::min(AllocSize - Offset, Length->getLimitedValue()));
865 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
866 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
868 // For PHI and select operands outside the alloca, we can't nuke the entire
869 // phi or select -- the other side might still be relevant, so we special
870 // case them here and use a separate structure to track the operands
871 // themselves which should be replaced with undef.
872 if (Offset >= AllocSize) {
873 P.DeadOperands.push_back(U);
877 insertUse(User, Offset, Size);
879 void visitPHINode(PHINode &PN) {
881 return markAsDead(PN);
883 insertPHIOrSelect(PN, Offset);
885 void visitSelectInst(SelectInst &SI) {
887 return markAsDead(SI);
889 if (Value *Result = foldSelectInst(SI)) {
891 // If the result of the constant fold will be the pointer, recurse
892 // through the select as if we had RAUW'ed it.
893 enqueueUsers(SI, Offset);
898 insertPHIOrSelect(SI, Offset);
901 /// \brief Unreachable, we've already visited the alloca once.
902 void visitInstruction(Instruction &I) {
903 llvm_unreachable("Unhandled instruction in use builder.");
907 void AllocaPartitioning::splitAndMergePartitions() {
908 size_t NumDeadPartitions = 0;
910 // Track the range of splittable partitions that we pass when accumulating
911 // overlapping unsplittable partitions.
912 uint64_t SplitEndOffset = 0ull;
914 Partition New(0ull, 0ull, false);
916 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
919 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
920 assert(New.BeginOffset == New.EndOffset);
923 assert(New.IsSplittable);
924 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
926 assert(New.BeginOffset != New.EndOffset);
928 // Scan the overlapping partitions.
929 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
930 // If the new partition we are forming is splittable, stop at the first
931 // unsplittable partition.
932 if (New.IsSplittable && !Partitions[j].IsSplittable)
935 // Grow the new partition to include any equally splittable range. 'j' is
936 // always equally splittable when New is splittable, but when New is not
937 // splittable, we may subsume some (or part of some) splitable partition
938 // without growing the new one.
939 if (New.IsSplittable == Partitions[j].IsSplittable) {
940 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
942 assert(!New.IsSplittable);
943 assert(Partitions[j].IsSplittable);
944 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
947 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
952 // If the new partition is splittable, chop off the end as soon as the
953 // unsplittable subsequent partition starts and ensure we eventually cover
954 // the splittable area.
955 if (j != e && New.IsSplittable) {
956 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
957 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
960 // Add the new partition if it differs from the original one and is
961 // non-empty. We can end up with an empty partition here if it was
962 // splittable but there is an unsplittable one that starts at the same
964 if (New != Partitions[i]) {
965 if (New.BeginOffset != New.EndOffset)
966 Partitions.push_back(New);
967 // Mark the old one for removal.
968 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
972 New.BeginOffset = New.EndOffset;
973 if (!New.IsSplittable) {
974 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
975 if (j != e && !Partitions[j].IsSplittable)
976 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
977 New.IsSplittable = true;
978 // If there is a trailing splittable partition which won't be fused into
979 // the next splittable partition go ahead and add it onto the partitions
981 if (New.BeginOffset < New.EndOffset &&
982 (j == e || !Partitions[j].IsSplittable ||
983 New.EndOffset < Partitions[j].BeginOffset)) {
984 Partitions.push_back(New);
985 New.BeginOffset = New.EndOffset = 0ull;
990 // Re-sort the partitions now that they have been split and merged into
991 // disjoint set of partitions. Also remove any of the dead partitions we've
992 // replaced in the process.
993 std::sort(Partitions.begin(), Partitions.end());
994 if (NumDeadPartitions) {
995 assert(Partitions.back().BeginOffset == UINT64_MAX);
996 assert(Partitions.back().EndOffset == UINT64_MAX);
997 assert((ptrdiff_t)NumDeadPartitions ==
998 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1000 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1003 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
1008 PointerEscapingInstr(0) {
1009 PartitionBuilder PB(TD, AI, *this);
1013 if (Partitions.size() > 1) {
1014 // Sort the uses. This arranges for the offsets to be in ascending order,
1015 // and the sizes to be in descending order.
1016 std::sort(Partitions.begin(), Partitions.end());
1018 // Intersect splittability for all partitions with equal offsets and sizes.
1019 // Then remove all but the first so that we have a sequence of non-equal but
1020 // potentially overlapping partitions.
1021 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1024 while (J != E && *I == *J) {
1025 I->IsSplittable &= J->IsSplittable;
1029 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1032 // Split splittable and merge unsplittable partitions into a disjoint set
1033 // of partitions over the used space of the allocation.
1034 splitAndMergePartitions();
1037 // Now build up the user lists for each of these disjoint partitions by
1038 // re-walking the recursive users of the alloca.
1039 Uses.resize(Partitions.size());
1040 UseBuilder UB(TD, AI, *this);
1042 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1043 std::stable_sort(use_begin(I), use_end(I));
1046 Type *AllocaPartitioning::getCommonType(iterator I) const {
1048 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1049 if (isa<MemIntrinsic>(*UI->User))
1051 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1055 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1056 UserTy = LI->getType();
1057 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1058 UserTy = SI->getValueOperand()->getType();
1059 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1060 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1061 UserTy = PtrTy->getElementType();
1062 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1063 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1064 UserTy = PtrTy->getElementType();
1067 if (Ty && Ty != UserTy)
1075 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1077 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1078 StringRef Indent) const {
1079 OS << Indent << "partition #" << (I - begin())
1080 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1081 << (I->IsSplittable ? " (splittable)" : "")
1082 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1086 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1087 StringRef Indent) const {
1088 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1090 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1091 << "used by: " << *UI->User << "\n";
1092 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1093 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1095 if (!MTO.IsSplittable)
1096 IsDest = UI->BeginOffset == MTO.DestBegin;
1098 IsDest = MTO.DestBegin != 0u;
1099 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1100 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1101 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1106 void AllocaPartitioning::print(raw_ostream &OS) const {
1107 if (PointerEscapingInstr) {
1108 OS << "No partitioning for alloca: " << AI << "\n"
1109 << " A pointer to this alloca escaped by:\n"
1110 << " " << *PointerEscapingInstr << "\n";
1114 OS << "Partitioning of alloca: " << AI << "\n";
1116 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1122 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1123 void AllocaPartitioning::dump() const { print(dbgs()); }
1125 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1129 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1131 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1132 /// the loads and stores of an alloca instruction, as well as updating its
1133 /// debug information. This is used when a domtree is unavailable and thus
1134 /// mem2reg in its full form can't be used to handle promotion of allocas to
1136 class AllocaPromoter : public LoadAndStorePromoter {
1140 SmallVector<DbgDeclareInst *, 4> DDIs;
1141 SmallVector<DbgValueInst *, 4> DVIs;
1144 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1145 AllocaInst &AI, DIBuilder &DIB)
1146 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1148 void run(const SmallVectorImpl<Instruction*> &Insts) {
1149 // Remember which alloca we're promoting (for isInstInList).
1150 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1151 for (Value::use_iterator UI = DebugNode->use_begin(),
1152 UE = DebugNode->use_end();
1154 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1155 DDIs.push_back(DDI);
1156 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1157 DVIs.push_back(DVI);
1160 LoadAndStorePromoter::run(Insts);
1161 AI.eraseFromParent();
1162 while (!DDIs.empty())
1163 DDIs.pop_back_val()->eraseFromParent();
1164 while (!DVIs.empty())
1165 DVIs.pop_back_val()->eraseFromParent();
1168 virtual bool isInstInList(Instruction *I,
1169 const SmallVectorImpl<Instruction*> &Insts) const {
1170 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1171 return LI->getOperand(0) == &AI;
1172 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1175 virtual void updateDebugInfo(Instruction *Inst) const {
1176 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1177 E = DDIs.end(); I != E; ++I) {
1178 DbgDeclareInst *DDI = *I;
1179 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1180 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1181 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1182 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1184 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1185 E = DVIs.end(); I != E; ++I) {
1186 DbgValueInst *DVI = *I;
1188 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1189 // If an argument is zero extended then use argument directly. The ZExt
1190 // may be zapped by an optimization pass in future.
1191 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1192 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1193 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1194 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1196 Arg = SI->getOperand(0);
1197 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1198 Arg = LI->getOperand(0);
1202 Instruction *DbgVal =
1203 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1205 DbgVal->setDebugLoc(DVI->getDebugLoc());
1209 } // end anon namespace
1213 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1215 /// This pass takes allocations which can be completely analyzed (that is, they
1216 /// don't escape) and tries to turn them into scalar SSA values. There are
1217 /// a few steps to this process.
1219 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1220 /// are used to try to split them into smaller allocations, ideally of
1221 /// a single scalar data type. It will split up memcpy and memset accesses
1222 /// as necessary and try to isolate invidual scalar accesses.
1223 /// 2) It will transform accesses into forms which are suitable for SSA value
1224 /// promotion. This can be replacing a memset with a scalar store of an
1225 /// integer value, or it can involve speculating operations on a PHI or
1226 /// select to be a PHI or select of the results.
1227 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1228 /// onto insert and extract operations on a vector value, and convert them to
1229 /// this form. By doing so, it will enable promotion of vector aggregates to
1230 /// SSA vector values.
1231 class SROA : public FunctionPass {
1232 const bool RequiresDomTree;
1235 const TargetData *TD;
1238 /// \brief Worklist of alloca instructions to simplify.
1240 /// Each alloca in the function is added to this. Each new alloca formed gets
1241 /// added to it as well to recursively simplify unless that alloca can be
1242 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1243 /// the one being actively rewritten, we add it back onto the list if not
1244 /// already present to ensure it is re-visited.
1245 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1247 /// \brief A collection of instructions to delete.
1248 /// We try to batch deletions to simplify code and make things a bit more
1250 SmallVector<Instruction *, 8> DeadInsts;
1252 /// \brief A set to prevent repeatedly marking an instruction split into many
1253 /// uses as dead. Only used to guard insertion into DeadInsts.
1254 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1256 /// \brief A collection of alloca instructions we can directly promote.
1257 std::vector<AllocaInst *> PromotableAllocas;
1260 SROA(bool RequiresDomTree = true)
1261 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1262 C(0), TD(0), DT(0) {
1263 initializeSROAPass(*PassRegistry::getPassRegistry());
1265 bool runOnFunction(Function &F);
1266 void getAnalysisUsage(AnalysisUsage &AU) const;
1268 const char *getPassName() const { return "SROA"; }
1272 friend class AllocaPartitionRewriter;
1273 friend class AllocaPartitionVectorRewriter;
1275 bool rewriteAllocaPartition(AllocaInst &AI,
1276 AllocaPartitioning &P,
1277 AllocaPartitioning::iterator PI);
1278 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1279 bool runOnAlloca(AllocaInst &AI);
1280 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
1281 bool promoteAllocas(Function &F);
1287 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1288 return new SROA(RequiresDomTree);
1291 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1293 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1294 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1297 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1299 /// If the provided GEP is all-constant, the total byte offset formed by the
1300 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1301 /// operands, the function returns false and the value of Offset is unmodified.
1302 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1304 APInt GEPOffset(Offset.getBitWidth(), 0);
1305 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1306 GTI != GTE; ++GTI) {
1307 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1310 if (OpC->isZero()) continue;
1312 // Handle a struct index, which adds its field offset to the pointer.
1313 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1314 unsigned ElementIdx = OpC->getZExtValue();
1315 const StructLayout *SL = TD.getStructLayout(STy);
1316 GEPOffset += APInt(Offset.getBitWidth(),
1317 SL->getElementOffset(ElementIdx));
1321 APInt TypeSize(Offset.getBitWidth(),
1322 TD.getTypeAllocSize(GTI.getIndexedType()));
1323 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1324 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1325 "vector element size is not a multiple of 8, cannot GEP over it");
1326 TypeSize = VTy->getScalarSizeInBits() / 8;
1329 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1335 /// \brief Build a GEP out of a base pointer and indices.
1337 /// This will return the BasePtr if that is valid, or build a new GEP
1338 /// instruction using the IRBuilder if GEP-ing is needed.
1339 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1340 SmallVectorImpl<Value *> &Indices,
1341 const Twine &Prefix) {
1342 if (Indices.empty())
1345 // A single zero index is a no-op, so check for this and avoid building a GEP
1347 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1350 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1353 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1354 /// TargetTy without changing the offset of the pointer.
1356 /// This routine assumes we've already established a properly offset GEP with
1357 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1358 /// zero-indices down through type layers until we find one the same as
1359 /// TargetTy. If we can't find one with the same type, we at least try to use
1360 /// one with the same size. If none of that works, we just produce the GEP as
1361 /// indicated by Indices to have the correct offset.
1362 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1363 Value *BasePtr, Type *Ty, Type *TargetTy,
1364 SmallVectorImpl<Value *> &Indices,
1365 const Twine &Prefix) {
1367 return buildGEP(IRB, BasePtr, Indices, Prefix);
1369 // See if we can descend into a struct and locate a field with the correct
1371 unsigned NumLayers = 0;
1372 Type *ElementTy = Ty;
1374 if (ElementTy->isPointerTy())
1376 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1377 ElementTy = SeqTy->getElementType();
1378 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1379 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1380 ElementTy = *STy->element_begin();
1381 Indices.push_back(IRB.getInt32(0));
1386 } while (ElementTy != TargetTy);
1387 if (ElementTy != TargetTy)
1388 Indices.erase(Indices.end() - NumLayers, Indices.end());
1390 return buildGEP(IRB, BasePtr, Indices, Prefix);
1393 /// \brief Recursively compute indices for a natural GEP.
1395 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1396 /// element types adding appropriate indices for the GEP.
1397 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1398 Value *Ptr, Type *Ty, APInt &Offset,
1400 SmallVectorImpl<Value *> &Indices,
1401 const Twine &Prefix) {
1403 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1405 // We can't recurse through pointer types.
1406 if (Ty->isPointerTy())
1409 // We try to analyze GEPs over vectors here, but note that these GEPs are
1410 // extremely poorly defined currently. The long-term goal is to remove GEPing
1411 // over a vector from the IR completely.
1412 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1413 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1414 if (ElementSizeInBits % 8)
1415 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1416 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1417 APInt NumSkippedElements = Offset.udiv(ElementSize);
1418 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1420 Offset -= NumSkippedElements * ElementSize;
1421 Indices.push_back(IRB.getInt(NumSkippedElements));
1422 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1423 Offset, TargetTy, Indices, Prefix);
1426 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1427 Type *ElementTy = ArrTy->getElementType();
1428 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1429 APInt NumSkippedElements = Offset.udiv(ElementSize);
1430 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1433 Offset -= NumSkippedElements * ElementSize;
1434 Indices.push_back(IRB.getInt(NumSkippedElements));
1435 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1439 StructType *STy = dyn_cast<StructType>(Ty);
1443 const StructLayout *SL = TD.getStructLayout(STy);
1444 uint64_t StructOffset = Offset.getZExtValue();
1445 if (StructOffset >= SL->getSizeInBytes())
1447 unsigned Index = SL->getElementContainingOffset(StructOffset);
1448 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1449 Type *ElementTy = STy->getElementType(Index);
1450 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1451 return 0; // The offset points into alignment padding.
1453 Indices.push_back(IRB.getInt32(Index));
1454 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1458 /// \brief Get a natural GEP from a base pointer to a particular offset and
1459 /// resulting in a particular type.
1461 /// The goal is to produce a "natural" looking GEP that works with the existing
1462 /// composite types to arrive at the appropriate offset and element type for
1463 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1464 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1465 /// Indices, and setting Ty to the result subtype.
1467 /// If no natural GEP can be constructed, this function returns null.
1468 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1469 Value *Ptr, APInt Offset, Type *TargetTy,
1470 SmallVectorImpl<Value *> &Indices,
1471 const Twine &Prefix) {
1472 PointerType *Ty = cast<PointerType>(Ptr->getType());
1474 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1476 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1479 Type *ElementTy = Ty->getElementType();
1480 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1481 if (ElementSize == 0)
1482 return 0; // Zero-length arrays can't help us build a natural GEP.
1483 APInt NumSkippedElements = Offset.udiv(ElementSize);
1485 Offset -= NumSkippedElements * ElementSize;
1486 Indices.push_back(IRB.getInt(NumSkippedElements));
1487 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1491 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1492 /// resulting pointer has PointerTy.
1494 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1495 /// and produces the pointer type desired. Where it cannot, it will try to use
1496 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1497 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1498 /// bitcast to the type.
1500 /// The strategy for finding the more natural GEPs is to peel off layers of the
1501 /// pointer, walking back through bit casts and GEPs, searching for a base
1502 /// pointer from which we can compute a natural GEP with the desired
1503 /// properities. The algorithm tries to fold as many constant indices into
1504 /// a single GEP as possible, thus making each GEP more independent of the
1505 /// surrounding code.
1506 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1507 Value *Ptr, APInt Offset, Type *PointerTy,
1508 const Twine &Prefix) {
1509 // Even though we don't look through PHI nodes, we could be called on an
1510 // instruction in an unreachable block, which may be on a cycle.
1511 SmallPtrSet<Value *, 4> Visited;
1512 Visited.insert(Ptr);
1513 SmallVector<Value *, 4> Indices;
1515 // We may end up computing an offset pointer that has the wrong type. If we
1516 // never are able to compute one directly that has the correct type, we'll
1517 // fall back to it, so keep it around here.
1518 Value *OffsetPtr = 0;
1520 // Remember any i8 pointer we come across to re-use if we need to do a raw
1523 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1525 Type *TargetTy = PointerTy->getPointerElementType();
1528 // First fold any existing GEPs into the offset.
1529 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1530 APInt GEPOffset(Offset.getBitWidth(), 0);
1531 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1533 Offset += GEPOffset;
1534 Ptr = GEP->getPointerOperand();
1535 if (!Visited.insert(Ptr))
1539 // See if we can perform a natural GEP here.
1541 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1543 if (P->getType() == PointerTy) {
1544 // Zap any offset pointer that we ended up computing in previous rounds.
1545 if (OffsetPtr && OffsetPtr->use_empty())
1546 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1547 I->eraseFromParent();
1555 // Stash this pointer if we've found an i8*.
1556 if (Ptr->getType()->isIntegerTy(8)) {
1558 Int8PtrOffset = Offset;
1561 // Peel off a layer of the pointer and update the offset appropriately.
1562 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1563 Ptr = cast<Operator>(Ptr)->getOperand(0);
1564 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1565 if (GA->mayBeOverridden())
1567 Ptr = GA->getAliasee();
1571 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1572 } while (Visited.insert(Ptr));
1576 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1577 Prefix + ".raw_cast");
1578 Int8PtrOffset = Offset;
1581 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1582 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1583 Prefix + ".raw_idx");
1587 // On the off chance we were targeting i8*, guard the bitcast here.
1588 if (Ptr->getType() != PointerTy)
1589 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1594 /// \brief Test whether the given alloca partition can be promoted to a vector.
1596 /// This is a quick test to check whether we can rewrite a particular alloca
1597 /// partition (and its newly formed alloca) into a vector alloca with only
1598 /// whole-vector loads and stores such that it could be promoted to a vector
1599 /// SSA value. We only can ensure this for a limited set of operations, and we
1600 /// don't want to do the rewrites unless we are confident that the result will
1601 /// be promotable, so we have an early test here.
1602 static bool isVectorPromotionViable(const TargetData &TD,
1604 AllocaPartitioning &P,
1605 uint64_t PartitionBeginOffset,
1606 uint64_t PartitionEndOffset,
1607 AllocaPartitioning::const_use_iterator I,
1608 AllocaPartitioning::const_use_iterator E) {
1609 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1613 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1614 uint64_t ElementSize = Ty->getScalarSizeInBits();
1616 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1617 // that aren't byte sized.
1618 if (ElementSize % 8)
1620 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1624 for (; I != E; ++I) {
1625 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1626 uint64_t BeginIndex = BeginOffset / ElementSize;
1627 if (BeginIndex * ElementSize != BeginOffset ||
1628 BeginIndex >= Ty->getNumElements())
1630 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1631 uint64_t EndIndex = EndOffset / ElementSize;
1632 if (EndIndex * ElementSize != EndOffset ||
1633 EndIndex > Ty->getNumElements())
1636 // FIXME: We should build shuffle vector instructions to handle
1637 // non-element-sized accesses.
1638 if ((EndOffset - BeginOffset) != ElementSize &&
1639 (EndOffset - BeginOffset) != VecSize)
1642 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1643 if (MI->isVolatile())
1645 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1646 const AllocaPartitioning::MemTransferOffsets &MTO
1647 = P.getMemTransferOffsets(*MTI);
1648 if (!MTO.IsSplittable)
1651 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1652 // Disable vector promotion when there are loads or stores of an FCA.
1654 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1662 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1663 /// use a new alloca.
1665 /// Also implements the rewriting to vector-based accesses when the partition
1666 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1668 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1670 // Befriend the base class so it can delegate to private visit methods.
1671 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1673 const TargetData &TD;
1674 AllocaPartitioning &P;
1676 AllocaInst &OldAI, &NewAI;
1677 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1679 // If we are rewriting an alloca partition which can be written as pure
1680 // vector operations, we stash extra information here. When VecTy is
1681 // non-null, we have some strict guarantees about the rewriten alloca:
1682 // - The new alloca is exactly the size of the vector type here.
1683 // - The accesses all either map to the entire vector or to a single
1685 // - The set of accessing instructions is only one of those handled above
1686 // in isVectorPromotionViable. Generally these are the same access kinds
1687 // which are promotable via mem2reg.
1690 uint64_t ElementSize;
1692 // The offset of the partition user currently being rewritten.
1693 uint64_t BeginOffset, EndOffset;
1694 Instruction *OldPtr;
1696 // The name prefix to use when rewriting instructions for this alloca.
1697 std::string NamePrefix;
1700 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1701 AllocaPartitioning::iterator PI,
1702 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1703 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1704 : TD(TD), P(P), Pass(Pass),
1705 OldAI(OldAI), NewAI(NewAI),
1706 NewAllocaBeginOffset(NewBeginOffset),
1707 NewAllocaEndOffset(NewEndOffset),
1708 VecTy(), ElementTy(), ElementSize(),
1709 BeginOffset(), EndOffset() {
1712 /// \brief Visit the users of the alloca partition and rewrite them.
1713 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1714 AllocaPartitioning::const_use_iterator E) {
1715 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1716 NewAllocaBeginOffset, NewAllocaEndOffset,
1719 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1720 ElementTy = VecTy->getElementType();
1721 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1722 "Only multiple-of-8 sized vector elements are viable");
1723 ElementSize = VecTy->getScalarSizeInBits() / 8;
1725 bool CanSROA = true;
1726 for (; I != E; ++I) {
1727 BeginOffset = I->BeginOffset;
1728 EndOffset = I->EndOffset;
1730 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1731 CanSROA &= visit(I->User);
1743 // Every instruction which can end up as a user must have a rewrite rule.
1744 bool visitInstruction(Instruction &I) {
1745 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1746 llvm_unreachable("No rewrite rule for this instruction!");
1749 Twine getName(const Twine &Suffix) {
1750 return NamePrefix + Suffix;
1753 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1754 assert(BeginOffset >= NewAllocaBeginOffset);
1755 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1756 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1759 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1760 assert(VecTy && "Can only call getIndex when rewriting a vector");
1761 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1762 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1763 uint32_t Index = RelOffset / ElementSize;
1764 assert(Index * ElementSize == RelOffset);
1765 return IRB.getInt32(Index);
1768 void deleteIfTriviallyDead(Value *V) {
1769 Instruction *I = cast<Instruction>(V);
1770 if (isInstructionTriviallyDead(I))
1771 Pass.DeadInsts.push_back(I);
1774 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1775 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1776 return IRB.CreateIntToPtr(V, Ty);
1777 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1778 return IRB.CreatePtrToInt(V, Ty);
1780 return IRB.CreateBitCast(V, Ty);
1783 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1785 if (LI.getType() == VecTy->getElementType() ||
1786 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1788 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1789 getIndex(IRB, BeginOffset),
1790 getName(".extract"));
1792 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1794 if (Result->getType() != LI.getType())
1795 Result = getValueCast(IRB, Result, LI.getType());
1796 LI.replaceAllUsesWith(Result);
1797 Pass.DeadInsts.push_back(&LI);
1799 DEBUG(dbgs() << " to: " << *Result << "\n");
1803 bool visitLoadInst(LoadInst &LI) {
1804 DEBUG(dbgs() << " original: " << LI << "\n");
1805 Value *OldOp = LI.getOperand(0);
1806 assert(OldOp == OldPtr);
1807 IRBuilder<> IRB(&LI);
1810 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1812 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1813 LI.getPointerOperand()->getType());
1814 LI.setOperand(0, NewPtr);
1815 DEBUG(dbgs() << " to: " << LI << "\n");
1817 deleteIfTriviallyDead(OldOp);
1818 return NewPtr == &NewAI && !LI.isVolatile();
1821 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1823 Value *V = SI.getValueOperand();
1824 if (V->getType() == ElementTy ||
1825 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1826 if (V->getType() != ElementTy)
1827 V = getValueCast(IRB, V, ElementTy);
1828 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1829 getIndex(IRB, BeginOffset),
1830 getName(".insert"));
1831 } else if (V->getType() != VecTy) {
1832 V = getValueCast(IRB, V, VecTy);
1834 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1835 Pass.DeadInsts.push_back(&SI);
1838 DEBUG(dbgs() << " to: " << *Store << "\n");
1842 bool visitStoreInst(StoreInst &SI) {
1843 DEBUG(dbgs() << " original: " << SI << "\n");
1844 Value *OldOp = SI.getOperand(1);
1845 assert(OldOp == OldPtr);
1846 IRBuilder<> IRB(&SI);
1849 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1851 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1852 SI.getPointerOperand()->getType());
1853 SI.setOperand(1, NewPtr);
1854 DEBUG(dbgs() << " to: " << SI << "\n");
1856 deleteIfTriviallyDead(OldOp);
1857 return NewPtr == &NewAI && !SI.isVolatile();
1860 bool visitMemSetInst(MemSetInst &II) {
1861 DEBUG(dbgs() << " original: " << II << "\n");
1862 IRBuilder<> IRB(&II);
1863 assert(II.getRawDest() == OldPtr);
1865 // If the memset has a variable size, it cannot be split, just adjust the
1866 // pointer to the new alloca.
1867 if (!isa<Constant>(II.getLength())) {
1868 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1869 deleteIfTriviallyDead(OldPtr);
1873 // Record this instruction for deletion.
1874 if (Pass.DeadSplitInsts.insert(&II))
1875 Pass.DeadInsts.push_back(&II);
1877 Type *AllocaTy = NewAI.getAllocatedType();
1878 Type *ScalarTy = AllocaTy->getScalarType();
1880 // If this doesn't map cleanly onto the alloca type, and that type isn't
1881 // a single value type, just emit a memset.
1882 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1883 EndOffset != NewAllocaEndOffset ||
1884 !AllocaTy->isSingleValueType() ||
1885 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1886 Type *SizeTy = II.getLength()->getType();
1887 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1890 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1891 II.getRawDest()->getType()),
1892 II.getValue(), Size, II.getAlignment(),
1895 DEBUG(dbgs() << " to: " << *New << "\n");
1899 // If we can represent this as a simple value, we have to build the actual
1900 // value to store, which requires expanding the byte present in memset to
1901 // a sensible representation for the alloca type. This is essentially
1902 // splatting the byte to a sufficiently wide integer, bitcasting to the
1903 // desired scalar type, and splatting it across any desired vector type.
1904 Value *V = II.getValue();
1905 IntegerType *VTy = cast<IntegerType>(V->getType());
1906 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1907 TD.getTypeSizeInBits(ScalarTy));
1908 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1909 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1910 ConstantExpr::getUDiv(
1911 Constant::getAllOnesValue(IntTy),
1912 ConstantExpr::getZExt(
1913 Constant::getAllOnesValue(V->getType()),
1915 getName(".isplat"));
1916 if (V->getType() != ScalarTy) {
1917 if (ScalarTy->isPointerTy())
1918 V = IRB.CreateIntToPtr(V, ScalarTy);
1919 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1920 V = IRB.CreateBitCast(V, ScalarTy);
1921 else if (ScalarTy->isIntegerTy())
1922 llvm_unreachable("Computed different integer types with equal widths");
1924 llvm_unreachable("Invalid scalar type");
1927 // If this is an element-wide memset of a vectorizable alloca, insert it.
1928 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1929 EndOffset < NewAllocaEndOffset)) {
1930 StoreInst *Store = IRB.CreateStore(
1931 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1932 getIndex(IRB, BeginOffset),
1933 getName(".insert")),
1936 DEBUG(dbgs() << " to: " << *Store << "\n");
1940 // Splat to a vector if needed.
1941 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1942 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1943 V = IRB.CreateShuffleVector(
1944 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1945 IRB.getInt32(0), getName(".vsplat.insert")),
1946 UndefValue::get(SplatSourceTy),
1947 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1948 getName(".vsplat.shuffle"));
1949 assert(V->getType() == VecTy);
1952 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1954 DEBUG(dbgs() << " to: " << *New << "\n");
1955 return !II.isVolatile();
1958 bool visitMemTransferInst(MemTransferInst &II) {
1959 // Rewriting of memory transfer instructions can be a bit tricky. We break
1960 // them into two categories: split intrinsics and unsplit intrinsics.
1962 DEBUG(dbgs() << " original: " << II << "\n");
1963 IRBuilder<> IRB(&II);
1965 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1966 bool IsDest = II.getRawDest() == OldPtr;
1968 const AllocaPartitioning::MemTransferOffsets &MTO
1969 = P.getMemTransferOffsets(II);
1971 // For unsplit intrinsics, we simply modify the source and destination
1972 // pointers in place. This isn't just an optimization, it is a matter of
1973 // correctness. With unsplit intrinsics we may be dealing with transfers
1974 // within a single alloca before SROA ran, or with transfers that have
1975 // a variable length. We may also be dealing with memmove instead of
1976 // memcpy, and so simply updating the pointers is the necessary for us to
1977 // update both source and dest of a single call.
1978 if (!MTO.IsSplittable) {
1979 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1981 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1983 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1985 DEBUG(dbgs() << " to: " << II << "\n");
1986 deleteIfTriviallyDead(OldOp);
1989 // For split transfer intrinsics we have an incredibly useful assurance:
1990 // the source and destination do not reside within the same alloca, and at
1991 // least one of them does not escape. This means that we can replace
1992 // memmove with memcpy, and we don't need to worry about all manner of
1993 // downsides to splitting and transforming the operations.
1995 // Compute the relative offset within the transfer.
1996 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1997 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
1998 : MTO.SourceBegin));
2000 // If this doesn't map cleanly onto the alloca type, and that type isn't
2001 // a single value type, just emit a memcpy.
2003 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2004 EndOffset != NewAllocaEndOffset ||
2005 !NewAI.getAllocatedType()->isSingleValueType());
2007 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2008 // size hasn't been shrunk based on analysis of the viable range, this is
2010 if (EmitMemCpy && &OldAI == &NewAI) {
2011 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2012 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2013 // Ensure the start lines up.
2014 assert(BeginOffset == OrigBegin);
2017 // Rewrite the size as needed.
2018 if (EndOffset != OrigEnd)
2019 II.setLength(ConstantInt::get(II.getLength()->getType(),
2020 EndOffset - BeginOffset));
2023 // Record this instruction for deletion.
2024 if (Pass.DeadSplitInsts.insert(&II))
2025 Pass.DeadInsts.push_back(&II);
2027 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2028 EndOffset < NewAllocaEndOffset);
2030 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2031 : II.getRawDest()->getType();
2033 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2036 // Compute the other pointer, folding as much as possible to produce
2037 // a single, simple GEP in most cases.
2038 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2039 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2040 getName("." + OtherPtr->getName()));
2042 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2043 // alloca that should be re-examined after rewriting this instruction.
2045 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2046 Pass.Worklist.insert(AI);
2050 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2051 : II.getRawSource()->getType());
2052 Type *SizeTy = II.getLength()->getType();
2053 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2055 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2056 IsDest ? OtherPtr : OurPtr,
2057 Size, II.getAlignment(),
2060 DEBUG(dbgs() << " to: " << *New << "\n");
2064 Value *SrcPtr = OtherPtr;
2065 Value *DstPtr = &NewAI;
2067 std::swap(SrcPtr, DstPtr);
2070 if (IsVectorElement && !IsDest) {
2071 // We have to extract rather than load.
2072 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
2073 getName(".copyload")),
2074 getIndex(IRB, BeginOffset),
2075 getName(".copyextract"));
2077 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
2080 if (IsVectorElement && IsDest) {
2081 // We have to insert into a loaded copy before storing.
2082 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
2083 Src, getIndex(IRB, BeginOffset),
2084 getName(".insert"));
2087 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
2089 DEBUG(dbgs() << " to: " << *Store << "\n");
2090 return !II.isVolatile();
2093 bool visitIntrinsicInst(IntrinsicInst &II) {
2094 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2095 II.getIntrinsicID() == Intrinsic::lifetime_end);
2096 DEBUG(dbgs() << " original: " << II << "\n");
2097 IRBuilder<> IRB(&II);
2098 assert(II.getArgOperand(1) == OldPtr);
2100 // Record this instruction for deletion.
2101 if (Pass.DeadSplitInsts.insert(&II))
2102 Pass.DeadInsts.push_back(&II);
2105 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2106 EndOffset - BeginOffset);
2107 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2109 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2110 New = IRB.CreateLifetimeStart(Ptr, Size);
2112 New = IRB.CreateLifetimeEnd(Ptr, Size);
2114 DEBUG(dbgs() << " to: " << *New << "\n");
2118 /// PHI instructions that use an alloca and are subsequently loaded can be
2119 /// rewritten to load both input pointers in the pred blocks and then PHI the
2120 /// results, allowing the load of the alloca to be promoted.
2122 /// %P2 = phi [i32* %Alloca, i32* %Other]
2123 /// %V = load i32* %P2
2125 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2127 /// %V2 = load i32* %Other
2129 /// %V = phi [i32 %V1, i32 %V2]
2131 /// We can do this to a select if its only uses are loads and if the operand
2132 /// to the select can be loaded unconditionally.
2134 /// FIXME: This should be hoisted into a generic utility, likely in
2135 /// Transforms/Util/Local.h
2136 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2137 // For now, we can only do this promotion if the load is in the same block
2138 // as the PHI, and if there are no stores between the phi and load.
2139 // TODO: Allow recursive phi users.
2140 // TODO: Allow stores.
2141 BasicBlock *BB = PN.getParent();
2142 unsigned MaxAlign = 0;
2143 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2145 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2146 if (LI == 0 || !LI->isSimple()) return false;
2148 // For now we only allow loads in the same block as the PHI. This is
2149 // a common case that happens when instcombine merges two loads through
2151 if (LI->getParent() != BB) return false;
2153 // Ensure that there are no instructions between the PHI and the load that
2155 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2156 if (BBI->mayWriteToMemory())
2159 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2160 Loads.push_back(LI);
2163 // We can only transform this if it is safe to push the loads into the
2164 // predecessor blocks. The only thing to watch out for is that we can't put
2165 // a possibly trapping load in the predecessor if it is a critical edge.
2166 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2168 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2169 Value *InVal = PN.getIncomingValue(Idx);
2171 // If the value is produced by the terminator of the predecessor (an
2172 // invoke) or it has side-effects, there is no valid place to put a load
2173 // in the predecessor.
2174 if (TI == InVal || TI->mayHaveSideEffects())
2177 // If the predecessor has a single successor, then the edge isn't
2179 if (TI->getNumSuccessors() == 1)
2182 // If this pointer is always safe to load, or if we can prove that there
2183 // is already a load in the block, then we can move the load to the pred
2185 if (InVal->isDereferenceablePointer() ||
2186 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2195 bool visitPHINode(PHINode &PN) {
2196 DEBUG(dbgs() << " original: " << PN << "\n");
2197 // We would like to compute a new pointer in only one place, but have it be
2198 // as local as possible to the PHI. To do that, we re-use the location of
2199 // the old pointer, which necessarily must be in the right position to
2200 // dominate the PHI.
2201 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2203 SmallVector<LoadInst *, 4> Loads;
2204 if (!isSafePHIToSpeculate(PN, Loads)) {
2205 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2206 // Replace the operands which were using the old pointer.
2207 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2208 for (; OI != OE; ++OI)
2212 DEBUG(dbgs() << " to: " << PN << "\n");
2213 deleteIfTriviallyDead(OldPtr);
2216 assert(!Loads.empty());
2218 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2219 IRBuilder<> PHIBuilder(&PN);
2220 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2221 NewPN->takeName(&PN);
2223 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2224 // matter which one we get and if any differ, it doesn't matter.
2225 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2226 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2227 unsigned Align = SomeLoad->getAlignment();
2228 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2230 // Rewrite all loads of the PN to use the new PHI.
2232 LoadInst *LI = Loads.pop_back_val();
2233 LI->replaceAllUsesWith(NewPN);
2234 Pass.DeadInsts.push_back(LI);
2235 } while (!Loads.empty());
2237 // Inject loads into all of the pred blocks.
2238 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2239 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2240 TerminatorInst *TI = Pred->getTerminator();
2241 Value *InVal = PN.getIncomingValue(Idx);
2242 IRBuilder<> PredBuilder(TI);
2244 // Map the value to the new alloca pointer if this was the old alloca
2246 bool ThisOperand = InVal == OldPtr;
2251 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2253 ++NumLoadsSpeculated;
2254 Load->setAlignment(Align);
2256 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2257 NewPN->addIncoming(Load, Pred);
2261 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2263 // No uses to rewrite.
2266 // Try to lookup and rewrite any partition uses corresponding to this phi
2268 AllocaPartitioning::iterator PI
2269 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2270 if (PI != P.end()) {
2271 // If the other pointer is within the partitioning, replace the PHI in
2272 // its uses with the load we just speculated, or add another load for
2273 // it to rewrite if we've already replaced the PHI.
2274 AllocaPartitioning::use_iterator UI
2275 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2276 if (isa<PHINode>(*UI->User))
2279 AllocaPartitioning::PartitionUse OtherUse = *UI;
2280 OtherUse.User = Load;
2281 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2286 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2287 return NewPtr == &NewAI;
2290 /// Select instructions that use an alloca and are subsequently loaded can be
2291 /// rewritten to load both input pointers and then select between the result,
2292 /// allowing the load of the alloca to be promoted.
2294 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2295 /// %V = load i32* %P2
2297 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2298 /// %V2 = load i32* %Other
2299 /// %V = select i1 %cond, i32 %V1, i32 %V2
2301 /// We can do this to a select if its only uses are loads and if the operand
2302 /// to the select can be loaded unconditionally.
2303 bool isSafeSelectToSpeculate(SelectInst &SI,
2304 SmallVectorImpl<LoadInst *> &Loads) {
2305 Value *TValue = SI.getTrueValue();
2306 Value *FValue = SI.getFalseValue();
2307 bool TDerefable = TValue->isDereferenceablePointer();
2308 bool FDerefable = FValue->isDereferenceablePointer();
2310 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2312 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2313 if (LI == 0 || !LI->isSimple()) return false;
2315 // Both operands to the select need to be dereferencable, either
2316 // absolutely (e.g. allocas) or at this point because we can see other
2318 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2319 LI->getAlignment(), &TD))
2321 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2322 LI->getAlignment(), &TD))
2324 Loads.push_back(LI);
2330 bool visitSelectInst(SelectInst &SI) {
2331 DEBUG(dbgs() << " original: " << SI << "\n");
2332 IRBuilder<> IRB(&SI);
2334 // Find the operand we need to rewrite here.
2335 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2337 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2339 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2340 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2342 // If the select isn't safe to speculate, just use simple logic to emit it.
2343 SmallVector<LoadInst *, 4> Loads;
2344 if (!isSafeSelectToSpeculate(SI, Loads)) {
2345 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2346 DEBUG(dbgs() << " to: " << SI << "\n");
2347 deleteIfTriviallyDead(OldPtr);
2351 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2352 AllocaPartitioning::iterator PI
2353 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2354 AllocaPartitioning::PartitionUse OtherUse;
2355 if (PI != P.end()) {
2356 // If the other pointer is within the partitioning, remove the select
2357 // from its uses. We'll add in the new loads below.
2358 AllocaPartitioning::use_iterator UI
2359 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2361 P.use_erase(PI, UI);
2364 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2365 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2366 // Replace the loads of the select with a select of two loads.
2367 while (!Loads.empty()) {
2368 LoadInst *LI = Loads.pop_back_val();
2370 IRB.SetInsertPoint(LI);
2372 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2374 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2375 NumLoadsSpeculated += 2;
2376 if (PI != P.end()) {
2377 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2378 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2379 OtherUse.User = OtherLoad;
2380 P.use_insert(PI, P.use_end(PI), OtherUse);
2383 // Transfer alignment and TBAA info if present.
2384 TL->setAlignment(LI->getAlignment());
2385 FL->setAlignment(LI->getAlignment());
2386 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2387 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2388 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2391 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2393 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2394 LI->replaceAllUsesWith(V);
2395 Pass.DeadInsts.push_back(LI);
2398 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2400 deleteIfTriviallyDead(OldPtr);
2401 return NewPtr == &NewAI;
2407 /// \brief Try to find a partition of the aggregate type passed in for a given
2408 /// offset and size.
2410 /// This recurses through the aggregate type and tries to compute a subtype
2411 /// based on the offset and size. When the offset and size span a sub-section
2412 /// of an array, it will even compute a new array type for that sub-section,
2413 /// and the same for structs.
2415 /// Note that this routine is very strict and tries to find a partition of the
2416 /// type which produces the *exact* right offset and size. It is not forgiving
2417 /// when the size or offset cause either end of type-based partition to be off.
2418 /// Also, this is a best-effort routine. It is reasonable to give up and not
2419 /// return a type if necessary.
2420 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2421 uint64_t Offset, uint64_t Size) {
2422 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2425 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2426 // We can't partition pointers...
2427 if (SeqTy->isPointerTy())
2430 Type *ElementTy = SeqTy->getElementType();
2431 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2432 uint64_t NumSkippedElements = Offset / ElementSize;
2433 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2434 if (NumSkippedElements >= ArrTy->getNumElements())
2436 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2437 if (NumSkippedElements >= VecTy->getNumElements())
2439 Offset -= NumSkippedElements * ElementSize;
2441 // First check if we need to recurse.
2442 if (Offset > 0 || Size < ElementSize) {
2443 // Bail if the partition ends in a different array element.
2444 if ((Offset + Size) > ElementSize)
2446 // Recurse through the element type trying to peel off offset bytes.
2447 return getTypePartition(TD, ElementTy, Offset, Size);
2449 assert(Offset == 0);
2451 if (Size == ElementSize)
2453 assert(Size > ElementSize);
2454 uint64_t NumElements = Size / ElementSize;
2455 if (NumElements * ElementSize != Size)
2457 return ArrayType::get(ElementTy, NumElements);
2460 StructType *STy = dyn_cast<StructType>(Ty);
2464 const StructLayout *SL = TD.getStructLayout(STy);
2465 if (Offset >= SL->getSizeInBytes())
2467 uint64_t EndOffset = Offset + Size;
2468 if (EndOffset > SL->getSizeInBytes())
2471 unsigned Index = SL->getElementContainingOffset(Offset);
2472 Offset -= SL->getElementOffset(Index);
2474 Type *ElementTy = STy->getElementType(Index);
2475 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2476 if (Offset >= ElementSize)
2477 return 0; // The offset points into alignment padding.
2479 // See if any partition must be contained by the element.
2480 if (Offset > 0 || Size < ElementSize) {
2481 if ((Offset + Size) > ElementSize)
2483 return getTypePartition(TD, ElementTy, Offset, Size);
2485 assert(Offset == 0);
2487 if (Size == ElementSize)
2490 StructType::element_iterator EI = STy->element_begin() + Index,
2491 EE = STy->element_end();
2492 if (EndOffset < SL->getSizeInBytes()) {
2493 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2494 if (Index == EndIndex)
2495 return 0; // Within a single element and its padding.
2497 // Don't try to form "natural" types if the elements don't line up with the
2499 // FIXME: We could potentially recurse down through the last element in the
2500 // sub-struct to find a natural end point.
2501 if (SL->getElementOffset(EndIndex) != EndOffset)
2504 assert(Index < EndIndex);
2505 EE = STy->element_begin() + EndIndex;
2508 // Try to build up a sub-structure.
2509 SmallVector<Type *, 4> ElementTys;
2511 ElementTys.push_back(*EI++);
2513 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2515 const StructLayout *SubSL = TD.getStructLayout(SubTy);
2516 if (Size != SubSL->getSizeInBytes())
2517 return 0; // The sub-struct doesn't have quite the size needed.
2522 /// \brief Rewrite an alloca partition's users.
2524 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2525 /// to rewrite uses of an alloca partition to be conducive for SSA value
2526 /// promotion. If the partition needs a new, more refined alloca, this will
2527 /// build that new alloca, preserving as much type information as possible, and
2528 /// rewrite the uses of the old alloca to point at the new one and have the
2529 /// appropriate new offsets. It also evaluates how successful the rewrite was
2530 /// at enabling promotion and if it was successful queues the alloca to be
2532 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2533 AllocaPartitioning &P,
2534 AllocaPartitioning::iterator PI) {
2535 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2536 if (P.use_begin(PI) == P.use_end(PI))
2537 return false; // No live uses left of this partition.
2539 // Try to compute a friendly type for this partition of the alloca. This
2540 // won't always succeed, in which case we fall back to a legal integer type
2541 // or an i8 array of an appropriate size.
2543 if (Type *PartitionTy = P.getCommonType(PI))
2544 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2545 AllocaTy = PartitionTy;
2547 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2548 PI->BeginOffset, AllocaSize))
2549 AllocaTy = PartitionTy;
2551 (AllocaTy->isArrayTy() &&
2552 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2553 TD->isLegalInteger(AllocaSize * 8))
2554 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2556 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2557 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
2559 // Check for the case where we're going to rewrite to a new alloca of the
2560 // exact same type as the original, and with the same access offsets. In that
2561 // case, re-use the existing alloca, but still run through the rewriter to
2562 // performe phi and select speculation.
2564 if (AllocaTy == AI.getAllocatedType()) {
2565 assert(PI->BeginOffset == 0 &&
2566 "Non-zero begin offset but same alloca type");
2567 assert(PI == P.begin() && "Begin offset is zero on later partition");
2570 // FIXME: The alignment here is overly conservative -- we could in many
2571 // cases get away with much weaker alignment constraints.
2572 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2573 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2578 DEBUG(dbgs() << "Rewriting alloca partition "
2579 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2582 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2583 PI->BeginOffset, PI->EndOffset);
2584 DEBUG(dbgs() << " rewriting ");
2585 DEBUG(P.print(dbgs(), PI, ""));
2586 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2587 DEBUG(dbgs() << " and queuing for promotion\n");
2588 PromotableAllocas.push_back(NewAI);
2589 } else if (NewAI != &AI) {
2590 // If we can't promote the alloca, iterate on it to check for new
2591 // refinements exposed by splitting the current alloca. Don't iterate on an
2592 // alloca which didn't actually change and didn't get promoted.
2593 Worklist.insert(NewAI);
2598 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2599 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2600 bool Changed = false;
2601 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2603 Changed |= rewriteAllocaPartition(AI, P, PI);
2608 /// \brief Analyze an alloca for SROA.
2610 /// This analyzes the alloca to ensure we can reason about it, builds
2611 /// a partitioning of the alloca, and then hands it off to be split and
2612 /// rewritten as needed.
2613 bool SROA::runOnAlloca(AllocaInst &AI) {
2614 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2615 ++NumAllocasAnalyzed;
2617 // Special case dead allocas, as they're trivial.
2618 if (AI.use_empty()) {
2619 AI.eraseFromParent();
2623 // Skip alloca forms that this analysis can't handle.
2624 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2625 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2628 // First check if this is a non-aggregate type that we should simply promote.
2629 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2630 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2631 PromotableAllocas.push_back(&AI);
2635 // Build the partition set using a recursive instruction-visiting builder.
2636 AllocaPartitioning P(*TD, AI);
2637 DEBUG(P.print(dbgs()));
2641 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2642 if (P.begin() == P.end())
2645 // Delete all the dead users of this alloca before splitting and rewriting it.
2646 bool Changed = false;
2647 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2648 DE = P.dead_user_end();
2651 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2652 DeadInsts.push_back(*DI);
2654 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2655 DE = P.dead_op_end();
2658 // Clobber the use with an undef value.
2659 **DO = UndefValue::get(OldV->getType());
2660 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2661 if (isInstructionTriviallyDead(OldI)) {
2663 DeadInsts.push_back(OldI);
2667 return splitAlloca(AI, P) || Changed;
2670 /// \brief Delete the dead instructions accumulated in this run.
2672 /// Recursively deletes the dead instructions we've accumulated. This is done
2673 /// at the very end to maximize locality of the recursive delete and to
2674 /// minimize the problems of invalidated instruction pointers as such pointers
2675 /// are used heavily in the intermediate stages of the algorithm.
2677 /// We also record the alloca instructions deleted here so that they aren't
2678 /// subsequently handed to mem2reg to promote.
2679 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
2680 DeadSplitInsts.clear();
2681 while (!DeadInsts.empty()) {
2682 Instruction *I = DeadInsts.pop_back_val();
2683 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2685 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2686 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2687 // Zero out the operand and see if it becomes trivially dead.
2689 if (isInstructionTriviallyDead(U))
2690 DeadInsts.push_back(U);
2693 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2694 DeletedAllocas.insert(AI);
2697 I->eraseFromParent();
2701 /// \brief Promote the allocas, using the best available technique.
2703 /// This attempts to promote whatever allocas have been identified as viable in
2704 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
2705 /// If there is a domtree available, we attempt to promote using the full power
2706 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
2707 /// based on the SSAUpdater utilities. This function returns whether any
2708 /// promotion occured.
2709 bool SROA::promoteAllocas(Function &F) {
2710 if (PromotableAllocas.empty())
2713 NumPromoted += PromotableAllocas.size();
2715 if (DT && !ForceSSAUpdater) {
2716 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2717 PromoteMemToReg(PromotableAllocas, *DT);
2718 PromotableAllocas.clear();
2722 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
2724 DIBuilder DIB(*F.getParent());
2725 SmallVector<Instruction*, 64> Insts;
2727 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
2728 AllocaInst *AI = PromotableAllocas[Idx];
2729 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
2731 Instruction *I = cast<Instruction>(*UI++);
2732 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
2733 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
2734 // leading to them) here. Eventually it should use them to optimize the
2735 // scalar values produced.
2736 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
2737 assert(onlyUsedByLifetimeMarkers(I) &&
2738 "Found a bitcast used outside of a lifetime marker.");
2739 while (!I->use_empty())
2740 cast<Instruction>(*I->use_begin())->eraseFromParent();
2741 I->eraseFromParent();
2744 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2745 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
2746 II->getIntrinsicID() == Intrinsic::lifetime_end);
2747 II->eraseFromParent();
2753 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
2757 PromotableAllocas.clear();
2762 /// \brief A predicate to test whether an alloca belongs to a set.
2763 class IsAllocaInSet {
2764 typedef SmallPtrSet<AllocaInst *, 4> SetType;
2768 IsAllocaInSet(const SetType &Set) : Set(Set) {}
2769 bool operator()(AllocaInst *AI) { return Set.count(AI); }
2773 bool SROA::runOnFunction(Function &F) {
2774 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2775 C = &F.getContext();
2776 TD = getAnalysisIfAvailable<TargetData>();
2778 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
2781 DT = getAnalysisIfAvailable<DominatorTree>();
2783 BasicBlock &EntryBB = F.getEntryBlock();
2784 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
2786 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2787 Worklist.insert(AI);
2789 bool Changed = false;
2790 // A set of deleted alloca instruction pointers which should be removed from
2791 // the list of promotable allocas.
2792 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
2794 while (!Worklist.empty()) {
2795 Changed |= runOnAlloca(*Worklist.pop_back_val());
2796 deleteDeadInstructions(DeletedAllocas);
2797 if (!DeletedAllocas.empty()) {
2798 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
2799 PromotableAllocas.end(),
2800 IsAllocaInSet(DeletedAllocas)),
2801 PromotableAllocas.end());
2802 DeletedAllocas.clear();
2806 Changed |= promoteAllocas(F);
2811 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
2812 if (RequiresDomTree)
2813 AU.addRequired<DominatorTree>();
2814 AU.setPreservesCFG();