LLVM API Documentation

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