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