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