1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "sroa"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/PtrUseVisitor.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/DIBuilder.h"
37 #include "llvm/DebugInfo.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/InstVisitor.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include "llvm/Transforms/Utils/SSAUpdater.h"
60 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
62 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
63 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
64 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
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 A custom IRBuilder inserter which prefixes all names if they are
79 template <bool preserveNames = true>
80 class IRBuilderPrefixedInserter :
81 public IRBuilderDefaultInserter<preserveNames> {
85 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
88 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
89 BasicBlock::iterator InsertPt) const {
90 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
91 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
95 // Specialization for not preserving the name is trivial.
97 class IRBuilderPrefixedInserter<false> :
98 public IRBuilderDefaultInserter<false> {
100 void SetNamePrefix(const Twine &P) {}
103 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
105 typedef llvm::IRBuilder<true, ConstantFolder,
106 IRBuilderPrefixedInserter<true> > IRBuilderTy;
108 typedef llvm::IRBuilder<false, ConstantFolder,
109 IRBuilderPrefixedInserter<false> > IRBuilderTy;
114 /// \brief A used slice of an alloca.
116 /// This structure represents a slice of an alloca used by some instruction. It
117 /// stores both the begin and end offsets of this use, a pointer to the use
118 /// itself, and a flag indicating whether we can classify the use as splittable
119 /// or not when forming partitions of the alloca.
121 /// \brief The beginning offset of the range.
122 uint64_t BeginOffset;
124 /// \brief The ending offset, not included in the range.
127 /// \brief Storage for both the use of this slice and whether it can be
129 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
132 Slice() : BeginOffset(), EndOffset() {}
133 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
134 : BeginOffset(BeginOffset), EndOffset(EndOffset),
135 UseAndIsSplittable(U, IsSplittable) {}
137 uint64_t beginOffset() const { return BeginOffset; }
138 uint64_t endOffset() const { return EndOffset; }
140 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
143 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
145 bool isDead() const { return getUse() == 0; }
146 void kill() { UseAndIsSplittable.setPointer(0); }
148 /// \brief Support for ordering ranges.
150 /// This provides an ordering over ranges such that start offsets are
151 /// always increasing, and within equal start offsets, the end offsets are
152 /// decreasing. Thus the spanning range comes first in a cluster with the
153 /// same start position.
154 bool operator<(const Slice &RHS) const {
155 if (beginOffset() < RHS.beginOffset()) return true;
156 if (beginOffset() > RHS.beginOffset()) return false;
157 if (isSplittable() != RHS.isSplittable()) return !isSplittable();
158 if (endOffset() > RHS.endOffset()) return true;
162 /// \brief Support comparison with a single offset to allow binary searches.
163 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
164 uint64_t RHSOffset) {
165 return LHS.beginOffset() < RHSOffset;
167 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
169 return LHSOffset < RHS.beginOffset();
172 bool operator==(const Slice &RHS) const {
173 return isSplittable() == RHS.isSplittable() &&
174 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
176 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
178 } // end anonymous namespace
181 template <typename T> struct isPodLike;
182 template <> struct isPodLike<Slice> {
183 static const bool value = true;
188 /// \brief Representation of the alloca slices.
190 /// This class represents the slices of an alloca which are formed by its
191 /// various uses. If a pointer escapes, we can't fully build a representation
192 /// for the slices used and we reflect that in this structure. The uses are
193 /// stored, sorted by increasing beginning offset and with unsplittable slices
194 /// starting at a particular offset before splittable slices.
197 /// \brief Construct the slices of a particular alloca.
198 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
200 /// \brief Whether we determined during the trivial analysis of the alloca
201 /// that it was immediately promotable with mem2reg.
202 bool isAllocaPromotable() const { return IsAllocaPromotable; }
204 /// \brief A list of directly stored values when \c isAllocaPromotable is
207 /// The contents are undefined if the alloca is not trivially promotable.
208 /// This is used to detect other allocas which should be iterated on when
209 /// doing direct promotion.
210 ArrayRef<Value *> getStoredValues() const { return StoredValues; }
212 /// \brief Test whether a pointer to the allocation escapes our analysis.
214 /// If this is true, the slices are never fully built and should be
216 bool isEscaped() const { return PointerEscapingInstr; }
218 /// \brief Support for iterating over the slices.
220 typedef SmallVectorImpl<Slice>::iterator iterator;
221 iterator begin() { return Slices.begin(); }
222 iterator end() { return Slices.end(); }
224 typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
225 const_iterator begin() const { return Slices.begin(); }
226 const_iterator end() const { return Slices.end(); }
229 /// \brief Allow iterating the dead users for this alloca.
231 /// These are instructions which will never actually use the alloca as they
232 /// are outside the allocated range. They are safe to replace with undef and
235 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
236 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
237 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
240 /// \brief Allow iterating the dead expressions referring to this alloca.
242 /// These are operands which have cannot actually be used to refer to the
243 /// alloca as they are outside its range and the user doesn't correct for
244 /// that. These mostly consist of PHI node inputs and the like which we just
245 /// need to replace with undef.
247 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
248 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
249 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
252 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
253 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
254 void printSlice(raw_ostream &OS, const_iterator I,
255 StringRef Indent = " ") const;
256 void printUse(raw_ostream &OS, const_iterator I,
257 StringRef Indent = " ") const;
258 void print(raw_ostream &OS) const;
259 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
260 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
264 template <typename DerivedT, typename RetT = void> class BuilderBase;
266 friend class AllocaSlices::SliceBuilder;
268 /// \brief Handle to alloca instruction to simplify method interfaces.
271 /// \brief A flag indicating if the alloca is trivially promotable.
273 /// While walking the alloca's uses we track when the uses exceed what
274 /// mem2reg can trivially handle. This essentially should match the logic in
275 /// \c isAllocaPromotable but re-using the existing walk of the pointer uses.
276 bool IsAllocaPromotable;
278 /// \brief Storage for stored values.
280 /// Only used while the alloca is trivially promotable.
281 SmallVector<Value *, 8> StoredValues;
283 /// \brief The instruction responsible for this alloca not having a known set
286 /// When an instruction (potentially) escapes the pointer to the alloca, we
287 /// store a pointer to that here and abort trying to form slices of the
288 /// alloca. This will be null if the alloca slices are analyzed successfully.
289 Instruction *PointerEscapingInstr;
291 /// \brief The slices of the alloca.
293 /// We store a vector of the slices formed by uses of the alloca here. This
294 /// vector is sorted by increasing begin offset, and then the unsplittable
295 /// slices before the splittable ones. See the Slice inner class for more
297 SmallVector<Slice, 8> Slices;
299 /// \brief Instructions which will become dead if we rewrite the alloca.
301 /// Note that these are not separated by slice. This is because we expect an
302 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
303 /// all these instructions can simply be removed and replaced with undef as
304 /// they come from outside of the allocated space.
305 SmallVector<Instruction *, 8> DeadUsers;
307 /// \brief Operands which will become dead if we rewrite the alloca.
309 /// These are operands that in their particular use can be replaced with
310 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
311 /// to PHI nodes and the like. They aren't entirely dead (there might be
312 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
313 /// want to swap this particular input for undef to simplify the use lists of
315 SmallVector<Use *, 8> DeadOperands;
319 static Value *foldSelectInst(SelectInst &SI) {
320 // If the condition being selected on is a constant or the same value is
321 // being selected between, fold the select. Yes this does (rarely) happen
323 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
324 return SI.getOperand(1+CI->isZero());
325 if (SI.getOperand(1) == SI.getOperand(2))
326 return SI.getOperand(1);
331 /// \brief Builder for the alloca slices.
333 /// This class builds a set of alloca slices by recursively visiting the uses
334 /// of an alloca and making a slice for each load and store at each offset.
335 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
336 friend class PtrUseVisitor<SliceBuilder>;
337 friend class InstVisitor<SliceBuilder>;
338 typedef PtrUseVisitor<SliceBuilder> Base;
340 const uint64_t AllocSize;
343 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
344 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
346 /// \brief Set to de-duplicate dead instructions found in the use walk.
347 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
350 SliceBuilder(const DataLayout &DL, AllocaSlices &S)
351 : PtrUseVisitor<SliceBuilder>(DL),
352 AllocSize(DL.getTypeAllocSize(S.AI.getAllocatedType())), S(S) {}
355 void markAsDead(Instruction &I) {
356 if (VisitedDeadInsts.insert(&I))
357 S.DeadUsers.push_back(&I);
360 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
361 bool IsSplittable = false) {
362 // Completely skip uses which have a zero size or start either before or
363 // past the end of the allocation.
364 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
365 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
366 << " which has zero size or starts outside of the "
367 << AllocSize << " byte alloca:\n"
368 << " alloca: " << S.AI << "\n"
369 << " use: " << I << "\n");
370 return markAsDead(I);
373 uint64_t BeginOffset = Offset.getZExtValue();
374 uint64_t EndOffset = BeginOffset + Size;
376 // Clamp the end offset to the end of the allocation. Note that this is
377 // formulated to handle even the case where "BeginOffset + Size" overflows.
378 // This may appear superficially to be something we could ignore entirely,
379 // but that is not so! There may be widened loads or PHI-node uses where
380 // some instructions are dead but not others. We can't completely ignore
381 // them, and so have to record at least the information here.
382 assert(AllocSize >= BeginOffset); // Established above.
383 if (Size > AllocSize - BeginOffset) {
384 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
385 << " to remain within the " << AllocSize << " byte alloca:\n"
386 << " alloca: " << S.AI << "\n"
387 << " use: " << I << "\n");
388 EndOffset = AllocSize;
391 S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
394 void visitBitCastInst(BitCastInst &BC) {
396 return markAsDead(BC);
398 return Base::visitBitCastInst(BC);
401 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
402 if (GEPI.use_empty())
403 return markAsDead(GEPI);
405 // FIXME: mem2reg shouldn't care about the nature of the GEP, but instead
406 // the offsets of the loads. Until then, we short-circuit here for the
408 if (GEPI.hasAllZeroIndices())
409 return Base::enqueueUsers(GEPI);
411 // Otherwise, there is something in the GEP, so we disable mem2reg and
413 S.IsAllocaPromotable = false;
414 return Base::visitGetElementPtrInst(GEPI);
417 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
418 uint64_t Size, bool IsVolatile) {
419 // We allow splitting of loads and stores where the type is an integer type
420 // and cover the entire alloca. This prevents us from splitting over
422 // FIXME: In the great blue eventually, we should eagerly split all integer
423 // loads and stores, and then have a separate step that merges adjacent
424 // alloca partitions into a single partition suitable for integer widening.
425 // Or we should skip the merge step and rely on GVN and other passes to
426 // merge adjacent loads and stores that survive mem2reg.
428 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
430 // mem2reg can only promote non-volatile loads and stores which exactly
431 // load the alloca (no offset and the right type).
432 if (IsVolatile || Offset != 0 || Ty != S.AI.getAllocatedType())
433 S.IsAllocaPromotable = false;
434 if (S.IsAllocaPromotable)
437 insertUse(I, Offset, Size, IsSplittable);
440 void visitLoadInst(LoadInst &LI) {
441 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
442 "All simple FCA loads should have been pre-split");
445 return PI.setAborted(&LI);
447 uint64_t Size = DL.getTypeStoreSize(LI.getType());
448 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
451 void visitStoreInst(StoreInst &SI) {
452 Value *ValOp = SI.getValueOperand();
454 return PI.setEscapedAndAborted(&SI);
456 return PI.setAborted(&SI);
458 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
460 // If this memory access can be shown to *statically* extend outside the
461 // bounds of of the allocation, it's behavior is undefined, so simply
462 // ignore it. Note that this is more strict than the generic clamping
463 // behavior of insertUse. We also try to handle cases which might run the
465 // FIXME: We should instead consider the pointer to have escaped if this
466 // function is being instrumented for addressing bugs or race conditions.
467 if (Offset.isNegative() || Size > AllocSize ||
468 Offset.ugt(AllocSize - Size)) {
469 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
470 << " which extends past the end of the " << AllocSize
472 << " alloca: " << S.AI << "\n"
473 << " use: " << SI << "\n");
474 return markAsDead(SI);
477 if (S.IsAllocaPromotable)
478 S.StoredValues.push_back(ValOp);
480 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
481 "All simple FCA stores should have been pre-split");
482 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
486 void visitMemSetInst(MemSetInst &II) {
487 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
488 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
489 if ((Length && Length->getValue() == 0) ||
490 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
491 // Zero-length mem transfer intrinsics can be ignored entirely.
492 return markAsDead(II);
495 return PI.setAborted(&II);
497 S.IsAllocaPromotable = false;
499 insertUse(II, Offset,
500 Length ? Length->getLimitedValue()
501 : AllocSize - Offset.getLimitedValue(),
505 void visitMemTransferInst(MemTransferInst &II) {
506 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
507 if ((Length && Length->getValue() == 0) ||
508 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
509 // Zero-length mem transfer intrinsics can be ignored entirely.
510 return markAsDead(II);
513 return PI.setAborted(&II);
515 S.IsAllocaPromotable = false;
517 uint64_t RawOffset = Offset.getLimitedValue();
518 uint64_t Size = Length ? Length->getLimitedValue()
519 : AllocSize - RawOffset;
521 // Check for the special case where the same exact value is used for both
523 if (*U == II.getRawDest() && *U == II.getRawSource()) {
524 // For non-volatile transfers this is a no-op.
525 if (!II.isVolatile())
526 return markAsDead(II);
528 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
531 // If we have seen both source and destination for a mem transfer, then
532 // they both point to the same alloca.
534 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
535 llvm::tie(MTPI, Inserted) =
536 MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
537 unsigned PrevIdx = MTPI->second;
539 Slice &PrevP = S.Slices[PrevIdx];
541 // Check if the begin offsets match and this is a non-volatile transfer.
542 // In that case, we can completely elide the transfer.
543 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
545 return markAsDead(II);
548 // Otherwise we have an offset transfer within the same alloca. We can't
550 PrevP.makeUnsplittable();
553 // Insert the use now that we've fixed up the splittable nature.
554 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
556 // Check that we ended up with a valid index in the map.
557 assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
558 "Map index doesn't point back to a slice with this user.");
561 // Disable SRoA for any intrinsics except for lifetime invariants.
562 // FIXME: What about debug intrinsics? This matches old behavior, but
563 // doesn't make sense.
564 void visitIntrinsicInst(IntrinsicInst &II) {
566 return PI.setAborted(&II);
568 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
569 II.getIntrinsicID() == Intrinsic::lifetime_end) {
570 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
571 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
572 Length->getLimitedValue());
573 insertUse(II, Offset, Size, true);
577 S.IsAllocaPromotable = false;
579 Base::visitIntrinsicInst(II);
582 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
583 // We consider any PHI or select that results in a direct load or store of
584 // the same offset to be a viable use for slicing purposes. These uses
585 // are considered unsplittable and the size is the maximum loaded or stored
587 SmallPtrSet<Instruction *, 4> Visited;
588 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
589 Visited.insert(Root);
590 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
591 // If there are no loads or stores, the access is dead. We mark that as
592 // a size zero access.
595 Instruction *I, *UsedI;
596 llvm::tie(UsedI, I) = Uses.pop_back_val();
598 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
599 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
602 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
603 Value *Op = SI->getOperand(0);
606 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
610 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
611 if (!GEP->hasAllZeroIndices())
613 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
614 !isa<SelectInst>(I)) {
618 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
620 if (Visited.insert(cast<Instruction>(*UI)))
621 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
622 } while (!Uses.empty());
627 void visitPHINode(PHINode &PN) {
629 return markAsDead(PN);
631 return PI.setAborted(&PN);
633 // See if we already have computed info on this node.
634 uint64_t &PHISize = PHIOrSelectSizes[&PN];
636 // This is a new PHI node, check for an unsafe use of the PHI node.
637 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
638 return PI.setAborted(UnsafeI);
641 // For PHI and select operands outside the alloca, we can't nuke the entire
642 // phi or select -- the other side might still be relevant, so we special
643 // case them here and use a separate structure to track the operands
644 // themselves which should be replaced with undef.
645 // FIXME: This should instead be escaped in the event we're instrumenting
646 // for address sanitization.
647 if ((Offset.isNegative() && (-Offset).uge(PHISize)) ||
648 (!Offset.isNegative() && Offset.uge(AllocSize))) {
649 S.DeadOperands.push_back(U);
653 S.IsAllocaPromotable = false;
655 insertUse(PN, Offset, PHISize);
658 void visitSelectInst(SelectInst &SI) {
660 return markAsDead(SI);
661 if (Value *Result = foldSelectInst(SI)) {
663 // If the result of the constant fold will be the pointer, recurse
664 // through the select as if we had RAUW'ed it.
667 // FIXME: mem2reg should support this pattern, but it doesn't.
668 S.IsAllocaPromotable = false;
670 // Otherwise the operand to the select is dead, and we can replace it
672 S.DeadOperands.push_back(U);
678 return PI.setAborted(&SI);
680 // See if we already have computed info on this node.
681 uint64_t &SelectSize = PHIOrSelectSizes[&SI];
683 // This is a new Select, check for an unsafe use of it.
684 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
685 return PI.setAborted(UnsafeI);
688 // For PHI and select operands outside the alloca, we can't nuke the entire
689 // phi or select -- the other side might still be relevant, so we special
690 // case them here and use a separate structure to track the operands
691 // themselves which should be replaced with undef.
692 // FIXME: This should instead be escaped in the event we're instrumenting
693 // for address sanitization.
694 if ((Offset.isNegative() && Offset.uge(SelectSize)) ||
695 (!Offset.isNegative() && Offset.uge(AllocSize))) {
696 S.DeadOperands.push_back(U);
700 S.IsAllocaPromotable = false;
702 insertUse(SI, Offset, SelectSize);
705 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
706 void visitInstruction(Instruction &I) {
711 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
712 : AI(AI), IsAllocaPromotable(true), PointerEscapingInstr(0) {
713 SliceBuilder PB(DL, *this);
714 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
715 if (PtrI.isEscaped() || PtrI.isAborted()) {
716 // FIXME: We should sink the escape vs. abort info into the caller nicely,
717 // possibly by just storing the PtrInfo in the AllocaSlices.
718 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
719 : PtrI.getAbortingInst();
720 assert(PointerEscapingInstr && "Did not track a bad instruction");
724 Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
725 std::mem_fun_ref(&Slice::isDead)),
728 // Sort the uses. This arranges for the offsets to be in ascending order,
729 // and the sizes to be in descending order.
730 std::sort(Slices.begin(), Slices.end());
733 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
735 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
736 StringRef Indent) const {
737 printSlice(OS, I, Indent);
738 printUse(OS, I, Indent);
741 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
742 StringRef Indent) const {
743 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
744 << " slice #" << (I - begin())
745 << (I->isSplittable() ? " (splittable)" : "") << "\n";
748 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
749 StringRef Indent) const {
750 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
753 void AllocaSlices::print(raw_ostream &OS) const {
754 if (PointerEscapingInstr) {
755 OS << "Can't analyze slices for alloca: " << AI << "\n"
756 << " A pointer to this alloca escaped by:\n"
757 << " " << *PointerEscapingInstr << "\n";
761 OS << "Slices of alloca: " << AI << "\n";
762 for (const_iterator I = begin(), E = end(); I != E; ++I)
766 void AllocaSlices::dump(const_iterator I) const { print(dbgs(), I); }
767 void AllocaSlices::dump() const { print(dbgs()); }
769 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
772 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
774 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
775 /// the loads and stores of an alloca instruction, as well as updating its
776 /// debug information. This is used when a domtree is unavailable and thus
777 /// mem2reg in its full form can't be used to handle promotion of allocas to
779 class AllocaPromoter : public LoadAndStorePromoter {
783 SmallVector<DbgDeclareInst *, 4> DDIs;
784 SmallVector<DbgValueInst *, 4> DVIs;
787 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
788 AllocaInst &AI, DIBuilder &DIB)
789 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
791 void run(const SmallVectorImpl<Instruction*> &Insts) {
792 // Remember which alloca we're promoting (for isInstInList).
793 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
794 for (Value::use_iterator UI = DebugNode->use_begin(),
795 UE = DebugNode->use_end();
797 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
799 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
803 LoadAndStorePromoter::run(Insts);
804 AI.eraseFromParent();
805 while (!DDIs.empty())
806 DDIs.pop_back_val()->eraseFromParent();
807 while (!DVIs.empty())
808 DVIs.pop_back_val()->eraseFromParent();
811 virtual bool isInstInList(Instruction *I,
812 const SmallVectorImpl<Instruction*> &Insts) const {
813 if (LoadInst *LI = dyn_cast<LoadInst>(I))
814 return LI->getOperand(0) == &AI;
815 return cast<StoreInst>(I)->getPointerOperand() == &AI;
818 virtual void updateDebugInfo(Instruction *Inst) const {
819 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
820 E = DDIs.end(); I != E; ++I) {
821 DbgDeclareInst *DDI = *I;
822 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
823 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
824 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
825 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
827 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
828 E = DVIs.end(); I != E; ++I) {
829 DbgValueInst *DVI = *I;
831 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
832 // If an argument is zero extended then use argument directly. The ZExt
833 // may be zapped by an optimization pass in future.
834 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
835 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
836 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
837 Arg = dyn_cast<Argument>(SExt->getOperand(0));
839 Arg = SI->getValueOperand();
840 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
841 Arg = LI->getPointerOperand();
845 Instruction *DbgVal =
846 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
848 DbgVal->setDebugLoc(DVI->getDebugLoc());
852 } // end anon namespace
856 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
858 /// This pass takes allocations which can be completely analyzed (that is, they
859 /// don't escape) and tries to turn them into scalar SSA values. There are
860 /// a few steps to this process.
862 /// 1) It takes allocations of aggregates and analyzes the ways in which they
863 /// are used to try to split them into smaller allocations, ideally of
864 /// a single scalar data type. It will split up memcpy and memset accesses
865 /// as necessary and try to isolate individual scalar accesses.
866 /// 2) It will transform accesses into forms which are suitable for SSA value
867 /// promotion. This can be replacing a memset with a scalar store of an
868 /// integer value, or it can involve speculating operations on a PHI or
869 /// select to be a PHI or select of the results.
870 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
871 /// onto insert and extract operations on a vector value, and convert them to
872 /// this form. By doing so, it will enable promotion of vector aggregates to
873 /// SSA vector values.
874 class SROA : public FunctionPass {
875 const bool RequiresDomTree;
878 const DataLayout *DL;
881 /// \brief Worklist of alloca instructions to simplify.
883 /// Each alloca in the function is added to this. Each new alloca formed gets
884 /// added to it as well to recursively simplify unless that alloca can be
885 /// directly promoted. Finally, each time we rewrite a use of an alloca other
886 /// the one being actively rewritten, we add it back onto the list if not
887 /// already present to ensure it is re-visited.
888 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
890 /// \brief A collection of instructions to delete.
891 /// We try to batch deletions to simplify code and make things a bit more
893 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
895 /// \brief Post-promotion worklist.
897 /// Sometimes we discover an alloca which has a high probability of becoming
898 /// viable for SROA after a round of promotion takes place. In those cases,
899 /// the alloca is enqueued here for re-processing.
901 /// Note that we have to be very careful to clear allocas out of this list in
902 /// the event they are deleted.
903 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
905 /// \brief A collection of alloca instructions we can directly promote.
906 std::vector<AllocaInst *> PromotableAllocas;
908 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
910 /// All of these PHIs have been checked for the safety of speculation and by
911 /// being speculated will allow promoting allocas currently in the promotable
913 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
915 /// \brief A worklist of select instructions to speculate prior to promoting
918 /// All of these select instructions have been checked for the safety of
919 /// speculation and by being speculated will allow promoting allocas
920 /// currently in the promotable queue.
921 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
924 SROA(bool RequiresDomTree = true)
925 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
927 initializeSROAPass(*PassRegistry::getPassRegistry());
929 bool runOnFunction(Function &F);
930 void getAnalysisUsage(AnalysisUsage &AU) const;
932 const char *getPassName() const { return "SROA"; }
936 friend class PHIOrSelectSpeculator;
937 friend class AllocaSliceRewriter;
939 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
940 AllocaSlices::iterator B, AllocaSlices::iterator E,
941 int64_t BeginOffset, int64_t EndOffset,
942 ArrayRef<AllocaSlices::iterator> SplitUses);
943 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
944 bool runOnAlloca(AllocaInst &AI);
945 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
946 bool promoteAllocas(Function &F);
952 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
953 return new SROA(RequiresDomTree);
956 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
958 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
959 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
962 /// Walk the range of a partitioning looking for a common type to cover this
963 /// sequence of slices.
964 static Type *findCommonType(AllocaSlices::const_iterator B,
965 AllocaSlices::const_iterator E,
966 uint64_t EndOffset) {
968 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
969 Use *U = I->getUse();
970 if (isa<IntrinsicInst>(*U->getUser()))
972 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
976 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
977 UserTy = LI->getType();
978 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
979 UserTy = SI->getValueOperand()->getType();
981 return 0; // Bail if we have weird uses.
983 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
984 // If the type is larger than the partition, skip it. We only encounter
985 // this for split integer operations where we want to use the type of the
986 // entity causing the split.
987 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
990 // If we have found an integer type use covering the alloca, use that
991 // regardless of the other types, as integers are often used for a
997 if (Ty && Ty != UserTy)
1005 /// PHI instructions that use an alloca and are subsequently loaded can be
1006 /// rewritten to load both input pointers in the pred blocks and then PHI the
1007 /// results, allowing the load of the alloca to be promoted.
1009 /// %P2 = phi [i32* %Alloca, i32* %Other]
1010 /// %V = load i32* %P2
1012 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1014 /// %V2 = load i32* %Other
1016 /// %V = phi [i32 %V1, i32 %V2]
1018 /// We can do this to a select if its only uses are loads and if the operands
1019 /// to the select can be loaded unconditionally.
1021 /// FIXME: This should be hoisted into a generic utility, likely in
1022 /// Transforms/Util/Local.h
1023 static bool isSafePHIToSpeculate(PHINode &PN,
1024 const DataLayout *DL = 0) {
1025 // For now, we can only do this promotion if the load is in the same block
1026 // as the PHI, and if there are no stores between the phi and load.
1027 // TODO: Allow recursive phi users.
1028 // TODO: Allow stores.
1029 BasicBlock *BB = PN.getParent();
1030 unsigned MaxAlign = 0;
1031 bool HaveLoad = false;
1032 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1034 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1035 if (LI == 0 || !LI->isSimple())
1038 // For now we only allow loads in the same block as the PHI. This is
1039 // a common case that happens when instcombine merges two loads through
1041 if (LI->getParent() != BB)
1044 // Ensure that there are no instructions between the PHI and the load that
1046 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1047 if (BBI->mayWriteToMemory())
1050 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1057 // We can only transform this if it is safe to push the loads into the
1058 // predecessor blocks. The only thing to watch out for is that we can't put
1059 // a possibly trapping load in the predecessor if it is a critical edge.
1060 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1061 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1062 Value *InVal = PN.getIncomingValue(Idx);
1064 // If the value is produced by the terminator of the predecessor (an
1065 // invoke) or it has side-effects, there is no valid place to put a load
1066 // in the predecessor.
1067 if (TI == InVal || TI->mayHaveSideEffects())
1070 // If the predecessor has a single successor, then the edge isn't
1072 if (TI->getNumSuccessors() == 1)
1075 // If this pointer is always safe to load, or if we can prove that there
1076 // is already a load in the block, then we can move the load to the pred
1078 if (InVal->isDereferenceablePointer() ||
1079 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1088 static void speculatePHINodeLoads(PHINode &PN) {
1089 DEBUG(dbgs() << " original: " << PN << "\n");
1091 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1092 IRBuilderTy PHIBuilder(&PN);
1093 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1094 PN.getName() + ".sroa.speculated");
1096 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1097 // matter which one we get and if any differ.
1098 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1099 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1100 unsigned Align = SomeLoad->getAlignment();
1102 // Rewrite all loads of the PN to use the new PHI.
1103 while (!PN.use_empty()) {
1104 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1105 LI->replaceAllUsesWith(NewPN);
1106 LI->eraseFromParent();
1109 // Inject loads into all of the pred blocks.
1110 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1111 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1112 TerminatorInst *TI = Pred->getTerminator();
1113 Value *InVal = PN.getIncomingValue(Idx);
1114 IRBuilderTy PredBuilder(TI);
1116 LoadInst *Load = PredBuilder.CreateLoad(
1117 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1118 ++NumLoadsSpeculated;
1119 Load->setAlignment(Align);
1121 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1122 NewPN->addIncoming(Load, Pred);
1125 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1126 PN.eraseFromParent();
1129 /// Select instructions that use an alloca and are subsequently loaded can be
1130 /// rewritten to load both input pointers and then select between the result,
1131 /// allowing the load of the alloca to be promoted.
1133 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1134 /// %V = load i32* %P2
1136 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1137 /// %V2 = load i32* %Other
1138 /// %V = select i1 %cond, i32 %V1, i32 %V2
1140 /// We can do this to a select if its only uses are loads and if the operand
1141 /// to the select can be loaded unconditionally.
1142 static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
1143 Value *TValue = SI.getTrueValue();
1144 Value *FValue = SI.getFalseValue();
1145 bool TDerefable = TValue->isDereferenceablePointer();
1146 bool FDerefable = FValue->isDereferenceablePointer();
1148 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1150 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1151 if (LI == 0 || !LI->isSimple())
1154 // Both operands to the select need to be dereferencable, either
1155 // absolutely (e.g. allocas) or at this point because we can see other
1158 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1161 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1168 static void speculateSelectInstLoads(SelectInst &SI) {
1169 DEBUG(dbgs() << " original: " << SI << "\n");
1171 IRBuilderTy IRB(&SI);
1172 Value *TV = SI.getTrueValue();
1173 Value *FV = SI.getFalseValue();
1174 // Replace the loads of the select with a select of two loads.
1175 while (!SI.use_empty()) {
1176 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1177 assert(LI->isSimple() && "We only speculate simple loads");
1179 IRB.SetInsertPoint(LI);
1181 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1183 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1184 NumLoadsSpeculated += 2;
1186 // Transfer alignment and TBAA info if present.
1187 TL->setAlignment(LI->getAlignment());
1188 FL->setAlignment(LI->getAlignment());
1189 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1190 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1191 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1194 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1195 LI->getName() + ".sroa.speculated");
1197 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1198 LI->replaceAllUsesWith(V);
1199 LI->eraseFromParent();
1201 SI.eraseFromParent();
1204 /// \brief Build a GEP out of a base pointer and indices.
1206 /// This will return the BasePtr if that is valid, or build a new GEP
1207 /// instruction using the IRBuilder if GEP-ing is needed.
1208 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1209 SmallVectorImpl<Value *> &Indices) {
1210 if (Indices.empty())
1213 // A single zero index is a no-op, so check for this and avoid building a GEP
1215 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1218 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
1221 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1222 /// TargetTy without changing the offset of the pointer.
1224 /// This routine assumes we've already established a properly offset GEP with
1225 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1226 /// zero-indices down through type layers until we find one the same as
1227 /// TargetTy. If we can't find one with the same type, we at least try to use
1228 /// one with the same size. If none of that works, we just produce the GEP as
1229 /// indicated by Indices to have the correct offset.
1230 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1231 Value *BasePtr, Type *Ty, Type *TargetTy,
1232 SmallVectorImpl<Value *> &Indices) {
1234 return buildGEP(IRB, BasePtr, Indices);
1236 // See if we can descend into a struct and locate a field with the correct
1238 unsigned NumLayers = 0;
1239 Type *ElementTy = Ty;
1241 if (ElementTy->isPointerTy())
1243 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1244 ElementTy = SeqTy->getElementType();
1245 // Note that we use the default address space as this index is over an
1246 // array or a vector, not a pointer.
1247 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
1248 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1249 if (STy->element_begin() == STy->element_end())
1250 break; // Nothing left to descend into.
1251 ElementTy = *STy->element_begin();
1252 Indices.push_back(IRB.getInt32(0));
1257 } while (ElementTy != TargetTy);
1258 if (ElementTy != TargetTy)
1259 Indices.erase(Indices.end() - NumLayers, Indices.end());
1261 return buildGEP(IRB, BasePtr, Indices);
1264 /// \brief Recursively compute indices for a natural GEP.
1266 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1267 /// element types adding appropriate indices for the GEP.
1268 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1269 Value *Ptr, Type *Ty, APInt &Offset,
1271 SmallVectorImpl<Value *> &Indices) {
1273 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
1275 // We can't recurse through pointer types.
1276 if (Ty->isPointerTy())
1279 // We try to analyze GEPs over vectors here, but note that these GEPs are
1280 // extremely poorly defined currently. The long-term goal is to remove GEPing
1281 // over a vector from the IR completely.
1282 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1283 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1284 if (ElementSizeInBits % 8)
1285 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1286 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1287 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1288 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1290 Offset -= NumSkippedElements * ElementSize;
1291 Indices.push_back(IRB.getInt(NumSkippedElements));
1292 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1293 Offset, TargetTy, Indices);
1296 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1297 Type *ElementTy = ArrTy->getElementType();
1298 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1299 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1300 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1303 Offset -= NumSkippedElements * ElementSize;
1304 Indices.push_back(IRB.getInt(NumSkippedElements));
1305 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1309 StructType *STy = dyn_cast<StructType>(Ty);
1313 const StructLayout *SL = DL.getStructLayout(STy);
1314 uint64_t StructOffset = Offset.getZExtValue();
1315 if (StructOffset >= SL->getSizeInBytes())
1317 unsigned Index = SL->getElementContainingOffset(StructOffset);
1318 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1319 Type *ElementTy = STy->getElementType(Index);
1320 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1321 return 0; // The offset points into alignment padding.
1323 Indices.push_back(IRB.getInt32(Index));
1324 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1328 /// \brief Get a natural GEP from a base pointer to a particular offset and
1329 /// resulting in a particular type.
1331 /// The goal is to produce a "natural" looking GEP that works with the existing
1332 /// composite types to arrive at the appropriate offset and element type for
1333 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1334 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1335 /// Indices, and setting Ty to the result subtype.
1337 /// If no natural GEP can be constructed, this function returns null.
1338 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1339 Value *Ptr, APInt Offset, Type *TargetTy,
1340 SmallVectorImpl<Value *> &Indices) {
1341 PointerType *Ty = cast<PointerType>(Ptr->getType());
1343 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1345 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1348 Type *ElementTy = Ty->getElementType();
1349 if (!ElementTy->isSized())
1350 return 0; // We can't GEP through an unsized element.
1351 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1352 if (ElementSize == 0)
1353 return 0; // Zero-length arrays can't help us build a natural GEP.
1354 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1356 Offset -= NumSkippedElements * ElementSize;
1357 Indices.push_back(IRB.getInt(NumSkippedElements));
1358 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1362 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1363 /// resulting pointer has PointerTy.
1365 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1366 /// and produces the pointer type desired. Where it cannot, it will try to use
1367 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1368 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1369 /// bitcast to the type.
1371 /// The strategy for finding the more natural GEPs is to peel off layers of the
1372 /// pointer, walking back through bit casts and GEPs, searching for a base
1373 /// pointer from which we can compute a natural GEP with the desired
1374 /// properties. The algorithm tries to fold as many constant indices into
1375 /// a single GEP as possible, thus making each GEP more independent of the
1376 /// surrounding code.
1377 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
1378 Value *Ptr, APInt Offset, Type *PointerTy) {
1379 // Even though we don't look through PHI nodes, we could be called on an
1380 // instruction in an unreachable block, which may be on a cycle.
1381 SmallPtrSet<Value *, 4> Visited;
1382 Visited.insert(Ptr);
1383 SmallVector<Value *, 4> Indices;
1385 // We may end up computing an offset pointer that has the wrong type. If we
1386 // never are able to compute one directly that has the correct type, we'll
1387 // fall back to it, so keep it around here.
1388 Value *OffsetPtr = 0;
1390 // Remember any i8 pointer we come across to re-use if we need to do a raw
1393 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1395 Type *TargetTy = PointerTy->getPointerElementType();
1398 // First fold any existing GEPs into the offset.
1399 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1400 APInt GEPOffset(Offset.getBitWidth(), 0);
1401 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1403 Offset += GEPOffset;
1404 Ptr = GEP->getPointerOperand();
1405 if (!Visited.insert(Ptr))
1409 // See if we can perform a natural GEP here.
1411 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1413 if (P->getType() == PointerTy) {
1414 // Zap any offset pointer that we ended up computing in previous rounds.
1415 if (OffsetPtr && OffsetPtr->use_empty())
1416 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1417 I->eraseFromParent();
1425 // Stash this pointer if we've found an i8*.
1426 if (Ptr->getType()->isIntegerTy(8)) {
1428 Int8PtrOffset = Offset;
1431 // Peel off a layer of the pointer and update the offset appropriately.
1432 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1433 Ptr = cast<Operator>(Ptr)->getOperand(0);
1434 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1435 if (GA->mayBeOverridden())
1437 Ptr = GA->getAliasee();
1441 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1442 } while (Visited.insert(Ptr));
1446 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1448 Int8PtrOffset = Offset;
1451 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1452 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1457 // On the off chance we were targeting i8*, guard the bitcast here.
1458 if (Ptr->getType() != PointerTy)
1459 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
1464 /// \brief Test whether we can convert a value from the old to the new type.
1466 /// This predicate should be used to guard calls to convertValue in order to
1467 /// ensure that we only try to convert viable values. The strategy is that we
1468 /// will peel off single element struct and array wrappings to get to an
1469 /// underlying value, and convert that value.
1470 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1473 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1474 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1475 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1477 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1479 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1482 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1483 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1485 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1493 /// \brief Generic routine to convert an SSA value to a value of a different
1496 /// This will try various different casting techniques, such as bitcasts,
1497 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1498 /// two types for viability with this routine.
1499 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1501 assert(canConvertValue(DL, V->getType(), Ty) &&
1502 "Value not convertable to type");
1503 if (V->getType() == Ty)
1505 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1506 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1507 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1508 return IRB.CreateZExt(V, NewITy);
1509 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1510 return IRB.CreateIntToPtr(V, Ty);
1511 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1512 return IRB.CreatePtrToInt(V, Ty);
1514 return IRB.CreateBitCast(V, Ty);
1517 /// \brief Test whether the given slice use can be promoted to a vector.
1519 /// This function is called to test each entry in a partioning which is slated
1520 /// for a single slice.
1521 static bool isVectorPromotionViableForSlice(
1522 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1523 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1524 AllocaSlices::const_iterator I) {
1525 // First validate the slice offsets.
1526 uint64_t BeginOffset =
1527 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1528 uint64_t BeginIndex = BeginOffset / ElementSize;
1529 if (BeginIndex * ElementSize != BeginOffset ||
1530 BeginIndex >= Ty->getNumElements())
1532 uint64_t EndOffset =
1533 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
1534 uint64_t EndIndex = EndOffset / ElementSize;
1535 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1538 assert(EndIndex > BeginIndex && "Empty vector!");
1539 uint64_t NumElements = EndIndex - BeginIndex;
1541 (NumElements == 1) ? Ty->getElementType()
1542 : VectorType::get(Ty->getElementType(), NumElements);
1545 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1547 Use *U = I->getUse();
1549 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1550 if (MI->isVolatile())
1552 if (!I->isSplittable())
1553 return false; // Skip any unsplittable intrinsics.
1554 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1555 // Disable vector promotion when there are loads or stores of an FCA.
1557 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1558 if (LI->isVolatile())
1560 Type *LTy = LI->getType();
1561 if (SliceBeginOffset > I->beginOffset() ||
1562 SliceEndOffset < I->endOffset()) {
1563 assert(LTy->isIntegerTy());
1566 if (!canConvertValue(DL, SliceTy, LTy))
1568 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1569 if (SI->isVolatile())
1571 Type *STy = SI->getValueOperand()->getType();
1572 if (SliceBeginOffset > I->beginOffset() ||
1573 SliceEndOffset < I->endOffset()) {
1574 assert(STy->isIntegerTy());
1577 if (!canConvertValue(DL, STy, SliceTy))
1586 /// \brief Test whether the given alloca partitioning and range of slices can be
1587 /// promoted to a vector.
1589 /// This is a quick test to check whether we can rewrite a particular alloca
1590 /// partition (and its newly formed alloca) into a vector alloca with only
1591 /// whole-vector loads and stores such that it could be promoted to a vector
1592 /// SSA value. We only can ensure this for a limited set of operations, and we
1593 /// don't want to do the rewrites unless we are confident that the result will
1594 /// be promotable, so we have an early test here.
1596 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1597 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1598 AllocaSlices::const_iterator I,
1599 AllocaSlices::const_iterator E,
1600 ArrayRef<AllocaSlices::iterator> SplitUses) {
1601 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1605 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
1607 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1608 // that aren't byte sized.
1609 if (ElementSize % 8)
1611 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
1612 "vector size not a multiple of element size?");
1616 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1617 SliceEndOffset, Ty, ElementSize, I))
1620 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1621 SUE = SplitUses.end();
1623 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1624 SliceEndOffset, Ty, ElementSize, *SUI))
1630 /// \brief Test whether a slice of an alloca is valid for integer widening.
1632 /// This implements the necessary checking for the \c isIntegerWideningViable
1633 /// test below on a single slice of the alloca.
1634 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1636 uint64_t AllocBeginOffset,
1637 uint64_t Size, AllocaSlices &S,
1638 AllocaSlices::const_iterator I,
1639 bool &WholeAllocaOp) {
1640 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1641 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1643 // We can't reasonably handle cases where the load or store extends past
1644 // the end of the aloca's type and into its padding.
1648 Use *U = I->getUse();
1650 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1651 if (LI->isVolatile())
1653 if (RelBegin == 0 && RelEnd == Size)
1654 WholeAllocaOp = true;
1655 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1656 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1658 } else if (RelBegin != 0 || RelEnd != Size ||
1659 !canConvertValue(DL, AllocaTy, LI->getType())) {
1660 // Non-integer loads need to be convertible from the alloca type so that
1661 // they are promotable.
1664 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1665 Type *ValueTy = SI->getValueOperand()->getType();
1666 if (SI->isVolatile())
1668 if (RelBegin == 0 && RelEnd == Size)
1669 WholeAllocaOp = true;
1670 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1671 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1673 } else if (RelBegin != 0 || RelEnd != Size ||
1674 !canConvertValue(DL, ValueTy, AllocaTy)) {
1675 // Non-integer stores need to be convertible to the alloca type so that
1676 // they are promotable.
1679 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1680 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1682 if (!I->isSplittable())
1683 return false; // Skip any unsplittable intrinsics.
1684 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1685 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1686 II->getIntrinsicID() != Intrinsic::lifetime_end)
1695 /// \brief Test whether the given alloca partition's integer operations can be
1696 /// widened to promotable ones.
1698 /// This is a quick test to check whether we can rewrite the integer loads and
1699 /// stores to a particular alloca into wider loads and stores and be able to
1700 /// promote the resulting alloca.
1702 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1703 uint64_t AllocBeginOffset, AllocaSlices &S,
1704 AllocaSlices::const_iterator I,
1705 AllocaSlices::const_iterator E,
1706 ArrayRef<AllocaSlices::iterator> SplitUses) {
1707 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1708 // Don't create integer types larger than the maximum bitwidth.
1709 if (SizeInBits > IntegerType::MAX_INT_BITS)
1712 // Don't try to handle allocas with bit-padding.
1713 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1716 // We need to ensure that an integer type with the appropriate bitwidth can
1717 // be converted to the alloca type, whatever that is. We don't want to force
1718 // the alloca itself to have an integer type if there is a more suitable one.
1719 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1720 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1721 !canConvertValue(DL, IntTy, AllocaTy))
1724 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1726 // While examining uses, we ensure that the alloca has a covering load or
1727 // store. We don't want to widen the integer operations only to fail to
1728 // promote due to some other unsplittable entry (which we may make splittable
1729 // later). However, if there are only splittable uses, go ahead and assume
1730 // that we cover the alloca.
1731 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
1734 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1735 S, I, WholeAllocaOp))
1738 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1739 SUE = SplitUses.end();
1741 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1742 S, *SUI, WholeAllocaOp))
1745 return WholeAllocaOp;
1748 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1749 IntegerType *Ty, uint64_t Offset,
1750 const Twine &Name) {
1751 DEBUG(dbgs() << " start: " << *V << "\n");
1752 IntegerType *IntTy = cast<IntegerType>(V->getType());
1753 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1754 "Element extends past full value");
1755 uint64_t ShAmt = 8*Offset;
1756 if (DL.isBigEndian())
1757 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1759 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1760 DEBUG(dbgs() << " shifted: " << *V << "\n");
1762 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1763 "Cannot extract to a larger integer!");
1765 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1766 DEBUG(dbgs() << " trunced: " << *V << "\n");
1771 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1772 Value *V, uint64_t Offset, const Twine &Name) {
1773 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1774 IntegerType *Ty = cast<IntegerType>(V->getType());
1775 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1776 "Cannot insert a larger integer!");
1777 DEBUG(dbgs() << " start: " << *V << "\n");
1779 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1780 DEBUG(dbgs() << " extended: " << *V << "\n");
1782 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1783 "Element store outside of alloca store");
1784 uint64_t ShAmt = 8*Offset;
1785 if (DL.isBigEndian())
1786 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1788 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1789 DEBUG(dbgs() << " shifted: " << *V << "\n");
1792 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1793 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1794 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1795 DEBUG(dbgs() << " masked: " << *Old << "\n");
1796 V = IRB.CreateOr(Old, V, Name + ".insert");
1797 DEBUG(dbgs() << " inserted: " << *V << "\n");
1802 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1803 unsigned BeginIndex, unsigned EndIndex,
1804 const Twine &Name) {
1805 VectorType *VecTy = cast<VectorType>(V->getType());
1806 unsigned NumElements = EndIndex - BeginIndex;
1807 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1809 if (NumElements == VecTy->getNumElements())
1812 if (NumElements == 1) {
1813 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1815 DEBUG(dbgs() << " extract: " << *V << "\n");
1819 SmallVector<Constant*, 8> Mask;
1820 Mask.reserve(NumElements);
1821 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1822 Mask.push_back(IRB.getInt32(i));
1823 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1824 ConstantVector::get(Mask),
1826 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1830 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
1831 unsigned BeginIndex, const Twine &Name) {
1832 VectorType *VecTy = cast<VectorType>(Old->getType());
1833 assert(VecTy && "Can only insert a vector into a vector");
1835 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1837 // Single element to insert.
1838 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1840 DEBUG(dbgs() << " insert: " << *V << "\n");
1844 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1845 "Too many elements!");
1846 if (Ty->getNumElements() == VecTy->getNumElements()) {
1847 assert(V->getType() == VecTy && "Vector type mismatch");
1850 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1852 // When inserting a smaller vector into the larger to store, we first
1853 // use a shuffle vector to widen it with undef elements, and then
1854 // a second shuffle vector to select between the loaded vector and the
1856 SmallVector<Constant*, 8> Mask;
1857 Mask.reserve(VecTy->getNumElements());
1858 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1859 if (i >= BeginIndex && i < EndIndex)
1860 Mask.push_back(IRB.getInt32(i - BeginIndex));
1862 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1863 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1864 ConstantVector::get(Mask),
1866 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1869 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1870 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1872 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1874 DEBUG(dbgs() << " blend: " << *V << "\n");
1879 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
1880 /// to use a new alloca.
1882 /// Also implements the rewriting to vector-based accesses when the partition
1883 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1885 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
1886 // Befriend the base class so it can delegate to private visit methods.
1887 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1888 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
1890 const DataLayout &DL;
1893 AllocaInst &OldAI, &NewAI;
1894 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1897 // If we are rewriting an alloca partition which can be written as pure
1898 // vector operations, we stash extra information here. When VecTy is
1899 // non-null, we have some strict guarantees about the rewritten alloca:
1900 // - The new alloca is exactly the size of the vector type here.
1901 // - The accesses all either map to the entire vector or to a single
1903 // - The set of accessing instructions is only one of those handled above
1904 // in isVectorPromotionViable. Generally these are the same access kinds
1905 // which are promotable via mem2reg.
1908 uint64_t ElementSize;
1910 // This is a convenience and flag variable that will be null unless the new
1911 // alloca's integer operations should be widened to this integer type due to
1912 // passing isIntegerWideningViable above. If it is non-null, the desired
1913 // integer type will be stored here for easy access during rewriting.
1916 // The offset of the slice currently being rewritten.
1917 uint64_t BeginOffset, EndOffset;
1921 Instruction *OldPtr;
1923 // Output members carrying state about the result of visiting and rewriting
1924 // the slice of the alloca.
1925 bool IsUsedByRewrittenSpeculatableInstructions;
1927 // Utility IR builder, whose name prefix is setup for each visited use, and
1928 // the insertion point is set to point to the user.
1932 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1933 AllocaInst &OldAI, AllocaInst &NewAI,
1934 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1935 bool IsVectorPromotable = false,
1936 bool IsIntegerPromotable = false)
1937 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
1938 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1939 NewAllocaTy(NewAI.getAllocatedType()),
1940 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1941 ElementTy(VecTy ? VecTy->getElementType() : 0),
1942 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
1943 IntTy(IsIntegerPromotable
1946 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
1948 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1949 OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1950 IRB(NewAI.getContext(), ConstantFolder()) {
1952 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
1953 "Only multiple-of-8 sized vector elements are viable");
1956 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1957 IsVectorPromotable != IsIntegerPromotable);
1960 bool visit(AllocaSlices::const_iterator I) {
1961 bool CanSROA = true;
1962 BeginOffset = I->beginOffset();
1963 EndOffset = I->endOffset();
1964 IsSplittable = I->isSplittable();
1966 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
1968 OldUse = I->getUse();
1969 OldPtr = cast<Instruction>(OldUse->get());
1971 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1972 IRB.SetInsertPoint(OldUserI);
1973 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1974 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
1976 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
1982 /// \brief Query whether this slice is used by speculatable instructions after
1985 /// These instructions (PHIs and Selects currently) require the alloca slice
1986 /// to run back through the rewriter. Thus, they are promotable, but not on
1987 /// this iteration. This is distinct from a slice which is unpromotable for
1988 /// some other reason, in which case we don't even want to perform the
1989 /// speculation. This can be querried at any time and reflects whether (at
1990 /// that point) a visit call has rewritten a speculatable instruction on the
1992 bool isUsedByRewrittenSpeculatableInstructions() const {
1993 return IsUsedByRewrittenSpeculatableInstructions;
1997 // Make sure the other visit overloads are visible.
2000 // Every instruction which can end up as a user must have a rewrite rule.
2001 bool visitInstruction(Instruction &I) {
2002 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2003 llvm_unreachable("No rewrite rule for this instruction!");
2006 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2008 assert(Offset >= NewAllocaBeginOffset);
2009 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
2010 Offset - NewAllocaBeginOffset),
2014 /// \brief Compute suitable alignment to access an offset into the new alloca.
2015 unsigned getOffsetAlign(uint64_t Offset) {
2016 unsigned NewAIAlign = NewAI.getAlignment();
2018 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2019 return MinAlign(NewAIAlign, Offset);
2022 /// \brief Compute suitable alignment to access a type at an offset of the
2025 /// \returns zero if the type's ABI alignment is a suitable alignment,
2026 /// otherwise returns the maximal suitable alignment.
2027 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2028 unsigned Align = getOffsetAlign(Offset);
2029 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
2032 unsigned getIndex(uint64_t Offset) {
2033 assert(VecTy && "Can only call getIndex when rewriting a vector");
2034 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2035 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2036 uint32_t Index = RelOffset / ElementSize;
2037 assert(Index * ElementSize == RelOffset);
2041 void deleteIfTriviallyDead(Value *V) {
2042 Instruction *I = cast<Instruction>(V);
2043 if (isInstructionTriviallyDead(I))
2044 Pass.DeadInsts.insert(I);
2047 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2048 uint64_t NewEndOffset) {
2049 unsigned BeginIndex = getIndex(NewBeginOffset);
2050 unsigned EndIndex = getIndex(NewEndOffset);
2051 assert(EndIndex > BeginIndex && "Empty vector!");
2053 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2055 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2058 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2059 uint64_t NewEndOffset) {
2060 assert(IntTy && "We cannot insert an integer to the alloca");
2061 assert(!LI.isVolatile());
2062 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2064 V = convertValue(DL, IRB, V, IntTy);
2065 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2066 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2067 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2068 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2073 bool visitLoadInst(LoadInst &LI) {
2074 DEBUG(dbgs() << " original: " << LI << "\n");
2075 Value *OldOp = LI.getOperand(0);
2076 assert(OldOp == OldPtr);
2078 // Compute the intersecting offset range.
2079 assert(BeginOffset < NewAllocaEndOffset);
2080 assert(EndOffset > NewAllocaBeginOffset);
2081 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2082 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2084 uint64_t Size = NewEndOffset - NewBeginOffset;
2086 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2088 bool IsPtrAdjusted = false;
2091 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
2092 } else if (IntTy && LI.getType()->isIntegerTy()) {
2093 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2094 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2095 canConvertValue(DL, NewAllocaTy, LI.getType())) {
2096 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2097 LI.isVolatile(), "load");
2099 Type *LTy = TargetTy->getPointerTo();
2100 V = IRB.CreateAlignedLoad(
2101 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2102 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2103 LI.isVolatile(), "load");
2104 IsPtrAdjusted = true;
2106 V = convertValue(DL, IRB, V, TargetTy);
2109 assert(!LI.isVolatile());
2110 assert(LI.getType()->isIntegerTy() &&
2111 "Only integer type loads and stores are split");
2112 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
2113 "Split load isn't smaller than original load");
2114 assert(LI.getType()->getIntegerBitWidth() ==
2115 DL.getTypeStoreSizeInBits(LI.getType()) &&
2116 "Non-byte-multiple bit width");
2117 // Move the insertion point just past the load so that we can refer to it.
2118 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2119 // Create a placeholder value with the same type as LI to use as the
2120 // basis for the new value. This allows us to replace the uses of LI with
2121 // the computed value, and then replace the placeholder with LI, leaving
2122 // LI only used for this computation.
2124 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2125 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
2127 LI.replaceAllUsesWith(V);
2128 Placeholder->replaceAllUsesWith(&LI);
2131 LI.replaceAllUsesWith(V);
2134 Pass.DeadInsts.insert(&LI);
2135 deleteIfTriviallyDead(OldOp);
2136 DEBUG(dbgs() << " to: " << *V << "\n");
2137 return !LI.isVolatile() && !IsPtrAdjusted;
2140 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2141 uint64_t NewBeginOffset,
2142 uint64_t NewEndOffset) {
2143 if (V->getType() != VecTy) {
2144 unsigned BeginIndex = getIndex(NewBeginOffset);
2145 unsigned EndIndex = getIndex(NewEndOffset);
2146 assert(EndIndex > BeginIndex && "Empty vector!");
2147 unsigned NumElements = EndIndex - BeginIndex;
2148 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2150 (NumElements == 1) ? ElementTy
2151 : VectorType::get(ElementTy, NumElements);
2152 if (V->getType() != SliceTy)
2153 V = convertValue(DL, IRB, V, SliceTy);
2155 // Mix in the existing elements.
2156 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2158 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2160 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2161 Pass.DeadInsts.insert(&SI);
2164 DEBUG(dbgs() << " to: " << *Store << "\n");
2168 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2169 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
2170 assert(IntTy && "We cannot extract an integer from the alloca");
2171 assert(!SI.isVolatile());
2172 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2173 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2175 Old = convertValue(DL, IRB, Old, IntTy);
2176 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2177 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2178 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
2181 V = convertValue(DL, IRB, V, NewAllocaTy);
2182 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2183 Pass.DeadInsts.insert(&SI);
2185 DEBUG(dbgs() << " to: " << *Store << "\n");
2189 bool visitStoreInst(StoreInst &SI) {
2190 DEBUG(dbgs() << " original: " << SI << "\n");
2191 Value *OldOp = SI.getOperand(1);
2192 assert(OldOp == OldPtr);
2194 Value *V = SI.getValueOperand();
2196 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2197 // alloca that should be re-examined after promoting this alloca.
2198 if (V->getType()->isPointerTy())
2199 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2200 Pass.PostPromotionWorklist.insert(AI);
2202 // Compute the intersecting offset range.
2203 assert(BeginOffset < NewAllocaEndOffset);
2204 assert(EndOffset > NewAllocaBeginOffset);
2205 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2206 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2208 uint64_t Size = NewEndOffset - NewBeginOffset;
2209 if (Size < DL.getTypeStoreSize(V->getType())) {
2210 assert(!SI.isVolatile());
2211 assert(V->getType()->isIntegerTy() &&
2212 "Only integer type loads and stores are split");
2213 assert(V->getType()->getIntegerBitWidth() ==
2214 DL.getTypeStoreSizeInBits(V->getType()) &&
2215 "Non-byte-multiple bit width");
2216 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2217 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
2222 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2224 if (IntTy && V->getType()->isIntegerTy())
2225 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
2228 if (NewBeginOffset == NewAllocaBeginOffset &&
2229 NewEndOffset == NewAllocaEndOffset &&
2230 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2231 V = convertValue(DL, IRB, V, NewAllocaTy);
2232 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2235 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2236 V->getType()->getPointerTo());
2237 NewSI = IRB.CreateAlignedStore(
2238 V, NewPtr, getOffsetTypeAlign(
2239 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2243 Pass.DeadInsts.insert(&SI);
2244 deleteIfTriviallyDead(OldOp);
2246 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2247 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2250 /// \brief Compute an integer value from splatting an i8 across the given
2251 /// number of bytes.
2253 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2254 /// call this routine.
2255 /// FIXME: Heed the advice above.
2257 /// \param V The i8 value to splat.
2258 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2259 Value *getIntegerSplat(Value *V, unsigned Size) {
2260 assert(Size > 0 && "Expected a positive number of bytes.");
2261 IntegerType *VTy = cast<IntegerType>(V->getType());
2262 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2266 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2267 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2268 ConstantExpr::getUDiv(
2269 Constant::getAllOnesValue(SplatIntTy),
2270 ConstantExpr::getZExt(
2271 Constant::getAllOnesValue(V->getType()),
2277 /// \brief Compute a vector splat for a given element value.
2278 Value *getVectorSplat(Value *V, unsigned NumElements) {
2279 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2280 DEBUG(dbgs() << " splat: " << *V << "\n");
2284 bool visitMemSetInst(MemSetInst &II) {
2285 DEBUG(dbgs() << " original: " << II << "\n");
2286 assert(II.getRawDest() == OldPtr);
2288 // If the memset has a variable size, it cannot be split, just adjust the
2289 // pointer to the new alloca.
2290 if (!isa<Constant>(II.getLength())) {
2292 assert(BeginOffset >= NewAllocaBeginOffset);
2294 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2295 Type *CstTy = II.getAlignmentCst()->getType();
2296 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
2298 deleteIfTriviallyDead(OldPtr);
2302 // Record this instruction for deletion.
2303 Pass.DeadInsts.insert(&II);
2305 Type *AllocaTy = NewAI.getAllocatedType();
2306 Type *ScalarTy = AllocaTy->getScalarType();
2308 // Compute the intersecting offset range.
2309 assert(BeginOffset < NewAllocaEndOffset);
2310 assert(EndOffset > NewAllocaBeginOffset);
2311 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2312 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2313 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2315 // If this doesn't map cleanly onto the alloca type, and that type isn't
2316 // a single value type, just emit a memset.
2317 if (!VecTy && !IntTy &&
2318 (BeginOffset > NewAllocaBeginOffset ||
2319 EndOffset < NewAllocaEndOffset ||
2320 !AllocaTy->isSingleValueType() ||
2321 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2322 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2323 Type *SizeTy = II.getLength()->getType();
2324 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2325 CallInst *New = IRB.CreateMemSet(
2326 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
2327 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
2329 DEBUG(dbgs() << " to: " << *New << "\n");
2333 // If we can represent this as a simple value, we have to build the actual
2334 // value to store, which requires expanding the byte present in memset to
2335 // a sensible representation for the alloca type. This is essentially
2336 // splatting the byte to a sufficiently wide integer, splatting it across
2337 // any desired vector width, and bitcasting to the final type.
2341 // If this is a memset of a vectorized alloca, insert it.
2342 assert(ElementTy == ScalarTy);
2344 unsigned BeginIndex = getIndex(NewBeginOffset);
2345 unsigned EndIndex = getIndex(NewEndOffset);
2346 assert(EndIndex > BeginIndex && "Empty vector!");
2347 unsigned NumElements = EndIndex - BeginIndex;
2348 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2351 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2352 Splat = convertValue(DL, IRB, Splat, ElementTy);
2353 if (NumElements > 1)
2354 Splat = getVectorSplat(Splat, NumElements);
2356 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2358 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2360 // If this is a memset on an alloca where we can widen stores, insert the
2362 assert(!II.isVolatile());
2364 uint64_t Size = NewEndOffset - NewBeginOffset;
2365 V = getIntegerSplat(II.getValue(), Size);
2367 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2368 EndOffset != NewAllocaBeginOffset)) {
2369 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2371 Old = convertValue(DL, IRB, Old, IntTy);
2372 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2373 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2375 assert(V->getType() == IntTy &&
2376 "Wrong type for an alloca wide integer!");
2378 V = convertValue(DL, IRB, V, AllocaTy);
2380 // Established these invariants above.
2381 assert(NewBeginOffset == NewAllocaBeginOffset);
2382 assert(NewEndOffset == NewAllocaEndOffset);
2384 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2385 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2386 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2388 V = convertValue(DL, IRB, V, AllocaTy);
2391 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2394 DEBUG(dbgs() << " to: " << *New << "\n");
2395 return !II.isVolatile();
2398 bool visitMemTransferInst(MemTransferInst &II) {
2399 // Rewriting of memory transfer instructions can be a bit tricky. We break
2400 // them into two categories: split intrinsics and unsplit intrinsics.
2402 DEBUG(dbgs() << " original: " << II << "\n");
2404 // Compute the intersecting offset range.
2405 assert(BeginOffset < NewAllocaEndOffset);
2406 assert(EndOffset > NewAllocaBeginOffset);
2407 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2408 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2410 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2411 bool IsDest = II.getRawDest() == OldPtr;
2413 // Compute the relative offset within the transfer.
2414 unsigned IntPtrWidth = DL.getPointerSizeInBits();
2415 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2417 unsigned Align = II.getAlignment();
2418 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2421 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2422 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
2424 // For unsplit intrinsics, we simply modify the source and destination
2425 // pointers in place. This isn't just an optimization, it is a matter of
2426 // correctness. With unsplit intrinsics we may be dealing with transfers
2427 // within a single alloca before SROA ran, or with transfers that have
2428 // a variable length. We may also be dealing with memmove instead of
2429 // memcpy, and so simply updating the pointers is the necessary for us to
2430 // update both source and dest of a single call.
2431 if (!IsSplittable) {
2432 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2435 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2437 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2438 II.getRawSource()->getType()));
2440 Type *CstTy = II.getAlignmentCst()->getType();
2441 II.setAlignment(ConstantInt::get(CstTy, Align));
2443 DEBUG(dbgs() << " to: " << II << "\n");
2444 deleteIfTriviallyDead(OldOp);
2447 // For split transfer intrinsics we have an incredibly useful assurance:
2448 // the source and destination do not reside within the same alloca, and at
2449 // least one of them does not escape. This means that we can replace
2450 // memmove with memcpy, and we don't need to worry about all manner of
2451 // downsides to splitting and transforming the operations.
2453 // If this doesn't map cleanly onto the alloca type, and that type isn't
2454 // a single value type, just emit a memcpy.
2456 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2457 EndOffset < NewAllocaEndOffset ||
2458 !NewAI.getAllocatedType()->isSingleValueType());
2460 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2461 // size hasn't been shrunk based on analysis of the viable range, this is
2463 if (EmitMemCpy && &OldAI == &NewAI) {
2464 // Ensure the start lines up.
2465 assert(NewBeginOffset == BeginOffset);
2467 // Rewrite the size as needed.
2468 if (NewEndOffset != EndOffset)
2469 II.setLength(ConstantInt::get(II.getLength()->getType(),
2470 NewEndOffset - NewBeginOffset));
2473 // Record this instruction for deletion.
2474 Pass.DeadInsts.insert(&II);
2476 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2477 // alloca that should be re-examined after rewriting this instruction.
2478 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2480 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2481 Pass.Worklist.insert(AI);
2484 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2485 : II.getRawDest()->getType();
2487 // Compute the other pointer, folding as much as possible to produce
2488 // a single, simple GEP in most cases.
2489 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2491 Value *OurPtr = getAdjustedAllocaPtr(
2492 IRB, NewBeginOffset,
2493 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
2494 Type *SizeTy = II.getLength()->getType();
2495 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2497 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2498 IsDest ? OtherPtr : OurPtr,
2499 Size, Align, II.isVolatile());
2501 DEBUG(dbgs() << " to: " << *New << "\n");
2505 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2506 // is equivalent to 1, but that isn't true if we end up rewriting this as
2511 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2512 NewEndOffset == NewAllocaEndOffset;
2513 uint64_t Size = NewEndOffset - NewBeginOffset;
2514 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2515 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2516 unsigned NumElements = EndIndex - BeginIndex;
2517 IntegerType *SubIntTy
2518 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2520 Type *OtherPtrTy = NewAI.getType();
2521 if (VecTy && !IsWholeAlloca) {
2522 if (NumElements == 1)
2523 OtherPtrTy = VecTy->getElementType();
2525 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2527 OtherPtrTy = OtherPtrTy->getPointerTo();
2528 } else if (IntTy && !IsWholeAlloca) {
2529 OtherPtrTy = SubIntTy->getPointerTo();
2532 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2533 Value *DstPtr = &NewAI;
2535 std::swap(SrcPtr, DstPtr);
2538 if (VecTy && !IsWholeAlloca && !IsDest) {
2539 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2541 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2542 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2543 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2545 Src = convertValue(DL, IRB, Src, IntTy);
2546 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2547 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2549 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2553 if (VecTy && !IsWholeAlloca && IsDest) {
2554 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2556 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2557 } else if (IntTy && !IsWholeAlloca && IsDest) {
2558 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2560 Old = convertValue(DL, IRB, Old, IntTy);
2561 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2562 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2563 Src = convertValue(DL, IRB, Src, NewAllocaTy);
2566 StoreInst *Store = cast<StoreInst>(
2567 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2569 DEBUG(dbgs() << " to: " << *Store << "\n");
2570 return !II.isVolatile();
2573 bool visitIntrinsicInst(IntrinsicInst &II) {
2574 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2575 II.getIntrinsicID() == Intrinsic::lifetime_end);
2576 DEBUG(dbgs() << " original: " << II << "\n");
2577 assert(II.getArgOperand(1) == OldPtr);
2579 // Compute the intersecting offset range.
2580 assert(BeginOffset < NewAllocaEndOffset);
2581 assert(EndOffset > NewAllocaBeginOffset);
2582 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2583 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2585 // Record this instruction for deletion.
2586 Pass.DeadInsts.insert(&II);
2589 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2590 NewEndOffset - NewBeginOffset);
2592 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
2594 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2595 New = IRB.CreateLifetimeStart(Ptr, Size);
2597 New = IRB.CreateLifetimeEnd(Ptr, Size);
2600 DEBUG(dbgs() << " to: " << *New << "\n");
2604 bool visitPHINode(PHINode &PN) {
2605 DEBUG(dbgs() << " original: " << PN << "\n");
2606 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2607 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2609 // We would like to compute a new pointer in only one place, but have it be
2610 // as local as possible to the PHI. To do that, we re-use the location of
2611 // the old pointer, which necessarily must be in the right position to
2612 // dominate the PHI.
2613 IRBuilderTy PtrBuilder(OldPtr);
2614 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2618 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
2619 // Replace the operands which were using the old pointer.
2620 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2622 DEBUG(dbgs() << " to: " << PN << "\n");
2623 deleteIfTriviallyDead(OldPtr);
2625 // Check whether we can speculate this PHI node, and if so remember that
2626 // fact and queue it up for another iteration after the speculation
2628 if (isSafePHIToSpeculate(PN, &DL)) {
2629 Pass.SpeculatablePHIs.insert(&PN);
2630 IsUsedByRewrittenSpeculatableInstructions = true;
2634 return false; // PHIs can't be promoted on their own.
2637 bool visitSelectInst(SelectInst &SI) {
2638 DEBUG(dbgs() << " original: " << SI << "\n");
2639 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2640 "Pointer isn't an operand!");
2641 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2642 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2644 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
2645 // Replace the operands which were using the old pointer.
2646 if (SI.getOperand(1) == OldPtr)
2647 SI.setOperand(1, NewPtr);
2648 if (SI.getOperand(2) == OldPtr)
2649 SI.setOperand(2, NewPtr);
2651 DEBUG(dbgs() << " to: " << SI << "\n");
2652 deleteIfTriviallyDead(OldPtr);
2654 // Check whether we can speculate this select instruction, and if so
2655 // remember that fact and queue it up for another iteration after the
2656 // speculation occurs.
2657 if (isSafeSelectToSpeculate(SI, &DL)) {
2658 Pass.SpeculatableSelects.insert(&SI);
2659 IsUsedByRewrittenSpeculatableInstructions = true;
2663 return false; // Selects can't be promoted on their own.
2670 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2672 /// This pass aggressively rewrites all aggregate loads and stores on
2673 /// a particular pointer (or any pointer derived from it which we can identify)
2674 /// with scalar loads and stores.
2675 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2676 // Befriend the base class so it can delegate to private visit methods.
2677 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2679 const DataLayout &DL;
2681 /// Queue of pointer uses to analyze and potentially rewrite.
2682 SmallVector<Use *, 8> Queue;
2684 /// Set to prevent us from cycling with phi nodes and loops.
2685 SmallPtrSet<User *, 8> Visited;
2687 /// The current pointer use being rewritten. This is used to dig up the used
2688 /// value (as opposed to the user).
2692 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2694 /// Rewrite loads and stores through a pointer and all pointers derived from
2696 bool rewrite(Instruction &I) {
2697 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2699 bool Changed = false;
2700 while (!Queue.empty()) {
2701 U = Queue.pop_back_val();
2702 Changed |= visit(cast<Instruction>(U->getUser()));
2708 /// Enqueue all the users of the given instruction for further processing.
2709 /// This uses a set to de-duplicate users.
2710 void enqueueUsers(Instruction &I) {
2711 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2713 if (Visited.insert(*UI))
2714 Queue.push_back(&UI.getUse());
2717 // Conservative default is to not rewrite anything.
2718 bool visitInstruction(Instruction &I) { return false; }
2720 /// \brief Generic recursive split emission class.
2721 template <typename Derived>
2724 /// The builder used to form new instructions.
2726 /// The indices which to be used with insert- or extractvalue to select the
2727 /// appropriate value within the aggregate.
2728 SmallVector<unsigned, 4> Indices;
2729 /// The indices to a GEP instruction which will move Ptr to the correct slot
2730 /// within the aggregate.
2731 SmallVector<Value *, 4> GEPIndices;
2732 /// The base pointer of the original op, used as a base for GEPing the
2733 /// split operations.
2736 /// Initialize the splitter with an insertion point, Ptr and start with a
2737 /// single zero GEP index.
2738 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2739 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2742 /// \brief Generic recursive split emission routine.
2744 /// This method recursively splits an aggregate op (load or store) into
2745 /// scalar or vector ops. It splits recursively until it hits a single value
2746 /// and emits that single value operation via the template argument.
2748 /// The logic of this routine relies on GEPs and insertvalue and
2749 /// extractvalue all operating with the same fundamental index list, merely
2750 /// formatted differently (GEPs need actual values).
2752 /// \param Ty The type being split recursively into smaller ops.
2753 /// \param Agg The aggregate value being built up or stored, depending on
2754 /// whether this is splitting a load or a store respectively.
2755 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2756 if (Ty->isSingleValueType())
2757 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2759 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2760 unsigned OldSize = Indices.size();
2762 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2764 assert(Indices.size() == OldSize && "Did not return to the old size");
2765 Indices.push_back(Idx);
2766 GEPIndices.push_back(IRB.getInt32(Idx));
2767 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2768 GEPIndices.pop_back();
2774 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2775 unsigned OldSize = Indices.size();
2777 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2779 assert(Indices.size() == OldSize && "Did not return to the old size");
2780 Indices.push_back(Idx);
2781 GEPIndices.push_back(IRB.getInt32(Idx));
2782 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2783 GEPIndices.pop_back();
2789 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2793 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2794 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2795 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2797 /// Emit a leaf load of a single value. This is called at the leaves of the
2798 /// recursive emission to actually load values.
2799 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2800 assert(Ty->isSingleValueType());
2801 // Load the single value and insert it using the indices.
2802 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2803 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2804 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2805 DEBUG(dbgs() << " to: " << *Load << "\n");
2809 bool visitLoadInst(LoadInst &LI) {
2810 assert(LI.getPointerOperand() == *U);
2811 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2814 // We have an aggregate being loaded, split it apart.
2815 DEBUG(dbgs() << " original: " << LI << "\n");
2816 LoadOpSplitter Splitter(&LI, *U);
2817 Value *V = UndefValue::get(LI.getType());
2818 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2819 LI.replaceAllUsesWith(V);
2820 LI.eraseFromParent();
2824 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2825 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2826 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2828 /// Emit a leaf store of a single value. This is called at the leaves of the
2829 /// recursive emission to actually produce stores.
2830 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2831 assert(Ty->isSingleValueType());
2832 // Extract the single value and store it using the indices.
2833 Value *Store = IRB.CreateStore(
2834 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2835 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2837 DEBUG(dbgs() << " to: " << *Store << "\n");
2841 bool visitStoreInst(StoreInst &SI) {
2842 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2844 Value *V = SI.getValueOperand();
2845 if (V->getType()->isSingleValueType())
2848 // We have an aggregate being stored, split it apart.
2849 DEBUG(dbgs() << " original: " << SI << "\n");
2850 StoreOpSplitter Splitter(&SI, *U);
2851 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2852 SI.eraseFromParent();
2856 bool visitBitCastInst(BitCastInst &BC) {
2861 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2866 bool visitPHINode(PHINode &PN) {
2871 bool visitSelectInst(SelectInst &SI) {
2878 /// \brief Strip aggregate type wrapping.
2880 /// This removes no-op aggregate types wrapping an underlying type. It will
2881 /// strip as many layers of types as it can without changing either the type
2882 /// size or the allocated size.
2883 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2884 if (Ty->isSingleValueType())
2887 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2888 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2891 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2892 InnerTy = ArrTy->getElementType();
2893 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2894 const StructLayout *SL = DL.getStructLayout(STy);
2895 unsigned Index = SL->getElementContainingOffset(0);
2896 InnerTy = STy->getElementType(Index);
2901 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2902 TypeSize > DL.getTypeSizeInBits(InnerTy))
2905 return stripAggregateTypeWrapping(DL, InnerTy);
2908 /// \brief Try to find a partition of the aggregate type passed in for a given
2909 /// offset and size.
2911 /// This recurses through the aggregate type and tries to compute a subtype
2912 /// based on the offset and size. When the offset and size span a sub-section
2913 /// of an array, it will even compute a new array type for that sub-section,
2914 /// and the same for structs.
2916 /// Note that this routine is very strict and tries to find a partition of the
2917 /// type which produces the *exact* right offset and size. It is not forgiving
2918 /// when the size or offset cause either end of type-based partition to be off.
2919 /// Also, this is a best-effort routine. It is reasonable to give up and not
2920 /// return a type if necessary.
2921 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
2922 uint64_t Offset, uint64_t Size) {
2923 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2924 return stripAggregateTypeWrapping(DL, Ty);
2925 if (Offset > DL.getTypeAllocSize(Ty) ||
2926 (DL.getTypeAllocSize(Ty) - Offset) < Size)
2929 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2930 // We can't partition pointers...
2931 if (SeqTy->isPointerTy())
2934 Type *ElementTy = SeqTy->getElementType();
2935 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2936 uint64_t NumSkippedElements = Offset / ElementSize;
2937 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
2938 if (NumSkippedElements >= ArrTy->getNumElements())
2940 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
2941 if (NumSkippedElements >= VecTy->getNumElements())
2944 Offset -= NumSkippedElements * ElementSize;
2946 // First check if we need to recurse.
2947 if (Offset > 0 || Size < ElementSize) {
2948 // Bail if the partition ends in a different array element.
2949 if ((Offset + Size) > ElementSize)
2951 // Recurse through the element type trying to peel off offset bytes.
2952 return getTypePartition(DL, ElementTy, Offset, Size);
2954 assert(Offset == 0);
2956 if (Size == ElementSize)
2957 return stripAggregateTypeWrapping(DL, ElementTy);
2958 assert(Size > ElementSize);
2959 uint64_t NumElements = Size / ElementSize;
2960 if (NumElements * ElementSize != Size)
2962 return ArrayType::get(ElementTy, NumElements);
2965 StructType *STy = dyn_cast<StructType>(Ty);
2969 const StructLayout *SL = DL.getStructLayout(STy);
2970 if (Offset >= SL->getSizeInBytes())
2972 uint64_t EndOffset = Offset + Size;
2973 if (EndOffset > SL->getSizeInBytes())
2976 unsigned Index = SL->getElementContainingOffset(Offset);
2977 Offset -= SL->getElementOffset(Index);
2979 Type *ElementTy = STy->getElementType(Index);
2980 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2981 if (Offset >= ElementSize)
2982 return 0; // The offset points into alignment padding.
2984 // See if any partition must be contained by the element.
2985 if (Offset > 0 || Size < ElementSize) {
2986 if ((Offset + Size) > ElementSize)
2988 return getTypePartition(DL, ElementTy, Offset, Size);
2990 assert(Offset == 0);
2992 if (Size == ElementSize)
2993 return stripAggregateTypeWrapping(DL, ElementTy);
2995 StructType::element_iterator EI = STy->element_begin() + Index,
2996 EE = STy->element_end();
2997 if (EndOffset < SL->getSizeInBytes()) {
2998 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2999 if (Index == EndIndex)
3000 return 0; // Within a single element and its padding.
3002 // Don't try to form "natural" types if the elements don't line up with the
3004 // FIXME: We could potentially recurse down through the last element in the
3005 // sub-struct to find a natural end point.
3006 if (SL->getElementOffset(EndIndex) != EndOffset)
3009 assert(Index < EndIndex);
3010 EE = STy->element_begin() + EndIndex;
3013 // Try to build up a sub-structure.
3014 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3016 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3017 if (Size != SubSL->getSizeInBytes())
3018 return 0; // The sub-struct doesn't have quite the size needed.
3023 /// \brief Rewrite an alloca partition's users.
3025 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3026 /// to rewrite uses of an alloca partition to be conducive for SSA value
3027 /// promotion. If the partition needs a new, more refined alloca, this will
3028 /// build that new alloca, preserving as much type information as possible, and
3029 /// rewrite the uses of the old alloca to point at the new one and have the
3030 /// appropriate new offsets. It also evaluates how successful the rewrite was
3031 /// at enabling promotion and if it was successful queues the alloca to be
3033 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3034 AllocaSlices::iterator B, AllocaSlices::iterator E,
3035 int64_t BeginOffset, int64_t EndOffset,
3036 ArrayRef<AllocaSlices::iterator> SplitUses) {
3037 assert(BeginOffset < EndOffset);
3038 uint64_t SliceSize = EndOffset - BeginOffset;
3040 // Try to compute a friendly type for this partition of the alloca. This
3041 // won't always succeed, in which case we fall back to a legal integer type
3042 // or an i8 array of an appropriate size.
3044 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3045 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3046 SliceTy = CommonUseTy;
3048 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3049 BeginOffset, SliceSize))
3050 SliceTy = TypePartitionTy;
3051 if ((!SliceTy || (SliceTy->isArrayTy() &&
3052 SliceTy->getArrayElementType()->isIntegerTy())) &&
3053 DL->isLegalInteger(SliceSize * 8))
3054 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3056 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3057 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3059 bool IsVectorPromotable = isVectorPromotionViable(
3060 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
3062 bool IsIntegerPromotable =
3063 !IsVectorPromotable &&
3064 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
3066 // Check for the case where we're going to rewrite to a new alloca of the
3067 // exact same type as the original, and with the same access offsets. In that
3068 // case, re-use the existing alloca, but still run through the rewriter to
3069 // perform phi and select speculation.
3071 if (SliceTy == AI.getAllocatedType()) {
3072 assert(BeginOffset == 0 &&
3073 "Non-zero begin offset but same alloca type");
3075 // FIXME: We should be able to bail at this point with "nothing changed".
3076 // FIXME: We might want to defer PHI speculation until after here.
3078 unsigned Alignment = AI.getAlignment();
3080 // The minimum alignment which users can rely on when the explicit
3081 // alignment is omitted or zero is that required by the ABI for this
3083 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3085 Alignment = MinAlign(Alignment, BeginOffset);
3086 // If we will get at least this much alignment from the type alone, leave
3087 // the alloca's alignment unconstrained.
3088 if (Alignment <= DL->getABITypeAlignment(SliceTy))
3090 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3091 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
3095 DEBUG(dbgs() << "Rewriting alloca partition "
3096 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3099 // Track the high watermark on several worklists that are only relevant for
3100 // promoted allocas. We will reset it to this point if the alloca is not in
3101 // fact scheduled for promotion.
3102 unsigned PPWOldSize = PostPromotionWorklist.size();
3103 unsigned SPOldSize = SpeculatablePHIs.size();
3104 unsigned SSOldSize = SpeculatableSelects.size();
3105 unsigned NumUses = 0;
3107 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3108 EndOffset, IsVectorPromotable,
3109 IsIntegerPromotable);
3110 bool Promotable = true;
3111 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3112 SUE = SplitUses.end();
3113 SUI != SUE; ++SUI) {
3114 DEBUG(dbgs() << " rewriting split ");
3115 DEBUG(S.printSlice(dbgs(), *SUI, ""));
3116 Promotable &= Rewriter.visit(*SUI);
3119 for (AllocaSlices::iterator I = B; I != E; ++I) {
3120 DEBUG(dbgs() << " rewriting ");
3121 DEBUG(S.printSlice(dbgs(), I, ""));
3122 Promotable &= Rewriter.visit(I);
3126 NumAllocaPartitionUses += NumUses;
3127 MaxUsesPerAllocaPartition =
3128 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3130 if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
3131 DEBUG(dbgs() << " and queuing for promotion\n");
3132 PromotableAllocas.push_back(NewAI);
3133 } else if (NewAI != &AI ||
3135 Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
3136 // If we can't promote the alloca, iterate on it to check for new
3137 // refinements exposed by splitting the current alloca. Don't iterate on an
3138 // alloca which didn't actually change and didn't get promoted.
3140 // Alternatively, if we could promote the alloca but have speculatable
3141 // instructions then we will speculate them after finishing our processing
3142 // of the original alloca. Mark the new one for re-visiting in the next
3143 // iteration so the speculated operations can be rewritten.
3145 // FIXME: We should actually track whether the rewriter changed anything.
3146 Worklist.insert(NewAI);
3149 // Drop any post-promotion work items if promotion didn't happen.
3151 while (PostPromotionWorklist.size() > PPWOldSize)
3152 PostPromotionWorklist.pop_back();
3153 while (SpeculatablePHIs.size() > SPOldSize)
3154 SpeculatablePHIs.pop_back();
3155 while (SpeculatableSelects.size() > SSOldSize)
3156 SpeculatableSelects.pop_back();
3163 struct IsSliceEndLessOrEqualTo {
3164 uint64_t UpperBound;
3166 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
3168 bool operator()(const AllocaSlices::iterator &I) {
3169 return I->endOffset() <= UpperBound;
3175 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3176 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3177 if (Offset >= MaxSplitUseEndOffset) {
3179 MaxSplitUseEndOffset = 0;
3183 size_t SplitUsesOldSize = SplitUses.size();
3184 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3185 IsSliceEndLessOrEqualTo(Offset)),
3187 if (SplitUsesOldSize == SplitUses.size())
3190 // Recompute the max. While this is linear, so is remove_if.
3191 MaxSplitUseEndOffset = 0;
3192 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
3193 SUI = SplitUses.begin(),
3194 SUE = SplitUses.end();
3196 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3199 /// \brief Walks the slices of an alloca and form partitions based on them,
3200 /// rewriting each of their uses.
3201 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3202 if (S.begin() == S.end())
3205 unsigned NumPartitions = 0;
3206 bool Changed = false;
3207 SmallVector<AllocaSlices::iterator, 4> SplitUses;
3208 uint64_t MaxSplitUseEndOffset = 0;
3210 uint64_t BeginOffset = S.begin()->beginOffset();
3212 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3213 SI != SE; SI = SJ) {
3214 uint64_t MaxEndOffset = SI->endOffset();
3216 if (!SI->isSplittable()) {
3217 // When we're forming an unsplittable region, it must always start at the
3218 // first slice and will extend through its end.
3219 assert(BeginOffset == SI->beginOffset());
3221 // Form a partition including all of the overlapping slices with this
3222 // unsplittable slice.
3223 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3224 if (!SJ->isSplittable())
3225 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3229 assert(SI->isSplittable()); // Established above.
3231 // Collect all of the overlapping splittable slices.
3232 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3233 SJ->isSplittable()) {
3234 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3238 // Back up MaxEndOffset and SJ if we ended the span early when
3239 // encountering an unsplittable slice.
3240 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3241 assert(!SJ->isSplittable());
3242 MaxEndOffset = SJ->beginOffset();
3246 // Check if we have managed to move the end offset forward yet. If so,
3247 // we'll have to rewrite uses and erase old split uses.
3248 if (BeginOffset < MaxEndOffset) {
3249 // Rewrite a sequence of overlapping slices.
3251 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
3254 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3257 // Accumulate all the splittable slices from the [SI,SJ) region which
3258 // overlap going forward.
3259 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3260 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3261 SplitUses.push_back(SK);
3262 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3265 // If we're already at the end and we have no split uses, we're done.
3266 if (SJ == SE && SplitUses.empty())
3269 // If we have no split uses or no gap in offsets, we're ready to move to
3271 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3272 BeginOffset = SJ->beginOffset();
3276 // Even if we have split slices, if the next slice is splittable and the
3277 // split slices reach it, we can simply set up the beginning offset of the
3278 // next iteration to bridge between them.
3279 if (SJ != SE && SJ->isSplittable() &&
3280 MaxSplitUseEndOffset > SJ->beginOffset()) {
3281 BeginOffset = MaxEndOffset;
3285 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3287 uint64_t PostSplitEndOffset =
3288 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3290 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3295 break; // Skip the rest, we don't need to do any cleanup.
3297 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3298 PostSplitEndOffset);
3300 // Now just reset the begin offset for the next iteration.
3301 BeginOffset = SJ->beginOffset();
3304 NumAllocaPartitions += NumPartitions;
3305 MaxPartitionsPerAlloca =
3306 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3311 /// \brief Analyze an alloca for SROA.
3313 /// This analyzes the alloca to ensure we can reason about it, builds
3314 /// the slices of the alloca, and then hands it off to be split and
3315 /// rewritten as needed.
3316 bool SROA::runOnAlloca(AllocaInst &AI) {
3317 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3318 ++NumAllocasAnalyzed;
3320 // Special case dead allocas, as they're trivial.
3321 if (AI.use_empty()) {
3322 AI.eraseFromParent();
3326 // Skip alloca forms that this analysis can't handle.
3327 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3328 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3331 bool Changed = false;
3333 // First, split any FCA loads and stores touching this alloca to promote
3334 // better splitting and promotion opportunities.
3335 AggLoadStoreRewriter AggRewriter(*DL);
3336 Changed |= AggRewriter.rewrite(AI);
3338 // Build the slices using a recursive instruction-visiting builder.
3339 AllocaSlices S(*DL, AI);
3340 DEBUG(S.print(dbgs()));
3344 // Delete all the dead users of this alloca before splitting and rewriting it.
3345 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3346 DE = S.dead_user_end();
3349 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3350 DeadInsts.insert(*DI);
3352 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3353 DE = S.dead_op_end();
3356 // Clobber the use with an undef value.
3357 **DO = UndefValue::get(OldV->getType());
3358 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3359 if (isInstructionTriviallyDead(OldI)) {
3361 DeadInsts.insert(OldI);
3365 // No slices to split. Leave the dead alloca for a later pass to clean up.
3366 if (S.begin() == S.end())
3369 // Trivially promotable, don't go through the splitting and rewriting.
3370 if (S.isAllocaPromotable()) {
3371 DEBUG(dbgs() << " Directly promoting alloca: " << AI << "\n");
3372 PromotableAllocas.push_back(&AI);
3374 // Walk through the stored values quickly here to handle directly
3375 // promotable allocas that require iterating on other allocas.
3376 ArrayRef<Value *> StoredValues = S.getStoredValues();
3377 for (ArrayRef<Value *>::iterator SVI = StoredValues.begin(),
3378 SVE = StoredValues.end();
3380 if ((*SVI)->getType()->isPointerTy())
3381 if (AllocaInst *SAI =
3382 dyn_cast<AllocaInst>((*SVI)->stripInBoundsOffsets()))
3383 PostPromotionWorklist.insert(SAI);
3387 Changed |= splitAlloca(AI, S);
3389 DEBUG(dbgs() << " Speculating PHIs\n");
3390 while (!SpeculatablePHIs.empty())
3391 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3393 DEBUG(dbgs() << " Speculating Selects\n");
3394 while (!SpeculatableSelects.empty())
3395 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3400 /// \brief Delete the dead instructions accumulated in this run.
3402 /// Recursively deletes the dead instructions we've accumulated. This is done
3403 /// at the very end to maximize locality of the recursive delete and to
3404 /// minimize the problems of invalidated instruction pointers as such pointers
3405 /// are used heavily in the intermediate stages of the algorithm.
3407 /// We also record the alloca instructions deleted here so that they aren't
3408 /// subsequently handed to mem2reg to promote.
3409 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3410 while (!DeadInsts.empty()) {
3411 Instruction *I = DeadInsts.pop_back_val();
3412 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3414 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3416 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3417 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3418 // Zero out the operand and see if it becomes trivially dead.
3420 if (isInstructionTriviallyDead(U))
3421 DeadInsts.insert(U);
3424 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3425 DeletedAllocas.insert(AI);
3428 I->eraseFromParent();
3432 /// \brief Promote the allocas, using the best available technique.
3434 /// This attempts to promote whatever allocas have been identified as viable in
3435 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3436 /// If there is a domtree available, we attempt to promote using the full power
3437 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3438 /// based on the SSAUpdater utilities. This function returns whether any
3439 /// promotion occurred.
3440 bool SROA::promoteAllocas(Function &F) {
3441 if (PromotableAllocas.empty())
3444 NumPromoted += PromotableAllocas.size();
3446 if (DT && !ForceSSAUpdater) {
3447 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3448 PromoteMemToReg(PromotableAllocas, *DT, DL);
3449 PromotableAllocas.clear();
3453 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3455 DIBuilder DIB(*F.getParent());
3456 SmallVector<Instruction*, 64> Insts;
3458 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3459 AllocaInst *AI = PromotableAllocas[Idx];
3460 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3462 Instruction *I = cast<Instruction>(*UI++);
3463 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3464 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3465 // leading to them) here. Eventually it should use them to optimize the
3466 // scalar values produced.
3467 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3468 assert(onlyUsedByLifetimeMarkers(I) &&
3469 "Found a bitcast used outside of a lifetime marker.");
3470 while (!I->use_empty())
3471 cast<Instruction>(*I->use_begin())->eraseFromParent();
3472 I->eraseFromParent();
3475 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3476 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3477 II->getIntrinsicID() == Intrinsic::lifetime_end);
3478 II->eraseFromParent();
3484 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3488 PromotableAllocas.clear();
3493 /// \brief A predicate to test whether an alloca belongs to a set.
3494 class IsAllocaInSet {
3495 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3499 typedef AllocaInst *argument_type;
3501 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3502 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3506 bool SROA::runOnFunction(Function &F) {
3507 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3508 C = &F.getContext();
3509 DL = getAnalysisIfAvailable<DataLayout>();
3511 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3514 DT = getAnalysisIfAvailable<DominatorTree>();
3516 BasicBlock &EntryBB = F.getEntryBlock();
3517 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3519 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3520 Worklist.insert(AI);
3522 bool Changed = false;
3523 // A set of deleted alloca instruction pointers which should be removed from
3524 // the list of promotable allocas.
3525 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3528 while (!Worklist.empty()) {
3529 Changed |= runOnAlloca(*Worklist.pop_back_val());
3530 deleteDeadInstructions(DeletedAllocas);
3532 // Remove the deleted allocas from various lists so that we don't try to
3533 // continue processing them.
3534 if (!DeletedAllocas.empty()) {
3535 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3536 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3537 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3538 PromotableAllocas.end(),
3539 IsAllocaInSet(DeletedAllocas)),
3540 PromotableAllocas.end());
3541 DeletedAllocas.clear();
3545 Changed |= promoteAllocas(F);
3547 Worklist = PostPromotionWorklist;
3548 PostPromotionWorklist.clear();
3549 } while (!Worklist.empty());
3554 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3555 if (RequiresDomTree)
3556 AU.addRequired<DominatorTree>();
3557 AU.setPreservesCFG();