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 // Retain the debug information attached to the alloca for use when
793 // rewriting loads and stores.
794 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
795 for (Value::use_iterator UI = DebugNode->use_begin(),
796 UE = DebugNode->use_end();
798 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
800 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
804 LoadAndStorePromoter::run(Insts);
806 // While we have the debug information, clear it off of the alloca. The
807 // caller takes care of deleting the alloca.
808 while (!DDIs.empty())
809 DDIs.pop_back_val()->eraseFromParent();
810 while (!DVIs.empty())
811 DVIs.pop_back_val()->eraseFromParent();
814 virtual bool isInstInList(Instruction *I,
815 const SmallVectorImpl<Instruction*> &Insts) const {
817 if (LoadInst *LI = dyn_cast<LoadInst>(I))
818 Ptr = LI->getOperand(0);
820 Ptr = cast<StoreInst>(I)->getPointerOperand();
822 // Only used to detect cycles, which will be rare and quickly found as
823 // we're walking up a chain of defs rather than down through uses.
824 SmallPtrSet<Value *, 4> Visited;
830 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
831 Ptr = BCI->getOperand(0);
832 else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
833 Ptr = GEPI->getPointerOperand();
837 } while (Visited.insert(Ptr));
842 virtual void updateDebugInfo(Instruction *Inst) const {
843 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
844 E = DDIs.end(); I != E; ++I) {
845 DbgDeclareInst *DDI = *I;
846 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
847 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
848 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
849 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
851 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
852 E = DVIs.end(); I != E; ++I) {
853 DbgValueInst *DVI = *I;
855 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
856 // If an argument is zero extended then use argument directly. The ZExt
857 // may be zapped by an optimization pass in future.
858 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
859 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
860 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
861 Arg = dyn_cast<Argument>(SExt->getOperand(0));
863 Arg = SI->getValueOperand();
864 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
865 Arg = LI->getPointerOperand();
869 Instruction *DbgVal =
870 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
872 DbgVal->setDebugLoc(DVI->getDebugLoc());
876 } // end anon namespace
880 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
882 /// This pass takes allocations which can be completely analyzed (that is, they
883 /// don't escape) and tries to turn them into scalar SSA values. There are
884 /// a few steps to this process.
886 /// 1) It takes allocations of aggregates and analyzes the ways in which they
887 /// are used to try to split them into smaller allocations, ideally of
888 /// a single scalar data type. It will split up memcpy and memset accesses
889 /// as necessary and try to isolate individual scalar accesses.
890 /// 2) It will transform accesses into forms which are suitable for SSA value
891 /// promotion. This can be replacing a memset with a scalar store of an
892 /// integer value, or it can involve speculating operations on a PHI or
893 /// select to be a PHI or select of the results.
894 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
895 /// onto insert and extract operations on a vector value, and convert them to
896 /// this form. By doing so, it will enable promotion of vector aggregates to
897 /// SSA vector values.
898 class SROA : public FunctionPass {
899 const bool RequiresDomTree;
902 const DataLayout *DL;
905 /// \brief Worklist of alloca instructions to simplify.
907 /// Each alloca in the function is added to this. Each new alloca formed gets
908 /// added to it as well to recursively simplify unless that alloca can be
909 /// directly promoted. Finally, each time we rewrite a use of an alloca other
910 /// the one being actively rewritten, we add it back onto the list if not
911 /// already present to ensure it is re-visited.
912 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
914 /// \brief A collection of instructions to delete.
915 /// We try to batch deletions to simplify code and make things a bit more
917 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
919 /// \brief Post-promotion worklist.
921 /// Sometimes we discover an alloca which has a high probability of becoming
922 /// viable for SROA after a round of promotion takes place. In those cases,
923 /// the alloca is enqueued here for re-processing.
925 /// Note that we have to be very careful to clear allocas out of this list in
926 /// the event they are deleted.
927 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
929 /// \brief A collection of alloca instructions we can directly promote.
930 std::vector<AllocaInst *> PromotableAllocas;
932 /// \brief A worklist of PHIs to speculate prior to promoting allocas.
934 /// All of these PHIs have been checked for the safety of speculation and by
935 /// being speculated will allow promoting allocas currently in the promotable
937 SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
939 /// \brief A worklist of select instructions to speculate prior to promoting
942 /// All of these select instructions have been checked for the safety of
943 /// speculation and by being speculated will allow promoting allocas
944 /// currently in the promotable queue.
945 SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
948 SROA(bool RequiresDomTree = true)
949 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
951 initializeSROAPass(*PassRegistry::getPassRegistry());
953 bool runOnFunction(Function &F);
954 void getAnalysisUsage(AnalysisUsage &AU) const;
956 const char *getPassName() const { return "SROA"; }
960 friend class PHIOrSelectSpeculator;
961 friend class AllocaSliceRewriter;
963 bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
964 AllocaSlices::iterator B, AllocaSlices::iterator E,
965 int64_t BeginOffset, int64_t EndOffset,
966 ArrayRef<AllocaSlices::iterator> SplitUses);
967 bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
968 bool runOnAlloca(AllocaInst &AI);
969 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
970 bool promoteAllocas(Function &F);
976 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
977 return new SROA(RequiresDomTree);
980 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
982 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
983 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
986 /// Walk the range of a partitioning looking for a common type to cover this
987 /// sequence of slices.
988 static Type *findCommonType(AllocaSlices::const_iterator B,
989 AllocaSlices::const_iterator E,
990 uint64_t EndOffset) {
992 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
993 Use *U = I->getUse();
994 if (isa<IntrinsicInst>(*U->getUser()))
996 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1000 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
1001 UserTy = LI->getType();
1002 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
1003 UserTy = SI->getValueOperand()->getType();
1005 return 0; // Bail if we have weird uses.
1007 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1008 // If the type is larger than the partition, skip it. We only encounter
1009 // this for split integer operations where we want to use the type of the
1010 // entity causing the split.
1011 if (ITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1014 // If we have found an integer type use covering the alloca, use that
1015 // regardless of the other types, as integers are often used for a
1021 if (Ty && Ty != UserTy)
1029 /// PHI instructions that use an alloca and are subsequently loaded can be
1030 /// rewritten to load both input pointers in the pred blocks and then PHI the
1031 /// results, allowing the load of the alloca to be promoted.
1033 /// %P2 = phi [i32* %Alloca, i32* %Other]
1034 /// %V = load i32* %P2
1036 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1038 /// %V2 = load i32* %Other
1040 /// %V = phi [i32 %V1, i32 %V2]
1042 /// We can do this to a select if its only uses are loads and if the operands
1043 /// to the select can be loaded unconditionally.
1045 /// FIXME: This should be hoisted into a generic utility, likely in
1046 /// Transforms/Util/Local.h
1047 static bool isSafePHIToSpeculate(PHINode &PN,
1048 const DataLayout *DL = 0) {
1049 // For now, we can only do this promotion if the load is in the same block
1050 // as the PHI, and if there are no stores between the phi and load.
1051 // TODO: Allow recursive phi users.
1052 // TODO: Allow stores.
1053 BasicBlock *BB = PN.getParent();
1054 unsigned MaxAlign = 0;
1055 bool HaveLoad = false;
1056 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); UI != UE;
1058 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1059 if (LI == 0 || !LI->isSimple())
1062 // For now we only allow loads in the same block as the PHI. This is
1063 // a common case that happens when instcombine merges two loads through
1065 if (LI->getParent() != BB)
1068 // Ensure that there are no instructions between the PHI and the load that
1070 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1071 if (BBI->mayWriteToMemory())
1074 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1081 // We can only transform this if it is safe to push the loads into the
1082 // predecessor blocks. The only thing to watch out for is that we can't put
1083 // a possibly trapping load in the predecessor if it is a critical edge.
1084 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1085 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1086 Value *InVal = PN.getIncomingValue(Idx);
1088 // If the value is produced by the terminator of the predecessor (an
1089 // invoke) or it has side-effects, there is no valid place to put a load
1090 // in the predecessor.
1091 if (TI == InVal || TI->mayHaveSideEffects())
1094 // If the predecessor has a single successor, then the edge isn't
1096 if (TI->getNumSuccessors() == 1)
1099 // If this pointer is always safe to load, or if we can prove that there
1100 // is already a load in the block, then we can move the load to the pred
1102 if (InVal->isDereferenceablePointer() ||
1103 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1112 static void speculatePHINodeLoads(PHINode &PN) {
1113 DEBUG(dbgs() << " original: " << PN << "\n");
1115 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1116 IRBuilderTy PHIBuilder(&PN);
1117 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1118 PN.getName() + ".sroa.speculated");
1120 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1121 // matter which one we get and if any differ.
1122 LoadInst *SomeLoad = cast<LoadInst>(*PN.use_begin());
1123 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1124 unsigned Align = SomeLoad->getAlignment();
1126 // Rewrite all loads of the PN to use the new PHI.
1127 while (!PN.use_empty()) {
1128 LoadInst *LI = cast<LoadInst>(*PN.use_begin());
1129 LI->replaceAllUsesWith(NewPN);
1130 LI->eraseFromParent();
1133 // Inject loads into all of the pred blocks.
1134 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1135 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1136 TerminatorInst *TI = Pred->getTerminator();
1137 Value *InVal = PN.getIncomingValue(Idx);
1138 IRBuilderTy PredBuilder(TI);
1140 LoadInst *Load = PredBuilder.CreateLoad(
1141 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1142 ++NumLoadsSpeculated;
1143 Load->setAlignment(Align);
1145 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1146 NewPN->addIncoming(Load, Pred);
1149 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1150 PN.eraseFromParent();
1153 /// Select instructions that use an alloca and are subsequently loaded can be
1154 /// rewritten to load both input pointers and then select between the result,
1155 /// allowing the load of the alloca to be promoted.
1157 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1158 /// %V = load i32* %P2
1160 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1161 /// %V2 = load i32* %Other
1162 /// %V = select i1 %cond, i32 %V1, i32 %V2
1164 /// We can do this to a select if its only uses are loads and if the operand
1165 /// to the select can be loaded unconditionally.
1166 static bool isSafeSelectToSpeculate(SelectInst &SI, const DataLayout *DL = 0) {
1167 Value *TValue = SI.getTrueValue();
1168 Value *FValue = SI.getFalseValue();
1169 bool TDerefable = TValue->isDereferenceablePointer();
1170 bool FDerefable = FValue->isDereferenceablePointer();
1172 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); UI != UE;
1174 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1175 if (LI == 0 || !LI->isSimple())
1178 // Both operands to the select need to be dereferencable, either
1179 // absolutely (e.g. allocas) or at this point because we can see other
1182 !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1185 !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1192 static void speculateSelectInstLoads(SelectInst &SI) {
1193 DEBUG(dbgs() << " original: " << SI << "\n");
1195 IRBuilderTy IRB(&SI);
1196 Value *TV = SI.getTrueValue();
1197 Value *FV = SI.getFalseValue();
1198 // Replace the loads of the select with a select of two loads.
1199 while (!SI.use_empty()) {
1200 LoadInst *LI = cast<LoadInst>(*SI.use_begin());
1201 assert(LI->isSimple() && "We only speculate simple loads");
1203 IRB.SetInsertPoint(LI);
1205 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1207 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1208 NumLoadsSpeculated += 2;
1210 // Transfer alignment and TBAA info if present.
1211 TL->setAlignment(LI->getAlignment());
1212 FL->setAlignment(LI->getAlignment());
1213 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1214 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1215 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1218 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1219 LI->getName() + ".sroa.speculated");
1221 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1222 LI->replaceAllUsesWith(V);
1223 LI->eraseFromParent();
1225 SI.eraseFromParent();
1228 /// \brief Build a GEP out of a base pointer and indices.
1230 /// This will return the BasePtr if that is valid, or build a new GEP
1231 /// instruction using the IRBuilder if GEP-ing is needed.
1232 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1233 SmallVectorImpl<Value *> &Indices) {
1234 if (Indices.empty())
1237 // A single zero index is a no-op, so check for this and avoid building a GEP
1239 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1242 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
1245 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1246 /// TargetTy without changing the offset of the pointer.
1248 /// This routine assumes we've already established a properly offset GEP with
1249 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1250 /// zero-indices down through type layers until we find one the same as
1251 /// TargetTy. If we can't find one with the same type, we at least try to use
1252 /// one with the same size. If none of that works, we just produce the GEP as
1253 /// indicated by Indices to have the correct offset.
1254 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1255 Value *BasePtr, Type *Ty, Type *TargetTy,
1256 SmallVectorImpl<Value *> &Indices) {
1258 return buildGEP(IRB, BasePtr, Indices);
1260 // See if we can descend into a struct and locate a field with the correct
1262 unsigned NumLayers = 0;
1263 Type *ElementTy = Ty;
1265 if (ElementTy->isPointerTy())
1267 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1268 ElementTy = SeqTy->getElementType();
1269 // Note that we use the default address space as this index is over an
1270 // array or a vector, not a pointer.
1271 Indices.push_back(IRB.getInt(APInt(DL.getPointerSizeInBits(0), 0)));
1272 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1273 if (STy->element_begin() == STy->element_end())
1274 break; // Nothing left to descend into.
1275 ElementTy = *STy->element_begin();
1276 Indices.push_back(IRB.getInt32(0));
1281 } while (ElementTy != TargetTy);
1282 if (ElementTy != TargetTy)
1283 Indices.erase(Indices.end() - NumLayers, Indices.end());
1285 return buildGEP(IRB, BasePtr, Indices);
1288 /// \brief Recursively compute indices for a natural GEP.
1290 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1291 /// element types adding appropriate indices for the GEP.
1292 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1293 Value *Ptr, Type *Ty, APInt &Offset,
1295 SmallVectorImpl<Value *> &Indices) {
1297 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices);
1299 // We can't recurse through pointer types.
1300 if (Ty->isPointerTy())
1303 // We try to analyze GEPs over vectors here, but note that these GEPs are
1304 // extremely poorly defined currently. The long-term goal is to remove GEPing
1305 // over a vector from the IR completely.
1306 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1307 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1308 if (ElementSizeInBits % 8)
1309 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
1310 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1311 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1312 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1314 Offset -= NumSkippedElements * ElementSize;
1315 Indices.push_back(IRB.getInt(NumSkippedElements));
1316 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1317 Offset, TargetTy, Indices);
1320 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1321 Type *ElementTy = ArrTy->getElementType();
1322 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1323 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1324 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1327 Offset -= NumSkippedElements * ElementSize;
1328 Indices.push_back(IRB.getInt(NumSkippedElements));
1329 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1333 StructType *STy = dyn_cast<StructType>(Ty);
1337 const StructLayout *SL = DL.getStructLayout(STy);
1338 uint64_t StructOffset = Offset.getZExtValue();
1339 if (StructOffset >= SL->getSizeInBytes())
1341 unsigned Index = SL->getElementContainingOffset(StructOffset);
1342 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1343 Type *ElementTy = STy->getElementType(Index);
1344 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1345 return 0; // The offset points into alignment padding.
1347 Indices.push_back(IRB.getInt32(Index));
1348 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1352 /// \brief Get a natural GEP from a base pointer to a particular offset and
1353 /// resulting in a particular type.
1355 /// The goal is to produce a "natural" looking GEP that works with the existing
1356 /// composite types to arrive at the appropriate offset and element type for
1357 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1358 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1359 /// Indices, and setting Ty to the result subtype.
1361 /// If no natural GEP can be constructed, this function returns null.
1362 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1363 Value *Ptr, APInt Offset, Type *TargetTy,
1364 SmallVectorImpl<Value *> &Indices) {
1365 PointerType *Ty = cast<PointerType>(Ptr->getType());
1367 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1369 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1372 Type *ElementTy = Ty->getElementType();
1373 if (!ElementTy->isSized())
1374 return 0; // We can't GEP through an unsized element.
1375 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1376 if (ElementSize == 0)
1377 return 0; // Zero-length arrays can't help us build a natural GEP.
1378 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1380 Offset -= NumSkippedElements * ElementSize;
1381 Indices.push_back(IRB.getInt(NumSkippedElements));
1382 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1386 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1387 /// resulting pointer has PointerTy.
1389 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1390 /// and produces the pointer type desired. Where it cannot, it will try to use
1391 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1392 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1393 /// bitcast to the type.
1395 /// The strategy for finding the more natural GEPs is to peel off layers of the
1396 /// pointer, walking back through bit casts and GEPs, searching for a base
1397 /// pointer from which we can compute a natural GEP with the desired
1398 /// properties. The algorithm tries to fold as many constant indices into
1399 /// a single GEP as possible, thus making each GEP more independent of the
1400 /// surrounding code.
1401 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL,
1402 Value *Ptr, APInt Offset, Type *PointerTy) {
1403 // Even though we don't look through PHI nodes, we could be called on an
1404 // instruction in an unreachable block, which may be on a cycle.
1405 SmallPtrSet<Value *, 4> Visited;
1406 Visited.insert(Ptr);
1407 SmallVector<Value *, 4> Indices;
1409 // We may end up computing an offset pointer that has the wrong type. If we
1410 // never are able to compute one directly that has the correct type, we'll
1411 // fall back to it, so keep it around here.
1412 Value *OffsetPtr = 0;
1414 // Remember any i8 pointer we come across to re-use if we need to do a raw
1417 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1419 Type *TargetTy = PointerTy->getPointerElementType();
1422 // First fold any existing GEPs into the offset.
1423 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1424 APInt GEPOffset(Offset.getBitWidth(), 0);
1425 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1427 Offset += GEPOffset;
1428 Ptr = GEP->getPointerOperand();
1429 if (!Visited.insert(Ptr))
1433 // See if we can perform a natural GEP here.
1435 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1437 if (P->getType() == PointerTy) {
1438 // Zap any offset pointer that we ended up computing in previous rounds.
1439 if (OffsetPtr && OffsetPtr->use_empty())
1440 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1441 I->eraseFromParent();
1449 // Stash this pointer if we've found an i8*.
1450 if (Ptr->getType()->isIntegerTy(8)) {
1452 Int8PtrOffset = Offset;
1455 // Peel off a layer of the pointer and update the offset appropriately.
1456 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1457 Ptr = cast<Operator>(Ptr)->getOperand(0);
1458 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1459 if (GA->mayBeOverridden())
1461 Ptr = GA->getAliasee();
1465 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1466 } while (Visited.insert(Ptr));
1470 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1472 Int8PtrOffset = Offset;
1475 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1476 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1481 // On the off chance we were targeting i8*, guard the bitcast here.
1482 if (Ptr->getType() != PointerTy)
1483 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
1488 /// \brief Test whether we can convert a value from the old to the new type.
1490 /// This predicate should be used to guard calls to convertValue in order to
1491 /// ensure that we only try to convert viable values. The strategy is that we
1492 /// will peel off single element struct and array wrappings to get to an
1493 /// underlying value, and convert that value.
1494 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1497 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1498 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1499 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1501 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1503 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1506 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1507 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1509 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1517 /// \brief Generic routine to convert an SSA value to a value of a different
1520 /// This will try various different casting techniques, such as bitcasts,
1521 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1522 /// two types for viability with this routine.
1523 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1525 assert(canConvertValue(DL, V->getType(), Ty) &&
1526 "Value not convertable to type");
1527 if (V->getType() == Ty)
1529 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
1530 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
1531 if (NewITy->getBitWidth() > OldITy->getBitWidth())
1532 return IRB.CreateZExt(V, NewITy);
1533 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1534 return IRB.CreateIntToPtr(V, Ty);
1535 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1536 return IRB.CreatePtrToInt(V, Ty);
1538 return IRB.CreateBitCast(V, Ty);
1541 /// \brief Test whether the given slice use can be promoted to a vector.
1543 /// This function is called to test each entry in a partioning which is slated
1544 /// for a single slice.
1545 static bool isVectorPromotionViableForSlice(
1546 const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
1547 uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
1548 AllocaSlices::const_iterator I) {
1549 // First validate the slice offsets.
1550 uint64_t BeginOffset =
1551 std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1552 uint64_t BeginIndex = BeginOffset / ElementSize;
1553 if (BeginIndex * ElementSize != BeginOffset ||
1554 BeginIndex >= Ty->getNumElements())
1556 uint64_t EndOffset =
1557 std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
1558 uint64_t EndIndex = EndOffset / ElementSize;
1559 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1562 assert(EndIndex > BeginIndex && "Empty vector!");
1563 uint64_t NumElements = EndIndex - BeginIndex;
1565 (NumElements == 1) ? Ty->getElementType()
1566 : VectorType::get(Ty->getElementType(), NumElements);
1569 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1571 Use *U = I->getUse();
1573 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1574 if (MI->isVolatile())
1576 if (!I->isSplittable())
1577 return false; // Skip any unsplittable intrinsics.
1578 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1579 // Disable vector promotion when there are loads or stores of an FCA.
1581 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1582 if (LI->isVolatile())
1584 Type *LTy = LI->getType();
1585 if (SliceBeginOffset > I->beginOffset() ||
1586 SliceEndOffset < I->endOffset()) {
1587 assert(LTy->isIntegerTy());
1590 if (!canConvertValue(DL, SliceTy, LTy))
1592 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1593 if (SI->isVolatile())
1595 Type *STy = SI->getValueOperand()->getType();
1596 if (SliceBeginOffset > I->beginOffset() ||
1597 SliceEndOffset < I->endOffset()) {
1598 assert(STy->isIntegerTy());
1601 if (!canConvertValue(DL, STy, SliceTy))
1610 /// \brief Test whether the given alloca partitioning and range of slices can be
1611 /// promoted to a vector.
1613 /// This is a quick test to check whether we can rewrite a particular alloca
1614 /// partition (and its newly formed alloca) into a vector alloca with only
1615 /// whole-vector loads and stores such that it could be promoted to a vector
1616 /// SSA value. We only can ensure this for a limited set of operations, and we
1617 /// don't want to do the rewrites unless we are confident that the result will
1618 /// be promotable, so we have an early test here.
1620 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
1621 uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
1622 AllocaSlices::const_iterator I,
1623 AllocaSlices::const_iterator E,
1624 ArrayRef<AllocaSlices::iterator> SplitUses) {
1625 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1629 uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
1631 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1632 // that aren't byte sized.
1633 if (ElementSize % 8)
1635 assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
1636 "vector size not a multiple of element size?");
1640 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1641 SliceEndOffset, Ty, ElementSize, I))
1644 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1645 SUE = SplitUses.end();
1647 if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
1648 SliceEndOffset, Ty, ElementSize, *SUI))
1654 /// \brief Test whether a slice of an alloca is valid for integer widening.
1656 /// This implements the necessary checking for the \c isIntegerWideningViable
1657 /// test below on a single slice of the alloca.
1658 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1660 uint64_t AllocBeginOffset,
1661 uint64_t Size, AllocaSlices &S,
1662 AllocaSlices::const_iterator I,
1663 bool &WholeAllocaOp) {
1664 uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
1665 uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
1667 // We can't reasonably handle cases where the load or store extends past
1668 // the end of the aloca's type and into its padding.
1672 Use *U = I->getUse();
1674 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1675 if (LI->isVolatile())
1677 if (RelBegin == 0 && RelEnd == Size)
1678 WholeAllocaOp = true;
1679 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1680 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1682 } else if (RelBegin != 0 || RelEnd != Size ||
1683 !canConvertValue(DL, AllocaTy, LI->getType())) {
1684 // Non-integer loads need to be convertible from the alloca type so that
1685 // they are promotable.
1688 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1689 Type *ValueTy = SI->getValueOperand()->getType();
1690 if (SI->isVolatile())
1692 if (RelBegin == 0 && RelEnd == Size)
1693 WholeAllocaOp = true;
1694 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1695 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1697 } else if (RelBegin != 0 || RelEnd != Size ||
1698 !canConvertValue(DL, ValueTy, AllocaTy)) {
1699 // Non-integer stores need to be convertible to the alloca type so that
1700 // they are promotable.
1703 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1704 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1706 if (!I->isSplittable())
1707 return false; // Skip any unsplittable intrinsics.
1708 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1709 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1710 II->getIntrinsicID() != Intrinsic::lifetime_end)
1719 /// \brief Test whether the given alloca partition's integer operations can be
1720 /// widened to promotable ones.
1722 /// This is a quick test to check whether we can rewrite the integer loads and
1723 /// stores to a particular alloca into wider loads and stores and be able to
1724 /// promote the resulting alloca.
1726 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1727 uint64_t AllocBeginOffset, AllocaSlices &S,
1728 AllocaSlices::const_iterator I,
1729 AllocaSlices::const_iterator E,
1730 ArrayRef<AllocaSlices::iterator> SplitUses) {
1731 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1732 // Don't create integer types larger than the maximum bitwidth.
1733 if (SizeInBits > IntegerType::MAX_INT_BITS)
1736 // Don't try to handle allocas with bit-padding.
1737 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1740 // We need to ensure that an integer type with the appropriate bitwidth can
1741 // be converted to the alloca type, whatever that is. We don't want to force
1742 // the alloca itself to have an integer type if there is a more suitable one.
1743 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1744 if (!canConvertValue(DL, AllocaTy, IntTy) ||
1745 !canConvertValue(DL, IntTy, AllocaTy))
1748 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1750 // While examining uses, we ensure that the alloca has a covering load or
1751 // store. We don't want to widen the integer operations only to fail to
1752 // promote due to some other unsplittable entry (which we may make splittable
1753 // later). However, if there are only splittable uses, go ahead and assume
1754 // that we cover the alloca.
1755 bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
1758 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1759 S, I, WholeAllocaOp))
1762 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
1763 SUE = SplitUses.end();
1765 if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1766 S, *SUI, WholeAllocaOp))
1769 return WholeAllocaOp;
1772 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1773 IntegerType *Ty, uint64_t Offset,
1774 const Twine &Name) {
1775 DEBUG(dbgs() << " start: " << *V << "\n");
1776 IntegerType *IntTy = cast<IntegerType>(V->getType());
1777 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1778 "Element extends past full value");
1779 uint64_t ShAmt = 8*Offset;
1780 if (DL.isBigEndian())
1781 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1783 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1784 DEBUG(dbgs() << " shifted: " << *V << "\n");
1786 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1787 "Cannot extract to a larger integer!");
1789 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1790 DEBUG(dbgs() << " trunced: " << *V << "\n");
1795 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1796 Value *V, uint64_t Offset, const Twine &Name) {
1797 IntegerType *IntTy = cast<IntegerType>(Old->getType());
1798 IntegerType *Ty = cast<IntegerType>(V->getType());
1799 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1800 "Cannot insert a larger integer!");
1801 DEBUG(dbgs() << " start: " << *V << "\n");
1803 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1804 DEBUG(dbgs() << " extended: " << *V << "\n");
1806 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1807 "Element store outside of alloca store");
1808 uint64_t ShAmt = 8*Offset;
1809 if (DL.isBigEndian())
1810 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1812 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1813 DEBUG(dbgs() << " shifted: " << *V << "\n");
1816 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1817 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1818 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1819 DEBUG(dbgs() << " masked: " << *Old << "\n");
1820 V = IRB.CreateOr(Old, V, Name + ".insert");
1821 DEBUG(dbgs() << " inserted: " << *V << "\n");
1826 static Value *extractVector(IRBuilderTy &IRB, Value *V,
1827 unsigned BeginIndex, unsigned EndIndex,
1828 const Twine &Name) {
1829 VectorType *VecTy = cast<VectorType>(V->getType());
1830 unsigned NumElements = EndIndex - BeginIndex;
1831 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1833 if (NumElements == VecTy->getNumElements())
1836 if (NumElements == 1) {
1837 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1839 DEBUG(dbgs() << " extract: " << *V << "\n");
1843 SmallVector<Constant*, 8> Mask;
1844 Mask.reserve(NumElements);
1845 for (unsigned i = BeginIndex; i != EndIndex; ++i)
1846 Mask.push_back(IRB.getInt32(i));
1847 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1848 ConstantVector::get(Mask),
1850 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1854 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
1855 unsigned BeginIndex, const Twine &Name) {
1856 VectorType *VecTy = cast<VectorType>(Old->getType());
1857 assert(VecTy && "Can only insert a vector into a vector");
1859 VectorType *Ty = dyn_cast<VectorType>(V->getType());
1861 // Single element to insert.
1862 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
1864 DEBUG(dbgs() << " insert: " << *V << "\n");
1868 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
1869 "Too many elements!");
1870 if (Ty->getNumElements() == VecTy->getNumElements()) {
1871 assert(V->getType() == VecTy && "Vector type mismatch");
1874 unsigned EndIndex = BeginIndex + Ty->getNumElements();
1876 // When inserting a smaller vector into the larger to store, we first
1877 // use a shuffle vector to widen it with undef elements, and then
1878 // a second shuffle vector to select between the loaded vector and the
1880 SmallVector<Constant*, 8> Mask;
1881 Mask.reserve(VecTy->getNumElements());
1882 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1883 if (i >= BeginIndex && i < EndIndex)
1884 Mask.push_back(IRB.getInt32(i - BeginIndex));
1886 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
1887 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1888 ConstantVector::get(Mask),
1890 DEBUG(dbgs() << " shuffle: " << *V << "\n");
1893 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
1894 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
1896 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
1898 DEBUG(dbgs() << " blend: " << *V << "\n");
1903 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
1904 /// to use a new alloca.
1906 /// Also implements the rewriting to vector-based accesses when the partition
1907 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1909 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
1910 // Befriend the base class so it can delegate to private visit methods.
1911 friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
1912 typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
1914 const DataLayout &DL;
1917 AllocaInst &OldAI, &NewAI;
1918 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1921 // If we are rewriting an alloca partition which can be written as pure
1922 // vector operations, we stash extra information here. When VecTy is
1923 // non-null, we have some strict guarantees about the rewritten alloca:
1924 // - The new alloca is exactly the size of the vector type here.
1925 // - The accesses all either map to the entire vector or to a single
1927 // - The set of accessing instructions is only one of those handled above
1928 // in isVectorPromotionViable. Generally these are the same access kinds
1929 // which are promotable via mem2reg.
1932 uint64_t ElementSize;
1934 // This is a convenience and flag variable that will be null unless the new
1935 // alloca's integer operations should be widened to this integer type due to
1936 // passing isIntegerWideningViable above. If it is non-null, the desired
1937 // integer type will be stored here for easy access during rewriting.
1940 // The offset of the slice currently being rewritten.
1941 uint64_t BeginOffset, EndOffset;
1945 Instruction *OldPtr;
1947 // Output members carrying state about the result of visiting and rewriting
1948 // the slice of the alloca.
1949 bool IsUsedByRewrittenSpeculatableInstructions;
1951 // Utility IR builder, whose name prefix is setup for each visited use, and
1952 // the insertion point is set to point to the user.
1956 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
1957 AllocaInst &OldAI, AllocaInst &NewAI,
1958 uint64_t NewBeginOffset, uint64_t NewEndOffset,
1959 bool IsVectorPromotable = false,
1960 bool IsIntegerPromotable = false)
1961 : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
1962 NewAllocaBeginOffset(NewBeginOffset), NewAllocaEndOffset(NewEndOffset),
1963 NewAllocaTy(NewAI.getAllocatedType()),
1964 VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : 0),
1965 ElementTy(VecTy ? VecTy->getElementType() : 0),
1966 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
1967 IntTy(IsIntegerPromotable
1970 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
1972 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
1973 OldPtr(), IsUsedByRewrittenSpeculatableInstructions(false),
1974 IRB(NewAI.getContext(), ConstantFolder()) {
1976 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
1977 "Only multiple-of-8 sized vector elements are viable");
1980 assert((!IsVectorPromotable && !IsIntegerPromotable) ||
1981 IsVectorPromotable != IsIntegerPromotable);
1984 bool visit(AllocaSlices::const_iterator I) {
1985 bool CanSROA = true;
1986 BeginOffset = I->beginOffset();
1987 EndOffset = I->endOffset();
1988 IsSplittable = I->isSplittable();
1990 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
1992 OldUse = I->getUse();
1993 OldPtr = cast<Instruction>(OldUse->get());
1995 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
1996 IRB.SetInsertPoint(OldUserI);
1997 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
1998 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2000 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2006 /// \brief Query whether this slice is used by speculatable instructions after
2009 /// These instructions (PHIs and Selects currently) require the alloca slice
2010 /// to run back through the rewriter. Thus, they are promotable, but not on
2011 /// this iteration. This is distinct from a slice which is unpromotable for
2012 /// some other reason, in which case we don't even want to perform the
2013 /// speculation. This can be querried at any time and reflects whether (at
2014 /// that point) a visit call has rewritten a speculatable instruction on the
2016 bool isUsedByRewrittenSpeculatableInstructions() const {
2017 return IsUsedByRewrittenSpeculatableInstructions;
2021 // Make sure the other visit overloads are visible.
2024 // Every instruction which can end up as a user must have a rewrite rule.
2025 bool visitInstruction(Instruction &I) {
2026 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2027 llvm_unreachable("No rewrite rule for this instruction!");
2030 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, uint64_t Offset,
2032 assert(Offset >= NewAllocaBeginOffset);
2033 return getAdjustedPtr(IRB, DL, &NewAI, APInt(DL.getPointerSizeInBits(),
2034 Offset - NewAllocaBeginOffset),
2038 /// \brief Compute suitable alignment to access an offset into the new alloca.
2039 unsigned getOffsetAlign(uint64_t Offset) {
2040 unsigned NewAIAlign = NewAI.getAlignment();
2042 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2043 return MinAlign(NewAIAlign, Offset);
2046 /// \brief Compute suitable alignment to access a type at an offset of the
2049 /// \returns zero if the type's ABI alignment is a suitable alignment,
2050 /// otherwise returns the maximal suitable alignment.
2051 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2052 unsigned Align = getOffsetAlign(Offset);
2053 return Align == DL.getABITypeAlignment(Ty) ? 0 : Align;
2056 unsigned getIndex(uint64_t Offset) {
2057 assert(VecTy && "Can only call getIndex when rewriting a vector");
2058 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2059 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2060 uint32_t Index = RelOffset / ElementSize;
2061 assert(Index * ElementSize == RelOffset);
2065 void deleteIfTriviallyDead(Value *V) {
2066 Instruction *I = cast<Instruction>(V);
2067 if (isInstructionTriviallyDead(I))
2068 Pass.DeadInsts.insert(I);
2071 Value *rewriteVectorizedLoadInst(uint64_t NewBeginOffset,
2072 uint64_t NewEndOffset) {
2073 unsigned BeginIndex = getIndex(NewBeginOffset);
2074 unsigned EndIndex = getIndex(NewEndOffset);
2075 assert(EndIndex > BeginIndex && "Empty vector!");
2077 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2079 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2082 Value *rewriteIntegerLoad(LoadInst &LI, uint64_t NewBeginOffset,
2083 uint64_t NewEndOffset) {
2084 assert(IntTy && "We cannot insert an integer to the alloca");
2085 assert(!LI.isVolatile());
2086 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2088 V = convertValue(DL, IRB, V, IntTy);
2089 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2090 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2091 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2092 V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2097 bool visitLoadInst(LoadInst &LI) {
2098 DEBUG(dbgs() << " original: " << LI << "\n");
2099 Value *OldOp = LI.getOperand(0);
2100 assert(OldOp == OldPtr);
2102 // Compute the intersecting offset range.
2103 assert(BeginOffset < NewAllocaEndOffset);
2104 assert(EndOffset > NewAllocaBeginOffset);
2105 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2106 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2108 uint64_t Size = NewEndOffset - NewBeginOffset;
2110 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2112 bool IsPtrAdjusted = false;
2115 V = rewriteVectorizedLoadInst(NewBeginOffset, NewEndOffset);
2116 } else if (IntTy && LI.getType()->isIntegerTy()) {
2117 V = rewriteIntegerLoad(LI, NewBeginOffset, NewEndOffset);
2118 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2119 canConvertValue(DL, NewAllocaTy, LI.getType())) {
2120 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2121 LI.isVolatile(), "load");
2123 Type *LTy = TargetTy->getPointerTo();
2124 V = IRB.CreateAlignedLoad(
2125 getAdjustedAllocaPtr(IRB, NewBeginOffset, LTy),
2126 getOffsetTypeAlign(TargetTy, NewBeginOffset - NewAllocaBeginOffset),
2127 LI.isVolatile(), "load");
2128 IsPtrAdjusted = true;
2130 V = convertValue(DL, IRB, V, TargetTy);
2133 assert(!LI.isVolatile());
2134 assert(LI.getType()->isIntegerTy() &&
2135 "Only integer type loads and stores are split");
2136 assert(Size < DL.getTypeStoreSize(LI.getType()) &&
2137 "Split load isn't smaller than original load");
2138 assert(LI.getType()->getIntegerBitWidth() ==
2139 DL.getTypeStoreSizeInBits(LI.getType()) &&
2140 "Non-byte-multiple bit width");
2141 // Move the insertion point just past the load so that we can refer to it.
2142 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2143 // Create a placeholder value with the same type as LI to use as the
2144 // basis for the new value. This allows us to replace the uses of LI with
2145 // the computed value, and then replace the placeholder with LI, leaving
2146 // LI only used for this computation.
2148 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2149 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
2151 LI.replaceAllUsesWith(V);
2152 Placeholder->replaceAllUsesWith(&LI);
2155 LI.replaceAllUsesWith(V);
2158 Pass.DeadInsts.insert(&LI);
2159 deleteIfTriviallyDead(OldOp);
2160 DEBUG(dbgs() << " to: " << *V << "\n");
2161 return !LI.isVolatile() && !IsPtrAdjusted;
2164 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2165 uint64_t NewBeginOffset,
2166 uint64_t NewEndOffset) {
2167 if (V->getType() != VecTy) {
2168 unsigned BeginIndex = getIndex(NewBeginOffset);
2169 unsigned EndIndex = getIndex(NewEndOffset);
2170 assert(EndIndex > BeginIndex && "Empty vector!");
2171 unsigned NumElements = EndIndex - BeginIndex;
2172 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2174 (NumElements == 1) ? ElementTy
2175 : VectorType::get(ElementTy, NumElements);
2176 if (V->getType() != SliceTy)
2177 V = convertValue(DL, IRB, V, SliceTy);
2179 // Mix in the existing elements.
2180 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2182 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2184 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2185 Pass.DeadInsts.insert(&SI);
2188 DEBUG(dbgs() << " to: " << *Store << "\n");
2192 bool rewriteIntegerStore(Value *V, StoreInst &SI,
2193 uint64_t NewBeginOffset, uint64_t NewEndOffset) {
2194 assert(IntTy && "We cannot extract an integer from the alloca");
2195 assert(!SI.isVolatile());
2196 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2197 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2199 Old = convertValue(DL, IRB, Old, IntTy);
2200 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2201 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2202 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
2205 V = convertValue(DL, IRB, V, NewAllocaTy);
2206 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2207 Pass.DeadInsts.insert(&SI);
2209 DEBUG(dbgs() << " to: " << *Store << "\n");
2213 bool visitStoreInst(StoreInst &SI) {
2214 DEBUG(dbgs() << " original: " << SI << "\n");
2215 Value *OldOp = SI.getOperand(1);
2216 assert(OldOp == OldPtr);
2218 Value *V = SI.getValueOperand();
2220 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2221 // alloca that should be re-examined after promoting this alloca.
2222 if (V->getType()->isPointerTy())
2223 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2224 Pass.PostPromotionWorklist.insert(AI);
2226 // Compute the intersecting offset range.
2227 assert(BeginOffset < NewAllocaEndOffset);
2228 assert(EndOffset > NewAllocaBeginOffset);
2229 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2230 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2232 uint64_t Size = NewEndOffset - NewBeginOffset;
2233 if (Size < DL.getTypeStoreSize(V->getType())) {
2234 assert(!SI.isVolatile());
2235 assert(V->getType()->isIntegerTy() &&
2236 "Only integer type loads and stores are split");
2237 assert(V->getType()->getIntegerBitWidth() ==
2238 DL.getTypeStoreSizeInBits(V->getType()) &&
2239 "Non-byte-multiple bit width");
2240 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2241 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
2246 return rewriteVectorizedStoreInst(V, SI, OldOp, NewBeginOffset,
2248 if (IntTy && V->getType()->isIntegerTy())
2249 return rewriteIntegerStore(V, SI, NewBeginOffset, NewEndOffset);
2252 if (NewBeginOffset == NewAllocaBeginOffset &&
2253 NewEndOffset == NewAllocaEndOffset &&
2254 canConvertValue(DL, V->getType(), NewAllocaTy)) {
2255 V = convertValue(DL, IRB, V, NewAllocaTy);
2256 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2259 Value *NewPtr = getAdjustedAllocaPtr(IRB, NewBeginOffset,
2260 V->getType()->getPointerTo());
2261 NewSI = IRB.CreateAlignedStore(
2262 V, NewPtr, getOffsetTypeAlign(
2263 V->getType(), NewBeginOffset - NewAllocaBeginOffset),
2267 Pass.DeadInsts.insert(&SI);
2268 deleteIfTriviallyDead(OldOp);
2270 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2271 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2274 /// \brief Compute an integer value from splatting an i8 across the given
2275 /// number of bytes.
2277 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2278 /// call this routine.
2279 /// FIXME: Heed the advice above.
2281 /// \param V The i8 value to splat.
2282 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2283 Value *getIntegerSplat(Value *V, unsigned Size) {
2284 assert(Size > 0 && "Expected a positive number of bytes.");
2285 IntegerType *VTy = cast<IntegerType>(V->getType());
2286 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2290 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2291 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
2292 ConstantExpr::getUDiv(
2293 Constant::getAllOnesValue(SplatIntTy),
2294 ConstantExpr::getZExt(
2295 Constant::getAllOnesValue(V->getType()),
2301 /// \brief Compute a vector splat for a given element value.
2302 Value *getVectorSplat(Value *V, unsigned NumElements) {
2303 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2304 DEBUG(dbgs() << " splat: " << *V << "\n");
2308 bool visitMemSetInst(MemSetInst &II) {
2309 DEBUG(dbgs() << " original: " << II << "\n");
2310 assert(II.getRawDest() == OldPtr);
2312 // If the memset has a variable size, it cannot be split, just adjust the
2313 // pointer to the new alloca.
2314 if (!isa<Constant>(II.getLength())) {
2316 assert(BeginOffset >= NewAllocaBeginOffset);
2318 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2319 Type *CstTy = II.getAlignmentCst()->getType();
2320 II.setAlignment(ConstantInt::get(CstTy, getOffsetAlign(BeginOffset)));
2322 deleteIfTriviallyDead(OldPtr);
2326 // Record this instruction for deletion.
2327 Pass.DeadInsts.insert(&II);
2329 Type *AllocaTy = NewAI.getAllocatedType();
2330 Type *ScalarTy = AllocaTy->getScalarType();
2332 // Compute the intersecting offset range.
2333 assert(BeginOffset < NewAllocaEndOffset);
2334 assert(EndOffset > NewAllocaBeginOffset);
2335 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2336 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2337 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2339 // If this doesn't map cleanly onto the alloca type, and that type isn't
2340 // a single value type, just emit a memset.
2341 if (!VecTy && !IntTy &&
2342 (BeginOffset > NewAllocaBeginOffset ||
2343 EndOffset < NewAllocaEndOffset ||
2344 !AllocaTy->isSingleValueType() ||
2345 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2346 DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
2347 Type *SizeTy = II.getLength()->getType();
2348 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2349 CallInst *New = IRB.CreateMemSet(
2350 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getRawDest()->getType()),
2351 II.getValue(), Size, getOffsetAlign(SliceOffset), II.isVolatile());
2353 DEBUG(dbgs() << " to: " << *New << "\n");
2357 // If we can represent this as a simple value, we have to build the actual
2358 // value to store, which requires expanding the byte present in memset to
2359 // a sensible representation for the alloca type. This is essentially
2360 // splatting the byte to a sufficiently wide integer, splatting it across
2361 // any desired vector width, and bitcasting to the final type.
2365 // If this is a memset of a vectorized alloca, insert it.
2366 assert(ElementTy == ScalarTy);
2368 unsigned BeginIndex = getIndex(NewBeginOffset);
2369 unsigned EndIndex = getIndex(NewEndOffset);
2370 assert(EndIndex > BeginIndex && "Empty vector!");
2371 unsigned NumElements = EndIndex - BeginIndex;
2372 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2375 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2376 Splat = convertValue(DL, IRB, Splat, ElementTy);
2377 if (NumElements > 1)
2378 Splat = getVectorSplat(Splat, NumElements);
2380 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2382 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2384 // If this is a memset on an alloca where we can widen stores, insert the
2386 assert(!II.isVolatile());
2388 uint64_t Size = NewEndOffset - NewBeginOffset;
2389 V = getIntegerSplat(II.getValue(), Size);
2391 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2392 EndOffset != NewAllocaBeginOffset)) {
2393 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2395 Old = convertValue(DL, IRB, Old, IntTy);
2396 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2397 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2399 assert(V->getType() == IntTy &&
2400 "Wrong type for an alloca wide integer!");
2402 V = convertValue(DL, IRB, V, AllocaTy);
2404 // Established these invariants above.
2405 assert(NewBeginOffset == NewAllocaBeginOffset);
2406 assert(NewEndOffset == NewAllocaEndOffset);
2408 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2409 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2410 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2412 V = convertValue(DL, IRB, V, AllocaTy);
2415 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2418 DEBUG(dbgs() << " to: " << *New << "\n");
2419 return !II.isVolatile();
2422 bool visitMemTransferInst(MemTransferInst &II) {
2423 // Rewriting of memory transfer instructions can be a bit tricky. We break
2424 // them into two categories: split intrinsics and unsplit intrinsics.
2426 DEBUG(dbgs() << " original: " << II << "\n");
2428 // Compute the intersecting offset range.
2429 assert(BeginOffset < NewAllocaEndOffset);
2430 assert(EndOffset > NewAllocaBeginOffset);
2431 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2432 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2434 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2435 bool IsDest = II.getRawDest() == OldPtr;
2437 // Compute the relative offset within the transfer.
2438 unsigned IntPtrWidth = DL.getPointerSizeInBits();
2439 APInt RelOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2441 unsigned Align = II.getAlignment();
2442 uint64_t SliceOffset = NewBeginOffset - NewAllocaBeginOffset;
2445 MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
2446 MinAlign(II.getAlignment(), getOffsetAlign(SliceOffset)));
2448 // For unsplit intrinsics, we simply modify the source and destination
2449 // pointers in place. This isn't just an optimization, it is a matter of
2450 // correctness. With unsplit intrinsics we may be dealing with transfers
2451 // within a single alloca before SROA ran, or with transfers that have
2452 // a variable length. We may also be dealing with memmove instead of
2453 // memcpy, and so simply updating the pointers is the necessary for us to
2454 // update both source and dest of a single call.
2455 if (!IsSplittable) {
2456 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2459 getAdjustedAllocaPtr(IRB, BeginOffset, II.getRawDest()->getType()));
2461 II.setSource(getAdjustedAllocaPtr(IRB, BeginOffset,
2462 II.getRawSource()->getType()));
2464 Type *CstTy = II.getAlignmentCst()->getType();
2465 II.setAlignment(ConstantInt::get(CstTy, Align));
2467 DEBUG(dbgs() << " to: " << II << "\n");
2468 deleteIfTriviallyDead(OldOp);
2471 // For split transfer intrinsics we have an incredibly useful assurance:
2472 // the source and destination do not reside within the same alloca, and at
2473 // least one of them does not escape. This means that we can replace
2474 // memmove with memcpy, and we don't need to worry about all manner of
2475 // downsides to splitting and transforming the operations.
2477 // If this doesn't map cleanly onto the alloca type, and that type isn't
2478 // a single value type, just emit a memcpy.
2480 = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
2481 EndOffset < NewAllocaEndOffset ||
2482 !NewAI.getAllocatedType()->isSingleValueType());
2484 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2485 // size hasn't been shrunk based on analysis of the viable range, this is
2487 if (EmitMemCpy && &OldAI == &NewAI) {
2488 // Ensure the start lines up.
2489 assert(NewBeginOffset == BeginOffset);
2491 // Rewrite the size as needed.
2492 if (NewEndOffset != EndOffset)
2493 II.setLength(ConstantInt::get(II.getLength()->getType(),
2494 NewEndOffset - NewBeginOffset));
2497 // Record this instruction for deletion.
2498 Pass.DeadInsts.insert(&II);
2500 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2501 // alloca that should be re-examined after rewriting this instruction.
2502 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2504 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2505 Pass.Worklist.insert(AI);
2508 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2509 : II.getRawDest()->getType();
2511 // Compute the other pointer, folding as much as possible to produce
2512 // a single, simple GEP in most cases.
2513 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2515 Value *OurPtr = getAdjustedAllocaPtr(
2516 IRB, NewBeginOffset,
2517 IsDest ? II.getRawDest()->getType() : II.getRawSource()->getType());
2518 Type *SizeTy = II.getLength()->getType();
2519 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2521 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2522 IsDest ? OtherPtr : OurPtr,
2523 Size, Align, II.isVolatile());
2525 DEBUG(dbgs() << " to: " << *New << "\n");
2529 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2530 // is equivalent to 1, but that isn't true if we end up rewriting this as
2535 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2536 NewEndOffset == NewAllocaEndOffset;
2537 uint64_t Size = NewEndOffset - NewBeginOffset;
2538 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2539 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2540 unsigned NumElements = EndIndex - BeginIndex;
2541 IntegerType *SubIntTy
2542 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2544 Type *OtherPtrTy = NewAI.getType();
2545 if (VecTy && !IsWholeAlloca) {
2546 if (NumElements == 1)
2547 OtherPtrTy = VecTy->getElementType();
2549 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2551 OtherPtrTy = OtherPtrTy->getPointerTo();
2552 } else if (IntTy && !IsWholeAlloca) {
2553 OtherPtrTy = SubIntTy->getPointerTo();
2556 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, RelOffset, OtherPtrTy);
2557 Value *DstPtr = &NewAI;
2559 std::swap(SrcPtr, DstPtr);
2562 if (VecTy && !IsWholeAlloca && !IsDest) {
2563 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2565 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2566 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2567 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2569 Src = convertValue(DL, IRB, Src, IntTy);
2570 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2571 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2573 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2577 if (VecTy && !IsWholeAlloca && IsDest) {
2578 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2580 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2581 } else if (IntTy && !IsWholeAlloca && IsDest) {
2582 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2584 Old = convertValue(DL, IRB, Old, IntTy);
2585 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2586 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2587 Src = convertValue(DL, IRB, Src, NewAllocaTy);
2590 StoreInst *Store = cast<StoreInst>(
2591 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2593 DEBUG(dbgs() << " to: " << *Store << "\n");
2594 return !II.isVolatile();
2597 bool visitIntrinsicInst(IntrinsicInst &II) {
2598 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2599 II.getIntrinsicID() == Intrinsic::lifetime_end);
2600 DEBUG(dbgs() << " original: " << II << "\n");
2601 assert(II.getArgOperand(1) == OldPtr);
2603 // Compute the intersecting offset range.
2604 assert(BeginOffset < NewAllocaEndOffset);
2605 assert(EndOffset > NewAllocaBeginOffset);
2606 uint64_t NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2607 uint64_t NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2609 // Record this instruction for deletion.
2610 Pass.DeadInsts.insert(&II);
2613 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2614 NewEndOffset - NewBeginOffset);
2616 getAdjustedAllocaPtr(IRB, NewBeginOffset, II.getArgOperand(1)->getType());
2618 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2619 New = IRB.CreateLifetimeStart(Ptr, Size);
2621 New = IRB.CreateLifetimeEnd(Ptr, Size);
2624 DEBUG(dbgs() << " to: " << *New << "\n");
2628 bool visitPHINode(PHINode &PN) {
2629 DEBUG(dbgs() << " original: " << PN << "\n");
2630 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2631 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2633 // We would like to compute a new pointer in only one place, but have it be
2634 // as local as possible to the PHI. To do that, we re-use the location of
2635 // the old pointer, which necessarily must be in the right position to
2636 // dominate the PHI.
2637 IRBuilderTy PtrBuilder(OldPtr);
2638 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2642 getAdjustedAllocaPtr(PtrBuilder, BeginOffset, OldPtr->getType());
2643 // Replace the operands which were using the old pointer.
2644 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2646 DEBUG(dbgs() << " to: " << PN << "\n");
2647 deleteIfTriviallyDead(OldPtr);
2649 // Check whether we can speculate this PHI node, and if so remember that
2650 // fact and queue it up for another iteration after the speculation
2652 if (isSafePHIToSpeculate(PN, &DL)) {
2653 Pass.SpeculatablePHIs.insert(&PN);
2654 IsUsedByRewrittenSpeculatableInstructions = true;
2658 return false; // PHIs can't be promoted on their own.
2661 bool visitSelectInst(SelectInst &SI) {
2662 DEBUG(dbgs() << " original: " << SI << "\n");
2663 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2664 "Pointer isn't an operand!");
2665 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2666 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2668 Value *NewPtr = getAdjustedAllocaPtr(IRB, BeginOffset, OldPtr->getType());
2669 // Replace the operands which were using the old pointer.
2670 if (SI.getOperand(1) == OldPtr)
2671 SI.setOperand(1, NewPtr);
2672 if (SI.getOperand(2) == OldPtr)
2673 SI.setOperand(2, NewPtr);
2675 DEBUG(dbgs() << " to: " << SI << "\n");
2676 deleteIfTriviallyDead(OldPtr);
2678 // Check whether we can speculate this select instruction, and if so
2679 // remember that fact and queue it up for another iteration after the
2680 // speculation occurs.
2681 if (isSafeSelectToSpeculate(SI, &DL)) {
2682 Pass.SpeculatableSelects.insert(&SI);
2683 IsUsedByRewrittenSpeculatableInstructions = true;
2687 return false; // Selects can't be promoted on their own.
2694 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2696 /// This pass aggressively rewrites all aggregate loads and stores on
2697 /// a particular pointer (or any pointer derived from it which we can identify)
2698 /// with scalar loads and stores.
2699 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2700 // Befriend the base class so it can delegate to private visit methods.
2701 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2703 const DataLayout &DL;
2705 /// Queue of pointer uses to analyze and potentially rewrite.
2706 SmallVector<Use *, 8> Queue;
2708 /// Set to prevent us from cycling with phi nodes and loops.
2709 SmallPtrSet<User *, 8> Visited;
2711 /// The current pointer use being rewritten. This is used to dig up the used
2712 /// value (as opposed to the user).
2716 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2718 /// Rewrite loads and stores through a pointer and all pointers derived from
2720 bool rewrite(Instruction &I) {
2721 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2723 bool Changed = false;
2724 while (!Queue.empty()) {
2725 U = Queue.pop_back_val();
2726 Changed |= visit(cast<Instruction>(U->getUser()));
2732 /// Enqueue all the users of the given instruction for further processing.
2733 /// This uses a set to de-duplicate users.
2734 void enqueueUsers(Instruction &I) {
2735 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2737 if (Visited.insert(*UI))
2738 Queue.push_back(&UI.getUse());
2741 // Conservative default is to not rewrite anything.
2742 bool visitInstruction(Instruction &I) { return false; }
2744 /// \brief Generic recursive split emission class.
2745 template <typename Derived>
2748 /// The builder used to form new instructions.
2750 /// The indices which to be used with insert- or extractvalue to select the
2751 /// appropriate value within the aggregate.
2752 SmallVector<unsigned, 4> Indices;
2753 /// The indices to a GEP instruction which will move Ptr to the correct slot
2754 /// within the aggregate.
2755 SmallVector<Value *, 4> GEPIndices;
2756 /// The base pointer of the original op, used as a base for GEPing the
2757 /// split operations.
2760 /// Initialize the splitter with an insertion point, Ptr and start with a
2761 /// single zero GEP index.
2762 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2763 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2766 /// \brief Generic recursive split emission routine.
2768 /// This method recursively splits an aggregate op (load or store) into
2769 /// scalar or vector ops. It splits recursively until it hits a single value
2770 /// and emits that single value operation via the template argument.
2772 /// The logic of this routine relies on GEPs and insertvalue and
2773 /// extractvalue all operating with the same fundamental index list, merely
2774 /// formatted differently (GEPs need actual values).
2776 /// \param Ty The type being split recursively into smaller ops.
2777 /// \param Agg The aggregate value being built up or stored, depending on
2778 /// whether this is splitting a load or a store respectively.
2779 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2780 if (Ty->isSingleValueType())
2781 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2783 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2784 unsigned OldSize = Indices.size();
2786 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2788 assert(Indices.size() == OldSize && "Did not return to the old size");
2789 Indices.push_back(Idx);
2790 GEPIndices.push_back(IRB.getInt32(Idx));
2791 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2792 GEPIndices.pop_back();
2798 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2799 unsigned OldSize = Indices.size();
2801 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2803 assert(Indices.size() == OldSize && "Did not return to the old size");
2804 Indices.push_back(Idx);
2805 GEPIndices.push_back(IRB.getInt32(Idx));
2806 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2807 GEPIndices.pop_back();
2813 llvm_unreachable("Only arrays and structs are aggregate loadable types");
2817 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2818 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2819 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2821 /// Emit a leaf load of a single value. This is called at the leaves of the
2822 /// recursive emission to actually load values.
2823 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2824 assert(Ty->isSingleValueType());
2825 // Load the single value and insert it using the indices.
2826 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2827 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2828 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2829 DEBUG(dbgs() << " to: " << *Load << "\n");
2833 bool visitLoadInst(LoadInst &LI) {
2834 assert(LI.getPointerOperand() == *U);
2835 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2838 // We have an aggregate being loaded, split it apart.
2839 DEBUG(dbgs() << " original: " << LI << "\n");
2840 LoadOpSplitter Splitter(&LI, *U);
2841 Value *V = UndefValue::get(LI.getType());
2842 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2843 LI.replaceAllUsesWith(V);
2844 LI.eraseFromParent();
2848 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2849 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2850 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2852 /// Emit a leaf store of a single value. This is called at the leaves of the
2853 /// recursive emission to actually produce stores.
2854 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2855 assert(Ty->isSingleValueType());
2856 // Extract the single value and store it using the indices.
2857 Value *Store = IRB.CreateStore(
2858 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2859 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2861 DEBUG(dbgs() << " to: " << *Store << "\n");
2865 bool visitStoreInst(StoreInst &SI) {
2866 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2868 Value *V = SI.getValueOperand();
2869 if (V->getType()->isSingleValueType())
2872 // We have an aggregate being stored, split it apart.
2873 DEBUG(dbgs() << " original: " << SI << "\n");
2874 StoreOpSplitter Splitter(&SI, *U);
2875 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2876 SI.eraseFromParent();
2880 bool visitBitCastInst(BitCastInst &BC) {
2885 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2890 bool visitPHINode(PHINode &PN) {
2895 bool visitSelectInst(SelectInst &SI) {
2902 /// \brief Strip aggregate type wrapping.
2904 /// This removes no-op aggregate types wrapping an underlying type. It will
2905 /// strip as many layers of types as it can without changing either the type
2906 /// size or the allocated size.
2907 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
2908 if (Ty->isSingleValueType())
2911 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2912 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
2915 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
2916 InnerTy = ArrTy->getElementType();
2917 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2918 const StructLayout *SL = DL.getStructLayout(STy);
2919 unsigned Index = SL->getElementContainingOffset(0);
2920 InnerTy = STy->getElementType(Index);
2925 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
2926 TypeSize > DL.getTypeSizeInBits(InnerTy))
2929 return stripAggregateTypeWrapping(DL, InnerTy);
2932 /// \brief Try to find a partition of the aggregate type passed in for a given
2933 /// offset and size.
2935 /// This recurses through the aggregate type and tries to compute a subtype
2936 /// based on the offset and size. When the offset and size span a sub-section
2937 /// of an array, it will even compute a new array type for that sub-section,
2938 /// and the same for structs.
2940 /// Note that this routine is very strict and tries to find a partition of the
2941 /// type which produces the *exact* right offset and size. It is not forgiving
2942 /// when the size or offset cause either end of type-based partition to be off.
2943 /// Also, this is a best-effort routine. It is reasonable to give up and not
2944 /// return a type if necessary.
2945 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
2946 uint64_t Offset, uint64_t Size) {
2947 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
2948 return stripAggregateTypeWrapping(DL, Ty);
2949 if (Offset > DL.getTypeAllocSize(Ty) ||
2950 (DL.getTypeAllocSize(Ty) - Offset) < Size)
2953 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2954 // We can't partition pointers...
2955 if (SeqTy->isPointerTy())
2958 Type *ElementTy = SeqTy->getElementType();
2959 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
2960 uint64_t NumSkippedElements = Offset / ElementSize;
2961 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
2962 if (NumSkippedElements >= ArrTy->getNumElements())
2964 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
2965 if (NumSkippedElements >= VecTy->getNumElements())
2968 Offset -= NumSkippedElements * ElementSize;
2970 // First check if we need to recurse.
2971 if (Offset > 0 || Size < ElementSize) {
2972 // Bail if the partition ends in a different array element.
2973 if ((Offset + Size) > ElementSize)
2975 // Recurse through the element type trying to peel off offset bytes.
2976 return getTypePartition(DL, ElementTy, Offset, Size);
2978 assert(Offset == 0);
2980 if (Size == ElementSize)
2981 return stripAggregateTypeWrapping(DL, ElementTy);
2982 assert(Size > ElementSize);
2983 uint64_t NumElements = Size / ElementSize;
2984 if (NumElements * ElementSize != Size)
2986 return ArrayType::get(ElementTy, NumElements);
2989 StructType *STy = dyn_cast<StructType>(Ty);
2993 const StructLayout *SL = DL.getStructLayout(STy);
2994 if (Offset >= SL->getSizeInBytes())
2996 uint64_t EndOffset = Offset + Size;
2997 if (EndOffset > SL->getSizeInBytes())
3000 unsigned Index = SL->getElementContainingOffset(Offset);
3001 Offset -= SL->getElementOffset(Index);
3003 Type *ElementTy = STy->getElementType(Index);
3004 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3005 if (Offset >= ElementSize)
3006 return 0; // The offset points into alignment padding.
3008 // See if any partition must be contained by the element.
3009 if (Offset > 0 || Size < ElementSize) {
3010 if ((Offset + Size) > ElementSize)
3012 return getTypePartition(DL, ElementTy, Offset, Size);
3014 assert(Offset == 0);
3016 if (Size == ElementSize)
3017 return stripAggregateTypeWrapping(DL, ElementTy);
3019 StructType::element_iterator EI = STy->element_begin() + Index,
3020 EE = STy->element_end();
3021 if (EndOffset < SL->getSizeInBytes()) {
3022 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3023 if (Index == EndIndex)
3024 return 0; // Within a single element and its padding.
3026 // Don't try to form "natural" types if the elements don't line up with the
3028 // FIXME: We could potentially recurse down through the last element in the
3029 // sub-struct to find a natural end point.
3030 if (SL->getElementOffset(EndIndex) != EndOffset)
3033 assert(Index < EndIndex);
3034 EE = STy->element_begin() + EndIndex;
3037 // Try to build up a sub-structure.
3038 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
3040 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3041 if (Size != SubSL->getSizeInBytes())
3042 return 0; // The sub-struct doesn't have quite the size needed.
3047 /// \brief Rewrite an alloca partition's users.
3049 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3050 /// to rewrite uses of an alloca partition to be conducive for SSA value
3051 /// promotion. If the partition needs a new, more refined alloca, this will
3052 /// build that new alloca, preserving as much type information as possible, and
3053 /// rewrite the uses of the old alloca to point at the new one and have the
3054 /// appropriate new offsets. It also evaluates how successful the rewrite was
3055 /// at enabling promotion and if it was successful queues the alloca to be
3057 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
3058 AllocaSlices::iterator B, AllocaSlices::iterator E,
3059 int64_t BeginOffset, int64_t EndOffset,
3060 ArrayRef<AllocaSlices::iterator> SplitUses) {
3061 assert(BeginOffset < EndOffset);
3062 uint64_t SliceSize = EndOffset - BeginOffset;
3064 // Try to compute a friendly type for this partition of the alloca. This
3065 // won't always succeed, in which case we fall back to a legal integer type
3066 // or an i8 array of an appropriate size.
3068 if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3069 if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3070 SliceTy = CommonUseTy;
3072 if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3073 BeginOffset, SliceSize))
3074 SliceTy = TypePartitionTy;
3075 if ((!SliceTy || (SliceTy->isArrayTy() &&
3076 SliceTy->getArrayElementType()->isIntegerTy())) &&
3077 DL->isLegalInteger(SliceSize * 8))
3078 SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3080 SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3081 assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3083 bool IsVectorPromotable = isVectorPromotionViable(
3084 *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
3086 bool IsIntegerPromotable =
3087 !IsVectorPromotable &&
3088 isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
3090 // Check for the case where we're going to rewrite to a new alloca of the
3091 // exact same type as the original, and with the same access offsets. In that
3092 // case, re-use the existing alloca, but still run through the rewriter to
3093 // perform phi and select speculation.
3095 if (SliceTy == AI.getAllocatedType()) {
3096 assert(BeginOffset == 0 &&
3097 "Non-zero begin offset but same alloca type");
3099 // FIXME: We should be able to bail at this point with "nothing changed".
3100 // FIXME: We might want to defer PHI speculation until after here.
3102 unsigned Alignment = AI.getAlignment();
3104 // The minimum alignment which users can rely on when the explicit
3105 // alignment is omitted or zero is that required by the ABI for this
3107 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3109 Alignment = MinAlign(Alignment, BeginOffset);
3110 // If we will get at least this much alignment from the type alone, leave
3111 // the alloca's alignment unconstrained.
3112 if (Alignment <= DL->getABITypeAlignment(SliceTy))
3114 NewAI = new AllocaInst(SliceTy, 0, Alignment,
3115 AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
3119 DEBUG(dbgs() << "Rewriting alloca partition "
3120 << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3123 // Track the high watermark on several worklists that are only relevant for
3124 // promoted allocas. We will reset it to this point if the alloca is not in
3125 // fact scheduled for promotion.
3126 unsigned PPWOldSize = PostPromotionWorklist.size();
3127 unsigned SPOldSize = SpeculatablePHIs.size();
3128 unsigned SSOldSize = SpeculatableSelects.size();
3129 unsigned NumUses = 0;
3131 AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
3132 EndOffset, IsVectorPromotable,
3133 IsIntegerPromotable);
3134 bool Promotable = true;
3135 for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
3136 SUE = SplitUses.end();
3137 SUI != SUE; ++SUI) {
3138 DEBUG(dbgs() << " rewriting split ");
3139 DEBUG(S.printSlice(dbgs(), *SUI, ""));
3140 Promotable &= Rewriter.visit(*SUI);
3143 for (AllocaSlices::iterator I = B; I != E; ++I) {
3144 DEBUG(dbgs() << " rewriting ");
3145 DEBUG(S.printSlice(dbgs(), I, ""));
3146 Promotable &= Rewriter.visit(I);
3150 NumAllocaPartitionUses += NumUses;
3151 MaxUsesPerAllocaPartition =
3152 std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3154 if (Promotable && !Rewriter.isUsedByRewrittenSpeculatableInstructions()) {
3155 DEBUG(dbgs() << " and queuing for promotion\n");
3156 PromotableAllocas.push_back(NewAI);
3157 } else if (NewAI != &AI ||
3159 Rewriter.isUsedByRewrittenSpeculatableInstructions())) {
3160 // If we can't promote the alloca, iterate on it to check for new
3161 // refinements exposed by splitting the current alloca. Don't iterate on an
3162 // alloca which didn't actually change and didn't get promoted.
3164 // Alternatively, if we could promote the alloca but have speculatable
3165 // instructions then we will speculate them after finishing our processing
3166 // of the original alloca. Mark the new one for re-visiting in the next
3167 // iteration so the speculated operations can be rewritten.
3169 // FIXME: We should actually track whether the rewriter changed anything.
3170 Worklist.insert(NewAI);
3173 // Drop any post-promotion work items if promotion didn't happen.
3175 while (PostPromotionWorklist.size() > PPWOldSize)
3176 PostPromotionWorklist.pop_back();
3177 while (SpeculatablePHIs.size() > SPOldSize)
3178 SpeculatablePHIs.pop_back();
3179 while (SpeculatableSelects.size() > SSOldSize)
3180 SpeculatableSelects.pop_back();
3187 struct IsSliceEndLessOrEqualTo {
3188 uint64_t UpperBound;
3190 IsSliceEndLessOrEqualTo(uint64_t UpperBound) : UpperBound(UpperBound) {}
3192 bool operator()(const AllocaSlices::iterator &I) {
3193 return I->endOffset() <= UpperBound;
3199 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3200 uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3201 if (Offset >= MaxSplitUseEndOffset) {
3203 MaxSplitUseEndOffset = 0;
3207 size_t SplitUsesOldSize = SplitUses.size();
3208 SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
3209 IsSliceEndLessOrEqualTo(Offset)),
3211 if (SplitUsesOldSize == SplitUses.size())
3214 // Recompute the max. While this is linear, so is remove_if.
3215 MaxSplitUseEndOffset = 0;
3216 for (SmallVectorImpl<AllocaSlices::iterator>::iterator
3217 SUI = SplitUses.begin(),
3218 SUE = SplitUses.end();
3220 MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
3223 /// \brief Walks the slices of an alloca and form partitions based on them,
3224 /// rewriting each of their uses.
3225 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
3226 if (S.begin() == S.end())
3229 unsigned NumPartitions = 0;
3230 bool Changed = false;
3231 SmallVector<AllocaSlices::iterator, 4> SplitUses;
3232 uint64_t MaxSplitUseEndOffset = 0;
3234 uint64_t BeginOffset = S.begin()->beginOffset();
3236 for (AllocaSlices::iterator SI = S.begin(), SJ = llvm::next(SI), SE = S.end();
3237 SI != SE; SI = SJ) {
3238 uint64_t MaxEndOffset = SI->endOffset();
3240 if (!SI->isSplittable()) {
3241 // When we're forming an unsplittable region, it must always start at the
3242 // first slice and will extend through its end.
3243 assert(BeginOffset == SI->beginOffset());
3245 // Form a partition including all of the overlapping slices with this
3246 // unsplittable slice.
3247 while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3248 if (!SJ->isSplittable())
3249 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3253 assert(SI->isSplittable()); // Established above.
3255 // Collect all of the overlapping splittable slices.
3256 while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3257 SJ->isSplittable()) {
3258 MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3262 // Back up MaxEndOffset and SJ if we ended the span early when
3263 // encountering an unsplittable slice.
3264 if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3265 assert(!SJ->isSplittable());
3266 MaxEndOffset = SJ->beginOffset();
3270 // Check if we have managed to move the end offset forward yet. If so,
3271 // we'll have to rewrite uses and erase old split uses.
3272 if (BeginOffset < MaxEndOffset) {
3273 // Rewrite a sequence of overlapping slices.
3275 rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
3278 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3281 // Accumulate all the splittable slices from the [SI,SJ) region which
3282 // overlap going forward.
3283 for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3284 if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3285 SplitUses.push_back(SK);
3286 MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3289 // If we're already at the end and we have no split uses, we're done.
3290 if (SJ == SE && SplitUses.empty())
3293 // If we have no split uses or no gap in offsets, we're ready to move to
3295 if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3296 BeginOffset = SJ->beginOffset();
3300 // Even if we have split slices, if the next slice is splittable and the
3301 // split slices reach it, we can simply set up the beginning offset of the
3302 // next iteration to bridge between them.
3303 if (SJ != SE && SJ->isSplittable() &&
3304 MaxSplitUseEndOffset > SJ->beginOffset()) {
3305 BeginOffset = MaxEndOffset;
3309 // Otherwise, we have a tail of split slices. Rewrite them with an empty
3311 uint64_t PostSplitEndOffset =
3312 SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3314 Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
3319 break; // Skip the rest, we don't need to do any cleanup.
3321 removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3322 PostSplitEndOffset);
3324 // Now just reset the begin offset for the next iteration.
3325 BeginOffset = SJ->beginOffset();
3328 NumAllocaPartitions += NumPartitions;
3329 MaxPartitionsPerAlloca =
3330 std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3335 /// \brief Analyze an alloca for SROA.
3337 /// This analyzes the alloca to ensure we can reason about it, builds
3338 /// the slices of the alloca, and then hands it off to be split and
3339 /// rewritten as needed.
3340 bool SROA::runOnAlloca(AllocaInst &AI) {
3341 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3342 ++NumAllocasAnalyzed;
3344 // Special case dead allocas, as they're trivial.
3345 if (AI.use_empty()) {
3346 AI.eraseFromParent();
3350 // Skip alloca forms that this analysis can't handle.
3351 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3352 DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3355 bool Changed = false;
3357 // First, split any FCA loads and stores touching this alloca to promote
3358 // better splitting and promotion opportunities.
3359 AggLoadStoreRewriter AggRewriter(*DL);
3360 Changed |= AggRewriter.rewrite(AI);
3362 // Build the slices using a recursive instruction-visiting builder.
3363 AllocaSlices S(*DL, AI);
3364 DEBUG(S.print(dbgs()));
3368 // Delete all the dead users of this alloca before splitting and rewriting it.
3369 for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
3370 DE = S.dead_user_end();
3373 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3374 DeadInsts.insert(*DI);
3376 for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
3377 DE = S.dead_op_end();
3380 // Clobber the use with an undef value.
3381 **DO = UndefValue::get(OldV->getType());
3382 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3383 if (isInstructionTriviallyDead(OldI)) {
3385 DeadInsts.insert(OldI);
3389 // No slices to split. Leave the dead alloca for a later pass to clean up.
3390 if (S.begin() == S.end())
3393 // Trivially promotable, don't go through the splitting and rewriting.
3394 if (S.isAllocaPromotable()) {
3395 DEBUG(dbgs() << " Directly promoting alloca: " << AI << "\n");
3396 PromotableAllocas.push_back(&AI);
3398 // Walk through the stored values quickly here to handle directly
3399 // promotable allocas that require iterating on other allocas.
3400 ArrayRef<Value *> StoredValues = S.getStoredValues();
3401 for (ArrayRef<Value *>::iterator SVI = StoredValues.begin(),
3402 SVE = StoredValues.end();
3404 if ((*SVI)->getType()->isPointerTy())
3405 if (AllocaInst *SAI =
3406 dyn_cast<AllocaInst>((*SVI)->stripInBoundsOffsets()))
3407 PostPromotionWorklist.insert(SAI);
3411 Changed |= splitAlloca(AI, S);
3413 DEBUG(dbgs() << " Speculating PHIs\n");
3414 while (!SpeculatablePHIs.empty())
3415 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3417 DEBUG(dbgs() << " Speculating Selects\n");
3418 while (!SpeculatableSelects.empty())
3419 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3424 /// \brief Delete the dead instructions accumulated in this run.
3426 /// Recursively deletes the dead instructions we've accumulated. This is done
3427 /// at the very end to maximize locality of the recursive delete and to
3428 /// minimize the problems of invalidated instruction pointers as such pointers
3429 /// are used heavily in the intermediate stages of the algorithm.
3431 /// We also record the alloca instructions deleted here so that they aren't
3432 /// subsequently handed to mem2reg to promote.
3433 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
3434 while (!DeadInsts.empty()) {
3435 Instruction *I = DeadInsts.pop_back_val();
3436 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3438 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3440 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3441 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3442 // Zero out the operand and see if it becomes trivially dead.
3444 if (isInstructionTriviallyDead(U))
3445 DeadInsts.insert(U);
3448 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3449 DeletedAllocas.insert(AI);
3452 I->eraseFromParent();
3456 static void enqueueUsersInWorklist(Instruction &I,
3457 SmallVectorImpl<Instruction *> &Worklist,
3458 SmallPtrSet<Instruction *, 8> &Visited) {
3459 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3461 if (Visited.insert(cast<Instruction>(*UI)))
3462 Worklist.push_back(cast<Instruction>(*UI));
3465 /// \brief Promote the allocas, using the best available technique.
3467 /// This attempts to promote whatever allocas have been identified as viable in
3468 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3469 /// If there is a domtree available, we attempt to promote using the full power
3470 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3471 /// based on the SSAUpdater utilities. This function returns whether any
3472 /// promotion occurred.
3473 bool SROA::promoteAllocas(Function &F) {
3474 if (PromotableAllocas.empty())
3477 NumPromoted += PromotableAllocas.size();
3479 if (DT && !ForceSSAUpdater) {
3480 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3481 PromoteMemToReg(PromotableAllocas, *DT, DL);
3482 PromotableAllocas.clear();
3486 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3488 DIBuilder DIB(*F.getParent());
3489 SmallVector<Instruction *, 64> Insts;
3491 // We need a worklist to walk the uses of each alloca.
3492 SmallVector<Instruction *, 8> Worklist;
3493 SmallPtrSet<Instruction *, 8> Visited;
3494 SmallVector<Instruction *, 32> DeadInsts;
3496 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3497 AllocaInst *AI = PromotableAllocas[Idx];
3502 enqueueUsersInWorklist(*AI, Worklist, Visited);
3504 while (!Worklist.empty()) {
3505 Instruction *I = Worklist.pop_back_val();
3507 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3508 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3509 // leading to them) here. Eventually it should use them to optimize the
3510 // scalar values produced.
3511 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3512 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3513 II->getIntrinsicID() == Intrinsic::lifetime_end);
3514 II->eraseFromParent();
3518 // Push the loads and stores we find onto the list. SROA will already
3519 // have validated that all loads and stores are viable candidates for
3521 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3522 assert(LI->getType() == AI->getAllocatedType());
3523 Insts.push_back(LI);
3526 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3527 assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3528 Insts.push_back(SI);
3532 // For everything else, we know that only no-op bitcasts and GEPs will
3533 // make it this far, just recurse through them and recall them for later
3535 DeadInsts.push_back(I);
3536 enqueueUsersInWorklist(*I, Worklist, Visited);
3538 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3539 while (!DeadInsts.empty())
3540 DeadInsts.pop_back_val()->eraseFromParent();
3541 AI->eraseFromParent();
3544 PromotableAllocas.clear();
3549 /// \brief A predicate to test whether an alloca belongs to a set.
3550 class IsAllocaInSet {
3551 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3555 typedef AllocaInst *argument_type;
3557 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3558 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
3562 bool SROA::runOnFunction(Function &F) {
3563 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3564 C = &F.getContext();
3565 DL = getAnalysisIfAvailable<DataLayout>();
3567 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3570 DT = getAnalysisIfAvailable<DominatorTree>();
3572 BasicBlock &EntryBB = F.getEntryBlock();
3573 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3575 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3576 Worklist.insert(AI);
3578 bool Changed = false;
3579 // A set of deleted alloca instruction pointers which should be removed from
3580 // the list of promotable allocas.
3581 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3584 while (!Worklist.empty()) {
3585 Changed |= runOnAlloca(*Worklist.pop_back_val());
3586 deleteDeadInstructions(DeletedAllocas);
3588 // Remove the deleted allocas from various lists so that we don't try to
3589 // continue processing them.
3590 if (!DeletedAllocas.empty()) {
3591 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3592 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3593 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3594 PromotableAllocas.end(),
3595 IsAllocaInSet(DeletedAllocas)),
3596 PromotableAllocas.end());
3597 DeletedAllocas.clear();
3601 Changed |= promoteAllocas(F);
3603 Worklist = PostPromotionWorklist;
3604 PostPromotionWorklist.clear();
3605 } while (!Worklist.empty());
3610 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3611 if (RequiresDomTree)
3612 AU.addRequired<DominatorTree>();
3613 AU.setPreservesCFG();