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