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 TBAA tag 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   MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
01155   unsigned Align = SomeLoad->getAlignment();
01156 
01157   // Rewrite all loads of the PN to use the new PHI.
01158   while (!PN.use_empty()) {
01159     LoadInst *LI = cast<LoadInst>(PN.user_back());
01160     LI->replaceAllUsesWith(NewPN);
01161     LI->eraseFromParent();
01162   }
01163 
01164   // Inject loads into all of the pred blocks.
01165   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
01166     BasicBlock *Pred = PN.getIncomingBlock(Idx);
01167     TerminatorInst *TI = Pred->getTerminator();
01168     Value *InVal = PN.getIncomingValue(Idx);
01169     IRBuilderTy PredBuilder(TI);
01170 
01171     LoadInst *Load = PredBuilder.CreateLoad(
01172         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
01173     ++NumLoadsSpeculated;
01174     Load->setAlignment(Align);
01175     if (TBAATag)
01176       Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
01177     NewPN->addIncoming(Load, Pred);
01178   }
01179 
01180   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
01181   PN.eraseFromParent();
01182 }
01183 
01184 /// Select instructions that use an alloca and are subsequently loaded can be
01185 /// rewritten to load both input pointers and then select between the result,
01186 /// allowing the load of the alloca to be promoted.
01187 /// From this:
01188 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01189 ///   %V = load i32* %P2
01190 /// to:
01191 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01192 ///   %V2 = load i32* %Other
01193 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01194 ///
01195 /// We can do this to a select if its only uses are loads and if the operand
01196 /// to the select can be loaded unconditionally.
01197 static bool isSafeSelectToSpeculate(SelectInst &SI,
01198                                     const DataLayout *DL = nullptr) {
01199   Value *TValue = SI.getTrueValue();
01200   Value *FValue = SI.getFalseValue();
01201   bool TDerefable = TValue->isDereferenceablePointer(DL);
01202   bool FDerefable = FValue->isDereferenceablePointer(DL);
01203 
01204   for (User *U : SI.users()) {
01205     LoadInst *LI = dyn_cast<LoadInst>(U);
01206     if (!LI || !LI->isSimple())
01207       return false;
01208 
01209     // Both operands to the select need to be dereferencable, either
01210     // absolutely (e.g. allocas) or at this point because we can see other
01211     // accesses to it.
01212     if (!TDerefable &&
01213         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
01214       return false;
01215     if (!FDerefable &&
01216         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
01217       return false;
01218   }
01219 
01220   return true;
01221 }
01222 
01223 static void speculateSelectInstLoads(SelectInst &SI) {
01224   DEBUG(dbgs() << "    original: " << SI << "\n");
01225 
01226   IRBuilderTy IRB(&SI);
01227   Value *TV = SI.getTrueValue();
01228   Value *FV = SI.getFalseValue();
01229   // Replace the loads of the select with a select of two loads.
01230   while (!SI.use_empty()) {
01231     LoadInst *LI = cast<LoadInst>(SI.user_back());
01232     assert(LI->isSimple() && "We only speculate simple loads");
01233 
01234     IRB.SetInsertPoint(LI);
01235     LoadInst *TL =
01236         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
01237     LoadInst *FL =
01238         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
01239     NumLoadsSpeculated += 2;
01240 
01241     // Transfer alignment and TBAA info if present.
01242     TL->setAlignment(LI->getAlignment());
01243     FL->setAlignment(LI->getAlignment());
01244     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
01245       TL->setMetadata(LLVMContext::MD_tbaa, Tag);
01246       FL->setMetadata(LLVMContext::MD_tbaa, Tag);
01247     }
01248 
01249     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
01250                                 LI->getName() + ".sroa.speculated");
01251 
01252     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
01253     LI->replaceAllUsesWith(V);
01254     LI->eraseFromParent();
01255   }
01256   SI.eraseFromParent();
01257 }
01258 
01259 /// \brief Build a GEP out of a base pointer and indices.
01260 ///
01261 /// This will return the BasePtr if that is valid, or build a new GEP
01262 /// instruction using the IRBuilder if GEP-ing is needed.
01263 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
01264                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
01265   if (Indices.empty())
01266     return BasePtr;
01267 
01268   // A single zero index is a no-op, so check for this and avoid building a GEP
01269   // in that case.
01270   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
01271     return BasePtr;
01272 
01273   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
01274 }
01275 
01276 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
01277 /// TargetTy without changing the offset of the pointer.
01278 ///
01279 /// This routine assumes we've already established a properly offset GEP with
01280 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
01281 /// zero-indices down through type layers until we find one the same as
01282 /// TargetTy. If we can't find one with the same type, we at least try to use
01283 /// one with the same size. If none of that works, we just produce the GEP as
01284 /// indicated by Indices to have the correct offset.
01285 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
01286                                     Value *BasePtr, Type *Ty, Type *TargetTy,
01287                                     SmallVectorImpl<Value *> &Indices,
01288                                     Twine NamePrefix) {
01289   if (Ty == TargetTy)
01290     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01291 
01292   // Pointer size to use for the indices.
01293   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
01294 
01295   // See if we can descend into a struct and locate a field with the correct
01296   // type.
01297   unsigned NumLayers = 0;
01298   Type *ElementTy = Ty;
01299   do {
01300     if (ElementTy->isPointerTy())
01301       break;
01302 
01303     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
01304       ElementTy = ArrayTy->getElementType();
01305       Indices.push_back(IRB.getIntN(PtrSize, 0));
01306     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
01307       ElementTy = VectorTy->getElementType();
01308       Indices.push_back(IRB.getInt32(0));
01309     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
01310       if (STy->element_begin() == STy->element_end())
01311         break; // Nothing left to descend into.
01312       ElementTy = *STy->element_begin();
01313       Indices.push_back(IRB.getInt32(0));
01314     } else {
01315       break;
01316     }
01317     ++NumLayers;
01318   } while (ElementTy != TargetTy);
01319   if (ElementTy != TargetTy)
01320     Indices.erase(Indices.end() - NumLayers, Indices.end());
01321 
01322   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
01323 }
01324 
01325 /// \brief Recursively compute indices for a natural GEP.
01326 ///
01327 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
01328 /// element types adding appropriate indices for the GEP.
01329 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
01330                                        Value *Ptr, Type *Ty, APInt &Offset,
01331                                        Type *TargetTy,
01332                                        SmallVectorImpl<Value *> &Indices,
01333                                        Twine NamePrefix) {
01334   if (Offset == 0)
01335     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, NamePrefix);
01336 
01337   // We can't recurse through pointer types.
01338   if (Ty->isPointerTy())
01339     return nullptr;
01340 
01341   // We try to analyze GEPs over vectors here, but note that these GEPs are
01342   // extremely poorly defined currently. The long-term goal is to remove GEPing
01343   // over a vector from the IR completely.
01344   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
01345     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
01346     if (ElementSizeInBits % 8 != 0) {
01347       // GEPs over non-multiple of 8 size vector elements are invalid.
01348       return nullptr;
01349     }
01350     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
01351     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01352     if (NumSkippedElements.ugt(VecTy->getNumElements()))
01353       return nullptr;
01354     Offset -= NumSkippedElements * ElementSize;
01355     Indices.push_back(IRB.getInt(NumSkippedElements));
01356     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
01357                                     Offset, TargetTy, Indices, NamePrefix);
01358   }
01359 
01360   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
01361     Type *ElementTy = ArrTy->getElementType();
01362     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01363     APInt NumSkippedElements = Offset.sdiv(ElementSize);
01364     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
01365       return nullptr;
01366 
01367     Offset -= NumSkippedElements * ElementSize;
01368     Indices.push_back(IRB.getInt(NumSkippedElements));
01369     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01370                                     Indices, NamePrefix);
01371   }
01372 
01373   StructType *STy = dyn_cast<StructType>(Ty);
01374   if (!STy)
01375     return nullptr;
01376 
01377   const StructLayout *SL = DL.getStructLayout(STy);
01378   uint64_t StructOffset = Offset.getZExtValue();
01379   if (StructOffset >= SL->getSizeInBytes())
01380     return nullptr;
01381   unsigned Index = SL->getElementContainingOffset(StructOffset);
01382   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
01383   Type *ElementTy = STy->getElementType(Index);
01384   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
01385     return nullptr; // The offset points into alignment padding.
01386 
01387   Indices.push_back(IRB.getInt32(Index));
01388   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01389                                   Indices, NamePrefix);
01390 }
01391 
01392 /// \brief Get a natural GEP from a base pointer to a particular offset and
01393 /// resulting in a particular type.
01394 ///
01395 /// The goal is to produce a "natural" looking GEP that works with the existing
01396 /// composite types to arrive at the appropriate offset and element type for
01397 /// a pointer. TargetTy is the element type the returned GEP should point-to if
01398 /// possible. We recurse by decreasing Offset, adding the appropriate index to
01399 /// Indices, and setting Ty to the result subtype.
01400 ///
01401 /// If no natural GEP can be constructed, this function returns null.
01402 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
01403                                       Value *Ptr, APInt Offset, Type *TargetTy,
01404                                       SmallVectorImpl<Value *> &Indices,
01405                                       Twine NamePrefix) {
01406   PointerType *Ty = cast<PointerType>(Ptr->getType());
01407 
01408   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
01409   // an i8.
01410   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
01411     return nullptr;
01412 
01413   Type *ElementTy = Ty->getElementType();
01414   if (!ElementTy->isSized())
01415     return nullptr; // We can't GEP through an unsized element.
01416   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
01417   if (ElementSize == 0)
01418     return nullptr; // Zero-length arrays can't help us build a natural GEP.
01419   APInt NumSkippedElements = Offset.sdiv(ElementSize);
01420 
01421   Offset -= NumSkippedElements * ElementSize;
01422   Indices.push_back(IRB.getInt(NumSkippedElements));
01423   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
01424                                   Indices, NamePrefix);
01425 }
01426 
01427 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
01428 /// resulting pointer has PointerTy.
01429 ///
01430 /// This tries very hard to compute a "natural" GEP which arrives at the offset
01431 /// and produces the pointer type desired. Where it cannot, it will try to use
01432 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
01433 /// fails, it will try to use an existing i8* and GEP to the byte offset and
01434 /// bitcast to the type.
01435 ///
01436 /// The strategy for finding the more natural GEPs is to peel off layers of the
01437 /// pointer, walking back through bit casts and GEPs, searching for a base
01438 /// pointer from which we can compute a natural GEP with the desired
01439 /// properties. The algorithm tries to fold as many constant indices into
01440 /// a single GEP as possible, thus making each GEP more independent of the
01441 /// surrounding code.
01442 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
01443                              APInt Offset, Type *PointerTy,
01444                              Twine NamePrefix) {
01445   // Even though we don't look through PHI nodes, we could be called on an
01446   // instruction in an unreachable block, which may be on a cycle.
01447   SmallPtrSet<Value *, 4> Visited;
01448   Visited.insert(Ptr);
01449   SmallVector<Value *, 4> Indices;
01450 
01451   // We may end up computing an offset pointer that has the wrong type. If we
01452   // never are able to compute one directly that has the correct type, we'll
01453   // fall back to it, so keep it around here.
01454   Value *OffsetPtr = nullptr;
01455 
01456   // Remember any i8 pointer we come across to re-use if we need to do a raw
01457   // byte offset.
01458   Value *Int8Ptr = nullptr;
01459   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
01460 
01461   Type *TargetTy = PointerTy->getPointerElementType();
01462 
01463   do {
01464     // First fold any existing GEPs into the offset.
01465     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
01466       APInt GEPOffset(Offset.getBitWidth(), 0);
01467       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
01468         break;
01469       Offset += GEPOffset;
01470       Ptr = GEP->getPointerOperand();
01471       if (!Visited.insert(Ptr))
01472         break;
01473     }
01474 
01475     // See if we can perform a natural GEP here.
01476     Indices.clear();
01477     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
01478                                            Indices, NamePrefix)) {
01479       if (P->getType() == PointerTy) {
01480         // Zap any offset pointer that we ended up computing in previous rounds.
01481         if (OffsetPtr && OffsetPtr->use_empty())
01482           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
01483             I->eraseFromParent();
01484         return P;
01485       }
01486       if (!OffsetPtr) {
01487         OffsetPtr = P;
01488       }
01489     }
01490 
01491     // Stash this pointer if we've found an i8*.
01492     if (Ptr->getType()->isIntegerTy(8)) {
01493       Int8Ptr = Ptr;
01494       Int8PtrOffset = Offset;
01495     }
01496 
01497     // Peel off a layer of the pointer and update the offset appropriately.
01498     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
01499       Ptr = cast<Operator>(Ptr)->getOperand(0);
01500     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
01501       if (GA->mayBeOverridden())
01502         break;
01503       Ptr = GA->getAliasee();
01504     } else {
01505       break;
01506     }
01507     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
01508   } while (Visited.insert(Ptr));
01509 
01510   if (!OffsetPtr) {
01511     if (!Int8Ptr) {
01512       Int8Ptr = IRB.CreateBitCast(
01513           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
01514           NamePrefix + "sroa_raw_cast");
01515       Int8PtrOffset = Offset;
01516     }
01517 
01518     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
01519       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
01520                             NamePrefix + "sroa_raw_idx");
01521   }
01522   Ptr = OffsetPtr;
01523 
01524   // On the off chance we were targeting i8*, guard the bitcast here.
01525   if (Ptr->getType() != PointerTy)
01526     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
01527 
01528   return Ptr;
01529 }
01530 
01531 /// \brief Test whether we can convert a value from the old to the new type.
01532 ///
01533 /// This predicate should be used to guard calls to convertValue in order to
01534 /// ensure that we only try to convert viable values. The strategy is that we
01535 /// will peel off single element struct and array wrappings to get to an
01536 /// underlying value, and convert that value.
01537 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
01538   if (OldTy == NewTy)
01539     return true;
01540   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01541     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01542       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
01543         return true;
01544   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
01545     return false;
01546   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
01547     return false;
01548 
01549   // We can convert pointers to integers and vice-versa. Same for vectors
01550   // of pointers and integers.
01551   OldTy = OldTy->getScalarType();
01552   NewTy = NewTy->getScalarType();
01553   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
01554     if (NewTy->isPointerTy() && OldTy->isPointerTy())
01555       return true;
01556     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
01557       return true;
01558     return false;
01559   }
01560 
01561   return true;
01562 }
01563 
01564 /// \brief Generic routine to convert an SSA value to a value of a different
01565 /// type.
01566 ///
01567 /// This will try various different casting techniques, such as bitcasts,
01568 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
01569 /// two types for viability with this routine.
01570 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01571                            Type *NewTy) {
01572   Type *OldTy = V->getType();
01573   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
01574 
01575   if (OldTy == NewTy)
01576     return V;
01577 
01578   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
01579     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
01580       if (NewITy->getBitWidth() > OldITy->getBitWidth())
01581         return IRB.CreateZExt(V, NewITy);
01582 
01583   // See if we need inttoptr for this type pair. A cast involving both scalars
01584   // and vectors requires and additional bitcast.
01585   if (OldTy->getScalarType()->isIntegerTy() &&
01586       NewTy->getScalarType()->isPointerTy()) {
01587     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
01588     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01589       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01590                                 NewTy);
01591 
01592     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
01593     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01594       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
01595                                 NewTy);
01596 
01597     return IRB.CreateIntToPtr(V, NewTy);
01598   }
01599 
01600   // See if we need ptrtoint for this type pair. A cast involving both scalars
01601   // and vectors requires and additional bitcast.
01602   if (OldTy->getScalarType()->isPointerTy() &&
01603       NewTy->getScalarType()->isIntegerTy()) {
01604     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
01605     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
01606       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01607                                NewTy);
01608 
01609     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
01610     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
01611       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
01612                                NewTy);
01613 
01614     return IRB.CreatePtrToInt(V, NewTy);
01615   }
01616 
01617   return IRB.CreateBitCast(V, NewTy);
01618 }
01619 
01620 /// \brief Test whether the given slice use can be promoted to a vector.
01621 ///
01622 /// This function is called to test each entry in a partioning which is slated
01623 /// for a single slice.
01624 static bool isVectorPromotionViableForSlice(
01625     const DataLayout &DL, AllocaSlices &S, uint64_t SliceBeginOffset,
01626     uint64_t SliceEndOffset, VectorType *Ty, uint64_t ElementSize,
01627     AllocaSlices::const_iterator I) {
01628   // First validate the slice offsets.
01629   uint64_t BeginOffset =
01630       std::max(I->beginOffset(), SliceBeginOffset) - SliceBeginOffset;
01631   uint64_t BeginIndex = BeginOffset / ElementSize;
01632   if (BeginIndex * ElementSize != BeginOffset ||
01633       BeginIndex >= Ty->getNumElements())
01634     return false;
01635   uint64_t EndOffset =
01636       std::min(I->endOffset(), SliceEndOffset) - SliceBeginOffset;
01637   uint64_t EndIndex = EndOffset / ElementSize;
01638   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
01639     return false;
01640 
01641   assert(EndIndex > BeginIndex && "Empty vector!");
01642   uint64_t NumElements = EndIndex - BeginIndex;
01643   Type *SliceTy =
01644       (NumElements == 1) ? Ty->getElementType()
01645                          : VectorType::get(Ty->getElementType(), NumElements);
01646 
01647   Type *SplitIntTy =
01648       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
01649 
01650   Use *U = I->getUse();
01651 
01652   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01653     if (MI->isVolatile())
01654       return false;
01655     if (!I->isSplittable())
01656       return false; // Skip any unsplittable intrinsics.
01657   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
01658     // Disable vector promotion when there are loads or stores of an FCA.
01659     return false;
01660   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01661     if (LI->isVolatile())
01662       return false;
01663     Type *LTy = LI->getType();
01664     if (SliceBeginOffset > I->beginOffset() ||
01665         SliceEndOffset < I->endOffset()) {
01666       assert(LTy->isIntegerTy());
01667       LTy = SplitIntTy;
01668     }
01669     if (!canConvertValue(DL, SliceTy, LTy))
01670       return false;
01671   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01672     if (SI->isVolatile())
01673       return false;
01674     Type *STy = SI->getValueOperand()->getType();
01675     if (SliceBeginOffset > I->beginOffset() ||
01676         SliceEndOffset < I->endOffset()) {
01677       assert(STy->isIntegerTy());
01678       STy = SplitIntTy;
01679     }
01680     if (!canConvertValue(DL, STy, SliceTy))
01681       return false;
01682   } else {
01683     return false;
01684   }
01685 
01686   return true;
01687 }
01688 
01689 /// \brief Test whether the given alloca partitioning and range of slices can be
01690 /// promoted to a vector.
01691 ///
01692 /// This is a quick test to check whether we can rewrite a particular alloca
01693 /// partition (and its newly formed alloca) into a vector alloca with only
01694 /// whole-vector loads and stores such that it could be promoted to a vector
01695 /// SSA value. We only can ensure this for a limited set of operations, and we
01696 /// don't want to do the rewrites unless we are confident that the result will
01697 /// be promotable, so we have an early test here.
01698 static bool
01699 isVectorPromotionViable(const DataLayout &DL, Type *AllocaTy, AllocaSlices &S,
01700                         uint64_t SliceBeginOffset, uint64_t SliceEndOffset,
01701                         AllocaSlices::const_iterator I,
01702                         AllocaSlices::const_iterator E,
01703                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01704   VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
01705   if (!Ty)
01706     return false;
01707 
01708   uint64_t ElementSize = DL.getTypeSizeInBits(Ty->getScalarType());
01709 
01710   // While the definition of LLVM vectors is bitpacked, we don't support sizes
01711   // that aren't byte sized.
01712   if (ElementSize % 8)
01713     return false;
01714   assert((DL.getTypeSizeInBits(Ty) % 8) == 0 &&
01715          "vector size not a multiple of element size?");
01716   ElementSize /= 8;
01717 
01718   for (; I != E; ++I)
01719     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01720                                          SliceEndOffset, Ty, ElementSize, I))
01721       return false;
01722 
01723   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01724                                                         SUE = SplitUses.end();
01725        SUI != SUE; ++SUI)
01726     if (!isVectorPromotionViableForSlice(DL, S, SliceBeginOffset,
01727                                          SliceEndOffset, Ty, ElementSize, *SUI))
01728       return false;
01729 
01730   return true;
01731 }
01732 
01733 /// \brief Test whether a slice of an alloca is valid for integer widening.
01734 ///
01735 /// This implements the necessary checking for the \c isIntegerWideningViable
01736 /// test below on a single slice of the alloca.
01737 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
01738                                             Type *AllocaTy,
01739                                             uint64_t AllocBeginOffset,
01740                                             uint64_t Size, AllocaSlices &S,
01741                                             AllocaSlices::const_iterator I,
01742                                             bool &WholeAllocaOp) {
01743   uint64_t RelBegin = I->beginOffset() - AllocBeginOffset;
01744   uint64_t RelEnd = I->endOffset() - AllocBeginOffset;
01745 
01746   // We can't reasonably handle cases where the load or store extends past
01747   // the end of the aloca's type and into its padding.
01748   if (RelEnd > Size)
01749     return false;
01750 
01751   Use *U = I->getUse();
01752 
01753   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
01754     if (LI->isVolatile())
01755       return false;
01756     if (RelBegin == 0 && RelEnd == Size)
01757       WholeAllocaOp = true;
01758     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
01759       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01760         return false;
01761     } else if (RelBegin != 0 || RelEnd != Size ||
01762                !canConvertValue(DL, AllocaTy, LI->getType())) {
01763       // Non-integer loads need to be convertible from the alloca type so that
01764       // they are promotable.
01765       return false;
01766     }
01767   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
01768     Type *ValueTy = SI->getValueOperand()->getType();
01769     if (SI->isVolatile())
01770       return false;
01771     if (RelBegin == 0 && RelEnd == Size)
01772       WholeAllocaOp = true;
01773     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
01774       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
01775         return false;
01776     } else if (RelBegin != 0 || RelEnd != Size ||
01777                !canConvertValue(DL, ValueTy, AllocaTy)) {
01778       // Non-integer stores need to be convertible to the alloca type so that
01779       // they are promotable.
01780       return false;
01781     }
01782   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
01783     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
01784       return false;
01785     if (!I->isSplittable())
01786       return false; // Skip any unsplittable intrinsics.
01787   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
01788     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01789         II->getIntrinsicID() != Intrinsic::lifetime_end)
01790       return false;
01791   } else {
01792     return false;
01793   }
01794 
01795   return true;
01796 }
01797 
01798 /// \brief Test whether the given alloca partition's integer operations can be
01799 /// widened to promotable ones.
01800 ///
01801 /// This is a quick test to check whether we can rewrite the integer loads and
01802 /// stores to a particular alloca into wider loads and stores and be able to
01803 /// promote the resulting alloca.
01804 static bool
01805 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
01806                         uint64_t AllocBeginOffset, AllocaSlices &S,
01807                         AllocaSlices::const_iterator I,
01808                         AllocaSlices::const_iterator E,
01809                         ArrayRef<AllocaSlices::iterator> SplitUses) {
01810   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
01811   // Don't create integer types larger than the maximum bitwidth.
01812   if (SizeInBits > IntegerType::MAX_INT_BITS)
01813     return false;
01814 
01815   // Don't try to handle allocas with bit-padding.
01816   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
01817     return false;
01818 
01819   // We need to ensure that an integer type with the appropriate bitwidth can
01820   // be converted to the alloca type, whatever that is. We don't want to force
01821   // the alloca itself to have an integer type if there is a more suitable one.
01822   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
01823   if (!canConvertValue(DL, AllocaTy, IntTy) ||
01824       !canConvertValue(DL, IntTy, AllocaTy))
01825     return false;
01826 
01827   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
01828 
01829   // While examining uses, we ensure that the alloca has a covering load or
01830   // store. We don't want to widen the integer operations only to fail to
01831   // promote due to some other unsplittable entry (which we may make splittable
01832   // later). However, if there are only splittable uses, go ahead and assume
01833   // that we cover the alloca.
01834   bool WholeAllocaOp = (I != E) ? false : DL.isLegalInteger(SizeInBits);
01835 
01836   for (; I != E; ++I)
01837     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01838                                          S, I, WholeAllocaOp))
01839       return false;
01840 
01841   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
01842                                                         SUE = SplitUses.end();
01843        SUI != SUE; ++SUI)
01844     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
01845                                          S, *SUI, WholeAllocaOp))
01846       return false;
01847 
01848   return WholeAllocaOp;
01849 }
01850 
01851 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
01852                              IntegerType *Ty, uint64_t Offset,
01853                              const Twine &Name) {
01854   DEBUG(dbgs() << "       start: " << *V << "\n");
01855   IntegerType *IntTy = cast<IntegerType>(V->getType());
01856   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01857          "Element extends past full value");
01858   uint64_t ShAmt = 8*Offset;
01859   if (DL.isBigEndian())
01860     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01861   if (ShAmt) {
01862     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
01863     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01864   }
01865   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01866          "Cannot extract to a larger integer!");
01867   if (Ty != IntTy) {
01868     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
01869     DEBUG(dbgs() << "     trunced: " << *V << "\n");
01870   }
01871   return V;
01872 }
01873 
01874 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
01875                             Value *V, uint64_t Offset, const Twine &Name) {
01876   IntegerType *IntTy = cast<IntegerType>(Old->getType());
01877   IntegerType *Ty = cast<IntegerType>(V->getType());
01878   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
01879          "Cannot insert a larger integer!");
01880   DEBUG(dbgs() << "       start: " << *V << "\n");
01881   if (Ty != IntTy) {
01882     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
01883     DEBUG(dbgs() << "    extended: " << *V << "\n");
01884   }
01885   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
01886          "Element store outside of alloca store");
01887   uint64_t ShAmt = 8*Offset;
01888   if (DL.isBigEndian())
01889     ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
01890   if (ShAmt) {
01891     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
01892     DEBUG(dbgs() << "     shifted: " << *V << "\n");
01893   }
01894 
01895   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
01896     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
01897     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
01898     DEBUG(dbgs() << "      masked: " << *Old << "\n");
01899     V = IRB.CreateOr(Old, V, Name + ".insert");
01900     DEBUG(dbgs() << "    inserted: " << *V << "\n");
01901   }
01902   return V;
01903 }
01904 
01905 static Value *extractVector(IRBuilderTy &IRB, Value *V,
01906                             unsigned BeginIndex, unsigned EndIndex,
01907                             const Twine &Name) {
01908   VectorType *VecTy = cast<VectorType>(V->getType());
01909   unsigned NumElements = EndIndex - BeginIndex;
01910   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
01911 
01912   if (NumElements == VecTy->getNumElements())
01913     return V;
01914 
01915   if (NumElements == 1) {
01916     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
01917                                  Name + ".extract");
01918     DEBUG(dbgs() << "     extract: " << *V << "\n");
01919     return V;
01920   }
01921 
01922   SmallVector<Constant*, 8> Mask;
01923   Mask.reserve(NumElements);
01924   for (unsigned i = BeginIndex; i != EndIndex; ++i)
01925     Mask.push_back(IRB.getInt32(i));
01926   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01927                               ConstantVector::get(Mask),
01928                               Name + ".extract");
01929   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
01930   return V;
01931 }
01932 
01933 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
01934                            unsigned BeginIndex, const Twine &Name) {
01935   VectorType *VecTy = cast<VectorType>(Old->getType());
01936   assert(VecTy && "Can only insert a vector into a vector");
01937 
01938   VectorType *Ty = dyn_cast<VectorType>(V->getType());
01939   if (!Ty) {
01940     // Single element to insert.
01941     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
01942                                 Name + ".insert");
01943     DEBUG(dbgs() <<  "     insert: " << *V << "\n");
01944     return V;
01945   }
01946 
01947   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
01948          "Too many elements!");
01949   if (Ty->getNumElements() == VecTy->getNumElements()) {
01950     assert(V->getType() == VecTy && "Vector type mismatch");
01951     return V;
01952   }
01953   unsigned EndIndex = BeginIndex + Ty->getNumElements();
01954 
01955   // When inserting a smaller vector into the larger to store, we first
01956   // use a shuffle vector to widen it with undef elements, and then
01957   // a second shuffle vector to select between the loaded vector and the
01958   // incoming vector.
01959   SmallVector<Constant*, 8> Mask;
01960   Mask.reserve(VecTy->getNumElements());
01961   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01962     if (i >= BeginIndex && i < EndIndex)
01963       Mask.push_back(IRB.getInt32(i - BeginIndex));
01964     else
01965       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
01966   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
01967                               ConstantVector::get(Mask),
01968                               Name + ".expand");
01969   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
01970 
01971   Mask.clear();
01972   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
01973     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
01974 
01975   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
01976 
01977   DEBUG(dbgs() << "    blend: " << *V << "\n");
01978   return V;
01979 }
01980 
01981 namespace {
01982 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
01983 /// to use a new alloca.
01984 ///
01985 /// Also implements the rewriting to vector-based accesses when the partition
01986 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
01987 /// lives here.
01988 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
01989   // Befriend the base class so it can delegate to private visit methods.
01990   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
01991   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
01992 
01993   const DataLayout &DL;
01994   AllocaSlices &S;
01995   SROA &Pass;
01996   AllocaInst &OldAI, &NewAI;
01997   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
01998   Type *NewAllocaTy;
01999 
02000   // If we are rewriting an alloca partition which can be written as pure
02001   // vector operations, we stash extra information here. When VecTy is
02002   // non-null, we have some strict guarantees about the rewritten alloca:
02003   //   - The new alloca is exactly the size of the vector type here.
02004   //   - The accesses all either map to the entire vector or to a single
02005   //     element.
02006   //   - The set of accessing instructions is only one of those handled above
02007   //     in isVectorPromotionViable. Generally these are the same access kinds
02008   //     which are promotable via mem2reg.
02009   VectorType *VecTy;
02010   Type *ElementTy;
02011   uint64_t ElementSize;
02012 
02013   // This is a convenience and flag variable that will be null unless the new
02014   // alloca's integer operations should be widened to this integer type due to
02015   // passing isIntegerWideningViable above. If it is non-null, the desired
02016   // integer type will be stored here for easy access during rewriting.
02017   IntegerType *IntTy;
02018 
02019   // The original offset of the slice currently being rewritten relative to
02020   // the original alloca.
02021   uint64_t BeginOffset, EndOffset;
02022   // The new offsets of the slice currently being rewritten relative to the
02023   // original alloca.
02024   uint64_t NewBeginOffset, NewEndOffset;
02025 
02026   uint64_t SliceSize;
02027   bool IsSplittable;
02028   bool IsSplit;
02029   Use *OldUse;
02030   Instruction *OldPtr;
02031 
02032   // Track post-rewrite users which are PHI nodes and Selects.
02033   SmallPtrSetImpl<PHINode *> &PHIUsers;
02034   SmallPtrSetImpl<SelectInst *> &SelectUsers;
02035 
02036   // Utility IR builder, whose name prefix is setup for each visited use, and
02037   // the insertion point is set to point to the user.
02038   IRBuilderTy IRB;
02039 
02040 public:
02041   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &S, SROA &Pass,
02042                       AllocaInst &OldAI, AllocaInst &NewAI,
02043                       uint64_t NewAllocaBeginOffset,
02044                       uint64_t NewAllocaEndOffset, bool IsVectorPromotable,
02045                       bool IsIntegerPromotable,
02046                       SmallPtrSetImpl<PHINode *> &PHIUsers,
02047                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
02048       : DL(DL), S(S), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
02049         NewAllocaBeginOffset(NewAllocaBeginOffset),
02050         NewAllocaEndOffset(NewAllocaEndOffset),
02051         NewAllocaTy(NewAI.getAllocatedType()),
02052         VecTy(IsVectorPromotable ? cast<VectorType>(NewAllocaTy) : nullptr),
02053         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
02054         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
02055         IntTy(IsIntegerPromotable
02056                   ? Type::getIntNTy(
02057                         NewAI.getContext(),
02058                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
02059                   : nullptr),
02060         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
02061         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
02062         IRB(NewAI.getContext(), ConstantFolder()) {
02063     if (VecTy) {
02064       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
02065              "Only multiple-of-8 sized vector elements are viable");
02066       ++NumVectorized;
02067     }
02068     assert((!IsVectorPromotable && !IsIntegerPromotable) ||
02069            IsVectorPromotable != IsIntegerPromotable);
02070   }
02071 
02072   bool visit(AllocaSlices::const_iterator I) {
02073     bool CanSROA = true;
02074     BeginOffset = I->beginOffset();
02075     EndOffset = I->endOffset();
02076     IsSplittable = I->isSplittable();
02077     IsSplit =
02078         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
02079 
02080     // Compute the intersecting offset range.
02081     assert(BeginOffset < NewAllocaEndOffset);
02082     assert(EndOffset > NewAllocaBeginOffset);
02083     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
02084     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
02085 
02086     SliceSize = NewEndOffset - NewBeginOffset;
02087 
02088     OldUse = I->getUse();
02089     OldPtr = cast<Instruction>(OldUse->get());
02090 
02091     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
02092     IRB.SetInsertPoint(OldUserI);
02093     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
02094     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
02095 
02096     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
02097     if (VecTy || IntTy)
02098       assert(CanSROA);
02099     return CanSROA;
02100   }
02101 
02102 private:
02103   // Make sure the other visit overloads are visible.
02104   using Base::visit;
02105 
02106   // Every instruction which can end up as a user must have a rewrite rule.
02107   bool visitInstruction(Instruction &I) {
02108     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
02109     llvm_unreachable("No rewrite rule for this instruction!");
02110   }
02111 
02112   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
02113     // Note that the offset computation can use BeginOffset or NewBeginOffset
02114     // interchangeably for unsplit slices.
02115     assert(IsSplit || BeginOffset == NewBeginOffset);
02116     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02117 
02118 #ifndef NDEBUG
02119     StringRef OldName = OldPtr->getName();
02120     // Skip through the last '.sroa.' component of the name.
02121     size_t LastSROAPrefix = OldName.rfind(".sroa.");
02122     if (LastSROAPrefix != StringRef::npos) {
02123       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
02124       // Look for an SROA slice index.
02125       size_t IndexEnd = OldName.find_first_not_of("0123456789");
02126       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
02127         // Strip the index and look for the offset.
02128         OldName = OldName.substr(IndexEnd + 1);
02129         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
02130         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
02131           // Strip the offset.
02132           OldName = OldName.substr(OffsetEnd + 1);
02133       }
02134     }
02135     // Strip any SROA suffixes as well.
02136     OldName = OldName.substr(0, OldName.find(".sroa_"));
02137 #endif
02138 
02139     return getAdjustedPtr(IRB, DL, &NewAI,
02140                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
02141 #ifndef NDEBUG
02142                           Twine(OldName) + "."
02143 #else
02144                           Twine()
02145 #endif
02146                           );
02147   }
02148 
02149   /// \brief Compute suitable alignment to access this slice of the *new* alloca.
02150   ///
02151   /// You can optionally pass a type to this routine and if that type's ABI
02152   /// alignment is itself suitable, this will return zero.
02153   unsigned getSliceAlign(Type *Ty = nullptr) {
02154     unsigned NewAIAlign = NewAI.getAlignment();
02155     if (!NewAIAlign)
02156       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
02157     unsigned Align = MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
02158     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
02159   }
02160 
02161   unsigned getIndex(uint64_t Offset) {
02162     assert(VecTy && "Can only call getIndex when rewriting a vector");
02163     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
02164     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
02165     uint32_t Index = RelOffset / ElementSize;
02166     assert(Index * ElementSize == RelOffset);
02167     return Index;
02168   }
02169 
02170   void deleteIfTriviallyDead(Value *V) {
02171     Instruction *I = cast<Instruction>(V);
02172     if (isInstructionTriviallyDead(I))
02173       Pass.DeadInsts.insert(I);
02174   }
02175 
02176   Value *rewriteVectorizedLoadInst() {
02177     unsigned BeginIndex = getIndex(NewBeginOffset);
02178     unsigned EndIndex = getIndex(NewEndOffset);
02179     assert(EndIndex > BeginIndex && "Empty vector!");
02180 
02181     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02182                                      "load");
02183     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
02184   }
02185 
02186   Value *rewriteIntegerLoad(LoadInst &LI) {
02187     assert(IntTy && "We cannot insert an integer to the alloca");
02188     assert(!LI.isVolatile());
02189     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02190                                      "load");
02191     V = convertValue(DL, IRB, V, IntTy);
02192     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02193     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02194     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
02195       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
02196                          "extract");
02197     return V;
02198   }
02199 
02200   bool visitLoadInst(LoadInst &LI) {
02201     DEBUG(dbgs() << "    original: " << LI << "\n");
02202     Value *OldOp = LI.getOperand(0);
02203     assert(OldOp == OldPtr);
02204 
02205     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
02206                              : LI.getType();
02207     bool IsPtrAdjusted = false;
02208     Value *V;
02209     if (VecTy) {
02210       V = rewriteVectorizedLoadInst();
02211     } else if (IntTy && LI.getType()->isIntegerTy()) {
02212       V = rewriteIntegerLoad(LI);
02213     } else if (NewBeginOffset == NewAllocaBeginOffset &&
02214                canConvertValue(DL, NewAllocaTy, LI.getType())) {
02215       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02216                                 LI.isVolatile(), LI.getName());
02217     } else {
02218       Type *LTy = TargetTy->getPointerTo();
02219       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
02220                                 getSliceAlign(TargetTy), LI.isVolatile(),
02221                                 LI.getName());
02222       IsPtrAdjusted = true;
02223     }
02224     V = convertValue(DL, IRB, V, TargetTy);
02225 
02226     if (IsSplit) {
02227       assert(!LI.isVolatile());
02228       assert(LI.getType()->isIntegerTy() &&
02229              "Only integer type loads and stores are split");
02230       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
02231              "Split load isn't smaller than original load");
02232       assert(LI.getType()->getIntegerBitWidth() ==
02233              DL.getTypeStoreSizeInBits(LI.getType()) &&
02234              "Non-byte-multiple bit width");
02235       // Move the insertion point just past the load so that we can refer to it.
02236       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
02237       // Create a placeholder value with the same type as LI to use as the
02238       // basis for the new value. This allows us to replace the uses of LI with
02239       // the computed value, and then replace the placeholder with LI, leaving
02240       // LI only used for this computation.
02241       Value *Placeholder
02242         = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
02243       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset,
02244                         "insert");
02245       LI.replaceAllUsesWith(V);
02246       Placeholder->replaceAllUsesWith(&LI);
02247       delete Placeholder;
02248     } else {
02249       LI.replaceAllUsesWith(V);
02250     }
02251 
02252     Pass.DeadInsts.insert(&LI);
02253     deleteIfTriviallyDead(OldOp);
02254     DEBUG(dbgs() << "          to: " << *V << "\n");
02255     return !LI.isVolatile() && !IsPtrAdjusted;
02256   }
02257 
02258   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
02259     if (V->getType() != VecTy) {
02260       unsigned BeginIndex = getIndex(NewBeginOffset);
02261       unsigned EndIndex = getIndex(NewEndOffset);
02262       assert(EndIndex > BeginIndex && "Empty vector!");
02263       unsigned NumElements = EndIndex - BeginIndex;
02264       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02265       Type *SliceTy =
02266           (NumElements == 1) ? ElementTy
02267                              : VectorType::get(ElementTy, NumElements);
02268       if (V->getType() != SliceTy)
02269         V = convertValue(DL, IRB, V, SliceTy);
02270 
02271       // Mix in the existing elements.
02272       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02273                                          "load");
02274       V = insertVector(IRB, Old, V, BeginIndex, "vec");
02275     }
02276     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02277     Pass.DeadInsts.insert(&SI);
02278 
02279     (void)Store;
02280     DEBUG(dbgs() << "          to: " << *Store << "\n");
02281     return true;
02282   }
02283 
02284   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
02285     assert(IntTy && "We cannot extract an integer from the alloca");
02286     assert(!SI.isVolatile());
02287     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
02288       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02289                                          "oldload");
02290       Old = convertValue(DL, IRB, Old, IntTy);
02291       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
02292       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
02293       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset,
02294                         "insert");
02295     }
02296     V = convertValue(DL, IRB, V, NewAllocaTy);
02297     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
02298     Pass.DeadInsts.insert(&SI);
02299     (void)Store;
02300     DEBUG(dbgs() << "          to: " << *Store << "\n");
02301     return true;
02302   }
02303 
02304   bool visitStoreInst(StoreInst &SI) {
02305     DEBUG(dbgs() << "    original: " << SI << "\n");
02306     Value *OldOp = SI.getOperand(1);
02307     assert(OldOp == OldPtr);
02308 
02309     Value *V = SI.getValueOperand();
02310 
02311     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02312     // alloca that should be re-examined after promoting this alloca.
02313     if (V->getType()->isPointerTy())
02314       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
02315         Pass.PostPromotionWorklist.insert(AI);
02316 
02317     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
02318       assert(!SI.isVolatile());
02319       assert(V->getType()->isIntegerTy() &&
02320              "Only integer type loads and stores are split");
02321       assert(V->getType()->getIntegerBitWidth() ==
02322              DL.getTypeStoreSizeInBits(V->getType()) &&
02323              "Non-byte-multiple bit width");
02324       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
02325       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset,
02326                          "extract");
02327     }
02328 
02329     if (VecTy)
02330       return rewriteVectorizedStoreInst(V, SI, OldOp);
02331     if (IntTy && V->getType()->isIntegerTy())
02332       return rewriteIntegerStore(V, SI);
02333 
02334     StoreInst *NewSI;
02335     if (NewBeginOffset == NewAllocaBeginOffset &&
02336         NewEndOffset == NewAllocaEndOffset &&
02337         canConvertValue(DL, V->getType(), NewAllocaTy)) {
02338       V = convertValue(DL, IRB, V, NewAllocaTy);
02339       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02340                                      SI.isVolatile());
02341     } else {
02342       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
02343       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
02344                                      SI.isVolatile());
02345     }
02346     (void)NewSI;
02347     Pass.DeadInsts.insert(&SI);
02348     deleteIfTriviallyDead(OldOp);
02349 
02350     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
02351     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
02352   }
02353 
02354   /// \brief Compute an integer value from splatting an i8 across the given
02355   /// number of bytes.
02356   ///
02357   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
02358   /// call this routine.
02359   /// FIXME: Heed the advice above.
02360   ///
02361   /// \param V The i8 value to splat.
02362   /// \param Size The number of bytes in the output (assuming i8 is one byte)
02363   Value *getIntegerSplat(Value *V, unsigned Size) {
02364     assert(Size > 0 && "Expected a positive number of bytes.");
02365     IntegerType *VTy = cast<IntegerType>(V->getType());
02366     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
02367     if (Size == 1)
02368       return V;
02369 
02370     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
02371     V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
02372                       ConstantExpr::getUDiv(
02373                         Constant::getAllOnesValue(SplatIntTy),
02374                         ConstantExpr::getZExt(
02375                           Constant::getAllOnesValue(V->getType()),
02376                           SplatIntTy)),
02377                       "isplat");
02378     return V;
02379   }
02380 
02381   /// \brief Compute a vector splat for a given element value.
02382   Value *getVectorSplat(Value *V, unsigned NumElements) {
02383     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
02384     DEBUG(dbgs() << "       splat: " << *V << "\n");
02385     return V;
02386   }
02387 
02388   bool visitMemSetInst(MemSetInst &II) {
02389     DEBUG(dbgs() << "    original: " << II << "\n");
02390     assert(II.getRawDest() == OldPtr);
02391 
02392     // If the memset has a variable size, it cannot be split, just adjust the
02393     // pointer to the new alloca.
02394     if (!isa<Constant>(II.getLength())) {
02395       assert(!IsSplit);
02396       assert(NewBeginOffset == BeginOffset);
02397       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
02398       Type *CstTy = II.getAlignmentCst()->getType();
02399       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
02400 
02401       deleteIfTriviallyDead(OldPtr);
02402       return false;
02403     }
02404 
02405     // Record this instruction for deletion.
02406     Pass.DeadInsts.insert(&II);
02407 
02408     Type *AllocaTy = NewAI.getAllocatedType();
02409     Type *ScalarTy = AllocaTy->getScalarType();
02410 
02411     // If this doesn't map cleanly onto the alloca type, and that type isn't
02412     // a single value type, just emit a memset.
02413     if (!VecTy && !IntTy &&
02414         (BeginOffset > NewAllocaBeginOffset ||
02415          EndOffset < NewAllocaEndOffset ||
02416          !AllocaTy->isSingleValueType() ||
02417          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
02418          DL.getTypeSizeInBits(ScalarTy)%8 != 0)) {
02419       Type *SizeTy = II.getLength()->getType();
02420       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02421       CallInst *New = IRB.CreateMemSet(
02422           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
02423           getSliceAlign(), II.isVolatile());
02424       (void)New;
02425       DEBUG(dbgs() << "          to: " << *New << "\n");
02426       return false;
02427     }
02428 
02429     // If we can represent this as a simple value, we have to build the actual
02430     // value to store, which requires expanding the byte present in memset to
02431     // a sensible representation for the alloca type. This is essentially
02432     // splatting the byte to a sufficiently wide integer, splatting it across
02433     // any desired vector width, and bitcasting to the final type.
02434     Value *V;
02435 
02436     if (VecTy) {
02437       // If this is a memset of a vectorized alloca, insert it.
02438       assert(ElementTy == ScalarTy);
02439 
02440       unsigned BeginIndex = getIndex(NewBeginOffset);
02441       unsigned EndIndex = getIndex(NewEndOffset);
02442       assert(EndIndex > BeginIndex && "Empty vector!");
02443       unsigned NumElements = EndIndex - BeginIndex;
02444       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
02445 
02446       Value *Splat =
02447           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
02448       Splat = convertValue(DL, IRB, Splat, ElementTy);
02449       if (NumElements > 1)
02450         Splat = getVectorSplat(Splat, NumElements);
02451 
02452       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02453                                          "oldload");
02454       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
02455     } else if (IntTy) {
02456       // If this is a memset on an alloca where we can widen stores, insert the
02457       // set integer.
02458       assert(!II.isVolatile());
02459 
02460       uint64_t Size = NewEndOffset - NewBeginOffset;
02461       V = getIntegerSplat(II.getValue(), Size);
02462 
02463       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
02464                     EndOffset != NewAllocaBeginOffset)) {
02465         Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02466                                            "oldload");
02467         Old = convertValue(DL, IRB, Old, IntTy);
02468         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02469         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
02470       } else {
02471         assert(V->getType() == IntTy &&
02472                "Wrong type for an alloca wide integer!");
02473       }
02474       V = convertValue(DL, IRB, V, AllocaTy);
02475     } else {
02476       // Established these invariants above.
02477       assert(NewBeginOffset == NewAllocaBeginOffset);
02478       assert(NewEndOffset == NewAllocaEndOffset);
02479 
02480       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
02481       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
02482         V = getVectorSplat(V, AllocaVecTy->getNumElements());
02483 
02484       V = convertValue(DL, IRB, V, AllocaTy);
02485     }
02486 
02487     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
02488                                         II.isVolatile());
02489     (void)New;
02490     DEBUG(dbgs() << "          to: " << *New << "\n");
02491     return !II.isVolatile();
02492   }
02493 
02494   bool visitMemTransferInst(MemTransferInst &II) {
02495     // Rewriting of memory transfer instructions can be a bit tricky. We break
02496     // them into two categories: split intrinsics and unsplit intrinsics.
02497 
02498     DEBUG(dbgs() << "    original: " << II << "\n");
02499 
02500     bool IsDest = &II.getRawDestUse() == OldUse;
02501     assert((IsDest && II.getRawDest() == OldPtr) ||
02502            (!IsDest && II.getRawSource() == OldPtr));
02503 
02504     unsigned SliceAlign = getSliceAlign();
02505 
02506     // For unsplit intrinsics, we simply modify the source and destination
02507     // pointers in place. This isn't just an optimization, it is a matter of
02508     // correctness. With unsplit intrinsics we may be dealing with transfers
02509     // within a single alloca before SROA ran, or with transfers that have
02510     // a variable length. We may also be dealing with memmove instead of
02511     // memcpy, and so simply updating the pointers is the necessary for us to
02512     // update both source and dest of a single call.
02513     if (!IsSplittable) {
02514       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02515       if (IsDest)
02516         II.setDest(AdjustedPtr);
02517       else
02518         II.setSource(AdjustedPtr);
02519 
02520       if (II.getAlignment() > SliceAlign) {
02521         Type *CstTy = II.getAlignmentCst()->getType();
02522         II.setAlignment(
02523             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
02524       }
02525 
02526       DEBUG(dbgs() << "          to: " << II << "\n");
02527       deleteIfTriviallyDead(OldPtr);
02528       return false;
02529     }
02530     // For split transfer intrinsics we have an incredibly useful assurance:
02531     // the source and destination do not reside within the same alloca, and at
02532     // least one of them does not escape. This means that we can replace
02533     // memmove with memcpy, and we don't need to worry about all manner of
02534     // downsides to splitting and transforming the operations.
02535 
02536     // If this doesn't map cleanly onto the alloca type, and that type isn't
02537     // a single value type, just emit a memcpy.
02538     bool EmitMemCpy
02539       = !VecTy && !IntTy && (BeginOffset > NewAllocaBeginOffset ||
02540                              EndOffset < NewAllocaEndOffset ||
02541                              !NewAI.getAllocatedType()->isSingleValueType());
02542 
02543     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
02544     // size hasn't been shrunk based on analysis of the viable range, this is
02545     // a no-op.
02546     if (EmitMemCpy && &OldAI == &NewAI) {
02547       // Ensure the start lines up.
02548       assert(NewBeginOffset == BeginOffset);
02549 
02550       // Rewrite the size as needed.
02551       if (NewEndOffset != EndOffset)
02552         II.setLength(ConstantInt::get(II.getLength()->getType(),
02553                                       NewEndOffset - NewBeginOffset));
02554       return false;
02555     }
02556     // Record this instruction for deletion.
02557     Pass.DeadInsts.insert(&II);
02558 
02559     // Strip all inbounds GEPs and pointer casts to try to dig out any root
02560     // alloca that should be re-examined after rewriting this instruction.
02561     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
02562     if (AllocaInst *AI
02563           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
02564       assert(AI != &OldAI && AI != &NewAI &&
02565              "Splittable transfers cannot reach the same alloca on both ends.");
02566       Pass.Worklist.insert(AI);
02567     }
02568 
02569     Type *OtherPtrTy = OtherPtr->getType();
02570     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
02571 
02572     // Compute the relative offset for the other pointer within the transfer.
02573     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
02574     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
02575     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
02576                                    OtherOffset.zextOrTrunc(64).getZExtValue());
02577 
02578     if (EmitMemCpy) {
02579       // Compute the other pointer, folding as much as possible to produce
02580       // a single, simple GEP in most cases.
02581       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02582                                 OtherPtr->getName() + ".");
02583 
02584       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02585       Type *SizeTy = II.getLength()->getType();
02586       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
02587 
02588       CallInst *New = IRB.CreateMemCpy(
02589           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
02590           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
02591       (void)New;
02592       DEBUG(dbgs() << "          to: " << *New << "\n");
02593       return false;
02594     }
02595 
02596     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
02597                          NewEndOffset == NewAllocaEndOffset;
02598     uint64_t Size = NewEndOffset - NewBeginOffset;
02599     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
02600     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
02601     unsigned NumElements = EndIndex - BeginIndex;
02602     IntegerType *SubIntTy
02603       = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : nullptr;
02604 
02605     // Reset the other pointer type to match the register type we're going to
02606     // use, but using the address space of the original other pointer.
02607     if (VecTy && !IsWholeAlloca) {
02608       if (NumElements == 1)
02609         OtherPtrTy = VecTy->getElementType();
02610       else
02611         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
02612 
02613       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
02614     } else if (IntTy && !IsWholeAlloca) {
02615       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
02616     } else {
02617       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
02618     }
02619 
02620     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
02621                                    OtherPtr->getName() + ".");
02622     unsigned SrcAlign = OtherAlign;
02623     Value *DstPtr = &NewAI;
02624     unsigned DstAlign = SliceAlign;
02625     if (!IsDest) {
02626       std::swap(SrcPtr, DstPtr);
02627       std::swap(SrcAlign, DstAlign);
02628     }
02629 
02630     Value *Src;
02631     if (VecTy && !IsWholeAlloca && !IsDest) {
02632       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02633                                   "load");
02634       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
02635     } else if (IntTy && !IsWholeAlloca && !IsDest) {
02636       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02637                                   "load");
02638       Src = convertValue(DL, IRB, Src, IntTy);
02639       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02640       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
02641     } else {
02642       Src = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
02643                                   "copyload");
02644     }
02645 
02646     if (VecTy && !IsWholeAlloca && IsDest) {
02647       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02648                                          "oldload");
02649       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
02650     } else if (IntTy && !IsWholeAlloca && IsDest) {
02651       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
02652                                          "oldload");
02653       Old = convertValue(DL, IRB, Old, IntTy);
02654       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
02655       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
02656       Src = convertValue(DL, IRB, Src, NewAllocaTy);
02657     }
02658 
02659     StoreInst *Store = cast<StoreInst>(
02660         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
02661     (void)Store;
02662     DEBUG(dbgs() << "          to: " << *Store << "\n");
02663     return !II.isVolatile();
02664   }
02665 
02666   bool visitIntrinsicInst(IntrinsicInst &II) {
02667     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
02668            II.getIntrinsicID() == Intrinsic::lifetime_end);
02669     DEBUG(dbgs() << "    original: " << II << "\n");
02670     assert(II.getArgOperand(1) == OldPtr);
02671 
02672     // Record this instruction for deletion.
02673     Pass.DeadInsts.insert(&II);
02674 
02675     ConstantInt *Size
02676       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
02677                          NewEndOffset - NewBeginOffset);
02678     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02679     Value *New;
02680     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
02681       New = IRB.CreateLifetimeStart(Ptr, Size);
02682     else
02683       New = IRB.CreateLifetimeEnd(Ptr, Size);
02684 
02685     (void)New;
02686     DEBUG(dbgs() << "          to: " << *New << "\n");
02687     return true;
02688   }
02689 
02690   bool visitPHINode(PHINode &PN) {
02691     DEBUG(dbgs() << "    original: " << PN << "\n");
02692     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
02693     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
02694 
02695     // We would like to compute a new pointer in only one place, but have it be
02696     // as local as possible to the PHI. To do that, we re-use the location of
02697     // the old pointer, which necessarily must be in the right position to
02698     // dominate the PHI.
02699     IRBuilderTy PtrBuilder(IRB);
02700     PtrBuilder.SetInsertPoint(OldPtr);
02701     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
02702 
02703     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
02704     // Replace the operands which were using the old pointer.
02705     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
02706 
02707     DEBUG(dbgs() << "          to: " << PN << "\n");
02708     deleteIfTriviallyDead(OldPtr);
02709 
02710     // PHIs can't be promoted on their own, but often can be speculated. We
02711     // check the speculation outside of the rewriter so that we see the
02712     // fully-rewritten alloca.
02713     PHIUsers.insert(&PN);
02714     return true;
02715   }
02716 
02717   bool visitSelectInst(SelectInst &SI) {
02718     DEBUG(dbgs() << "    original: " << SI << "\n");
02719     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
02720            "Pointer isn't an operand!");
02721     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
02722     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
02723 
02724     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
02725     // Replace the operands which were using the old pointer.
02726     if (SI.getOperand(1) == OldPtr)
02727       SI.setOperand(1, NewPtr);
02728     if (SI.getOperand(2) == OldPtr)
02729       SI.setOperand(2, NewPtr);
02730 
02731     DEBUG(dbgs() << "          to: " << SI << "\n");
02732     deleteIfTriviallyDead(OldPtr);
02733 
02734     // Selects can't be promoted on their own, but often can be speculated. We
02735     // check the speculation outside of the rewriter so that we see the
02736     // fully-rewritten alloca.
02737     SelectUsers.insert(&SI);
02738     return true;
02739   }
02740 
02741 };
02742 }
02743 
02744 namespace {
02745 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
02746 ///
02747 /// This pass aggressively rewrites all aggregate loads and stores on
02748 /// a particular pointer (or any pointer derived from it which we can identify)
02749 /// with scalar loads and stores.
02750 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
02751   // Befriend the base class so it can delegate to private visit methods.
02752   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
02753 
02754   const DataLayout &DL;
02755 
02756   /// Queue of pointer uses to analyze and potentially rewrite.
02757   SmallVector<Use *, 8> Queue;
02758 
02759   /// Set to prevent us from cycling with phi nodes and loops.
02760   SmallPtrSet<User *, 8> Visited;
02761 
02762   /// The current pointer use being rewritten. This is used to dig up the used
02763   /// value (as opposed to the user).
02764   Use *U;
02765 
02766 public:
02767   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
02768 
02769   /// Rewrite loads and stores through a pointer and all pointers derived from
02770   /// it.
02771   bool rewrite(Instruction &I) {
02772     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
02773     enqueueUsers(I);
02774     bool Changed = false;
02775     while (!Queue.empty()) {
02776       U = Queue.pop_back_val();
02777       Changed |= visit(cast<Instruction>(U->getUser()));
02778     }
02779     return Changed;
02780   }
02781 
02782 private:
02783   /// Enqueue all the users of the given instruction for further processing.
02784   /// This uses a set to de-duplicate users.
02785   void enqueueUsers(Instruction &I) {
02786     for (Use &U : I.uses())
02787       if (Visited.insert(U.getUser()))
02788         Queue.push_back(&U);
02789   }
02790 
02791   // Conservative default is to not rewrite anything.
02792   bool visitInstruction(Instruction &I) { return false; }
02793 
02794   /// \brief Generic recursive split emission class.
02795   template <typename Derived>
02796   class OpSplitter {
02797   protected:
02798     /// The builder used to form new instructions.
02799     IRBuilderTy IRB;
02800     /// The indices which to be used with insert- or extractvalue to select the
02801     /// appropriate value within the aggregate.
02802     SmallVector<unsigned, 4> Indices;
02803     /// The indices to a GEP instruction which will move Ptr to the correct slot
02804     /// within the aggregate.
02805     SmallVector<Value *, 4> GEPIndices;
02806     /// The base pointer of the original op, used as a base for GEPing the
02807     /// split operations.
02808     Value *Ptr;
02809 
02810     /// Initialize the splitter with an insertion point, Ptr and start with a
02811     /// single zero GEP index.
02812     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
02813       : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
02814 
02815   public:
02816     /// \brief Generic recursive split emission routine.
02817     ///
02818     /// This method recursively splits an aggregate op (load or store) into
02819     /// scalar or vector ops. It splits recursively until it hits a single value
02820     /// and emits that single value operation via the template argument.
02821     ///
02822     /// The logic of this routine relies on GEPs and insertvalue and
02823     /// extractvalue all operating with the same fundamental index list, merely
02824     /// formatted differently (GEPs need actual values).
02825     ///
02826     /// \param Ty  The type being split recursively into smaller ops.
02827     /// \param Agg The aggregate value being built up or stored, depending on
02828     /// whether this is splitting a load or a store respectively.
02829     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
02830       if (Ty->isSingleValueType())
02831         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
02832 
02833       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02834         unsigned OldSize = Indices.size();
02835         (void)OldSize;
02836         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
02837              ++Idx) {
02838           assert(Indices.size() == OldSize && "Did not return to the old size");
02839           Indices.push_back(Idx);
02840           GEPIndices.push_back(IRB.getInt32(Idx));
02841           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
02842           GEPIndices.pop_back();
02843           Indices.pop_back();
02844         }
02845         return;
02846       }
02847 
02848       if (StructType *STy = dyn_cast<StructType>(Ty)) {
02849         unsigned OldSize = Indices.size();
02850         (void)OldSize;
02851         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
02852              ++Idx) {
02853           assert(Indices.size() == OldSize && "Did not return to the old size");
02854           Indices.push_back(Idx);
02855           GEPIndices.push_back(IRB.getInt32(Idx));
02856           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
02857           GEPIndices.pop_back();
02858           Indices.pop_back();
02859         }
02860         return;
02861       }
02862 
02863       llvm_unreachable("Only arrays and structs are aggregate loadable types");
02864     }
02865   };
02866 
02867   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
02868     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02869       : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
02870 
02871     /// Emit a leaf load of a single value. This is called at the leaves of the
02872     /// recursive emission to actually load values.
02873     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02874       assert(Ty->isSingleValueType());
02875       // Load the single value and insert it using the indices.
02876       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
02877       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
02878       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
02879       DEBUG(dbgs() << "          to: " << *Load << "\n");
02880     }
02881   };
02882 
02883   bool visitLoadInst(LoadInst &LI) {
02884     assert(LI.getPointerOperand() == *U);
02885     if (!LI.isSimple() || LI.getType()->isSingleValueType())
02886       return false;
02887 
02888     // We have an aggregate being loaded, split it apart.
02889     DEBUG(dbgs() << "    original: " << LI << "\n");
02890     LoadOpSplitter Splitter(&LI, *U);
02891     Value *V = UndefValue::get(LI.getType());
02892     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
02893     LI.replaceAllUsesWith(V);
02894     LI.eraseFromParent();
02895     return true;
02896   }
02897 
02898   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
02899     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
02900       : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
02901 
02902     /// Emit a leaf store of a single value. This is called at the leaves of the
02903     /// recursive emission to actually produce stores.
02904     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
02905       assert(Ty->isSingleValueType());
02906       // Extract the single value and store it using the indices.
02907       Value *Store = IRB.CreateStore(
02908         IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
02909         IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
02910       (void)Store;
02911       DEBUG(dbgs() << "          to: " << *Store << "\n");
02912     }
02913   };
02914 
02915   bool visitStoreInst(StoreInst &SI) {
02916     if (!SI.isSimple() || SI.getPointerOperand() != *U)
02917       return false;
02918     Value *V = SI.getValueOperand();
02919     if (V->getType()->isSingleValueType())
02920       return false;
02921 
02922     // We have an aggregate being stored, split it apart.
02923     DEBUG(dbgs() << "    original: " << SI << "\n");
02924     StoreOpSplitter Splitter(&SI, *U);
02925     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
02926     SI.eraseFromParent();
02927     return true;
02928   }
02929 
02930   bool visitBitCastInst(BitCastInst &BC) {
02931     enqueueUsers(BC);
02932     return false;
02933   }
02934 
02935   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
02936     enqueueUsers(GEPI);
02937     return false;
02938   }
02939 
02940   bool visitPHINode(PHINode &PN) {
02941     enqueueUsers(PN);
02942     return false;
02943   }
02944 
02945   bool visitSelectInst(SelectInst &SI) {
02946     enqueueUsers(SI);
02947     return false;
02948   }
02949 };
02950 }
02951 
02952 /// \brief Strip aggregate type wrapping.
02953 ///
02954 /// This removes no-op aggregate types wrapping an underlying type. It will
02955 /// strip as many layers of types as it can without changing either the type
02956 /// size or the allocated size.
02957 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
02958   if (Ty->isSingleValueType())
02959     return Ty;
02960 
02961   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
02962   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
02963 
02964   Type *InnerTy;
02965   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
02966     InnerTy = ArrTy->getElementType();
02967   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
02968     const StructLayout *SL = DL.getStructLayout(STy);
02969     unsigned Index = SL->getElementContainingOffset(0);
02970     InnerTy = STy->getElementType(Index);
02971   } else {
02972     return Ty;
02973   }
02974 
02975   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
02976       TypeSize > DL.getTypeSizeInBits(InnerTy))
02977     return Ty;
02978 
02979   return stripAggregateTypeWrapping(DL, InnerTy);
02980 }
02981 
02982 /// \brief Try to find a partition of the aggregate type passed in for a given
02983 /// offset and size.
02984 ///
02985 /// This recurses through the aggregate type and tries to compute a subtype
02986 /// based on the offset and size. When the offset and size span a sub-section
02987 /// of an array, it will even compute a new array type for that sub-section,
02988 /// and the same for structs.
02989 ///
02990 /// Note that this routine is very strict and tries to find a partition of the
02991 /// type which produces the *exact* right offset and size. It is not forgiving
02992 /// when the size or offset cause either end of type-based partition to be off.
02993 /// Also, this is a best-effort routine. It is reasonable to give up and not
02994 /// return a type if necessary.
02995 static Type *getTypePartition(const DataLayout &DL, Type *Ty,
02996                               uint64_t Offset, uint64_t Size) {
02997   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
02998     return stripAggregateTypeWrapping(DL, Ty);
02999   if (Offset > DL.getTypeAllocSize(Ty) ||
03000       (DL.getTypeAllocSize(Ty) - Offset) < Size)
03001     return nullptr;
03002 
03003   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
03004     // We can't partition pointers...
03005     if (SeqTy->isPointerTy())
03006       return nullptr;
03007 
03008     Type *ElementTy = SeqTy->getElementType();
03009     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03010     uint64_t NumSkippedElements = Offset / ElementSize;
03011     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
03012       if (NumSkippedElements >= ArrTy->getNumElements())
03013         return nullptr;
03014     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
03015       if (NumSkippedElements >= VecTy->getNumElements())
03016         return nullptr;
03017     }
03018     Offset -= NumSkippedElements * ElementSize;
03019 
03020     // First check if we need to recurse.
03021     if (Offset > 0 || Size < ElementSize) {
03022       // Bail if the partition ends in a different array element.
03023       if ((Offset + Size) > ElementSize)
03024         return nullptr;
03025       // Recurse through the element type trying to peel off offset bytes.
03026       return getTypePartition(DL, ElementTy, Offset, Size);
03027     }
03028     assert(Offset == 0);
03029 
03030     if (Size == ElementSize)
03031       return stripAggregateTypeWrapping(DL, ElementTy);
03032     assert(Size > ElementSize);
03033     uint64_t NumElements = Size / ElementSize;
03034     if (NumElements * ElementSize != Size)
03035       return nullptr;
03036     return ArrayType::get(ElementTy, NumElements);
03037   }
03038 
03039   StructType *STy = dyn_cast<StructType>(Ty);
03040   if (!STy)
03041     return nullptr;
03042 
03043   const StructLayout *SL = DL.getStructLayout(STy);
03044   if (Offset >= SL->getSizeInBytes())
03045     return nullptr;
03046   uint64_t EndOffset = Offset + Size;
03047   if (EndOffset > SL->getSizeInBytes())
03048     return nullptr;
03049 
03050   unsigned Index = SL->getElementContainingOffset(Offset);
03051   Offset -= SL->getElementOffset(Index);
03052 
03053   Type *ElementTy = STy->getElementType(Index);
03054   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
03055   if (Offset >= ElementSize)
03056     return nullptr; // The offset points into alignment padding.
03057 
03058   // See if any partition must be contained by the element.
03059   if (Offset > 0 || Size < ElementSize) {
03060     if ((Offset + Size) > ElementSize)
03061       return nullptr;
03062     return getTypePartition(DL, ElementTy, Offset, Size);
03063   }
03064   assert(Offset == 0);
03065 
03066   if (Size == ElementSize)
03067     return stripAggregateTypeWrapping(DL, ElementTy);
03068 
03069   StructType::element_iterator EI = STy->element_begin() + Index,
03070                                EE = STy->element_end();
03071   if (EndOffset < SL->getSizeInBytes()) {
03072     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
03073     if (Index == EndIndex)
03074       return nullptr; // Within a single element and its padding.
03075 
03076     // Don't try to form "natural" types if the elements don't line up with the
03077     // expected size.
03078     // FIXME: We could potentially recurse down through the last element in the
03079     // sub-struct to find a natural end point.
03080     if (SL->getElementOffset(EndIndex) != EndOffset)
03081       return nullptr;
03082 
03083     assert(Index < EndIndex);
03084     EE = STy->element_begin() + EndIndex;
03085   }
03086 
03087   // Try to build up a sub-structure.
03088   StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
03089                                       STy->isPacked());
03090   const StructLayout *SubSL = DL.getStructLayout(SubTy);
03091   if (Size != SubSL->getSizeInBytes())
03092     return nullptr; // The sub-struct doesn't have quite the size needed.
03093 
03094   return SubTy;
03095 }
03096 
03097 /// \brief Rewrite an alloca partition's users.
03098 ///
03099 /// This routine drives both of the rewriting goals of the SROA pass. It tries
03100 /// to rewrite uses of an alloca partition to be conducive for SSA value
03101 /// promotion. If the partition needs a new, more refined alloca, this will
03102 /// build that new alloca, preserving as much type information as possible, and
03103 /// rewrite the uses of the old alloca to point at the new one and have the
03104 /// appropriate new offsets. It also evaluates how successful the rewrite was
03105 /// at enabling promotion and if it was successful queues the alloca to be
03106 /// promoted.
03107 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &S,
03108                             AllocaSlices::iterator B, AllocaSlices::iterator E,
03109                             int64_t BeginOffset, int64_t EndOffset,
03110                             ArrayRef<AllocaSlices::iterator> SplitUses) {
03111   assert(BeginOffset < EndOffset);
03112   uint64_t SliceSize = EndOffset - BeginOffset;
03113 
03114   // Try to compute a friendly type for this partition of the alloca. This
03115   // won't always succeed, in which case we fall back to a legal integer type
03116   // or an i8 array of an appropriate size.
03117   Type *SliceTy = nullptr;
03118   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
03119     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
03120       SliceTy = CommonUseTy;
03121   if (!SliceTy)
03122     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
03123                                                  BeginOffset, SliceSize))
03124       SliceTy = TypePartitionTy;
03125   if ((!SliceTy || (SliceTy->isArrayTy() &&
03126                     SliceTy->getArrayElementType()->isIntegerTy())) &&
03127       DL->isLegalInteger(SliceSize * 8))
03128     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
03129   if (!SliceTy)
03130     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
03131   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
03132 
03133   bool IsVectorPromotable = isVectorPromotionViable(
03134       *DL, SliceTy, S, BeginOffset, EndOffset, B, E, SplitUses);
03135 
03136   bool IsIntegerPromotable =
03137       !IsVectorPromotable &&
03138       isIntegerWideningViable(*DL, SliceTy, BeginOffset, S, B, E, SplitUses);
03139 
03140   // Check for the case where we're going to rewrite to a new alloca of the
03141   // exact same type as the original, and with the same access offsets. In that
03142   // case, re-use the existing alloca, but still run through the rewriter to
03143   // perform phi and select speculation.
03144   AllocaInst *NewAI;
03145   if (SliceTy == AI.getAllocatedType()) {
03146     assert(BeginOffset == 0 &&
03147            "Non-zero begin offset but same alloca type");
03148     NewAI = &AI;
03149     // FIXME: We should be able to bail at this point with "nothing changed".
03150     // FIXME: We might want to defer PHI speculation until after here.
03151   } else {
03152     unsigned Alignment = AI.getAlignment();
03153     if (!Alignment) {
03154       // The minimum alignment which users can rely on when the explicit
03155       // alignment is omitted or zero is that required by the ABI for this
03156       // type.
03157       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
03158     }
03159     Alignment = MinAlign(Alignment, BeginOffset);
03160     // If we will get at least this much alignment from the type alone, leave
03161     // the alloca's alignment unconstrained.
03162     if (Alignment <= DL->getABITypeAlignment(SliceTy))
03163       Alignment = 0;
03164     NewAI = new AllocaInst(SliceTy, nullptr, Alignment,
03165                            AI.getName() + ".sroa." + Twine(B - S.begin()), &AI);
03166     ++NumNewAllocas;
03167   }
03168 
03169   DEBUG(dbgs() << "Rewriting alloca partition "
03170                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
03171                << "\n");
03172 
03173   // Track the high watermark on the worklist as it is only relevant for
03174   // promoted allocas. We will reset it to this point if the alloca is not in
03175   // fact scheduled for promotion.
03176   unsigned PPWOldSize = PostPromotionWorklist.size();
03177   unsigned NumUses = 0;
03178   SmallPtrSet<PHINode *, 8> PHIUsers;
03179   SmallPtrSet<SelectInst *, 8> SelectUsers;
03180 
03181   AllocaSliceRewriter Rewriter(*DL, S, *this, AI, *NewAI, BeginOffset,
03182                                EndOffset, IsVectorPromotable,
03183                                IsIntegerPromotable, PHIUsers, SelectUsers);
03184   bool Promotable = true;
03185   for (ArrayRef<AllocaSlices::iterator>::const_iterator SUI = SplitUses.begin(),
03186                                                         SUE = SplitUses.end();
03187        SUI != SUE; ++SUI) {
03188     DEBUG(dbgs() << "  rewriting split ");
03189     DEBUG(S.printSlice(dbgs(), *SUI, ""));
03190     Promotable &= Rewriter.visit(*SUI);
03191     ++NumUses;
03192   }
03193   for (AllocaSlices::iterator I = B; I != E; ++I) {
03194     DEBUG(dbgs() << "  rewriting ");
03195     DEBUG(S.printSlice(dbgs(), I, ""));
03196     Promotable &= Rewriter.visit(I);
03197     ++NumUses;
03198   }
03199 
03200   NumAllocaPartitionUses += NumUses;
03201   MaxUsesPerAllocaPartition =
03202       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
03203 
03204   // Now that we've processed all the slices in the new partition, check if any
03205   // PHIs or Selects would block promotion.
03206   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03207                                             E = PHIUsers.end();
03208        I != E; ++I)
03209     if (!isSafePHIToSpeculate(**I, DL)) {
03210       Promotable = false;
03211       PHIUsers.clear();
03212       SelectUsers.clear();
03213       break;
03214     }
03215   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03216                                                E = SelectUsers.end();
03217        I != E; ++I)
03218     if (!isSafeSelectToSpeculate(**I, DL)) {
03219       Promotable = false;
03220       PHIUsers.clear();
03221       SelectUsers.clear();
03222       break;
03223     }
03224 
03225   if (Promotable) {
03226     if (PHIUsers.empty() && SelectUsers.empty()) {
03227       // Promote the alloca.
03228       PromotableAllocas.push_back(NewAI);
03229     } else {
03230       // If we have either PHIs or Selects to speculate, add them to those
03231       // worklists and re-queue the new alloca so that we promote in on the
03232       // next iteration.
03233       for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
03234                                                 E = PHIUsers.end();
03235            I != E; ++I)
03236         SpeculatablePHIs.insert(*I);
03237       for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
03238                                                    E = SelectUsers.end();
03239            I != E; ++I)
03240         SpeculatableSelects.insert(*I);
03241       Worklist.insert(NewAI);
03242     }
03243   } else {
03244     // If we can't promote the alloca, iterate on it to check for new
03245     // refinements exposed by splitting the current alloca. Don't iterate on an
03246     // alloca which didn't actually change and didn't get promoted.
03247     if (NewAI != &AI)
03248       Worklist.insert(NewAI);
03249 
03250     // Drop any post-promotion work items if promotion didn't happen.
03251     while (PostPromotionWorklist.size() > PPWOldSize)
03252       PostPromotionWorklist.pop_back();
03253   }
03254 
03255   return true;
03256 }
03257 
03258 static void
03259 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
03260                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
03261   if (Offset >= MaxSplitUseEndOffset) {
03262     SplitUses.clear();
03263     MaxSplitUseEndOffset = 0;
03264     return;
03265   }
03266 
03267   size_t SplitUsesOldSize = SplitUses.size();
03268   SplitUses.erase(std::remove_if(SplitUses.begin(), SplitUses.end(),
03269                                  [Offset](const AllocaSlices::iterator &I) {
03270                     return I->endOffset() <= Offset;
03271                   }),
03272                   SplitUses.end());
03273   if (SplitUsesOldSize == SplitUses.size())
03274     return;
03275 
03276   // Recompute the max. While this is linear, so is remove_if.
03277   MaxSplitUseEndOffset = 0;
03278   for (SmallVectorImpl<AllocaSlices::iterator>::iterator
03279            SUI = SplitUses.begin(),
03280            SUE = SplitUses.end();
03281        SUI != SUE; ++SUI)
03282     MaxSplitUseEndOffset = std::max((*SUI)->endOffset(), MaxSplitUseEndOffset);
03283 }
03284 
03285 /// \brief Walks the slices of an alloca and form partitions based on them,
03286 /// rewriting each of their uses.
03287 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &S) {
03288   if (S.begin() == S.end())
03289     return false;
03290 
03291   unsigned NumPartitions = 0;
03292   bool Changed = false;
03293   SmallVector<AllocaSlices::iterator, 4> SplitUses;
03294   uint64_t MaxSplitUseEndOffset = 0;
03295 
03296   uint64_t BeginOffset = S.begin()->beginOffset();
03297 
03298   for (AllocaSlices::iterator SI = S.begin(), SJ = std::next(SI), SE = S.end();
03299        SI != SE; SI = SJ) {
03300     uint64_t MaxEndOffset = SI->endOffset();
03301 
03302     if (!SI->isSplittable()) {
03303       // When we're forming an unsplittable region, it must always start at the
03304       // first slice and will extend through its end.
03305       assert(BeginOffset == SI->beginOffset());
03306 
03307       // Form a partition including all of the overlapping slices with this
03308       // unsplittable slice.
03309       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03310         if (!SJ->isSplittable())
03311           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03312         ++SJ;
03313       }
03314     } else {
03315       assert(SI->isSplittable()); // Established above.
03316 
03317       // Collect all of the overlapping splittable slices.
03318       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
03319              SJ->isSplittable()) {
03320         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
03321         ++SJ;
03322       }
03323 
03324       // Back up MaxEndOffset and SJ if we ended the span early when
03325       // encountering an unsplittable slice.
03326       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
03327         assert(!SJ->isSplittable());
03328         MaxEndOffset = SJ->beginOffset();
03329       }
03330     }
03331 
03332     // Check if we have managed to move the end offset forward yet. If so,
03333     // we'll have to rewrite uses and erase old split uses.
03334     if (BeginOffset < MaxEndOffset) {
03335       // Rewrite a sequence of overlapping slices.
03336       Changed |=
03337           rewritePartition(AI, S, SI, SJ, BeginOffset, MaxEndOffset, SplitUses);
03338       ++NumPartitions;
03339 
03340       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
03341     }
03342 
03343     // Accumulate all the splittable slices from the [SI,SJ) region which
03344     // overlap going forward.
03345     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
03346       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
03347         SplitUses.push_back(SK);
03348         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
03349       }
03350 
03351     // If we're already at the end and we have no split uses, we're done.
03352     if (SJ == SE && SplitUses.empty())
03353       break;
03354 
03355     // If we have no split uses or no gap in offsets, we're ready to move to
03356     // the next slice.
03357     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
03358       BeginOffset = SJ->beginOffset();
03359       continue;
03360     }
03361 
03362     // Even if we have split slices, if the next slice is splittable and the
03363     // split slices reach it, we can simply set up the beginning offset of the
03364     // next iteration to bridge between them.
03365     if (SJ != SE && SJ->isSplittable() &&
03366         MaxSplitUseEndOffset > SJ->beginOffset()) {
03367       BeginOffset = MaxEndOffset;
03368       continue;
03369     }
03370 
03371     // Otherwise, we have a tail of split slices. Rewrite them with an empty
03372     // range of slices.
03373     uint64_t PostSplitEndOffset =
03374         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
03375 
03376     Changed |= rewritePartition(AI, S, SJ, SJ, MaxEndOffset, PostSplitEndOffset,
03377                                 SplitUses);
03378     ++NumPartitions;
03379 
03380     if (SJ == SE)
03381       break; // Skip the rest, we don't need to do any cleanup.
03382 
03383     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
03384                             PostSplitEndOffset);
03385 
03386     // Now just reset the begin offset for the next iteration.
03387     BeginOffset = SJ->beginOffset();
03388   }
03389 
03390   NumAllocaPartitions += NumPartitions;
03391   MaxPartitionsPerAlloca =
03392       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
03393 
03394   return Changed;
03395 }
03396 
03397 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
03398 void SROA::clobberUse(Use &U) {
03399   Value *OldV = U;
03400   // Replace the use with an undef value.
03401   U = UndefValue::get(OldV->getType());
03402 
03403   // Check for this making an instruction dead. We have to garbage collect
03404   // all the dead instructions to ensure the uses of any alloca end up being
03405   // minimal.
03406   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
03407     if (isInstructionTriviallyDead(OldI)) {
03408       DeadInsts.insert(OldI);
03409     }
03410 }
03411 
03412 /// \brief Analyze an alloca for SROA.
03413 ///
03414 /// This analyzes the alloca to ensure we can reason about it, builds
03415 /// the slices of the alloca, and then hands it off to be split and
03416 /// rewritten as needed.
03417 bool SROA::runOnAlloca(AllocaInst &AI) {
03418   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
03419   ++NumAllocasAnalyzed;
03420 
03421   // Special case dead allocas, as they're trivial.
03422   if (AI.use_empty()) {
03423     AI.eraseFromParent();
03424     return true;
03425   }
03426 
03427   // Skip alloca forms that this analysis can't handle.
03428   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
03429       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
03430     return false;
03431 
03432   bool Changed = false;
03433 
03434   // First, split any FCA loads and stores touching this alloca to promote
03435   // better splitting and promotion opportunities.
03436   AggLoadStoreRewriter AggRewriter(*DL);
03437   Changed |= AggRewriter.rewrite(AI);
03438 
03439   // Build the slices using a recursive instruction-visiting builder.
03440   AllocaSlices S(*DL, AI);
03441   DEBUG(S.print(dbgs()));
03442   if (S.isEscaped())
03443     return Changed;
03444 
03445   // Delete all the dead users of this alloca before splitting and rewriting it.
03446   for (AllocaSlices::dead_user_iterator DI = S.dead_user_begin(),
03447                                         DE = S.dead_user_end();
03448        DI != DE; ++DI) {
03449     // Free up everything used by this instruction.
03450     for (Use &DeadOp : (*DI)->operands())
03451       clobberUse(DeadOp);
03452 
03453     // Now replace the uses of this instruction.
03454     (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
03455 
03456     // And mark it for deletion.
03457     DeadInsts.insert(*DI);
03458     Changed = true;
03459   }
03460   for (AllocaSlices::dead_op_iterator DO = S.dead_op_begin(),
03461                                       DE = S.dead_op_end();
03462        DO != DE; ++DO) {
03463     clobberUse(**DO);
03464     Changed = true;
03465   }
03466 
03467   // No slices to split. Leave the dead alloca for a later pass to clean up.
03468   if (S.begin() == S.end())
03469     return Changed;
03470 
03471   Changed |= splitAlloca(AI, S);
03472 
03473   DEBUG(dbgs() << "  Speculating PHIs\n");
03474   while (!SpeculatablePHIs.empty())
03475     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
03476 
03477   DEBUG(dbgs() << "  Speculating Selects\n");
03478   while (!SpeculatableSelects.empty())
03479     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
03480 
03481   return Changed;
03482 }
03483 
03484 /// \brief Delete the dead instructions accumulated in this run.
03485 ///
03486 /// Recursively deletes the dead instructions we've accumulated. This is done
03487 /// at the very end to maximize locality of the recursive delete and to
03488 /// minimize the problems of invalidated instruction pointers as such pointers
03489 /// are used heavily in the intermediate stages of the algorithm.
03490 ///
03491 /// We also record the alloca instructions deleted here so that they aren't
03492 /// subsequently handed to mem2reg to promote.
03493 void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
03494   while (!DeadInsts.empty()) {
03495     Instruction *I = DeadInsts.pop_back_val();
03496     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
03497 
03498     I->replaceAllUsesWith(UndefValue::get(I->getType()));
03499 
03500     for (Use &Operand : I->operands())
03501       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
03502         // Zero out the operand and see if it becomes trivially dead.
03503         Operand = nullptr;
03504         if (isInstructionTriviallyDead(U))
03505           DeadInsts.insert(U);
03506       }
03507 
03508     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03509       DeletedAllocas.insert(AI);
03510 
03511     ++NumDeleted;
03512     I->eraseFromParent();
03513   }
03514 }
03515 
03516 static void enqueueUsersInWorklist(Instruction &I,
03517                                    SmallVectorImpl<Instruction *> &Worklist,
03518                                    SmallPtrSet<Instruction *, 8> &Visited) {
03519   for (User *U : I.users())
03520     if (Visited.insert(cast<Instruction>(U)))
03521       Worklist.push_back(cast<Instruction>(U));
03522 }
03523 
03524 /// \brief Promote the allocas, using the best available technique.
03525 ///
03526 /// This attempts to promote whatever allocas have been identified as viable in
03527 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
03528 /// If there is a domtree available, we attempt to promote using the full power
03529 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
03530 /// based on the SSAUpdater utilities. This function returns whether any
03531 /// promotion occurred.
03532 bool SROA::promoteAllocas(Function &F) {
03533   if (PromotableAllocas.empty())
03534     return false;
03535 
03536   NumPromoted += PromotableAllocas.size();
03537 
03538   if (DT && !ForceSSAUpdater) {
03539     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
03540     PromoteMemToReg(PromotableAllocas, *DT);
03541     PromotableAllocas.clear();
03542     return true;
03543   }
03544 
03545   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
03546   SSAUpdater SSA;
03547   DIBuilder DIB(*F.getParent());
03548   SmallVector<Instruction *, 64> Insts;
03549 
03550   // We need a worklist to walk the uses of each alloca.
03551   SmallVector<Instruction *, 8> Worklist;
03552   SmallPtrSet<Instruction *, 8> Visited;
03553   SmallVector<Instruction *, 32> DeadInsts;
03554 
03555   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
03556     AllocaInst *AI = PromotableAllocas[Idx];
03557     Insts.clear();
03558     Worklist.clear();
03559     Visited.clear();
03560 
03561     enqueueUsersInWorklist(*AI, Worklist, Visited);
03562 
03563     while (!Worklist.empty()) {
03564       Instruction *I = Worklist.pop_back_val();
03565 
03566       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
03567       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
03568       // leading to them) here. Eventually it should use them to optimize the
03569       // scalar values produced.
03570       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
03571         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
03572                II->getIntrinsicID() == Intrinsic::lifetime_end);
03573         II->eraseFromParent();
03574         continue;
03575       }
03576 
03577       // Push the loads and stores we find onto the list. SROA will already
03578       // have validated that all loads and stores are viable candidates for
03579       // promotion.
03580       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
03581         assert(LI->getType() == AI->getAllocatedType());
03582         Insts.push_back(LI);
03583         continue;
03584       }
03585       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
03586         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
03587         Insts.push_back(SI);
03588         continue;
03589       }
03590 
03591       // For everything else, we know that only no-op bitcasts and GEPs will
03592       // make it this far, just recurse through them and recall them for later
03593       // removal.
03594       DeadInsts.push_back(I);
03595       enqueueUsersInWorklist(*I, Worklist, Visited);
03596     }
03597     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
03598     while (!DeadInsts.empty())
03599       DeadInsts.pop_back_val()->eraseFromParent();
03600     AI->eraseFromParent();
03601   }
03602 
03603   PromotableAllocas.clear();
03604   return true;
03605 }
03606 
03607 bool SROA::runOnFunction(Function &F) {
03608   if (skipOptnoneFunction(F))
03609     return false;
03610 
03611   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
03612   C = &F.getContext();
03613   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
03614   if (!DLP) {
03615     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
03616     return false;
03617   }
03618   DL = &DLP->getDataLayout();
03619   DominatorTreeWrapperPass *DTWP =
03620       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
03621   DT = DTWP ? &DTWP->getDomTree() : nullptr;
03622 
03623   BasicBlock &EntryBB = F.getEntryBlock();
03624   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
03625        I != E; ++I)
03626     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
03627       Worklist.insert(AI);
03628 
03629   bool Changed = false;
03630   // A set of deleted alloca instruction pointers which should be removed from
03631   // the list of promotable allocas.
03632   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
03633 
03634   do {
03635     while (!Worklist.empty()) {
03636       Changed |= runOnAlloca(*Worklist.pop_back_val());
03637       deleteDeadInstructions(DeletedAllocas);
03638 
03639       // Remove the deleted allocas from various lists so that we don't try to
03640       // continue processing them.
03641       if (!DeletedAllocas.empty()) {
03642         auto IsInSet = [&](AllocaInst *AI) {
03643           return DeletedAllocas.count(AI);
03644         };
03645         Worklist.remove_if(IsInSet);
03646         PostPromotionWorklist.remove_if(IsInSet);
03647         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
03648                                                PromotableAllocas.end(),
03649                                                IsInSet),
03650                                 PromotableAllocas.end());
03651         DeletedAllocas.clear();
03652       }
03653     }
03654 
03655     Changed |= promoteAllocas(F);
03656 
03657     Worklist = PostPromotionWorklist;
03658     PostPromotionWorklist.clear();
03659   } while (!Worklist.empty());
03660 
03661   return Changed;
03662 }
03663 
03664 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
03665   if (RequiresDomTree)
03666     AU.addRequired<DominatorTreeWrapperPass>();
03667   AU.setPreservesCFG();
03668 }