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