LLVM API Documentation

SROA.cpp
Go to the documentation of this file.
00001 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 /// This transformation implements the well known scalar replacement of
00011 /// aggregates transformation. It tries to identify promotable elements of an
00012 /// aggregate alloca, and promote them to registers. It will also try to
00013 /// convert uses of an element (or set of elements) of an alloca into a vector
00014 /// or bitfield-style integer scalar if appropriate.
00015 ///
00016 /// It works to do this with minimal slicing of the alloca so that regions
00017 /// which are merely transferred in and out of external memory remain unchanged
00018 /// and are not decomposed to scalar code.
00019 ///
00020 /// Because this also performs alloca promotion, it can be thought of as also
00021 /// serving the purpose of SSA formation. The algorithm iterates on the
00022 /// function until all opportunities for promotion have been realized.
00023 ///
00024 //===----------------------------------------------------------------------===//
00025 
00026 #include "llvm/Transforms/Scalar.h"
00027 #include "llvm/ADT/STLExtras.h"
00028 #include "llvm/ADT/SetVector.h"
00029 #include "llvm/ADT/SmallVector.h"
00030 #include "llvm/ADT/Statistic.h"
00031 #include "llvm/Analysis/Loads.h"
00032 #include "llvm/Analysis/PtrUseVisitor.h"
00033 #include "llvm/Analysis/ValueTracking.h"
00034 #include "llvm/IR/Constants.h"
00035 #include "llvm/IR/DIBuilder.h"
00036 #include "llvm/IR/DataLayout.h"
00037 #include "llvm/IR/DebugInfo.h"
00038 #include "llvm/IR/DerivedTypes.h"
00039 #include "llvm/IR/Dominators.h"
00040 #include "llvm/IR/Function.h"
00041 #include "llvm/IR/IRBuilder.h"
00042 #include "llvm/IR/InstVisitor.h"
00043 #include "llvm/IR/Instructions.h"
00044 #include "llvm/IR/IntrinsicInst.h"
00045 #include "llvm/IR/LLVMContext.h"
00046 #include "llvm/IR/Operator.h"
00047 #include "llvm/Pass.h"
00048 #include "llvm/Support/CommandLine.h"
00049 #include "llvm/Support/Compiler.h"
00050 #include "llvm/Support/Debug.h"
00051 #include "llvm/Support/ErrorHandling.h"
00052 #include "llvm/Support/MathExtras.h"
00053 #include "llvm/Support/TimeValue.h"
00054 #include "llvm/Support/raw_ostream.h"
00055 #include "llvm/Transforms/Utils/Local.h"
00056 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00057 #include "llvm/Transforms/Utils/SSAUpdater.h"
00058 
00059 #if __cplusplus >= 201103L && !defined(NDEBUG)
00060 // We only use this for a debug check in C++11
00061 #include <random>
00062 #endif
00063 
00064 using namespace llvm;
00065 
00066 #define DEBUG_TYPE "sroa"
00067 
00068 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
00069 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
00070 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
00071 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
00072 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
00073 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
00074 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
00075 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
00076 STATISTIC(NumDeleted, "Number of instructions deleted");
00077 STATISTIC(NumVectorized, "Number of vectorized aggregates");
00078 
00079 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
00080 /// forming SSA values through the SSAUpdater infrastructure.
00081 static cl::opt<bool>
00082 ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
00083 
00084 /// Hidden option to enable randomly shuffling the slices to help uncover
00085 /// instability in their order.
00086 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
00087                                              cl::init(false), cl::Hidden);
00088 
00089 /// Hidden option to experiment with completely strict handling of inbounds
00090 /// GEPs.
00091 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds",
00092                                         cl::init(false), cl::Hidden);
00093 
00094 namespace {
00095 /// \brief A custom IRBuilder inserter which prefixes all names if they are
00096 /// preserved.
00097 template <bool preserveNames = true>
00098 class IRBuilderPrefixedInserter :
00099     public IRBuilderDefaultInserter<preserveNames> {
00100   std::string Prefix;
00101 
00102 public:
00103   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
00104 
00105 protected:
00106   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
00107                     BasicBlock::iterator InsertPt) const {
00108     IRBuilderDefaultInserter<preserveNames>::InsertHelper(
00109         I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
00110   }
00111 };
00112 
00113 // Specialization for not preserving the name is trivial.
00114 template <>
00115 class IRBuilderPrefixedInserter<false> :
00116     public IRBuilderDefaultInserter<false> {
00117 public:
00118   void SetNamePrefix(const Twine &P) {}
00119 };
00120 
00121 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
00122 #ifndef NDEBUG
00123 typedef llvm::IRBuilder<true, ConstantFolder,
00124                         IRBuilderPrefixedInserter<true> > IRBuilderTy;
00125 #else
00126 typedef llvm::IRBuilder<false, ConstantFolder,
00127                         IRBuilderPrefixedInserter<false> > IRBuilderTy;
00128 #endif
00129 }
00130 
00131 namespace {
00132 /// \brief A used slice of an alloca.
00133 ///
00134 /// This structure represents a slice of an alloca used by some instruction. It
00135 /// stores both the begin and end offsets of this use, a pointer to the use
00136 /// itself, and a flag indicating whether we can classify the use as splittable
00137 /// or not when forming partitions of the alloca.
00138 class Slice {
00139   /// \brief The beginning offset of the range.
00140   uint64_t BeginOffset;
00141 
00142   /// \brief The ending offset, not included in the range.
00143   uint64_t EndOffset;
00144 
00145   /// \brief Storage for both the use of this slice and whether it can be
00146   /// split.
00147   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
00148 
00149 public:
00150   Slice() : BeginOffset(), EndOffset() {}
00151   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
00152       : BeginOffset(BeginOffset), EndOffset(EndOffset),
00153         UseAndIsSplittable(U, IsSplittable) {}
00154 
00155   uint64_t beginOffset() const { return BeginOffset; }
00156   uint64_t endOffset() const { return EndOffset; }
00157 
00158   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
00159   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
00160 
00161   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
00162 
00163   bool isDead() const { return getUse() == nullptr; }
00164   void kill() { UseAndIsSplittable.setPointer(nullptr); }
00165 
00166   /// \brief Support for ordering ranges.
00167   ///
00168   /// This provides an ordering over ranges such that start offsets are
00169   /// always increasing, and within equal start offsets, the end offsets are
00170   /// decreasing. Thus the spanning range comes first in a cluster with the
00171   /// same start position.
00172   bool operator<(const Slice &RHS) const {
00173     if (beginOffset() < RHS.beginOffset()) return true;
00174     if (beginOffset() > RHS.beginOffset()) return false;
00175     if (isSplittable() != RHS.isSplittable()) return !isSplittable();
00176     if (endOffset() > RHS.endOffset()) return true;
00177     return false;
00178   }
00179 
00180   /// \brief Support comparison with a single offset to allow binary searches.
00181   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
00182                                               uint64_t RHSOffset) {
00183     return LHS.beginOffset() < RHSOffset;
00184   }
00185   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
00186                                               const Slice &RHS) {
00187     return LHSOffset < RHS.beginOffset();
00188   }
00189 
00190   bool operator==(const Slice &RHS) const {
00191     return isSplittable() == RHS.isSplittable() &&
00192            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
00193   }
00194   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
00195 };
00196 } // end anonymous namespace
00197 
00198 namespace llvm {
00199 template <typename T> struct isPodLike;
00200 template <> struct isPodLike<Slice> {
00201    static const bool value = true;
00202 };
00203 }
00204 
00205 namespace {
00206 /// \brief Representation of the alloca slices.
00207 ///
00208 /// This class represents the slices of an alloca which are formed by its
00209 /// various uses. If a pointer escapes, we can't fully build a representation
00210 /// for the slices used and we reflect that in this structure. The uses are
00211 /// stored, sorted by increasing beginning offset and with unsplittable slices
00212 /// starting at a particular offset before splittable slices.
00213 class AllocaSlices {
00214 public:
00215   /// \brief Construct the slices of a particular alloca.
00216   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
00217 
00218   /// \brief Test whether a pointer to the allocation escapes our analysis.
00219   ///
00220   /// If this is true, the slices are never fully built and should be
00221   /// ignored.
00222   bool isEscaped() const { return PointerEscapingInstr; }
00223 
00224   /// \brief Support for iterating over the slices.
00225   /// @{
00226   typedef SmallVectorImpl<Slice>::iterator iterator;
00227   iterator begin() { return Slices.begin(); }
00228   iterator end() { return Slices.end(); }
00229 
00230   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
00231   const_iterator begin() const { return Slices.begin(); }
00232   const_iterator end() const { return Slices.end(); }
00233   /// @}
00234 
00235   /// \brief Allow iterating the dead users for this alloca.
00236   ///
00237   /// These are instructions which will never actually use the alloca as they
00238   /// are outside the allocated range. They are safe to replace with undef and
00239   /// delete.
00240   /// @{
00241   typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
00242   dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
00243   dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
00244   /// @}
00245 
00246   /// \brief Allow iterating the dead expressions referring to this alloca.
00247   ///
00248   /// These are operands which have cannot actually be used to refer to the
00249   /// alloca as they are outside its range and the user doesn't correct for
00250   /// that. These mostly consist of PHI node inputs and the like which we just
00251   /// need to replace with undef.
00252   /// @{
00253   typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
00254   dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
00255   dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
00256   /// @}
00257 
00258 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00259   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
00260   void printSlice(raw_ostream &OS, const_iterator I,
00261                   StringRef Indent = "  ") const;
00262   void printUse(raw_ostream &OS, const_iterator I,
00263                 StringRef Indent = "  ") const;
00264   void print(raw_ostream &OS) const;
00265   void dump(const_iterator I) const;
00266   void dump() const;
00267 #endif
00268 
00269 private:
00270   template <typename DerivedT, typename RetT = void> class BuilderBase;
00271   class SliceBuilder;
00272   friend class AllocaSlices::SliceBuilder;
00273 
00274 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00275   /// \brief Handle to alloca instruction to simplify method interfaces.
00276   AllocaInst &AI;
00277 #endif
00278 
00279   /// \brief The instruction responsible for this alloca not having a known set
00280   /// of slices.
00281   ///
00282   /// When an instruction (potentially) escapes the pointer to the alloca, we
00283   /// store a pointer to that here and abort trying to form slices of the
00284   /// alloca. This will be null if the alloca slices are analyzed successfully.
00285   Instruction *PointerEscapingInstr;
00286 
00287   /// \brief The slices of the alloca.
00288   ///
00289   /// We store a vector of the slices formed by uses of the alloca here. This
00290   /// vector is sorted by increasing begin offset, and then the unsplittable
00291   /// slices before the splittable ones. See the Slice inner class for more
00292   /// details.
00293   SmallVector<Slice, 8> Slices;
00294 
00295   /// \brief Instructions which will become dead if we rewrite the alloca.
00296   ///
00297   /// Note that these are not separated by slice. This is because we expect an
00298   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
00299   /// all these instructions can simply be removed and replaced with undef as
00300   /// they come from outside of the allocated space.
00301   SmallVector<Instruction *, 8> DeadUsers;
00302 
00303   /// \brief Operands which will become dead if we rewrite the alloca.
00304   ///
00305   /// These are operands that in their particular use can be replaced with
00306   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
00307   /// to PHI nodes and the like. They aren't entirely dead (there might be
00308   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
00309   /// want to swap this particular input for undef to simplify the use lists of
00310   /// the alloca.
00311   SmallVector<Use *, 8> DeadOperands;
00312 };
00313 }
00314 
00315 static Value *foldSelectInst(SelectInst &SI) {
00316   // If the condition being selected on is a constant or the same value is
00317   // being selected between, fold the select. Yes this does (rarely) happen
00318   // early on.
00319   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
00320     return SI.getOperand(1+CI->isZero());
00321   if (SI.getOperand(1) == SI.getOperand(2))
00322     return SI.getOperand(1);
00323 
00324   return nullptr;
00325 }
00326 
00327 /// \brief Builder for the alloca slices.
00328 ///
00329 /// This class builds a set of alloca slices by recursively visiting the uses
00330 /// of an alloca and making a slice for each load and store at each offset.
00331 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
00332   friend class PtrUseVisitor<SliceBuilder>;
00333   friend class InstVisitor<SliceBuilder>;
00334   typedef PtrUseVisitor<SliceBuilder> Base;
00335 
00336   const uint64_t AllocSize;
00337   AllocaSlices &S;
00338 
00339   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
00340   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
00341 
00342   /// \brief Set to de-duplicate dead instructions found in the use walk.
00343   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
00344 
00345 public:
00346   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &S)
00347       : PtrUseVisitor<SliceBuilder>(DL),
00348         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), S(S) {}
00349 
00350 private:
00351   void markAsDead(Instruction &I) {
00352     if (VisitedDeadInsts.insert(&I))
00353       S.DeadUsers.push_back(&I);
00354   }
00355 
00356   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
00357                  bool IsSplittable = false) {
00358     // Completely skip uses which have a zero size or start either before or
00359     // past the end of the allocation.
00360     if (Size == 0 || Offset.uge(AllocSize)) {
00361       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
00362                    << " which has zero size or starts outside of the "
00363                    << AllocSize << " byte alloca:\n"
00364                    << "    alloca: " << S.AI << "\n"
00365                    << "       use: " << I << "\n");
00366       return markAsDead(I);
00367     }
00368 
00369     uint64_t BeginOffset = Offset.getZExtValue();
00370     uint64_t EndOffset = BeginOffset + Size;
00371 
00372     // Clamp the end offset to the end of the allocation. Note that this is
00373     // formulated to handle even the case where "BeginOffset + Size" overflows.
00374     // This may appear superficially to be something we could ignore entirely,
00375     // but that is not so! There may be widened loads or PHI-node uses where
00376     // some instructions are dead but not others. We can't completely ignore
00377     // them, and so have to record at least the information here.
00378     assert(AllocSize >= BeginOffset); // Established above.
00379     if (Size > AllocSize - BeginOffset) {
00380       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
00381                    << " to remain within the " << AllocSize << " byte alloca:\n"
00382                    << "    alloca: " << S.AI << "\n"
00383                    << "       use: " << I << "\n");
00384       EndOffset = AllocSize;
00385     }
00386 
00387     S.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
00388   }
00389 
00390   void visitBitCastInst(BitCastInst &BC) {
00391     if (BC.use_empty())
00392       return markAsDead(BC);
00393 
00394     return Base::visitBitCastInst(BC);
00395   }
00396 
00397   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
00398     if (GEPI.use_empty())
00399       return markAsDead(GEPI);
00400 
00401     if (SROAStrictInbounds && GEPI.isInBounds()) {
00402       // FIXME: This is a manually un-factored variant of the basic code inside
00403       // of GEPs with checking of the inbounds invariant specified in the
00404       // langref in a very strict sense. If we ever want to enable
00405       // SROAStrictInbounds, this code should be factored cleanly into
00406       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
00407       // by writing out the code here where we have tho underlying allocation
00408       // size readily available.
00409       APInt GEPOffset = Offset;
00410       for (gep_type_iterator GTI = gep_type_begin(GEPI),
00411                              GTE = gep_type_end(GEPI);
00412            GTI != GTE; ++GTI) {
00413         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
00414         if (!OpC)
00415           break;
00416 
00417         // Handle a struct index, which adds its field offset to the pointer.
00418         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00419           unsigned ElementIdx = OpC->getZExtValue();
00420           const StructLayout *SL = DL.getStructLayout(STy);
00421           GEPOffset +=
00422               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
00423         } else {
00424           // For array or vector indices, scale the index by the size of the type.
00425           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
00426           GEPOffset += Index * APInt(Offset.getBitWidth(),
00427                                      DL.getTypeAllocSize(GTI.getIndexedType()));
00428         }
00429 
00430         // If this index has computed an intermediate pointer which is not
00431         // inbounds, then the result of the GEP is a poison value and we can
00432         // delete it and all uses.
00433         if (GEPOffset.ugt(AllocSize))
00434           return markAsDead(GEPI);
00435       }
00436     }
00437 
00438     return Base::visitGetElementPtrInst(GEPI);
00439   }
00440 
00441   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
00442                          uint64_t Size, bool IsVolatile) {
00443     // We allow splitting of loads and stores where the type is an integer type
00444     // and cover the entire alloca. This prevents us from splitting over
00445     // eagerly.
00446     // FIXME: In the great blue eventually, we should eagerly split all integer
00447     // loads and stores, and then have a separate step that merges adjacent
00448     // alloca partitions into a single partition suitable for integer widening.
00449     // Or we should skip the merge step and rely on GVN and other passes to
00450     // merge adjacent loads and stores that survive mem2reg.
00451     bool IsSplittable =
00452         Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
00453 
00454     insertUse(I, Offset, Size, IsSplittable);
00455   }
00456 
00457   void visitLoadInst(LoadInst &LI) {
00458     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
00459            "All simple FCA loads should have been pre-split");
00460 
00461     if (!IsOffsetKnown)
00462       return PI.setAborted(&LI);
00463 
00464     uint64_t Size = DL.getTypeStoreSize(LI.getType());
00465     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
00466   }
00467 
00468   void visitStoreInst(StoreInst &SI) {
00469     Value *ValOp = SI.getValueOperand();
00470     if (ValOp == *U)
00471       return PI.setEscapedAndAborted(&SI);
00472     if (!IsOffsetKnown)
00473       return PI.setAborted(&SI);
00474 
00475     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
00476 
00477     // If this memory access can be shown to *statically* extend outside the
00478     // bounds of of the allocation, it's behavior is undefined, so simply
00479     // ignore it. Note that this is more strict than the generic clamping
00480     // behavior of insertUse. We also try to handle cases which might run the
00481     // risk of overflow.
00482     // FIXME: We should instead consider the pointer to have escaped if this
00483     // function is being instrumented for addressing bugs or race conditions.
00484     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
00485       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
00486                    << " which extends past the end of the " << AllocSize
00487                    << " byte alloca:\n"
00488                    << "    alloca: " << S.AI << "\n"
00489                    << "       use: " << SI << "\n");
00490       return markAsDead(SI);
00491     }
00492 
00493     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
00494            "All simple FCA stores should have been pre-split");
00495     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
00496   }
00497 
00498 
00499   void visitMemSetInst(MemSetInst &II) {
00500     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
00501     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00502     if ((Length && Length->getValue() == 0) ||
00503         (IsOffsetKnown && Offset.uge(AllocSize)))
00504       // Zero-length mem transfer intrinsics can be ignored entirely.
00505       return markAsDead(II);
00506 
00507     if (!IsOffsetKnown)
00508       return PI.setAborted(&II);
00509 
00510     insertUse(II, Offset,
00511               Length ? Length->getLimitedValue()
00512                      : AllocSize - Offset.getLimitedValue(),
00513               (bool)Length);
00514   }
00515 
00516   void visitMemTransferInst(MemTransferInst &II) {
00517     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
00518     if (Length && Length->getValue() == 0)
00519       // Zero-length mem transfer intrinsics can be ignored entirely.
00520       return markAsDead(II);
00521 
00522     // Because we can visit these intrinsics twice, also check to see if the
00523     // first time marked this instruction as dead. If so, skip it.
00524     if (VisitedDeadInsts.count(&II))
00525       return;
00526 
00527     if (!IsOffsetKnown)
00528       return PI.setAborted(&II);
00529 
00530     // This side of the transfer is completely out-of-bounds, and so we can
00531     // nuke the entire transfer. However, we also need to nuke the other side
00532     // if already added to our partitions.
00533     // FIXME: Yet another place we really should bypass this when
00534     // instrumenting for ASan.
00535     if (Offset.uge(AllocSize)) {
00536       SmallDenseMap<Instruction *, unsigned>::iterator MTPI = MemTransferSliceMap.find(&II);
00537       if (MTPI != MemTransferSliceMap.end())
00538         S.Slices[MTPI->second].kill();
00539       return markAsDead(II);
00540     }
00541 
00542     uint64_t RawOffset = Offset.getLimitedValue();
00543     uint64_t Size = Length ? Length->getLimitedValue()
00544                            : AllocSize - RawOffset;
00545 
00546     // Check for the special case where the same exact value is used for both
00547     // source and dest.
00548     if (*U == II.getRawDest() && *U == II.getRawSource()) {
00549       // For non-volatile transfers this is a no-op.
00550       if (!II.isVolatile())
00551         return markAsDead(II);
00552 
00553       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
00554     }
00555 
00556     // If we have seen both source and destination for a mem transfer, then
00557     // they both point to the same alloca.
00558     bool Inserted;
00559     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
00560     std::tie(MTPI, Inserted) =
00561         MemTransferSliceMap.insert(std::make_pair(&II, S.Slices.size()));
00562     unsigned PrevIdx = MTPI->second;
00563     if (!Inserted) {
00564       Slice &PrevP = S.Slices[PrevIdx];
00565 
00566       // Check if the begin offsets match and this is a non-volatile transfer.
00567       // In that case, we can completely elide the transfer.
00568       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
00569         PrevP.kill();
00570         return markAsDead(II);
00571       }
00572 
00573       // Otherwise we have an offset transfer within the same alloca. We can't
00574       // split those.
00575       PrevP.makeUnsplittable();
00576     }
00577 
00578     // Insert the use now that we've fixed up the splittable nature.
00579     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
00580 
00581     // Check that we ended up with a valid index in the map.
00582     assert(S.Slices[PrevIdx].getUse()->getUser() == &II &&
00583            "Map index doesn't point back to a slice with this user.");
00584   }
00585 
00586   // Disable SRoA for any intrinsics except for lifetime invariants.
00587   // FIXME: What about debug intrinsics? This matches old behavior, but
00588   // doesn't make sense.
00589   void visitIntrinsicInst(IntrinsicInst &II) {
00590     if (!IsOffsetKnown)
00591       return PI.setAborted(&II);
00592 
00593     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
00594         II.getIntrinsicID() == Intrinsic::lifetime_end) {
00595       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
00596       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
00597                                Length->getLimitedValue());
00598       insertUse(II, Offset, Size, true);
00599       return;
00600     }
00601 
00602     Base::visitIntrinsicInst(II);
00603   }
00604 
00605   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
00606     // We consider any PHI or select that results in a direct load or store of
00607     // the same offset to be a viable use for slicing purposes. These uses
00608     // are considered unsplittable and the size is the maximum loaded or stored
00609     // size.
00610     SmallPtrSet<Instruction *, 4> Visited;
00611     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
00612     Visited.insert(Root);
00613     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
00614     // If there are no loads or stores, the access is dead. We mark that as
00615     // a size zero access.
00616     Size = 0;
00617     do {
00618       Instruction *I, *UsedI;
00619       std::tie(UsedI, I) = Uses.pop_back_val();
00620 
00621       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00622         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
00623         continue;
00624       }
00625       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00626         Value *Op = SI->getOperand(0);
00627         if (Op == UsedI)
00628           return SI;
00629         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
00630         continue;
00631       }
00632 
00633       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00634         if (!GEP->hasAllZeroIndices())
00635           return GEP;
00636       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
00637                  !isa<SelectInst>(I)) {
00638         return I;
00639       }
00640 
00641       for (User *U : I->users())
00642         if (Visited.insert(cast<Instruction>(U)))
00643           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
00644     } while (!Uses.empty());
00645 
00646     return nullptr;
00647   }
00648 
00649   void visitPHINode(PHINode &PN) {
00650     if (PN.use_empty())
00651       return markAsDead(PN);
00652     if (!IsOffsetKnown)
00653       return PI.setAborted(&PN);
00654 
00655     // See if we already have computed info on this node.
00656     uint64_t &PHISize = PHIOrSelectSizes[&PN];
00657     if (!PHISize) {
00658       // This is a new PHI node, check for an unsafe use of the PHI node.
00659       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHISize))
00660         return PI.setAborted(UnsafeI);
00661     }
00662 
00663     // For PHI and select operands outside the alloca, we can't nuke the entire
00664     // phi or select -- the other side might still be relevant, so we special
00665     // case them here and use a separate structure to track the operands
00666     // themselves which should be replaced with undef.
00667     // FIXME: This should instead be escaped in the event we're instrumenting
00668     // for address sanitization.
00669     if (Offset.uge(AllocSize)) {
00670       S.DeadOperands.push_back(U);
00671       return;
00672     }
00673 
00674     insertUse(PN, Offset, PHISize);
00675   }
00676 
00677   void visitSelectInst(SelectInst &SI) {
00678     if (SI.use_empty())
00679       return markAsDead(SI);
00680     if (Value *Result = foldSelectInst(SI)) {
00681       if (Result == *U)
00682         // If the result of the constant fold will be the pointer, recurse
00683         // through the select as if we had RAUW'ed it.
00684         enqueueUsers(SI);
00685       else
00686         // Otherwise the operand to the select is dead, and we can replace it
00687         // with undef.
00688         S.DeadOperands.push_back(U);
00689 
00690       return;
00691     }
00692     if (!IsOffsetKnown)
00693       return PI.setAborted(&SI);
00694 
00695     // See if we already have computed info on this node.
00696     uint64_t &SelectSize = PHIOrSelectSizes[&SI];
00697     if (!SelectSize) {
00698       // This is a new Select, check for an unsafe use of it.
00699       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectSize))
00700         return PI.setAborted(UnsafeI);
00701     }
00702 
00703     // For PHI and select operands outside the alloca, we can't nuke the entire
00704     // phi or select -- the other side might still be relevant, so we special
00705     // case them here and use a separate structure to track the operands
00706     // themselves which should be replaced with undef.
00707     // FIXME: This should instead be escaped in the event we're instrumenting
00708     // for address sanitization.
00709     if (Offset.uge(AllocSize)) {
00710       S.DeadOperands.push_back(U);
00711       return;
00712     }
00713 
00714     insertUse(SI, Offset, SelectSize);
00715   }
00716 
00717   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
00718   void visitInstruction(Instruction &I) {
00719     PI.setAborted(&I);
00720   }
00721 };
00722 
00723 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
00724     :
00725 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00726       AI(AI),
00727 #endif
00728       PointerEscapingInstr(nullptr) {
00729   SliceBuilder PB(DL, AI, *this);
00730   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
00731   if (PtrI.isEscaped() || PtrI.isAborted()) {
00732     // FIXME: We should sink the escape vs. abort info into the caller nicely,
00733     // possibly by just storing the PtrInfo in the AllocaSlices.
00734     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
00735                                                   : PtrI.getAbortingInst();
00736     assert(PointerEscapingInstr && "Did not track a bad instruction");
00737     return;
00738   }
00739 
00740   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
00741                               std::mem_fun_ref(&Slice::isDead)),
00742                Slices.end());
00743 
00744 #if __cplusplus >= 201103L && !defined(NDEBUG)
00745   if (SROARandomShuffleSlices) {
00746     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
00747     std::shuffle(Slices.begin(), Slices.end(), MT);
00748   }
00749 #endif
00750 
00751   // Sort the uses. This arranges for the offsets to be in ascending order,
00752   // and the sizes to be in descending order.
00753   std::sort(Slices.begin(), Slices.end());
00754 }
00755 
00756 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00757 
00758 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
00759                          StringRef Indent) const {
00760   printSlice(OS, I, Indent);
00761   printUse(OS, I, Indent);
00762 }
00763 
00764 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
00765                               StringRef Indent) const {
00766   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
00767      << " slice #" << (I - begin())
00768      << (I->isSplittable() ? " (splittable)" : "") << "\n";
00769 }
00770 
00771 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
00772                             StringRef Indent) const {
00773   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
00774 }
00775 
00776 void AllocaSlices::print(raw_ostream &OS) const {
00777   if (PointerEscapingInstr) {
00778     OS << "Can't analyze slices for alloca: " << AI << "\n"
00779        << "  A pointer to this alloca escaped by:\n"
00780        << "  " << *PointerEscapingInstr << "\n";
00781     return;
00782   }
00783 
00784   OS << "Slices of alloca: " << AI << "\n";
00785   for (const_iterator I = begin(), E = end(); I != E; ++I)
00786     print(OS, I);
00787 }
00788 
00789 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
00790   print(dbgs(), I);
00791 }
00792 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
00793 
00794 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00795 
00796 namespace {
00797 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
00798 ///
00799 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
00800 /// the loads and stores of an alloca instruction, as well as updating its
00801 /// debug information. This is used when a domtree is unavailable and thus
00802 /// mem2reg in its full form can't be used to handle promotion of allocas to
00803 /// scalar values.
00804 class AllocaPromoter : public LoadAndStorePromoter {
00805   AllocaInst &AI;
00806   DIBuilder &DIB;
00807 
00808   SmallVector<DbgDeclareInst *, 4> DDIs;
00809   SmallVector<DbgValueInst *, 4> DVIs;
00810 
00811 public:
00812   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
00813                  AllocaInst &AI, DIBuilder &DIB)
00814       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
00815 
00816   void run(const SmallVectorImpl<Instruction*> &Insts) {
00817     // Retain the debug information attached to the alloca for use when
00818     // rewriting loads and stores.
00819     if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
00820       for (User *U : DebugNode->users())
00821         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
00822           DDIs.push_back(DDI);
00823         else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
00824           DVIs.push_back(DVI);
00825     }
00826 
00827     LoadAndStorePromoter::run(Insts);
00828 
00829     // While we have the debug information, clear it off of the alloca. The
00830     // caller takes care of deleting the alloca.
00831     while (!DDIs.empty())
00832       DDIs.pop_back_val()->eraseFromParent();
00833     while (!DVIs.empty())
00834       DVIs.pop_back_val()->eraseFromParent();
00835   }
00836 
00837   bool isInstInList(Instruction *I,
00838                     const SmallVectorImpl<Instruction*> &Insts) const override {
00839     Value *Ptr;
00840     if (LoadInst *LI = dyn_cast<LoadInst>(I))
00841       Ptr = LI->getOperand(0);
00842     else
00843       Ptr = cast<StoreInst>(I)->getPointerOperand();
00844 
00845     // Only used to detect cycles, which will be rare and quickly found as
00846     // we're walking up a chain of defs rather than down through uses.
00847     SmallPtrSet<Value *, 4> Visited;
00848 
00849     do {
00850       if (Ptr == &AI)
00851         return true;
00852 
00853       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
00854         Ptr = BCI->getOperand(0);
00855       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
00856         Ptr = GEPI->getPointerOperand();
00857       else
00858         return false;
00859 
00860     } while (Visited.insert(Ptr));
00861 
00862     return false;
00863   }
00864 
00865   void updateDebugInfo(Instruction *Inst) const override {
00866     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
00867            E = DDIs.end(); I != E; ++I) {
00868       DbgDeclareInst *DDI = *I;
00869       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00870         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
00871       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
00872         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
00873     }
00874     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
00875            E = DVIs.end(); I != E; ++I) {
00876       DbgValueInst *DVI = *I;
00877       Value *Arg = nullptr;
00878       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00879         // If an argument is zero extended then use argument directly. The ZExt
00880         // may be zapped by an optimization pass in future.
00881         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
00882           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
00883         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
00884           Arg = dyn_cast<Argument>(SExt->getOperand(0));
00885         if (!Arg)
00886           Arg = SI->getValueOperand();
00887       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00888         Arg = LI->getPointerOperand();
00889       } else {
00890         continue;
00891       }
00892       Instruction *DbgVal =
00893         DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
00894                                      Inst);
00895       DbgVal->setDebugLoc(DVI->getDebugLoc());
00896     }
00897   }
00898 };
00899 } // end anon namespace
00900 
00901 
00902 namespace {
00903 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
00904 ///
00905 /// This pass takes allocations which can be completely analyzed (that is, they
00906 /// don't escape) and tries to turn them into scalar SSA values. There are
00907 /// a few steps to this process.
00908 ///
00909 /// 1) It takes allocations of aggregates and analyzes the ways in which they
00910 ///    are used to try to split them into smaller allocations, ideally of
00911 ///    a single scalar data type. It will split up memcpy and memset accesses
00912 ///    as necessary and try to isolate individual scalar accesses.
00913 /// 2) It will transform accesses into forms which are suitable for SSA value
00914 ///    promotion. This can be replacing a memset with a scalar store of an
00915 ///    integer value, or it can involve speculating operations on a PHI or
00916 ///    select to be a PHI or select of the results.
00917 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
00918 ///    onto insert and extract operations on a vector value, and convert them to
00919 ///    this form. By doing so, it will enable promotion of vector aggregates to
00920 ///    SSA vector values.
00921 class SROA : public FunctionPass {
00922   const bool RequiresDomTree;
00923 
00924   LLVMContext *C;
00925   const DataLayout *DL;
00926   DominatorTree *DT;
00927 
00928   /// \brief Worklist of alloca instructions to simplify.
00929   ///
00930   /// Each alloca in the function is added to this. Each new alloca formed gets
00931   /// added to it as well to recursively simplify unless that alloca can be
00932   /// directly promoted. Finally, each time we rewrite a use of an alloca other
00933   /// the one being actively rewritten, we add it back onto the list if not
00934   /// already present to ensure it is re-visited.
00935   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
00936 
00937   /// \brief A collection of instructions to delete.
00938   /// We try to batch deletions to simplify code and make things a bit more
00939   /// efficient.
00940   SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
00941 
00942   /// \brief Post-promotion worklist.
00943   ///
00944   /// Sometimes we discover an alloca which has a high probability of becoming
00945   /// viable for SROA after a round of promotion takes place. In those cases,
00946   /// the alloca is enqueued here for re-processing.
00947   ///
00948   /// Note that we have to be very careful to clear allocas out of this list in
00949   /// the event they are deleted.
00950   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
00951 
00952   /// \brief A collection of alloca instructions we can directly promote.
00953   std::vector<AllocaInst *> PromotableAllocas;
00954 
00955   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
00956   ///
00957   /// All of these PHIs have been checked for the safety of speculation and by
00958   /// being speculated will allow promoting allocas currently in the promotable
00959   /// queue.
00960   SetVector<PHINode *, SmallVector<PHINode *, 2> > SpeculatablePHIs;
00961 
00962   /// \brief A worklist of select instructions to speculate prior to promoting
00963   /// allocas.
00964   ///
00965   /// All of these select instructions have been checked for the safety of
00966   /// speculation and by being speculated will allow promoting allocas
00967   /// currently in the promotable queue.
00968   SetVector<SelectInst *, SmallVector<SelectInst *, 2> > SpeculatableSelects;
00969 
00970 public:
00971   SROA(bool RequiresDomTree = true)
00972       : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
00973         C(nullptr), DL(nullptr), DT(nullptr) {
00974     initializeSROAPass(*PassRegistry::getPassRegistry());
00975   }
00976   bool runOnFunction(Function &F) override;
00977   void getAnalysisUsage(AnalysisUsage &AU) const override;
00978 
00979   const char *getPassName() const override { return "SROA"; }
00980   static char ID;
00981 
00982 private:
00983   friend class PHIOrSelectSpeculator;
00984   friend class AllocaSliceRewriter;
00985 
00986   bool rewritePartition(AllocaInst &AI, AllocaSlices &S,
00987                         AllocaSlices::iterator B, AllocaSlices::iterator E,
00988                         int64_t BeginOffset, int64_t EndOffset,
00989                         ArrayRef<AllocaSlices::iterator> SplitUses);
00990   bool splitAlloca(AllocaInst &AI, AllocaSlices &S);
00991   bool runOnAlloca(AllocaInst &AI);
00992   void clobberUse(Use &U);
00993   void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
00994   bool promoteAllocas(Function &F);
00995 };
00996 }
00997 
00998 char SROA::ID = 0;
00999 
01000 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
01001   return new SROA(RequiresDomTree);
01002 }
01003 
01004 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
01005                       false, false)
01006 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
01007 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
01008                     false, false)
01009 
01010 /// Walk the range of a partitioning looking for a common type to cover this
01011 /// sequence of slices.
01012 static Type *findCommonType(AllocaSlices::const_iterator B,
01013                             AllocaSlices::const_iterator E,
01014                             uint64_t EndOffset) {
01015   Type *Ty = nullptr;
01016   bool TyIsCommon = true;
01017   IntegerType *ITy = nullptr;
01018 
01019   // Note that we need to look at *every* alloca slice's Use to ensure we
01020   // always get consistent results regardless of the order of slices.
01021   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
01022     Use *U = I->getUse();
01023     if (isa<IntrinsicInst>(*U->getUser()))
01024       continue;
01025     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
01026       continue;
01027 
01028     Type *UserTy = nullptr;
01029     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01030       UserTy = LI->getType();
01031     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01032       UserTy = SI->getValueOperand()->getType();
01033     }
01034 
01035     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
01036       // If the type is larger than the partition, skip it. We only encounter
01037       // this for split integer operations where we want to use the type of the
01038       // entity causing the split. Also skip if the type is not a byte width
01039       // multiple.
01040       if (UserITy->getBitWidth() % 8 != 0 ||
01041           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
01042         continue;
01043 
01044       // Track the largest bitwidth integer type used in this way in case there
01045       // is no common type.
01046       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
01047         ITy = UserITy;
01048     }
01049 
01050     // To avoid depending on the order of slices, Ty and TyIsCommon must not
01051     // depend on types skipped above.
01052     if (!UserTy || (Ty && Ty != UserTy))
01053       TyIsCommon = false; // Give up on anything but an iN type.
01054     else
01055       Ty = UserTy;
01056   }
01057 
01058   return TyIsCommon ? Ty : ITy;
01059 }
01060 
01061 /// PHI instructions that use an alloca and are subsequently loaded can be
01062 /// rewritten to load both input pointers in the pred blocks and then PHI the
01063 /// results, allowing the load of the alloca to be promoted.
01064 /// From this:
01065 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01066 ///   %V = load i32* %P2
01067 /// to:
01068 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01069 ///   ...
01070 ///   %V2 = load i32* %Other
01071 ///   ...
01072 ///   %V = phi [i32 %V1, i32 %V2]
01073 ///
01074 /// We can do this to a select if its only uses are loads and if the operands
01075 /// to the select can be loaded unconditionally.
01076 ///
01077 /// FIXME: This should be hoisted into a generic utility, likely in
01078 /// Transforms/Util/Local.h
01079 static bool isSafePHIToSpeculate(PHINode &PN,
01080                                  const DataLayout *DL = nullptr) {
01081   // For now, we can only do this promotion if the load is in the same block
01082   // as the PHI, and if there are no stores between the phi and load.
01083   // TODO: Allow recursive phi users.
01084   // TODO: Allow stores.
01085   BasicBlock *BB = PN.getParent();
01086   unsigned MaxAlign = 0;
01087   bool HaveLoad = false;
01088   for (User *U : PN.users()) {
01089     LoadInst *LI = dyn_cast<LoadInst>(U);
01090     if (!LI || !LI->isSimple())
01091       return false;
01092 
01093     // For now we only allow loads in the same block as the PHI.  This is
01094     // a common case that happens when instcombine merges two loads through
01095     // a PHI.
01096     if (LI->getParent() != BB)
01097       return false;
01098 
01099     // Ensure that there are no instructions between the PHI and the load that
01100     // could store.
01101     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
01102       if (BBI->mayWriteToMemory())
01103         return false;
01104 
01105     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01106     HaveLoad = true;
01107   }
01108 
01109   if (!HaveLoad)
01110     return false;
01111 
01112   // We can only transform this if it is safe to push the loads into the
01113   // predecessor blocks. The only thing to watch out for is that we can't put
01114   // a possibly trapping load in the predecessor if it is a critical edge.
01115   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01116     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
01117     Value *InVal = PN.getIncomingValue(Idx);
01118 
01119     // If the value is produced by the terminator of the predecessor (an
01120     // invoke) or it has side-effects, there is no valid place to put a load
01121     // in the predecessor.
01122     if (TI == InVal || TI->mayHaveSideEffects())
01123       return false;
01124 
01125     // If the predecessor has a single successor, then the edge isn't
01126     // critical.
01127     if (TI->getNumSuccessors() == 1)
01128       continue;
01129 
01130     // If this pointer is always safe to load, or if we can prove that there
01131     // is already a load in the block, then we can move the load to the pred
01132     // block.
01133     if (InVal->isDereferenceablePointer(DL) ||
01134         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
01135       continue;
01136 
01137     return false;
01138   }
01139 
01140   return true;
01141 }
01142 
01143 static void speculatePHINodeLoads(PHINode &PN) {
01144   DEBUG(dbgs() << "    original: " << PN << "\n");
01145 
01146   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
01147   IRBuilderTy PHIBuilder(&PN);
01148   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
01149                                         PN.getName() + ".sroa.speculated");
01150 
01151   // Get the AA tags and alignment to use from one of the loads.  It doesn't
01152   // matter which one we get and if any differ.
01153   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
01154 
01155   AAMDNodes AATags;
01156   SomeLoad->getAAMetadata(AATags);
01157   unsigned Align = SomeLoad->getAlignment();
01158 
01159   // Rewrite all loads of the PN to use the new PHI.
01160   while (!PN.use_empty()) {
01161     LoadInst *LI = cast<LoadInst>(PN.user_back());
01162     LI->replaceAllUsesWith(NewPN);
01163     LI->eraseFromParent();
01164   }
01165 
01166   // Inject loads into all of the pred blocks.
01167   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01168     BasicBlock *Pred = PN.getIncomingBlock(Idx);
01169     TerminatorInst *TI = Pred->getTerminator();
01170     Value *InVal = PN.getIncomingValue(Idx);
01171     IRBuilderTy PredBuilder(TI);
01172 
01173     LoadInst *Load = PredBuilder.CreateLoad(
01174         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
01175     ++NumLoadsSpeculated;
01176     Load->setAlignment(Align);
01177     if (AATags)
01178       Load->setAAMetadata(AATags);
01179     NewPN->addIncoming(Load, Pred);
01180   }
01181 
01182   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
01183   PN.eraseFromParent();
01184 }
01185 
01186 /// Select instructions that use an alloca and are subsequently loaded can be
01187 /// rewritten to load both input pointers and then select between the result,
01188 /// allowing the load of the alloca to be promoted.
01189 /// From this:
01190 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01191 ///   %V = load i32* %P2
01192 /// to:
01193 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01194 ///   %V2 = load i32* %Other
01195 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01196 ///
01197 /// We can do this to a select if its only uses are loads and if the operand
01198 /// to the select can be loaded unconditionally.
01199 static bool isSafeSelectToSpeculate(SelectInst &SI,
01200                                     const DataLayout *DL = nullptr) {
01201   Value *TValue = SI.getTrueValue();
01202   Value *FValue = SI.getFalseValue();
01203   bool TDerefable = TValue->isDereferenceablePointer(DL);
01204   bool FDerefable = FValue->isDereferenceablePointer(DL);
01205 
01206   for (User *U : SI.users()) {
01207     LoadInst *LI = dyn_cast<LoadInst>(U);
01208     if (!LI || !LI->isSimple())
01209       return false;
01210 
01211     // Both operands to the select need to be dereferencable, either
01212     // absolutely (e.g. allocas) or at this point because we can see other
01213     // accesses to it.
01214     if (!TDerefable &&
01215         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
01216       return false;
01217     if (!FDerefable &&
01218         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
01219       return false;
01220   }
01221 
01222   return true;
01223 }
01224 
01225 static void speculateSelectInstLoads(SelectInst &SI) {
01226   DEBUG(dbgs() << "    original: " << SI << "\n");
01227 
01228   IRBuilderTy IRB(&SI);
01229   Value *TV = SI.getTrueValue();
01230   Value *FV = SI.getFalseValue();
01231   // Replace the loads of the select with a select of two loads.
01232   while (!SI.use_empty()) {
01233     LoadInst *LI = cast<LoadInst>(SI.user_back());
01234     assert(LI->isSimple() && "We only speculate simple loads");
01235 
01236     IRB.SetInsertPoint(LI);
01237     LoadInst *TL =
01238         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
01239     LoadInst *FL =
01240         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
01241     NumLoadsSpeculated += 2;
01242 
01243     // Transfer alignment and AA info if present.
01244     TL->setAlignment(LI->getAlignment());
01245     FL->setAlignment(LI->getAlignment());
01246 
01247     AAMDNodes Tags;
01248     LI->getAAMetadata(Tags);
01249     if (Tags) {
01250       TL->setAAMetadata(Tags);
01251       FL->setAAMetadata(Tags);
01252     }
01253 
01254     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
01255                                 LI->getName() + ".sroa.speculated");
01256 
01257     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
01258     LI->replaceAllUsesWith(V);
01259     LI->eraseFromParent();
01260   }
01261   SI.eraseFromParent();
01262 }
01263 
01264 /// \brief Build a GEP out of a base pointer and indices.
01265 ///
01266 /// This will return the BasePtr if that is valid, or build a new GEP
01267 /// instruction using the IRBuilder if GEP-ing is needed.
01268 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
01269                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
01270   if (Indices.empty())
01271     return BasePtr;
01272 
01273   // A single zero index is a no-op, so check for this and avoid building a GEP
01274   // in that case.
01275   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
01276     return BasePtr;
01277 
01278   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
01279 }
01280 
01281 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
01282 /// TargetTy without changing the offset of the pointer.
01283 ///
01284 /// This routine assumes we've already established a properly offset GEP with
01285 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
01286 /// zero-indices down through type layers until we find one the same as
01287 /// TargetTy. If we can't find one with the same type, we at least try to use
01288 /// one with the same size. If none of that works, we just produce the GEP as
01289 /// indicated by Indices to have the correct offset.
01290 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
01291                                     Value *BasePtr, Type *Ty, Type *TargetTy,
01292                                     SmallVectorImpl<Value *> &Indices,
01293                                     Twine NamePrefix) {
01294   if (Ty == TargetTy)
01295     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01296 
01297   // Pointer size to use for the indices.
01298   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
01299 
01300   // See if we can descend into a struct and locate a field with the correct
01301   // type.
01302   unsigned NumLayers = 0;
01303   Type *ElementTy = Ty;
01304   do {
01305     if (ElementTy->isPointerTy())
01306       break;
01307 
01308     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
01309       ElementTy = ArrayTy->getElementType();
01310       Indices.push_back(IRB.getIntN(PtrSize, 0));
01311     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
01312       ElementTy = VectorTy->getElementType();
01313       Indices.push_back(IRB.getInt32(0));
01314     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
01315       if (STy->element_begin() == STy->element_end())
01316         break; // Nothing left to descend into.
01317       ElementTy = *STy->element_begin();
01318       Indices.push_back(IRB.getInt32(0));
01319     } else {
01320       break;
01321     }
01322     ++NumLayers;
01323   } while (ElementTy != TargetTy);
01324   if (ElementTy != TargetTy)
01325     Indices.erase(Indices.end() - NumLayers, Indices.end());
01326 
01327   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01328 }
01329 
01330 /// \brief Recursively compute indices for a natural GEP.
01331 ///
01332 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
01333 /// element types adding appropriate indices for the GEP.
01334 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
01335                                        Value *Ptr, Type *Ty, APInt &Offset,
01336                                        Type *TargetTy,
01337                                        SmallVectorImpl<Value *> &Indices,
01338                                        Twine NamePrefix) {
01339   if (Offset == 0)
01340     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
01341 
01342   // We can't recurse through pointer types.
01343   if (Ty->isPointerTy())
01344     return nullptr;
01345 
01346   // We try to analyze GEPs over vectors here, but note that these GEPs are
01347   // extremely poorly defined currently. The long-term goal is to remove GEPing
01348   // over a vector from the IR completely.
01349   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
01350     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
01351     if (ElementSizeInBits % 8 != 0) {
01352       // GEPs over non-multiple of 8 size vector elements are invalid.
01353       return nullptr;
01354     }
01355     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
01356     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01357     if (NumSkippedElements.ugt(VecTy->getNumElements()))
01358       return nullptr;
01359     Offset -= NumSkippedElements * ElementSize;
01360     Indices.push_back(IRB.getInt(NumSkippedElements));
01361     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
01362                                     Offset, TargetTy, Indices, NamePrefix);
01363   }
01364 
01365   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
01366     Type *ElementTy = ArrTy->getElementType();
01367     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01368     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01369     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
01370       return nullptr;
01371 
01372     Offset -= NumSkippedElements * ElementSize;
01373     Indices.push_back(IRB.getInt(NumSkippedElements));
01374     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01375                                     Indices, NamePrefix);
01376   }
01377 
01378   StructType *STy = dyn_cast<StructType>(Ty);
01379   if (!STy)
01380     return nullptr;
01381 
01382   const StructLayout *SL = DL.getStructLayout(STy);
01383   uint64_t StructOffset = Offset.getZExtValue();
01384   if (StructOffset >= SL->getSizeInBytes())
01385     return nullptr;
01386   unsigned Index = SL->getElementContainingOffset(StructOffset);
01387   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
01388   Type *ElementTy = STy->getElementType(Index);
01389   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
01390     return nullptr; // The offset points into alignment padding.
01391 
01392   Indices.push_back(IRB.getInt32(Index));
01393   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01394                                   Indices, NamePrefix);
01395 }
01396 
01397 /// \brief Get a natural GEP from a base pointer to a particular offset and
01398 /// resulting in a particular type.
01399 ///
01400 /// The goal is to produce a "natural" looking GEP that works with the existing
01401 /// composite types to arrive at the appropriate offset and element type for
01402 /// a pointer. TargetTy is the element type the returned GEP should point-to if
01403 /// possible. We recurse by decreasing Offset, adding the appropriate index to
01404 /// Indices, and setting Ty to the result subtype.
01405 ///
01406 /// If no natural GEP can be constructed, this function returns null.
01407 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
01408                                       Value *Ptr, APInt Offset, Type *TargetTy,
01409                                       SmallVectorImpl<Value *> &Indices,
01410                                       Twine NamePrefix) {
01411   PointerType *Ty = cast<PointerType>(Ptr->getType());
01412 
01413   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
01414   // an i8.
01415   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
01416     return nullptr;
01417 
01418   Type *ElementTy = Ty->getElementType();
01419   if (!ElementTy->isSized())
01420     return nullptr; // We can't GEP through an unsized element.
01421   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01422   if (ElementSize == 0)
01423     return nullptr; // Zero-length arrays can't help us build a natural GEP.
01424   APInt NumSkippedElements = Offset.sdiv(ElementSize);
01425 
01426   Offset -= NumSkippedElements * ElementSize;
01427   Indices.push_back(IRB.getInt(NumSkippedElements));
01428   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01429                                   Indices, NamePrefix);
01430 }
01431 
01432 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
01433 /// resulting pointer has PointerTy.
01434 ///
01435 /// This tries very hard to compute a "natural" GEP which arrives at the offset
01436 /// and produces the pointer type desired. Where it cannot, it will try to use
01437 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
01438 /// fails, it will try to use an existing i8* and GEP to the byte offset and
01439 /// bitcast to the type.
01440 ///
01441 /// The strategy for finding the more natural GEPs is to peel off layers of the
01442 /// pointer, walking back through bit casts and GEPs, searching for a base
01443 /// pointer from which we can compute a natural GEP with the desired
01444 /// properties. The algorithm tries to fold as many constant indices into
01445 /// a single GEP as possible, thus making each GEP more independent of the
01446 /// surrounding code.
01447 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
01448                              APInt Offset, Type *PointerTy,
01449                              Twine NamePrefix) {
01450   // Even though we don't look through PHI nodes, we could be called on an
01451   // instruction in an unreachable block, which may be on a cycle.
01452   SmallPtrSet<Value *, 4> Visited;
01453   Visited.insert(Ptr);
01454   SmallVector<Value *, 4> Indices;
01455 
01456   // We may end up computing an offset pointer that has the wrong type. If we
01457   // never are able to compute one directly that has the correct type, we'll
01458   // fall back to it, so keep it around here.
01459   Value *OffsetPtr = nullptr;
01460 
01461   // Remember any i8 pointer we come across to re-use if we need to do a raw
01462   // byte offset.
01463   Value *Int8Ptr = nullptr;
01464   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
01465 
01466   Type *TargetTy = PointerTy->getPointerElementType();
01467 
01468   do {
01469     // First fold any existing GEPs into the offset.
01470     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
01471       APInt GEPOffset(Offset.getBitWidth(), 0);
01472       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
01473         break;
01474       Offset += GEPOffset;
01475       Ptr = GEP->getPointerOperand();
01476       if (!Visited.insert(Ptr))
01477         break;
01478     }
01479 
01480     // See if we can perform a natural GEP here.
01481     Indices.clear();
01482     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
01483                                            Indices, NamePrefix)) {
01484       if (P->getType() == PointerTy) {
01485         // Zap any offset pointer that we ended up computing in previous rounds.
01486         if (OffsetPtr && OffsetPtr->use_empty())
01487           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
01488             I->eraseFromParent();
01489         return P;
01490       }
01491       if (!OffsetPtr) {
01492         OffsetPtr = P;
01493       }
01494     }
01495 
01496     // Stash this pointer if we've found an i8*.
01497     if (Ptr->getType()->isIntegerTy(8)) {
01498       Int8Ptr = Ptr;
01499       Int8PtrOffset = Offset;
01500     }
01501 
01502     // Peel off a layer of the pointer and update the offset appropriately.
01503     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
01504       Ptr = cast<Operator>(Ptr)->getOperand(0);
01505     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
01506       if (GA->mayBeOverridden())
01507         break;
01508       Ptr = GA->getAliasee();
01509     } else {
01510       break;
01511     }
01512     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
01513   } while (Visited.insert(Ptr));
01514 
01515   if (!OffsetPtr) {
01516     if (!Int8Ptr) {
01517       Int8Ptr = IRB.CreateBitCast(
01518           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
01519           NamePrefix + "sroa_raw_cast");
01520       Int8PtrOffset = Offset;
01521     }
01522 
01523     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
01524       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
01525                             NamePrefix + "sroa_raw_idx");
01526   }
01527   Ptr = OffsetPtr;
01528 
01529   // On the off chance we were targeting i8*, guard the bitcast here.
01530   if (Ptr->getType() != PointerTy)
01531     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
01532 
01533   return Ptr;
01534 }
01535 
01536 /// \brief Test whether we can convert a value from the old to the new type.
01537 ///
01538 /// This predicate should be used to guard calls to convertValue in order to
01539 /// ensure that we only try to convert viable values. The strategy is that we
01540 /// will peel off single element struct and array wrappings to get to an
01541 /// underlying value, and convert that value.
01542 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
01543   if (OldTy == NewTy)
01544     return true;
01545   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01546     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01547       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
01548         return true;
01549   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
01550     return false;
01551   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
01552     return false;
01553 
01554   // We can convert pointers to integers and vice-versa. Same for vectors
01555   // of pointers and integers.
01556   OldTy = OldTy->getScalarType();
01557   NewTy = NewTy->getScalarType();
01558   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
01559     if (NewTy->isPointerTy() && OldTy->isPointerTy())
01560       return true;
01561     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
01562       return true;
01563     return false;
01564   }
01565 
01566   return true;
01567 }
01568 
01569 /// \brief Generic routine to convert an SSA value to a value of a different
01570 /// type.
01571 ///
01572 /// This will try various different casting techniques, such as bitcasts,
01573 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
01574 /// two types for viability with this routine.
01575 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01576                            Type *NewTy) {
01577   Type *OldTy = V->getType();
01578   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
01579 
01580   if (OldTy == NewTy)
01581     return V;
01582 
01583   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01584     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01585       if (NewITy->getBitWidth() > OldITy->getBitWidth())
01586         return IRB.CreateZExt(V, NewITy);
01587 
01588   // See if we need inttoptr for this type pair. A cast involving both scalars
01589   // and vectors requires and additional bitcast.
01590   if (OldTy->getScalarType()->isIntegerTy() &&
01591       NewTy->getScalarType()->isPointerTy()) {
01592     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
01593     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01594       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01595                                 NewTy);
01596 
01597     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
01598     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01599       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01600                                 NewTy);
01601 
01602     return IRB.CreateIntToPtr(V, NewTy);
01603   }
01604 
01605   // See if we need ptrtoint for this type pair. A cast involving both scalars
01606   // and vectors requires and additional bitcast.
01607   if (OldTy->getScalarType()->isPointerTy() &&
01608       NewTy->getScalarType()->isIntegerTy()) {
01609     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
01610     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01611       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01612                                NewTy);
01613 
01614     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
01615     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01616       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01617                                NewTy);
01618 
01619     return IRB.CreatePtrToInt(V, NewTy);
01620   }
01621 
01622   return IRB.CreateBitCast(V, NewTy);
01623 }
01624 
01625 /// \brief Test whether the given slice use can be promoted to a vector.
01626 ///
01627 /// This function is called to test each entry in a partioning which is slated
01628 /// for a single slice.
01629 static bool isVectorPromotionViableForSlice(
01630     const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
01631     uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
01632     AllocaSlices::const_iterator I) {
01633   // First validate the slice offsets.
01634   uint64_t BeginOffset =
01635       std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
01636   uint64_t BeginIndex = BeginOffset / ElementSize;
01637   if (BeginIndex * ElementSize != BeginOffset ||
01638       BeginIndex >= Ty->getNumElements())
01639     return false;
01640   uint64_t EndOffset =
01641       std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
01642   uint64_t EndIndex = EndOffset / ElementSize;
01643   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
01644     return false;
01645 
01646   assert(EndIndex > BeginIndex && "Empty vector!");
01647   uint64_t NumElements = EndIndex - BeginIndex;
01648   Type *SliceTy =
01649       (NumElements == 1) ? Ty->getElementType()
01650                          : VectorType::get(Ty->getElementType(), NumElements);
01651 
01652   Type *SplitIntTy =
01653       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
01654 
01655   Use *U = I->getUse();
01656 
01657   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01658     if (MI->isVolatile())
01659       return false;
01660     if (!I->isSplittable())
01661       return false; // Skip any unsplittable intrinsics.
01662   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
01663     // Disable vector promotion when there are loads or stores of an FCA.
01664     return false;
01665   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01666     if (LI->isVolatile())
01667       return false;
01668     Type *LTy = LI->getType();
01669     if (SliceBeginOffset > I->beginOffset() ||
01670         SliceEndOffset < I->endOffset()) {
01671       assert(LTy->isIntegerTy());
01672       LTy = SplitIntTy;
01673     }
01674     if (!canConvertValue(DL, SliceTy, LTy))
01675       return false;
01676   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01677     if (SI->isVolatile())
01678       return false;
01679     Type *STy = SI->getValueOperand()->getType();
01680     if (SliceBeginOffset > I->beginOffset() ||
01681         SliceEndOffset < I->endOffset()) {
01682       assert(STy->isIntegerTy());
01683       STy = SplitIntTy;
01684     }
01685     if (!canConvertValue(DL, STy, SliceTy))
01686       return false;
01687   } else {
01688     return false;
01689   }
01690 
01691   return true;
01692 }
01693 
01694 /// \brief Test whether the given alloca partitioning and range of slices can be
01695 /// promoted to a vector.
01696 ///
01697 /// This is a quick test to check whether we can rewrite a particular alloca
01698 /// partition (and its newly formed alloca) into a vector alloca with only
01699 /// whole-vector loads and stores such that it could be promoted to a vector
01700 /// SSA value. We only can ensure this for a limited set of operations, and we
01701 /// don't want to do the rewrites unless we are confident that the result will
01702 /// be promotable, so we have an early test here.
01703 static bool
01704 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
01705                         uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
01706                         AllocaSlices::const_iterator I,
01707                         AllocaSlices::const_iterator E,
01708                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01709   VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
01710   if (!Ty)
01711     return false;
01712 
01713   uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
01714 
01715   // While the definition of LLVM vectors is bitpacked, we don't support sizes
01716   // that aren't byte sized.
01717   if (ElementSize % 8)
01718     return false;
01719   assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
01720          "vector size not a multiple of element size?");
01721   ElementSize /= 8;
01722 
01723   for (; I != E; ++I)
01724     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01725                                          SliceEndOffset, Ty, ElementSize, I))
01726       return false;
01727 
01728   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01729                                                         SUE = SplitUses.end();
01730        SUI != SUE; ++SUI)
01731     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01732                                          SliceEndOffset, Ty, ElementSize, *SUI))
01733       return false;
01734 
01735   return true;
01736 }
01737 
01738 /// \brief Test whether a slice of an alloca is valid for integer widening.
01739 ///
01740 /// This implements the necessary checking for the \c isIntegerWideningViable
01741 /// test below on a single slice of the alloca.
01742 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
01743                                             Type *AllocaTy,
01744                                             uint64_t AllocBeginOffset,
01745                                             uint64_t Size, AllocaSlices &S,
01746                                             AllocaSlices::const_iterator I,
01747                                             bool &WholeAllocaOp) {
01748   uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
01749   uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
01750 
01751   // We can't reasonably handle cases where the load or store extends past
01752   // the end of the aloca's type and into its padding.
01753   if (RelEnd > Size)
01754     return false;
01755 
01756   Use *U = I->getUse();
01757 
01758   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01759     if (LI->isVolatile())
01760       return false;
01761     if (RelBegin == 0 && RelEnd == Size)
01762       WholeAllocaOp = true;
01763     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
01764       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01765         return false;
01766     } else if (RelBegin != 0 || RelEnd != Size ||
01767                !canConvertValue(DL, AllocaTy, LI->getType())) {
01768       // Non-integer loads need to be convertible from the alloca type so that
01769       // they are promotable.
01770       return false;
01771     }
01772   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01773     Type *ValueTy = SI->getValueOperand()->getType();
01774     if (SI->isVolatile())
01775       return false;
01776     if (RelBegin == 0 && RelEnd == Size)
01777       WholeAllocaOp = true;
01778     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
01779       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01780         return false;
01781     } else if (RelBegin != 0 || RelEnd != Size ||
01782                !canConvertValue(DL, ValueTy, AllocaTy)) {
01783       // Non-integer stores need to be convertible to the alloca type so that
01784       // they are promotable.
01785       return false;
01786     }
01787   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01788     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
01789       return false;
01790     if (!I->isSplittable())
01791       return false; // Skip any unsplittable intrinsics.
01792   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
01793     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01794         II->getIntrinsicID() != Intrinsic::lifetime_end)
01795       return false;
01796   } else {
01797     return false;
01798   }
01799 
01800   return true;
01801 }
01802 
01803 /// \brief Test whether the given alloca partition's integer operations can be
01804 /// widened to promotable ones.
01805 ///
01806 /// This is a quick test to check whether we can rewrite the integer loads and
01807 /// stores to a particular alloca into wider loads and stores and be able to
01808 /// promote the resulting alloca.
01809 static bool
01810 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
01811                         uint64_t AllocBeginOffset, AllocaSlices &S,
01812                         AllocaSlices::const_iterator I,
01813                         AllocaSlices::const_iterator E,
01814                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01815   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
01816   // Don't create integer types larger than the maximum bitwidth.
01817   if (SizeInBits > IntegerType::MAX_INT_BITS)
01818     return false;
01819 
01820   // Don't try to handle allocas with bit-padding.
01821   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
01822     return false;
01823 
01824   // We need to ensure that an integer type with the appropriate bitwidth can
01825   // be converted to the alloca type, whatever that is. We don't want to force
01826   // the alloca itself to have an integer type if there is a more suitable one.
01827   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
01828   if (!canConvertValue(DL, AllocaTy, IntTy) ||
01829       !canConvertValue(DL, IntTy, AllocaTy))
01830     return false;
01831 
01832   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
01833 
01834   // While examining uses, we ensure that the alloca has a covering load or
01835   // store. We don't want to widen the integer operations only to fail to
01836   // promote due to some other unsplittable entry (which we may make splittable
01837   // later). However, if there are only splittable uses, go ahead and assume
01838   // that we cover the alloca.
01839   bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
01840 
01841   for (; I != E; ++I)
01842     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01843                                          S, I, WholeAllocaOp))
01844       return false;
01845 
01846   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01847                                                         SUE = SplitUses.end();
01848        SUI != SUE; ++SUI)
01849     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01850                                          S, *SUI, WholeAllocaOp))
01851       return false;
01852 
01853   return WholeAllocaOp;
01854 }
01855 
01856 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01857                              IntegerType *Ty, uint64_t Offset,
01858                              const Twine &Name) {
01859   DEBUG(dbgs() << "       start: " << *V << "\n");
01860   IntegerType *IntTy = cast<IntegerType>(V->getType());
01861   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01862          "Element extends past full value");
01863   uint64_t ShAmt = 8*Offset;
01864   if (DL.isBigEndian())
01865     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01866   if (ShAmt) {
01867     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
01868     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01869   }
01870   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01871          "Cannot extract to a larger integer!");
01872   if (Ty != IntTy) {
01873     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
01874     DEBUG(dbgs() << "     trunced: " << *V << "\n");
01875   }
01876   return V;
01877 }
01878 
01879 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
01880                             Value *V, uint64_t Offset, const Twine &Name) {
01881   IntegerType *IntTy = cast<IntegerType>(Old->getType());
01882   IntegerType *Ty = cast<IntegerType>(V->getType());
01883   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01884          "Cannot insert a larger integer!");
01885   DEBUG(dbgs() << "       start: " << *V << "\n");
01886   if (Ty != IntTy) {
01887     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
01888     DEBUG(dbgs() << "    extended: " << *V << "\n");
01889   }
01890   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01891          "Element store outside of alloca store");
01892   uint64_t ShAmt = 8*Offset;
01893   if (DL.isBigEndian())
01894     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01895   if (ShAmt) {
01896     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
01897     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01898   }
01899 
01900   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
01901     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
01902     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
01903     DEBUG(dbgs() << "      masked: " << *Old << "\n");
01904     V = IRB.CreateOr(Old, V, Name + ".insert");
01905     DEBUG(dbgs() << "    inserted: " << *V << "\n");
01906   }
01907   return V;
01908 }
01909 
01910 static Value *extractVector(IRBuilderTy &IRB, Value *V,
01911                             unsigned BeginIndex, unsigned EndIndex,
01912                             const Twine &Name) {
01913   VectorType *VecTy = cast<VectorType>(V->getType());
01914   unsigned NumElements = EndIndex - BeginIndex;
01915   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
01916 
01917   if (NumElements == VecTy->getNumElements())
01918     return V;
01919 
01920   if (NumElements == 1) {
01921     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
01922                                  Name + ".extract");
01923     DEBUG(dbgs() << "     extract: " << *V << "\n");
01924     return V;
01925   }
01926 
01927   SmallVector<Constant*, 8> Mask;
01928   Mask.reserve(NumElements);
01929   for (unsigned i = BeginIndex; i != EndIndex; ++i)
01930     Mask.push_back(IRB.getInt32(i));
01931   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01932                               ConstantVector::get(Mask),
01933                               Name + ".extract");
01934   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
01935   return V;
01936 }
01937 
01938 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
01939                            unsigned BeginIndex, const Twine &Name) {
01940   VectorType *VecTy = cast<VectorType>(Old->getType());
01941   assert(VecTy && "Can only insert a vector into a vector");
01942 
01943   VectorType *Ty = dyn_cast<VectorType>(V->getType());
01944   if (!Ty) {
01945     // Single element to insert.
01946     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
01947                                 Name + ".insert");
01948     DEBUG(dbgs() <<  "     insert: " << *V << "\n");
01949     return V;
01950   }
01951 
01952   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
01953          "Too many elements!");
01954   if (Ty->getNumElements() == VecTy->getNumElements()) {
01955     assert(V->getType() == VecTy && "Vector type mismatch");
01956     return V;
01957   }
01958   unsigned EndIndex = BeginIndex + Ty->getNumElements();
01959 
01960   // When inserting a smaller vector into the larger to store, we first
01961   // use a shuffle vector to widen it with undef elements, and then
01962   // a second shuffle vector to select between the loaded vector and the
01963   // incoming vector.
01964   SmallVector<Constant*, 8> Mask;
01965   Mask.reserve(VecTy->getNumElements());
01966   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01967     if (i >= BeginIndex && i < EndIndex)
01968       Mask.push_back(IRB.getInt32(i - BeginIndex));
01969     else
01970       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
01971   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01972                               ConstantVector::get(Mask),
01973                               Name + ".expand");
01974   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
01975 
01976   Mask.clear();
01977   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01978     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
01979 
01980   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
01981 
01982   DEBUG(dbgs() << "    blend: " << *V << "\n");
01983   return V;
01984 }
01985 
01986 namespace {
01987 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
01988 /// to use a new alloca.
01989 ///
01990 /// Also implements the rewriting to vector-based accesses when the partition
01991 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
01992 /// lives here.
01993 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
01994   // Befriend the base class so it can delegate to private visit methods.
01995   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
01996   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
01997 
01998   const DataLayout &DL;
01999   AllocaSlices &S;
02000   SROA &Pass;
02001   AllocaInst &OldAI, &NewAI;
02002   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
02003   Type *NewAllocaTy;
02004 
02005   // If we are rewriting an alloca partition which can be written as pure
02006   // vector operations, we stash extra information here. When VecTy is
02007   // non-null, we have some strict guarantees about the rewritten alloca:
02008   //   - The new alloca is exactly the size of the vector type here.
02009   //   - The accesses all either map to the entire vector or to a single
02010   //     element.
02011   //   - The set of accessing instructions is only one of those handled above
02012   //     in isVectorPromotionViable. Generally these are the same access kinds
02013   //     which are promotable via mem2reg.
02014   VectorType *VecTy;
02015   Type *ElementTy;
02016   uint64_t ElementSize;
02017 
02018   // This is a convenience and flag variable that will be null unless the new
02019   // alloca's integer operations should be widened to this integer type due to
02020   // passing isIntegerWideningViable above. If it is non-null, the desired
02021   // integer type will be stored here for easy access during rewriting.
02022   IntegerType *IntTy;
02023 
02024   // The original offset of the slice currently being rewritten relative to
02025   // the original alloca.
02026   uint64_t BeginOffset, EndOffset;
02027   // The new offsets of the slice currently being rewritten relative to the
02028   // original alloca.
02029   uint64_t NewBeginOffset, NewEndOffset;
02030 
02031   uint64_t SliceSize;
02032   bool IsSplittable;
02033   bool IsSplit;
02034   Use *OldUse;
02035   Instruction *OldPtr;
02036 
02037   // Track post-rewrite users which are PHI nodes and Selects.
02038   SmallPtrSetImpl<PHINode *> &PHIUsers;
02039   SmallPtrSetImpl<SelectInst *> &SelectUsers;
02040 
02041   // Utility IR builder, whose name prefix is setup for each visited use, and
02042   // the insertion point is set to point to the user.
02043   IRBuilderTy IRB;
02044 
02045 public:
02046   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
02047                       AllocaInst &OldAI, AllocaInst &NewAI,
02048                       uint64_t NewAllocaBeginOffset,
02049                       uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
02050                       bool IsIntegerPromotable,
02051                       SmallPtrSetImpl<PHINode *> &PHIUsers,
02052                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
02053       : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
02054         NewAllocaBeginOffset(NewAllocaBeginOffset),
02055         NewAllocaEndOffset(NewAllocaEndOffset),
02056         NewAllocaTy(NewAI.getAllocatedType()),
02057         VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : nullptr),
02058         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
02059         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
02060         IntTy(IsIntegerPromotable
02061                   ? Type::getIntNTy(
02062                         NewAI.getContext(),
02063                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
02064                   : nullptr),
02065         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
02066         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
02067         IRB(NewAI.getContext(), ConstantFolder()) {
02068     if (VecTy) {
02069       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
02070              "Only multiple-of-8 sized vector elements are viable");
02071       ++NumVectorized;
02072     }
02073     assert((!IsVectorPromotable && !IsIntegerPromotable) ||
02074            IsVectorPromotable != IsIntegerPromotable);
02075   }
02076 
02077   bool visit(AllocaSlices::const_iterator I) {
02078     bool CanSROA = true;
02079     BeginOffset = I->beginOffset();
02080     EndOffset = I->endOffset();
02081     IsSplittable = I->isSplittable();
02082     IsSplit =
02083         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
02084 
02085     // Compute the intersecting offset range.
02086     assert(BeginOffset < NewAllocaEndOffset);
02087     assert(EndOffset > NewAllocaBeginOffset);
02088     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
02089     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
02090 
02091     SliceSize = NewEndOffset - NewBeginOffset;
02092 
02093     OldUse = I->getUse();
02094     OldPtr = cast<Instruction>(OldUse->get());
02095 
02096     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
02097     IRB.SetInsertPoint(OldUserI);
02098     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
02099     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
02100 
02101     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
02102     if (VecTy || IntTy)
02103       assert(CanSROA);
02104     return CanSROA;
02105   }
02106 
02107 private:
02108   // Make sure the other visit overloads are visible.
02109   using Base::visit;
02110 
02111   // Every instruction which can end up as a user must have a rewrite rule.
02112   bool visitInstruction(Instruction &I) {
02113     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
02114     llvm_unreachable("No rewrite rule for this instruction!");
02115   }
02116 
02117   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
02118     // Note that the offset computation can use BeginOffset or NewBeginOffset
02119     // interchangeably for unsplit slices.
02120     assert(IsSplit || BeginOffset == NewBeginOffset);
02121     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02122 
02123 #ifndef NDEBUG
02124     StringRef OldName = OldPtr->getName();
02125     // Skip through the last '.sroa.' component of the name.
02126     size_t LastSROAPrefix = OldName.rfind(".sroa.");
02127     if (LastSROAPrefix != StringRef::npos) {
02128       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
02129       // Look for an SROA slice index.
02130       size_t IndexEnd = OldName.find_first_not_of("0123456789");
02131       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
02132         // Strip the index and look for the offset.
02133         OldName = OldName.substr(IndexEnd + 1);
02134         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
02135         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
02136           // Strip the offset.
02137           OldName = OldName.substr(OffsetEnd + 1);
02138       }
02139     }
02140     // Strip any SROA suffixes as well.
02141     OldName = OldName.substr(0, OldName.find(".sroa_"));
02142 #endif
02143 
02144     return getAdjustedPtr(IRB, DL, &NewAI,
02145                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
02146 #ifndef NDEBUG
02147                           Twine(OldName) + "."
02148 #else
02149                           Twine()
02150 #endif
02151                           );
02152   }
02153 
02154   /// \brief Compute suitable alignment to access this slice of the *new* alloca.
02155   ///
02156   /// You can optionally pass a type to this routine and if that type's ABI
02157   /// alignment is itself suitable, this will return zero.
02158   unsigned getSliceAlign(Type *Ty = nullptr) {
02159     unsigned NewAIAlign = NewAI.getAlignment();
02160     if (!NewAIAlign)
02161       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
02162     unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
02163     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
02164   }
02165 
02166   unsigned getIndex(uint64_t Offset) {
02167     assert(VecTy && "Can only call getIndex when rewriting a vector");
02168     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
02169     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
02170     uint32_t Index = RelOffset / ElementSize;
02171     assert(Index * ElementSize == RelOffset);
02172     return Index;
02173   }
02174 
02175   void deleteIfTriviallyDead(Value *V) {
02176     Instruction *I = cast<Instruction>(V);
02177     if (isInstructionTriviallyDead(I))
02178       Pass.DeadInsts.insert(I);
02179   }
02180 
02181   Value *rewriteVectorizedLoadInst() {
02182     unsigned BeginIndex = getIndex(NewBeginOffset);
02183     unsigned EndIndex = getIndex(NewEndOffset);
02184     assert(EndIndex > BeginIndex && "Empty vector!");
02185 
02186     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02187                                      "load");
02188     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
02189   }
02190 
02191   Value *rewriteIntegerLoad(LoadInst &LI) {
02192     assert(IntTy && "We cannot insert an integer to the alloca");
02193     assert(!LI.isVolatile());
02194     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02195                                      "load");
02196     V = convertValue(DL, IRB, V, IntTy);
02197     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02198     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02199     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
02200       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
02201                          "extract");
02202     return V;
02203   }
02204 
02205   bool visitLoadInst(LoadInst &LI) {
02206     DEBUG(dbgs() << "    original: " << LI << "\n");
02207     Value *OldOp = LI.getOperand(0);
02208     assert(OldOp == OldPtr);
02209 
02210     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
02211                              : LI.getType();
02212     bool IsPtrAdjusted = false;
02213     Value *V;
02214     if (VecTy) {
02215       V = rewriteVectorizedLoadInst();
02216     } else if (IntTy && LI.getType()->isIntegerTy()) {
02217       V = rewriteIntegerLoad(LI);
02218     } else if (NewBeginOffset == NewAllocaBeginOffset &&
02219                canConvertValue(DL, NewAllocaTy, LI.getType())) {
02220       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02221                                 LI.isVolatile(), LI.getName());
02222     } else {
02223       Type *LTy = TargetTy->getPointerTo();
02224       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
02225                                 getSliceAlign(TargetTy), LI.isVolatile(),
02226                                 LI.getName());
02227       IsPtrAdjusted = true;
02228     }
02229     V = convertValue(DL, IRB, V, TargetTy);
02230 
02231     if (IsSplit) {
02232       assert(!LI.isVolatile());
02233       assert(LI.getType()->isIntegerTy() &&
02234              "Only integer type loads and stores are split");
02235       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
02236              "Split load isn't smaller than original load");
02237       assert(LI.getType()->getIntegerBitWidth() ==
02238              DL.getTypeStoreSizeInBits(LI.getType()) &&
02239              "Non-byte-multiple bit width");
02240       // Move the insertion point just past the load so that we can refer to it.
02241       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
02242       // Create a placeholder value with the same type as LI to use as the
02243       // basis for the new value. This allows us to replace the uses of LI with
02244       // the computed value, and then replace the placeholder with LI, leaving
02245       // LI only used for this computation.
02246       Value *Placeholder
02247         = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
02248       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
02249                         "insert");
02250       LI.replaceAllUsesWith(V);
02251       Placeholder->replaceAllUsesWith(&LI);
02252       delete Placeholder;
02253     } else {
02254       LI.replaceAllUsesWith(V);
02255     }
02256 
02257     Pass.DeadInsts.insert(&LI);
02258     deleteIfTriviallyDead(OldOp);
02259     DEBUG(dbgs() << "          to: " << *V << "\n");
02260     return !LI.isVolatile() && !IsPtrAdjusted;
02261   }
02262 
02263   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
02264     if (V->getType() != VecTy) {
02265       unsigned BeginIndex = getIndex(NewBeginOffset);
02266       unsigned EndIndex = getIndex(NewEndOffset);
02267       assert(EndIndex > BeginIndex && "Empty vector!");
02268       unsigned NumElements = EndIndex - BeginIndex;
02269       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02270       Type *SliceTy =
02271           (NumElements == 1) ? ElementTy
02272                              : VectorType::get(ElementTy, NumElements);
02273       if (V->getType() != SliceTy)
02274         V = convertValue(DL, IRB, V, SliceTy);
02275 
02276       // Mix in the existing elements.
02277       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02278                                          "load");
02279       V = insertVector(IRB, Old, V, BeginIndex, "vec");
02280     }
02281     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02282     Pass.DeadInsts.insert(&SI);
02283 
02284     (void)Store;
02285     DEBUG(dbgs() << "          to: " << *Store << "\n");
02286     return true;
02287   }
02288 
02289   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
02290     assert(IntTy && "We cannot extract an integer from the alloca");
02291     assert(!SI.isVolatile());
02292     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
02293       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02294                                          "oldload");
02295       Old = convertValue(DL, IRB, Old, IntTy);
02296       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02297       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
02298       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
02299                         "insert");
02300     }
02301     V = convertValue(DL, IRB, V, NewAllocaTy);
02302     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02303     Pass.DeadInsts.insert(&SI);
02304     (void)Store;
02305     DEBUG(dbgs() << "          to: " << *Store << "\n");
02306     return true;
02307   }
02308 
02309   bool visitStoreInst(StoreInst &SI) {
02310     DEBUG(dbgs() << "    original: " << SI << "\n");
02311     Value *OldOp = SI.getOperand(1);
02312     assert(OldOp == OldPtr);
02313 
02314     Value *V = SI.getValueOperand();
02315 
02316     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02317     // alloca that should be re-examined after promoting this alloca.
02318     if (V->getType()->isPointerTy())
02319       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
02320         Pass.PostPromotionWorklist.insert(AI);
02321 
02322     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
02323       assert(!SI.isVolatile());
02324       assert(V->getType()->isIntegerTy() &&
02325              "Only integer type loads and stores are split");
02326       assert(V->getType()->getIntegerBitWidth() ==
02327              DL.getTypeStoreSizeInBits(V->getType()) &&
02328              "Non-byte-multiple bit width");
02329       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
02330       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
02331                          "extract");
02332     }
02333 
02334     if (VecTy)
02335       return rewriteVectorizedStoreInst(V, SI, OldOp);
02336     if (IntTy && V->getType()->isIntegerTy())
02337       return rewriteIntegerStore(V, SI);
02338 
02339     StoreInst *NewSI;
02340     if (NewBeginOffset == NewAllocaBeginOffset &&
02341         NewEndOffset == NewAllocaEndOffset &&
02342         canConvertValue(DL, V->getType(), NewAllocaTy)) {
02343       V = convertValue(DL, IRB, V, NewAllocaTy);
02344       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02345                                      SI.isVolatile());
02346     } else {
02347       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
02348       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
02349                                      SI.isVolatile());
02350     }
02351     (void)NewSI;
02352     Pass.DeadInsts.insert(&SI);
02353     deleteIfTriviallyDead(OldOp);
02354 
02355     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
02356     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
02357   }
02358 
02359   /// \brief Compute an integer value from splatting an i8 across the given
02360   /// number of bytes.
02361   ///
02362   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
02363   /// call this routine.
02364   /// FIXME: Heed the advice above.
02365   ///
02366   /// \param V The i8 value to splat.
02367   /// \param Size The number of bytes in the output (assuming i8 is one byte)
02368   Value *getIntegerSplat(Value *V, unsigned Size) {
02369     assert(Size > 0 && "Expected a positive number of bytes.");
02370     IntegerType *VTy = cast<IntegerType>(V->getType());
02371     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
02372     if (Size == 1)
02373       return V;
02374 
02375     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
02376     V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
02377                       ConstantExpr::getUDiv(
02378                         Constant::getAllOnesValue(SplatIntTy),
02379                         ConstantExpr::getZExt(
02380                           Constant::getAllOnesValue(V->getType()),
02381                           SplatIntTy)),
02382                       "isplat");
02383     return V;
02384   }
02385 
02386   /// \brief Compute a vector splat for a given element value.
02387   Value *getVectorSplat(Value *V, unsigned NumElements) {
02388     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
02389     DEBUG(dbgs() << "       splat: " << *V << "\n");
02390     return V;
02391   }
02392 
02393   bool visitMemSetInst(MemSetInst &II) {
02394     DEBUG(dbgs() << "    original: " << II << "\n");
02395     assert(II.getRawDest() == OldPtr);
02396 
02397     // If the memset has a variable size, it cannot be split, just adjust the
02398     // pointer to the new alloca.
02399     if (!isa<Constant>(II.getLength())) {
02400       assert(!IsSplit);
02401       assert(NewBeginOffset == BeginOffset);
02402       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
02403       Type *CstTy = II.getAlignmentCst()->getType();
02404       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
02405 
02406       deleteIfTriviallyDead(OldPtr);
02407       return false;
02408     }
02409 
02410     // Record this instruction for deletion.
02411     Pass.DeadInsts.insert(&II);
02412 
02413     Type *AllocaTy = NewAI.getAllocatedType();
02414     Type *ScalarTy = AllocaTy->getScalarType();
02415 
02416     // If this doesn't map cleanly onto the alloca type, and that type isn't
02417     // a single value type, just emit a memset.
02418     if (!VecTy && !IntTy &&
02419         (BeginOffset > NewAllocaBeginOffset ||
02420          EndOffset < NewAllocaEndOffset ||
02421          !AllocaTy->isSingleValueType() ||
02422          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
02423          DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
02424       Type *SizeTy = II.getLength()->getType();
02425       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02426       CallInst *New = IRB.CreateMemSet(
02427           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
02428           getSliceAlign(), II.isVolatile());
02429       (void)New;
02430       DEBUG(dbgs() << "          to: " << *New << "\n");
02431       return false;
02432     }
02433 
02434     // If we can represent this as a simple value, we have to build the actual
02435     // value to store, which requires expanding the byte present in memset to
02436     // a sensible representation for the alloca type. This is essentially
02437     // splatting the byte to a sufficiently wide integer, splatting it across
02438     // any desired vector width, and bitcasting to the final type.
02439     Value *V;
02440 
02441     if (VecTy) {
02442       // If this is a memset of a vectorized alloca, insert it.
02443       assert(ElementTy == ScalarTy);
02444 
02445       unsigned BeginIndex = getIndex(NewBeginOffset);
02446       unsigned EndIndex = getIndex(NewEndOffset);
02447       assert(EndIndex > BeginIndex && "Empty vector!");
02448       unsigned NumElements = EndIndex - BeginIndex;
02449       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02450 
02451       Value *Splat =
02452           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
02453       Splat = convertValue(DL, IRB, Splat, ElementTy);
02454       if (NumElements > 1)
02455         Splat = getVectorSplat(Splat, NumElements);
02456 
02457       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02458                                          "oldload");
02459       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
02460     } else if (IntTy) {
02461       // If this is a memset on an alloca where we can widen stores, insert the
02462       // set integer.
02463       assert(!II.isVolatile());
02464 
02465       uint64_t Size = NewEndOffset - NewBeginOffset;
02466       V = getIntegerSplat(II.getValue(), Size);
02467 
02468       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
02469                     EndOffset != NewAllocaBeginOffset)) {
02470         Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02471                                            "oldload");
02472         Old = convertValue(DL, IRB, Old, IntTy);
02473         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02474         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
02475       } else {
02476         assert(V->getType() == IntTy &&
02477                "Wrong type for an alloca wide integer!");
02478       }
02479       V = convertValue(DL, IRB, V, AllocaTy);
02480     } else {
02481       // Established these invariants above.
02482       assert(NewBeginOffset == NewAllocaBeginOffset);
02483       assert(NewEndOffset == NewAllocaEndOffset);
02484 
02485       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
02486       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
02487         V = getVectorSplat(V, AllocaVecTy->getNumElements());
02488 
02489       V = convertValue(DL, IRB, V, AllocaTy);
02490     }
02491 
02492     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02493                                         II.isVolatile());
02494     (void)New;
02495     DEBUG(dbgs() << "          to: " << *New << "\n");
02496     return !II.isVolatile();
02497   }
02498 
02499   bool visitMemTransferInst(MemTransferInst &II) {
02500     // Rewriting of memory transfer instructions can be a bit tricky. We break
02501     // them into two categories: split intrinsics and unsplit intrinsics.
02502 
02503     DEBUG(dbgs() << "    original: " << II << "\n");
02504 
02505     bool IsDest = &II.getRawDestUse() == OldUse;
02506     assert((IsDest && II.getRawDest() == OldPtr) ||
02507            (!IsDest && II.getRawSource() == OldPtr));
02508 
02509     unsigned SliceAlign = getSliceAlign();
02510 
02511     // For unsplit intrinsics, we simply modify the source and destination
02512     // pointers in place. This isn't just an optimization, it is a matter of
02513     // correctness. With unsplit intrinsics we may be dealing with transfers
02514     // within a single alloca before SROA ran, or with transfers that have
02515     // a variable length. We may also be dealing with memmove instead of
02516     // memcpy, and so simply updating the pointers is the necessary for us to
02517     // update both source and dest of a single call.
02518     if (!IsSplittable) {
02519       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02520       if (IsDest)
02521         II.setDest(AdjustedPtr);
02522       else
02523         II.setSource(AdjustedPtr);
02524 
02525       if (II.getAlignment() > SliceAlign) {
02526         Type *CstTy = II.getAlignmentCst()->getType();
02527         II.setAlignment(
02528             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
02529       }
02530 
02531       DEBUG(dbgs() << "          to: " << II << "\n");
02532       deleteIfTriviallyDead(OldPtr);
02533       return false;
02534     }
02535     // For split transfer intrinsics we have an incredibly useful assurance:
02536     // the source and destination do not reside within the same alloca, and at
02537     // least one of them does not escape. This means that we can replace
02538     // memmove with memcpy, and we don't need to worry about all manner of
02539     // downsides to splitting and transforming the operations.
02540 
02541     // If this doesn't map cleanly onto the alloca type, and that type isn't
02542     // a single value type, just emit a memcpy.
02543     bool EmitMemCpy
02544       = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
02545                              EndOffset < NewAllocaEndOffset ||
02546                              !NewAI.getAllocatedType()->isSingleValueType());
02547 
02548     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
02549     // size hasn't been shrunk based on analysis of the viable range, this is
02550     // a no-op.
02551     if (EmitMemCpy && &OldAI == &NewAI) {
02552       // Ensure the start lines up.
02553       assert(NewBeginOffset == BeginOffset);
02554 
02555       // Rewrite the size as needed.
02556       if (NewEndOffset != EndOffset)
02557         II.setLength(ConstantInt::get(II.getLength()->getType(),
02558                                       NewEndOffset - NewBeginOffset));
02559       return false;
02560     }
02561     // Record this instruction for deletion.
02562     Pass.DeadInsts.insert(&II);
02563 
02564     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02565     // alloca that should be re-examined after rewriting this instruction.
02566     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
02567     if (AllocaInst *AI
02568           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
02569       assert(AI != &OldAI && AI != &NewAI &&
02570              "Splittable transfers cannot reach the same alloca on both ends.");
02571       Pass.Worklist.insert(AI);
02572     }
02573 
02574     Type *OtherPtrTy = OtherPtr->getType();
02575     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
02576 
02577     // Compute the relative offset for the other pointer within the transfer.
02578     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
02579     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
02580     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
02581                                    OtherOffset.zextOrTrunc(64).getZExtValue());
02582 
02583     if (EmitMemCpy) {
02584       // Compute the other pointer, folding as much as possible to produce
02585       // a single, simple GEP in most cases.
02586       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02587                                 OtherPtr->getName() + ".");
02588 
02589       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02590       Type *SizeTy = II.getLength()->getType();
02591       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02592 
02593       CallInst *New = IRB.CreateMemCpy(
02594           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
02595           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
02596       (void)New;
02597       DEBUG(dbgs() << "          to: " << *New << "\n");
02598       return false;
02599     }
02600 
02601     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
02602                          NewEndOffset == NewAllocaEndOffset;
02603     uint64_t Size = NewEndOffset - NewBeginOffset;
02604     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
02605     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
02606     unsigned NumElements = EndIndex - BeginIndex;
02607     IntegerType *SubIntTy
02608       = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
02609 
02610     // Reset the other pointer type to match the register type we're going to
02611     // use, but using the address space of the original other pointer.
02612     if (VecTy && !IsWholeAlloca) {
02613       if (NumElements == 1)
02614         OtherPtrTy = VecTy->getElementType();
02615       else
02616         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
02617 
02618       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
02619     } else if (IntTy && !IsWholeAlloca) {
02620       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
02621     } else {
02622       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
02623     }
02624 
02625     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02626                                    OtherPtr->getName() + ".");
02627     unsigned SrcAlign = OtherAlign;
02628     Value *DstPtr = &NewAI;
02629     unsigned DstAlign = SliceAlign;
02630     if (!IsDest) {
02631       std::swap(SrcPtr, DstPtr);
02632       std::swap(SrcAlign, DstAlign);
02633     }
02634 
02635     Value *Src;
02636     if (VecTy && !IsWholeAlloca && !IsDest) {
02637       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02638                                   "load");
02639       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
02640     } else if (IntTy && !IsWholeAlloca && !IsDest) {
02641       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02642                                   "load");
02643       Src = convertValue(DL, IRB, Src, IntTy);
02644       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02645       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
02646     } else {
02647       Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
02648                                   "copyload");
02649     }
02650 
02651     if (VecTy && !IsWholeAlloca && IsDest) {
02652       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02653                                          "oldload");
02654       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
02655     } else if (IntTy && !IsWholeAlloca && IsDest) {
02656       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02657                                          "oldload");
02658       Old = convertValue(DL, IRB, Old, IntTy);
02659       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02660       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
02661       Src = convertValue(DL, IRB, Src, NewAllocaTy);
02662     }
02663 
02664     StoreInst *Store = cast<StoreInst>(
02665         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
02666     (void)Store;
02667     DEBUG(dbgs() << "          to: " << *Store << "\n");
02668     return !II.isVolatile();
02669   }
02670 
02671   bool visitIntrinsicInst(IntrinsicInst &II) {
02672     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
02673            II.getIntrinsicID() == Intrinsic::lifetime_end);
02674     DEBUG(dbgs() << "    original: " << II << "\n");
02675     assert(II.getArgOperand(1) == OldPtr);
02676 
02677     // Record this instruction for deletion.
02678     Pass.DeadInsts.insert(&II);
02679 
02680     ConstantInt *Size
02681       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
02682                          NewEndOffset - NewBeginOffset);
02683     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02684     Value *New;
02685     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
02686       New = IRB.CreateLifetimeStart(Ptr, Size);
02687     else
02688       New = IRB.CreateLifetimeEnd(Ptr, Size);
02689 
02690     (void)New;
02691     DEBUG(dbgs() << "          to: " << *New << "\n");
02692     return true;
02693   }
02694 
02695   bool visitPHINode(PHINode &PN) {
02696     DEBUG(dbgs() << "    original: " << PN << "\n");
02697     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
02698     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
02699 
02700     // We would like to compute a new pointer in only one place, but have it be
02701     // as local as possible to the PHI. To do that, we re-use the location of
02702     // the old pointer, which necessarily must be in the right position to
02703     // dominate the PHI.
02704     IRBuilderTy PtrBuilder(IRB);
02705     PtrBuilder.SetInsertPoint(OldPtr);
02706     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
02707 
02708     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
02709     // Replace the operands which were using the old pointer.
02710     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
02711 
02712     DEBUG(dbgs() << "          to: " << PN << "\n");
02713     deleteIfTriviallyDead(OldPtr);
02714 
02715     // PHIs can't be promoted on their own, but often can be speculated. We
02716     // check the speculation outside of the rewriter so that we see the
02717     // fully-rewritten alloca.
02718     PHIUsers.insert(&PN);
02719     return true;
02720   }
02721 
02722   bool visitSelectInst(SelectInst &SI) {
02723     DEBUG(dbgs() << "    original: " << SI << "\n");
02724     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
02725            "Pointer isn't an operand!");
02726     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
02727     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
02728 
02729     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02730     // Replace the operands which were using the old pointer.
02731     if (SI.getOperand(1) == OldPtr)
02732       SI.setOperand(1, NewPtr);
02733     if (SI.getOperand(2) == OldPtr)
02734       SI.setOperand(2, NewPtr);
02735 
02736     DEBUG(dbgs() << "          to: " << SI << "\n");
02737     deleteIfTriviallyDead(OldPtr);
02738 
02739     // Selects can't be promoted on their own, but often can be speculated. We
02740     // check the speculation outside of the rewriter so that we see the
02741     // fully-rewritten alloca.
02742     SelectUsers.insert(&SI);
02743     return true;
02744   }
02745 
02746 };
02747 }
02748 
02749 namespace {
02750 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
02751 ///
02752 /// This pass aggressively rewrites all aggregate loads and stores on
02753 /// a particular pointer (or any pointer derived from it which we can identify)
02754 /// with scalar loads and stores.
02755 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
02756   // Befriend the base class so it can delegate to private visit methods.
02757   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
02758 
02759   const DataLayout &DL;
02760 
02761   /// Queue of pointer uses to analyze and potentially rewrite.
02762   SmallVector<Use *, 8> Queue;
02763 
02764   /// Set to prevent us from cycling with phi nodes and loops.
02765   SmallPtrSet<User *, 8> Visited;
02766 
02767   /// The current pointer use being rewritten. This is used to dig up the used
02768   /// value (as opposed to the user).
02769   Use *U;
02770 
02771 public:
02772   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
02773 
02774   /// Rewrite loads and stores through a pointer and all pointers derived from
02775   /// it.
02776   bool rewrite(Instruction &I) {
02777     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
02778     enqueueUsers(I);
02779     bool Changed = false;
02780     while (!Queue.empty()) {
02781       U = Queue.pop_back_val();
02782       Changed |= visit(cast<Instruction>(U->getUser()));
02783     }
02784     return Changed;
02785   }
02786 
02787 private:
02788   /// Enqueue all the users of the given instruction for further processing.
02789   /// This uses a set to de-duplicate users.
02790   void enqueueUsers(Instruction &I) {
02791     for (Use &U : I.uses())
02792       if (Visited.insert(U.getUser()))
02793         Queue.push_back(&U);
02794   }
02795 
02796   // Conservative default is to not rewrite anything.
02797   bool visitInstruction(Instruction &I) { return false; }
02798 
02799   /// \brief Generic recursive split emission class.
02800   template <typename Derived>
02801   class OpSplitter {
02802   protected:
02803     /// The builder used to form new instructions.
02804     IRBuilderTy IRB;
02805     /// The indices which to be used with insert- or extractvalue to select the
02806     /// appropriate value within the aggregate.
02807     SmallVector<unsigned, 4> Indices;
02808     /// The indices to a GEP instruction which will move Ptr to the correct slot
02809     /// within the aggregate.
02810     SmallVector<Value *, 4> GEPIndices;
02811     /// The base pointer of the original op, used as a base for GEPing the
02812     /// split operations.
02813     Value *Ptr;
02814 
02815     /// Initialize the splitter with an insertion point, Ptr and start with a
02816     /// single zero GEP index.
02817     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
02818       : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
02819 
02820   public:
02821     /// \brief Generic recursive split emission routine.
02822     ///
02823     /// This method recursively splits an aggregate op (load or store) into
02824     /// scalar or vector ops. It splits recursively until it hits a single value
02825     /// and emits that single value operation via the template argument.
02826     ///
02827     /// The logic of this routine relies on GEPs and insertvalue and
02828     /// extractvalue all operating with the same fundamental index list, merely
02829     /// formatted differently (GEPs need actual values).
02830     ///
02831     /// \param Ty  The type being split recursively into smaller ops.
02832     /// \param Agg The aggregate value being built up or stored, depending on
02833     /// whether this is splitting a load or a store respectively.
02834     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
02835       if (Ty->isSingleValueType())
02836         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
02837 
02838       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02839         unsigned OldSize = Indices.size();
02840         (void)OldSize;
02841         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
02842              ++Idx) {
02843           assert(Indices.size() == OldSize && "Did not return to the old size");
02844           Indices.push_back(Idx);
02845           GEPIndices.push_back(IRB.getInt32(Idx));
02846           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
02847           GEPIndices.pop_back();
02848           Indices.pop_back();
02849         }
02850         return;
02851       }
02852 
02853       if (StructType *STy = dyn_cast<StructType>(Ty)) {
02854         unsigned OldSize = Indices.size();
02855         (void)OldSize;
02856         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
02857              ++Idx) {
02858           assert(Indices.size() == OldSize && "Did not return to the old size");
02859           Indices.push_back(Idx);
02860           GEPIndices.push_back(IRB.getInt32(Idx));
02861           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
02862           GEPIndices.pop_back();
02863           Indices.pop_back();
02864         }
02865         return;
02866       }
02867 
02868       llvm_unreachable("Only arrays and structs are aggregate loadable types");
02869     }
02870   };
02871 
02872   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
02873     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02874       : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
02875 
02876     /// Emit a leaf load of a single value. This is called at the leaves of the
02877     /// recursive emission to actually load values.
02878     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02879       assert(Ty->isSingleValueType());
02880       // Load the single value and insert it using the indices.
02881       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
02882       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
02883       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
02884       DEBUG(dbgs() << "          to: " << *Load << "\n");
02885     }
02886   };
02887 
02888   bool visitLoadInst(LoadInst &LI) {
02889     assert(LI.getPointerOperand() == *U);
02890     if (!LI.isSimple() || LI.getType()->isSingleValueType())
02891       return false;
02892 
02893     // We have an aggregate being loaded, split it apart.
02894     DEBUG(dbgs() << "    original: " << LI << "\n");
02895     LoadOpSplitter Splitter(&LI, *U);
02896     Value *V = UndefValue::get(LI.getType());
02897     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
02898     LI.replaceAllUsesWith(V);
02899     LI.eraseFromParent();
02900     return true;
02901   }
02902 
02903   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
02904     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02905       : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
02906 
02907     /// Emit a leaf store of a single value. This is called at the leaves of the
02908     /// recursive emission to actually produce stores.
02909     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02910       assert(Ty->isSingleValueType());
02911       // Extract the single value and store it using the indices.
02912       Value *Store = IRB.CreateStore(
02913         IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
02914         IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
02915       (void)Store;
02916       DEBUG(dbgs() << "          to: " << *Store << "\n");
02917     }
02918   };
02919 
02920   bool visitStoreInst(StoreInst &SI) {
02921     if (!SI.isSimple() || SI.getPointerOperand() != *U)
02922       return false;
02923     Value *V = SI.getValueOperand();
02924     if (V->getType()->isSingleValueType())
02925       return false;
02926 
02927     // We have an aggregate being stored, split it apart.
02928     DEBUG(dbgs() << "    original: " << SI << "\n");
02929     StoreOpSplitter Splitter(&SI, *U);
02930     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
02931     SI.eraseFromParent();
02932     return true;
02933   }
02934 
02935   bool visitBitCastInst(BitCastInst &BC) {
02936     enqueueUsers(BC);
02937     return false;
02938   }
02939 
02940   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
02941     enqueueUsers(GEPI);
02942     return false;
02943   }
02944 
02945   bool visitPHINode(PHINode &PN) {
02946     enqueueUsers(PN);
02947     return false;
02948   }
02949 
02950   bool visitSelectInst(SelectInst &SI) {
02951     enqueueUsers(SI);
02952     return false;
02953   }
02954 };
02955 }
02956 
02957 /// \brief Strip aggregate type wrapping.
02958 ///
02959 /// This removes no-op aggregate types wrapping an underlying type. It will
02960 /// strip as many layers of types as it can without changing either the type
02961 /// size or the allocated size.
02962 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
02963   if (Ty->isSingleValueType())
02964     return Ty;
02965 
02966   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
02967   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
02968 
02969   Type *InnerTy;
02970   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
02971     InnerTy = ArrTy->getElementType();
02972   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
02973     const StructLayout *SL = DL.getStructLayout(STy);
02974     unsigned Index = SL->getElementContainingOffset(0);
02975     InnerTy = STy->getElementType(Index);
02976   } else {
02977     return Ty;
02978   }
02979 
02980   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
02981       TypeSize > DL.getTypeSizeInBits(InnerTy))
02982     return Ty;
02983 
02984   return stripAggregateTypeWrapping(DL, InnerTy);
02985 }
02986 
02987 /// \brief Try to find a partition of the aggregate type passed in for a given
02988 /// offset and size.
02989 ///
02990 /// This recurses through the aggregate type and tries to compute a subtype
02991 /// based on the offset and size. When the offset and size span a sub-section
02992 /// of an array, it will even compute a new array type for that sub-section,
02993 /// and the same for structs.
02994 ///
02995 /// Note that this routine is very strict and tries to find a partition of the
02996 /// type which produces the *exact* right offset and size. It is not forgiving
02997 /// when the size or offset cause either end of type-based partition to be off.
02998 /// Also, this is a best-effort routine. It is reasonable to give up and not
02999 /// return a type if necessary.
03000 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
03001                               uint64_t Offset, uint64_t Size) {
03002   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
03003     return stripAggregateTypeWrapping(DL, Ty);
03004   if (Offset > DL.getTypeAllocSize(Ty) ||
03005       (DL.getTypeAllocSize(Ty) - Offset) < Size)
03006     return nullptr;
03007 
03008   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
03009     // We can't partition pointers...
03010     if (SeqTy->isPointerTy())
03011       return nullptr;
03012 
03013     Type *ElementTy = SeqTy->getElementType();
03014     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03015     uint64_t NumSkippedElements = Offset / ElementSize;
03016     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
03017       if (NumSkippedElements >= ArrTy->getNumElements())
03018         return nullptr;
03019     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
03020       if (NumSkippedElements >= VecTy->getNumElements())
03021         return nullptr;
03022     }
03023     Offset -= NumSkippedElements * ElementSize;
03024 
03025     // First check if we need to recurse.
03026     if (Offset > 0 || Size < ElementSize) {
03027       // Bail if the partition ends in a different array element.
03028       if ((Offset + Size) > ElementSize)
03029         return nullptr;
03030       // Recurse through the element type trying to peel off offset bytes.
03031       return getTypePartition(DL, ElementTy, Offset, Size);
03032     }
03033     assert(Offset == 0);
03034 
03035     if (Size == ElementSize)
03036       return stripAggregateTypeWrapping(DL, ElementTy);
03037     assert(Size > ElementSize);
03038     uint64_t NumElements = Size / ElementSize;
03039     if (NumElements * ElementSize != Size)
03040       return nullptr;
03041     return ArrayType::get(ElementTy, NumElements);
03042   }
03043 
03044   StructType *STy = dyn_cast<StructType>(Ty);
03045   if (!STy)
03046     return nullptr;
03047 
03048   const StructLayout *SL = DL.getStructLayout(STy);
03049   if (Offset >= SL->getSizeInBytes())
03050     return nullptr;
03051   uint64_t EndOffset = Offset + Size;
03052   if (EndOffset > SL->getSizeInBytes())
03053     return nullptr;
03054 
03055   unsigned Index = SL->getElementContainingOffset(Offset);
03056   Offset -= SL->getElementOffset(Index);
03057 
03058   Type *ElementTy = STy->getElementType(Index);
03059   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03060   if (Offset >= ElementSize)
03061     return nullptr; // The offset points into alignment padding.
03062 
03063   // See if any partition must be contained by the element.
03064   if (Offset > 0 || Size < ElementSize) {
03065     if ((Offset + Size) > ElementSize)
03066       return nullptr;
03067     return getTypePartition(DL, ElementTy, Offset, Size);
03068   }
03069   assert(Offset == 0);
03070 
03071   if (Size == ElementSize)
03072     return stripAggregateTypeWrapping(DL, ElementTy);
03073 
03074   StructType::element_iterator EI = STy->element_begin() + Index,
03075                                EE = STy->element_end();
03076   if (EndOffset < SL->getSizeInBytes()) {
03077     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
03078     if (Index == EndIndex)
03079       return nullptr; // Within a single element and its padding.
03080 
03081     // Don't try to form "natural" types if the elements don't line up with the
03082     // expected size.
03083     // FIXME: We could potentially recurse down through the last element in the
03084     // sub-struct to find a natural end point.
03085     if (SL->getElementOffset(EndIndex) != EndOffset)
03086       return nullptr;
03087 
03088     assert(Index < EndIndex);
03089     EE = STy->element_begin() + EndIndex;
03090   }
03091 
03092   // Try to build up a sub-structure.
03093   StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
03094                                       STy->isPacked());
03095   const StructLayout *SubSL = DL.getStructLayout(SubTy);
03096   if (Size != SubSL->getSizeInBytes())
03097     return nullptr; // The sub-struct doesn't have quite the size needed.
03098 
03099   return SubTy;
03100 }
03101 
03102 /// \brief Rewrite an alloca partition's users.
03103 ///
03104 /// This routine drives both of the rewriting goals of the SROA pass. It tries
03105 /// to rewrite uses of an alloca partition to be conducive for SSA value
03106 /// promotion. If the partition needs a new, more refined alloca, this will
03107 /// build that new alloca, preserving as much type information as possible, and
03108 /// rewrite the uses of the old alloca to point at the new one and have the
03109 /// appropriate new offsets. It also evaluates how successful the rewrite was
03110 /// at enabling promotion and if it was successful queues the alloca to be
03111 /// promoted.
03112 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
03113                             AllocaSlices::iterator B, AllocaSlices::iterator E,
03114                             int64_t BeginOffset, int64_t EndOffset,
03115                             ArrayRef<AllocaSlices::iterator> SplitUses) {
03116   assert(BeginOffset < EndOffset);
03117   uint64_t SliceSize = EndOffset - BeginOffset;
03118 
03119   // Try to compute a friendly type for this partition of the alloca. This
03120   // won't always succeed, in which case we fall back to a legal integer type
03121   // or an i8 array of an appropriate size.
03122   Type *SliceTy = nullptr;
03123   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
03124     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
03125       SliceTy = CommonUseTy;
03126   if (!SliceTy)
03127     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
03128                                                  BeginOffset, SliceSize))
03129       SliceTy = TypePartitionTy;
03130   if ((!SliceTy || (SliceTy->isArrayTy() &&
03131                     SliceTy->getArrayElementType()->isIntegerTy())) &&
03132       DL->isLegalInteger(SliceSize * 8))
03133     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
03134   if (!SliceTy)
03135     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
03136   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
03137 
03138   bool IsVectorPromotable = isVectorPromotionViable(
03139       *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
03140 
03141   bool IsIntegerPromotable =
03142       !IsVectorPromotable &&
03143       isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
03144 
03145   // Check for the case where we're going to rewrite to a new alloca of the
03146   // exact same type as the original, and with the same access offsets. In that
03147   // case, re-use the existing alloca, but still run through the rewriter to
03148   // perform phi and select speculation.
03149   AllocaInst *NewAI;
03150   if (SliceTy == AI.getAllocatedType()) {
03151     assert(BeginOffset == 0 &&
03152            "Non-zero begin offset but same alloca type");
03153     NewAI = &AI;
03154     // FIXME: We should be able to bail at this point with "nothing changed".
03155     // FIXME: We might want to defer PHI speculation until after here.
03156   } else {
03157     unsigned Alignment = AI.getAlignment();
03158     if (!Alignment) {
03159       // The minimum alignment which users can rely on when the explicit
03160       // alignment is omitted or zero is that required by the ABI for this
03161       // type.
03162       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
03163     }
03164     Alignment = MinAlign(Alignment, BeginOffset);
03165     // If we will get at least this much alignment from the type alone, leave
03166     // the alloca's alignment unconstrained.
03167     if (Alignment <= DL->getABITypeAlignment(SliceTy))
03168       Alignment = 0;
03169     NewAI = new AllocaInst(SliceTy, nullptr, Alignment,
03170                            AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
03171     ++NumNewAllocas;
03172   }
03173 
03174   DEBUG(dbgs() << "Rewriting alloca partition "
03175                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
03176                << "\n");
03177 
03178   // Track the high watermark on the worklist as it is only relevant for
03179   // promoted allocas. We will reset it to this point if the alloca is not in
03180   // fact scheduled for promotion.
03181   unsigned PPWOldSize = PostPromotionWorklist.size();
03182   unsigned NumUses = 0;
03183   SmallPtrSet<PHINode *, 8> PHIUsers;
03184   SmallPtrSet<SelectInst *, 8> SelectUsers;
03185 
03186   AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
03187                                EndOffset, IsVectorPromotable,
03188                                IsIntegerPromotable, PHIUsers, SelectUsers);
03189   bool Promotable = true;
03190   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
03191                                                         SUE = SplitUses.end();
03192        SUI != SUE; ++SUI) {
03193     DEBUG(dbgs() << "  rewriting split ");
03194     DEBUG(S.printSlice(dbgs(), *SUI, ""));
03195     Promotable &= Rewriter.visit(*SUI);
03196     ++NumUses;
03197   }
03198   for (AllocaSlices::iterator I = B; I != E; ++I) {
03199     DEBUG(dbgs() << "  rewriting ");
03200     DEBUG(S.printSlice(dbgs(), I, ""));
03201     Promotable &= Rewriter.visit(I);
03202     ++NumUses;
03203   }
03204 
03205   NumAllocaPartitionUses += NumUses;
03206   MaxUsesPerAllocaPartition =
03207       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
03208 
03209   // Now that we've processed all the slices in the new partition, check if any
03210   // PHIs or Selects would block promotion.
03211   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03212                                             E = PHIUsers.end();
03213        I != E; ++I)
03214     if (!isSafePHIToSpeculate(**I, DL)) {
03215       Promotable = false;
03216       PHIUsers.clear();
03217       SelectUsers.clear();
03218       break;
03219     }
03220   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03221                                                E = SelectUsers.end();
03222        I != E; ++I)
03223     if (!isSafeSelectToSpeculate(**I, DL)) {
03224       Promotable = false;
03225       PHIUsers.clear();
03226       SelectUsers.clear();
03227       break;
03228     }
03229 
03230   if (Promotable) {
03231     if (PHIUsers.empty() && SelectUsers.empty()) {
03232       // Promote the alloca.
03233       PromotableAllocas.push_back(NewAI);
03234     } else {
03235       // If we have either PHIs or Selects to speculate, add them to those
03236       // worklists and re-queue the new alloca so that we promote in on the
03237       // next iteration.
03238       for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03239                                                 E = PHIUsers.end();
03240            I != E; ++I)
03241         SpeculatablePHIs.insert(*I);
03242       for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03243                                                    E = SelectUsers.end();
03244            I != E; ++I)
03245         SpeculatableSelects.insert(*I);
03246       Worklist.insert(NewAI);
03247     }
03248   } else {
03249     // If we can't promote the alloca, iterate on it to check for new
03250     // refinements exposed by splitting the current alloca. Don't iterate on an
03251     // alloca which didn't actually change and didn't get promoted.
03252     if (NewAI != &AI)
03253       Worklist.insert(NewAI);
03254 
03255     // Drop any post-promotion work items if promotion didn't happen.
03256     while (PostPromotionWorklist.size() > PPWOldSize)
03257       PostPromotionWorklist.pop_back();
03258   }
03259 
03260   return true;
03261 }
03262 
03263 static void
03264 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
03265                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
03266   if (Offset >= MaxSplitUseEndOffset) {
03267     SplitUses.clear();
03268     MaxSplitUseEndOffset = 0;
03269     return;
03270   }
03271 
03272   size_t SplitUsesOldSize = SplitUses.size();
03273   SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
03274                                  [Offset](const AllocaSlices::iterator &I) {
03275                     return I->endOffset() <= Offset;
03276                   }),
03277                   SplitUses.end());
03278   if (SplitUsesOldSize == SplitUses.size())
03279     return;
03280 
03281   // Recompute the max. While this is linear, so is remove_if.
03282   MaxSplitUseEndOffset = 0;
03283   for (SmallVectorImpl<AllocaSlices::iterator>::iterator
03284            SUI = SplitUses.begin(),
03285            SUE = SplitUses.end();
03286        SUI != SUE; ++SUI)
03287     MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
03288 }
03289 
03290 /// \brief Walks the slices of an alloca and form partitions based on them,
03291 /// rewriting each of their uses.
03292 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
03293   if (S.begin() == S.end())
03294     return false;
03295 
03296   unsigned NumPartitions = 0;
03297   bool Changed = false;
03298   SmallVector<AllocaSlices::iterator, 4> SplitUses;
03299   uint64_t MaxSplitUseEndOffset = 0;
03300 
03301   uint64_t BeginOffset = S.begin()->beginOffset();
03302 
03303   for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
03304        SI != SE; SI = SJ) {
03305     uint64_t MaxEndOffset = SI->endOffset();
03306 
03307     if (!SI->isSplittable()) {
03308       // When we're forming an unsplittable region, it must always start at the
03309       // first slice and will extend through its end.
03310       assert(BeginOffset == SI->beginOffset());
03311 
03312       // Form a partition including all of the overlapping slices with this
03313       // unsplittable slice.
03314       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03315         if (!SJ->isSplittable())
03316           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03317         ++SJ;
03318       }
03319     } else {
03320       assert(SI->isSplittable()); // Established above.
03321 
03322       // Collect all of the overlapping splittable slices.
03323       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
03324              SJ->isSplittable()) {
03325         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03326         ++SJ;
03327       }
03328 
03329       // Back up MaxEndOffset and SJ if we ended the span early when
03330       // encountering an unsplittable slice.
03331       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03332         assert(!SJ->isSplittable());
03333         MaxEndOffset = SJ->beginOffset();
03334       }
03335     }
03336 
03337     // Check if we have managed to move the end offset forward yet. If so,
03338     // we'll have to rewrite uses and erase old split uses.
03339     if (BeginOffset < MaxEndOffset) {
03340       // Rewrite a sequence of overlapping slices.
03341       Changed |=
03342           rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
03343       ++NumPartitions;
03344 
03345       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
03346     }
03347 
03348     // Accumulate all the splittable slices from the [SI,SJ) region which
03349     // overlap going forward.
03350     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
03351       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
03352         SplitUses.push_back(SK);
03353         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
03354       }
03355 
03356     // If we're already at the end and we have no split uses, we're done.
03357     if (SJ == SE && SplitUses.empty())
03358       break;
03359 
03360     // If we have no split uses or no gap in offsets, we're ready to move to
03361     // the next slice.
03362     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
03363       BeginOffset = SJ->beginOffset();
03364       continue;
03365     }
03366 
03367     // Even if we have split slices, if the next slice is splittable and the
03368     // split slices reach it, we can simply set up the beginning offset of the
03369     // next iteration to bridge between them.
03370     if (SJ != SE && SJ->isSplittable() &&
03371         MaxSplitUseEndOffset > SJ->beginOffset()) {
03372       BeginOffset = MaxEndOffset;
03373       continue;
03374     }
03375 
03376     // Otherwise, we have a tail of split slices. Rewrite them with an empty
03377     // range of slices.
03378     uint64_t PostSplitEndOffset =
03379         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
03380 
03381     Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
03382                                 SplitUses);
03383     ++NumPartitions;
03384 
03385     if (SJ == SE)
03386       break; // Skip the rest, we don't need to do any cleanup.
03387 
03388     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
03389                             PostSplitEndOffset);
03390 
03391     // Now just reset the begin offset for the next iteration.
03392     BeginOffset = SJ->beginOffset();
03393   }
03394 
03395   NumAllocaPartitions += NumPartitions;
03396   MaxPartitionsPerAlloca =
03397       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
03398 
03399   return Changed;
03400 }
03401 
03402 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
03403 void SROA::clobberUse(Use &U) {
03404   Value *OldV = U;
03405   // Replace the use with an undef value.
03406   U = UndefValue::get(OldV->getType());
03407 
03408   // Check for this making an instruction dead. We have to garbage collect
03409   // all the dead instructions to ensure the uses of any alloca end up being
03410   // minimal.
03411   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
03412     if (isInstructionTriviallyDead(OldI)) {
03413       DeadInsts.insert(OldI);
03414     }
03415 }
03416 
03417 /// \brief Analyze an alloca for SROA.
03418 ///
03419 /// This analyzes the alloca to ensure we can reason about it, builds
03420 /// the slices of the alloca, and then hands it off to be split and
03421 /// rewritten as needed.
03422 bool SROA::runOnAlloca(AllocaInst &AI) {
03423   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
03424   ++NumAllocasAnalyzed;
03425 
03426   // Special case dead allocas, as they're trivial.
03427   if (AI.use_empty()) {
03428     AI.eraseFromParent();
03429     return true;
03430   }
03431 
03432   // Skip alloca forms that this analysis can't handle.
03433   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
03434       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
03435     return false;
03436 
03437   bool Changed = false;
03438 
03439   // First, split any FCA loads and stores touching this alloca to promote
03440   // better splitting and promotion opportunities.
03441   AggLoadStoreRewriter AggRewriter(*DL);
03442   Changed |= AggRewriter.rewrite(AI);
03443 
03444   // Build the slices using a recursive instruction-visiting builder.
03445   AllocaSlices S(*DL, AI);
03446   DEBUG(S.print(dbgs()));
03447   if (S.isEscaped())
03448     return Changed;
03449 
03450   // Delete all the dead users of this alloca before splitting and rewriting it.
03451   for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
03452                                         DE = S.dead_user_end();
03453        DI != DE; ++DI) {
03454     // Free up everything used by this instruction.
03455     for (Use &DeadOp : (*DI)->operands())
03456       clobberUse(DeadOp);
03457 
03458     // Now replace the uses of this instruction.
03459     (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
03460 
03461     // And mark it for deletion.
03462     DeadInsts.insert(*DI);
03463     Changed = true;
03464   }
03465   for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
03466                                       DE = S.dead_op_end();
03467        DO != DE; ++DO) {
03468     clobberUse(**DO);
03469     Changed = true;
03470   }
03471 
03472   // No slices to split. Leave the dead alloca for a later pass to clean up.
03473   if (S.begin() == S.end())
03474     return Changed;
03475 
03476   Changed |= splitAlloca(AI, S);
03477 
03478   DEBUG(dbgs() << "  Speculating PHIs\n");
03479   while (!SpeculatablePHIs.empty())
03480     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
03481 
03482   DEBUG(dbgs() << "  Speculating Selects\n");
03483   while (!SpeculatableSelects.empty())
03484     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
03485 
03486   return Changed;
03487 }
03488 
03489 /// \brief Delete the dead instructions accumulated in this run.
03490 ///
03491 /// Recursively deletes the dead instructions we've accumulated. This is done
03492 /// at the very end to maximize locality of the recursive delete and to
03493 /// minimize the problems of invalidated instruction pointers as such pointers
03494 /// are used heavily in the intermediate stages of the algorithm.
03495 ///
03496 /// We also record the alloca instructions deleted here so that they aren't
03497 /// subsequently handed to mem2reg to promote.
03498 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
03499   while (!DeadInsts.empty()) {
03500     Instruction *I = DeadInsts.pop_back_val();
03501     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
03502 
03503     I->replaceAllUsesWith(UndefValue::get(I->getType()));
03504 
03505     for (Use &Operand : I->operands())
03506       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
03507         // Zero out the operand and see if it becomes trivially dead.
03508         Operand = nullptr;
03509         if (isInstructionTriviallyDead(U))
03510           DeadInsts.insert(U);
03511       }
03512 
03513     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03514       DeletedAllocas.insert(AI);
03515 
03516     ++NumDeleted;
03517     I->eraseFromParent();
03518   }
03519 }
03520 
03521 static void enqueueUsersInWorklist(Instruction &I,
03522                                    SmallVectorImpl<Instruction *> &Worklist,
03523                                    SmallPtrSet<Instruction *, 8> &Visited) {
03524   for (User *U : I.users())
03525     if (Visited.insert(cast<Instruction>(U)))
03526       Worklist.push_back(cast<Instruction>(U));
03527 }
03528 
03529 /// \brief Promote the allocas, using the best available technique.
03530 ///
03531 /// This attempts to promote whatever allocas have been identified as viable in
03532 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
03533 /// If there is a domtree available, we attempt to promote using the full power
03534 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
03535 /// based on the SSAUpdater utilities. This function returns whether any
03536 /// promotion occurred.
03537 bool SROA::promoteAllocas(Function &F) {
03538   if (PromotableAllocas.empty())
03539     return false;
03540 
03541   NumPromoted += PromotableAllocas.size();
03542 
03543   if (DT && !ForceSSAUpdater) {
03544     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
03545     PromoteMemToReg(PromotableAllocas, *DT);
03546     PromotableAllocas.clear();
03547     return true;
03548   }
03549 
03550   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
03551   SSAUpdater SSA;
03552   DIBuilder DIB(*F.getParent());
03553   SmallVector<Instruction *, 64> Insts;
03554 
03555   // We need a worklist to walk the uses of each alloca.
03556   SmallVector<Instruction *, 8> Worklist;
03557   SmallPtrSet<Instruction *, 8> Visited;
03558   SmallVector<Instruction *, 32> DeadInsts;
03559 
03560   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
03561     AllocaInst *AI = PromotableAllocas[Idx];
03562     Insts.clear();
03563     Worklist.clear();
03564     Visited.clear();
03565 
03566     enqueueUsersInWorklist(*AI, Worklist, Visited);
03567 
03568     while (!Worklist.empty()) {
03569       Instruction *I = Worklist.pop_back_val();
03570 
03571       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
03572       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
03573       // leading to them) here. Eventually it should use them to optimize the
03574       // scalar values produced.
03575       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
03576         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
03577                II->getIntrinsicID() == Intrinsic::lifetime_end);
03578         II->eraseFromParent();
03579         continue;
03580       }
03581 
03582       // Push the loads and stores we find onto the list. SROA will already
03583       // have validated that all loads and stores are viable candidates for
03584       // promotion.
03585       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
03586         assert(LI->getType() == AI->getAllocatedType());
03587         Insts.push_back(LI);
03588         continue;
03589       }
03590       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
03591         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
03592         Insts.push_back(SI);
03593         continue;
03594       }
03595 
03596       // For everything else, we know that only no-op bitcasts and GEPs will
03597       // make it this far, just recurse through them and recall them for later
03598       // removal.
03599       DeadInsts.push_back(I);
03600       enqueueUsersInWorklist(*I, Worklist, Visited);
03601     }
03602     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
03603     while (!DeadInsts.empty())
03604       DeadInsts.pop_back_val()->eraseFromParent();
03605     AI->eraseFromParent();
03606   }
03607 
03608   PromotableAllocas.clear();
03609   return true;
03610 }
03611 
03612 bool SROA::runOnFunction(Function &F) {
03613   if (skipOptnoneFunction(F))
03614     return false;
03615 
03616   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
03617   C = &F.getContext();
03618   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
03619   if (!DLP) {
03620     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
03621     return false;
03622   }
03623   DL = &DLP->getDataLayout();
03624   DominatorTreeWrapperPass *DTWP =
03625       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
03626   DT = DTWP ? &DTWP->getDomTree() : nullptr;
03627 
03628   BasicBlock &EntryBB = F.getEntryBlock();
03629   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
03630        I != E; ++I)
03631     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03632       Worklist.insert(AI);
03633 
03634   bool Changed = false;
03635   // A set of deleted alloca instruction pointers which should be removed from
03636   // the list of promotable allocas.
03637   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
03638 
03639   do {
03640     while (!Worklist.empty()) {
03641       Changed |= runOnAlloca(*Worklist.pop_back_val());
03642       deleteDeadInstructions(DeletedAllocas);
03643 
03644       // Remove the deleted allocas from various lists so that we don't try to
03645       // continue processing them.
03646       if (!DeletedAllocas.empty()) {
03647         auto IsInSet = [&](AllocaInst *AI) {
03648           return DeletedAllocas.count(AI);
03649         };
03650         Worklist.remove_if(IsInSet);
03651         PostPromotionWorklist.remove_if(IsInSet);
03652         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
03653                                                PromotableAllocas.end(),
03654                                                IsInSet),
03655                                 PromotableAllocas.end());
03656         DeletedAllocas.clear();
03657       }
03658     }
03659 
03660     Changed |= promoteAllocas(F);
03661 
03662     Worklist = PostPromotionWorklist;
03663     PostPromotionWorklist.clear();
03664   } while (!Worklist.empty());
03665 
03666   return Changed;
03667 }
03668 
03669 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
03670   if (RequiresDomTree)
03671     AU.addRequired<DominatorTreeWrapperPass>();
03672   AU.setPreservesCFG();
03673 }