1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
15 ///
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
19 ///
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
23 ///
24 //===----------------------------------------------------------------------===//
25 
26 #include "llvm/Transforms/Scalar/SROA.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/AssumptionCache.h"
31 #include "llvm/Analysis/GlobalsModRef.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/PtrUseVisitor.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DIBuilder.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InstVisitor.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Operator.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/TimeValue.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 
58 #ifndef NDEBUG
59 // We only use this for a debug check.
60 #include <random>
61 #endif
62 
63 using namespace llvm;
64 using namespace llvm::sroa;
65 
66 #define DEBUG_TYPE "sroa"
67 
68 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
69 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
70 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
71 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
72 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
73 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
74 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
75 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
76 STATISTIC(NumDeleted, "Number of instructions deleted");
77 STATISTIC(NumVectorized, "Number of vectorized aggregates");
78 
79 /// Hidden option to enable randomly shuffling the slices to help uncover
80 /// instability in their order.
81 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
82                                              cl::init(false), cl::Hidden);
83 
84 /// Hidden option to experiment with completely strict handling of inbounds
85 /// GEPs.
86 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
87                                         cl::Hidden);
88 
89 namespace {
90 /// \brief A custom IRBuilder inserter which prefixes all names, but only in
91 /// Assert builds.
92 class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
93   std::string Prefix;
94   const Twine getNameWithPrefix(const Twine &Name) const {
95     return Name.isTriviallyEmpty() ? Name : Prefix + Name;
96   }
97 
98 public:
99   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
100 
101 protected:
102   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
103                     BasicBlock::iterator InsertPt) const {
104     IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
105                                            InsertPt);
106   }
107 };
108 
109 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
110 using IRBuilderTy = llvm::IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
111 }
112 
113 namespace {
114 /// \brief A used slice of an alloca.
115 ///
116 /// This structure represents a slice of an alloca used by some instruction. It
117 /// stores both the begin and end offsets of this use, a pointer to the use
118 /// itself, and a flag indicating whether we can classify the use as splittable
119 /// or not when forming partitions of the alloca.
120 class Slice {
121   /// \brief The beginning offset of the range.
122   uint64_t BeginOffset;
123 
124   /// \brief The ending offset, not included in the range.
125   uint64_t EndOffset;
126 
127   /// \brief Storage for both the use of this slice and whether it can be
128   /// split.
129   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
130 
131 public:
132   Slice() : BeginOffset(), EndOffset() {}
133   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
134       : BeginOffset(BeginOffset), EndOffset(EndOffset),
135         UseAndIsSplittable(U, IsSplittable) {}
136 
137   uint64_t beginOffset() const { return BeginOffset; }
138   uint64_t endOffset() const { return EndOffset; }
139 
140   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
141   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
142 
143   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
144 
145   bool isDead() const { return getUse() == nullptr; }
146   void kill() { UseAndIsSplittable.setPointer(nullptr); }
147 
148   /// \brief Support for ordering ranges.
149   ///
150   /// This provides an ordering over ranges such that start offsets are
151   /// always increasing, and within equal start offsets, the end offsets are
152   /// decreasing. Thus the spanning range comes first in a cluster with the
153   /// same start position.
154   bool operator<(const Slice &RHS) const {
155     if (beginOffset() < RHS.beginOffset())
156       return true;
157     if (beginOffset() > RHS.beginOffset())
158       return false;
159     if (isSplittable() != RHS.isSplittable())
160       return !isSplittable();
161     if (endOffset() > RHS.endOffset())
162       return true;
163     return false;
164   }
165 
166   /// \brief Support comparison with a single offset to allow binary searches.
167   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
168                                               uint64_t RHSOffset) {
169     return LHS.beginOffset() < RHSOffset;
170   }
171   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
172                                               const Slice &RHS) {
173     return LHSOffset < RHS.beginOffset();
174   }
175 
176   bool operator==(const Slice &RHS) const {
177     return isSplittable() == RHS.isSplittable() &&
178            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
179   }
180   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
181 };
182 } // end anonymous namespace
183 
184 namespace llvm {
185 template <typename T> struct isPodLike;
186 template <> struct isPodLike<Slice> { static const bool value = true; };
187 }
188 
189 /// \brief Representation of the alloca slices.
190 ///
191 /// This class represents the slices of an alloca which are formed by its
192 /// various uses. If a pointer escapes, we can't fully build a representation
193 /// for the slices used and we reflect that in this structure. The uses are
194 /// stored, sorted by increasing beginning offset and with unsplittable slices
195 /// starting at a particular offset before splittable slices.
196 class llvm::sroa::AllocaSlices {
197 public:
198   /// \brief Construct the slices of a particular alloca.
199   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
200 
201   /// \brief Test whether a pointer to the allocation escapes our analysis.
202   ///
203   /// If this is true, the slices are never fully built and should be
204   /// ignored.
205   bool isEscaped() const { return PointerEscapingInstr; }
206 
207   /// \brief Support for iterating over the slices.
208   /// @{
209   typedef SmallVectorImpl<Slice>::iterator iterator;
210   typedef iterator_range<iterator> range;
211   iterator begin() { return Slices.begin(); }
212   iterator end() { return Slices.end(); }
213 
214   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
215   typedef iterator_range<const_iterator> const_range;
216   const_iterator begin() const { return Slices.begin(); }
217   const_iterator end() const { return Slices.end(); }
218   /// @}
219 
220   /// \brief Erase a range of slices.
221   void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
222 
223   /// \brief Insert new slices for this alloca.
224   ///
225   /// This moves the slices into the alloca's slices collection, and re-sorts
226   /// everything so that the usual ordering properties of the alloca's slices
227   /// hold.
228   void insert(ArrayRef<Slice> NewSlices) {
229     int OldSize = Slices.size();
230     Slices.append(NewSlices.begin(), NewSlices.end());
231     auto SliceI = Slices.begin() + OldSize;
232     std::sort(SliceI, Slices.end());
233     std::inplace_merge(Slices.begin(), SliceI, Slices.end());
234   }
235 
236   // Forward declare the iterator and range accessor for walking the
237   // partitions.
238   class partition_iterator;
239   iterator_range<partition_iterator> partitions();
240 
241   /// \brief Access the dead users for this alloca.
242   ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
243 
244   /// \brief Access the dead operands referring to this alloca.
245   ///
246   /// These are operands which have cannot actually be used to refer to the
247   /// alloca as they are outside its range and the user doesn't correct for
248   /// that. These mostly consist of PHI node inputs and the like which we just
249   /// need to replace with undef.
250   ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
251 
252 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
253   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
254   void printSlice(raw_ostream &OS, const_iterator I,
255                   StringRef Indent = "  ") const;
256   void printUse(raw_ostream &OS, const_iterator I,
257                 StringRef Indent = "  ") const;
258   void print(raw_ostream &OS) const;
259   void dump(const_iterator I) const;
260   void dump() const;
261 #endif
262 
263 private:
264   template <typename DerivedT, typename RetT = void> class BuilderBase;
265   class SliceBuilder;
266   friend class AllocaSlices::SliceBuilder;
267 
268 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
269   /// \brief Handle to alloca instruction to simplify method interfaces.
270   AllocaInst &AI;
271 #endif
272 
273   /// \brief The instruction responsible for this alloca not having a known set
274   /// of slices.
275   ///
276   /// When an instruction (potentially) escapes the pointer to the alloca, we
277   /// store a pointer to that here and abort trying to form slices of the
278   /// alloca. This will be null if the alloca slices are analyzed successfully.
279   Instruction *PointerEscapingInstr;
280 
281   /// \brief The slices of the alloca.
282   ///
283   /// We store a vector of the slices formed by uses of the alloca here. This
284   /// vector is sorted by increasing begin offset, and then the unsplittable
285   /// slices before the splittable ones. See the Slice inner class for more
286   /// details.
287   SmallVector<Slice, 8> Slices;
288 
289   /// \brief Instructions which will become dead if we rewrite the alloca.
290   ///
291   /// Note that these are not separated by slice. This is because we expect an
292   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
293   /// all these instructions can simply be removed and replaced with undef as
294   /// they come from outside of the allocated space.
295   SmallVector<Instruction *, 8> DeadUsers;
296 
297   /// \brief Operands which will become dead if we rewrite the alloca.
298   ///
299   /// These are operands that in their particular use can be replaced with
300   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
301   /// to PHI nodes and the like. They aren't entirely dead (there might be
302   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
303   /// want to swap this particular input for undef to simplify the use lists of
304   /// the alloca.
305   SmallVector<Use *, 8> DeadOperands;
306 };
307 
308 /// \brief A partition of the slices.
309 ///
310 /// An ephemeral representation for a range of slices which can be viewed as
311 /// a partition of the alloca. This range represents a span of the alloca's
312 /// memory which cannot be split, and provides access to all of the slices
313 /// overlapping some part of the partition.
314 ///
315 /// Objects of this type are produced by traversing the alloca's slices, but
316 /// are only ephemeral and not persistent.
317 class llvm::sroa::Partition {
318 private:
319   friend class AllocaSlices;
320   friend class AllocaSlices::partition_iterator;
321 
322   typedef AllocaSlices::iterator iterator;
323 
324   /// \brief The beginning and ending offsets of the alloca for this
325   /// partition.
326   uint64_t BeginOffset, EndOffset;
327 
328   /// \brief The start end end iterators of this partition.
329   iterator SI, SJ;
330 
331   /// \brief A collection of split slice tails overlapping the partition.
332   SmallVector<Slice *, 4> SplitTails;
333 
334   /// \brief Raw constructor builds an empty partition starting and ending at
335   /// the given iterator.
336   Partition(iterator SI) : SI(SI), SJ(SI) {}
337 
338 public:
339   /// \brief The start offset of this partition.
340   ///
341   /// All of the contained slices start at or after this offset.
342   uint64_t beginOffset() const { return BeginOffset; }
343 
344   /// \brief The end offset of this partition.
345   ///
346   /// All of the contained slices end at or before this offset.
347   uint64_t endOffset() const { return EndOffset; }
348 
349   /// \brief The size of the partition.
350   ///
351   /// Note that this can never be zero.
352   uint64_t size() const {
353     assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
354     return EndOffset - BeginOffset;
355   }
356 
357   /// \brief Test whether this partition contains no slices, and merely spans
358   /// a region occupied by split slices.
359   bool empty() const { return SI == SJ; }
360 
361   /// \name Iterate slices that start within the partition.
362   /// These may be splittable or unsplittable. They have a begin offset >= the
363   /// partition begin offset.
364   /// @{
365   // FIXME: We should probably define a "concat_iterator" helper and use that
366   // to stitch together pointee_iterators over the split tails and the
367   // contiguous iterators of the partition. That would give a much nicer
368   // interface here. We could then additionally expose filtered iterators for
369   // split, unsplit, and unsplittable splices based on the usage patterns.
370   iterator begin() const { return SI; }
371   iterator end() const { return SJ; }
372   /// @}
373 
374   /// \brief Get the sequence of split slice tails.
375   ///
376   /// These tails are of slices which start before this partition but are
377   /// split and overlap into the partition. We accumulate these while forming
378   /// partitions.
379   ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
380 };
381 
382 /// \brief An iterator over partitions of the alloca's slices.
383 ///
384 /// This iterator implements the core algorithm for partitioning the alloca's
385 /// slices. It is a forward iterator as we don't support backtracking for
386 /// efficiency reasons, and re-use a single storage area to maintain the
387 /// current set of split slices.
388 ///
389 /// It is templated on the slice iterator type to use so that it can operate
390 /// with either const or non-const slice iterators.
391 class AllocaSlices::partition_iterator
392     : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
393                                   Partition> {
394   friend class AllocaSlices;
395 
396   /// \brief Most of the state for walking the partitions is held in a class
397   /// with a nice interface for examining them.
398   Partition P;
399 
400   /// \brief We need to keep the end of the slices to know when to stop.
401   AllocaSlices::iterator SE;
402 
403   /// \brief We also need to keep track of the maximum split end offset seen.
404   /// FIXME: Do we really?
405   uint64_t MaxSplitSliceEndOffset;
406 
407   /// \brief Sets the partition to be empty at given iterator, and sets the
408   /// end iterator.
409   partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
410       : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
411     // If not already at the end, advance our state to form the initial
412     // partition.
413     if (SI != SE)
414       advance();
415   }
416 
417   /// \brief Advance the iterator to the next partition.
418   ///
419   /// Requires that the iterator not be at the end of the slices.
420   void advance() {
421     assert((P.SI != SE || !P.SplitTails.empty()) &&
422            "Cannot advance past the end of the slices!");
423 
424     // Clear out any split uses which have ended.
425     if (!P.SplitTails.empty()) {
426       if (P.EndOffset >= MaxSplitSliceEndOffset) {
427         // If we've finished all splits, this is easy.
428         P.SplitTails.clear();
429         MaxSplitSliceEndOffset = 0;
430       } else {
431         // Remove the uses which have ended in the prior partition. This
432         // cannot change the max split slice end because we just checked that
433         // the prior partition ended prior to that max.
434         P.SplitTails.erase(
435             std::remove_if(
436                 P.SplitTails.begin(), P.SplitTails.end(),
437                 [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
438             P.SplitTails.end());
439         assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
440                            [&](Slice *S) {
441                              return S->endOffset() == MaxSplitSliceEndOffset;
442                            }) &&
443                "Could not find the current max split slice offset!");
444         assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
445                            [&](Slice *S) {
446                              return S->endOffset() <= MaxSplitSliceEndOffset;
447                            }) &&
448                "Max split slice end offset is not actually the max!");
449       }
450     }
451 
452     // If P.SI is already at the end, then we've cleared the split tail and
453     // now have an end iterator.
454     if (P.SI == SE) {
455       assert(P.SplitTails.empty() && "Failed to clear the split slices!");
456       return;
457     }
458 
459     // If we had a non-empty partition previously, set up the state for
460     // subsequent partitions.
461     if (P.SI != P.SJ) {
462       // Accumulate all the splittable slices which started in the old
463       // partition into the split list.
464       for (Slice &S : P)
465         if (S.isSplittable() && S.endOffset() > P.EndOffset) {
466           P.SplitTails.push_back(&S);
467           MaxSplitSliceEndOffset =
468               std::max(S.endOffset(), MaxSplitSliceEndOffset);
469         }
470 
471       // Start from the end of the previous partition.
472       P.SI = P.SJ;
473 
474       // If P.SI is now at the end, we at most have a tail of split slices.
475       if (P.SI == SE) {
476         P.BeginOffset = P.EndOffset;
477         P.EndOffset = MaxSplitSliceEndOffset;
478         return;
479       }
480 
481       // If the we have split slices and the next slice is after a gap and is
482       // not splittable immediately form an empty partition for the split
483       // slices up until the next slice begins.
484       if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
485           !P.SI->isSplittable()) {
486         P.BeginOffset = P.EndOffset;
487         P.EndOffset = P.SI->beginOffset();
488         return;
489       }
490     }
491 
492     // OK, we need to consume new slices. Set the end offset based on the
493     // current slice, and step SJ past it. The beginning offset of the
494     // partition is the beginning offset of the next slice unless we have
495     // pre-existing split slices that are continuing, in which case we begin
496     // at the prior end offset.
497     P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
498     P.EndOffset = P.SI->endOffset();
499     ++P.SJ;
500 
501     // There are two strategies to form a partition based on whether the
502     // partition starts with an unsplittable slice or a splittable slice.
503     if (!P.SI->isSplittable()) {
504       // When we're forming an unsplittable region, it must always start at
505       // the first slice and will extend through its end.
506       assert(P.BeginOffset == P.SI->beginOffset());
507 
508       // Form a partition including all of the overlapping slices with this
509       // unsplittable slice.
510       while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
511         if (!P.SJ->isSplittable())
512           P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
513         ++P.SJ;
514       }
515 
516       // We have a partition across a set of overlapping unsplittable
517       // partitions.
518       return;
519     }
520 
521     // If we're starting with a splittable slice, then we need to form
522     // a synthetic partition spanning it and any other overlapping splittable
523     // splices.
524     assert(P.SI->isSplittable() && "Forming a splittable partition!");
525 
526     // Collect all of the overlapping splittable slices.
527     while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
528            P.SJ->isSplittable()) {
529       P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
530       ++P.SJ;
531     }
532 
533     // Back upiP.EndOffset if we ended the span early when encountering an
534     // unsplittable slice. This synthesizes the early end offset of
535     // a partition spanning only splittable slices.
536     if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
537       assert(!P.SJ->isSplittable());
538       P.EndOffset = P.SJ->beginOffset();
539     }
540   }
541 
542 public:
543   bool operator==(const partition_iterator &RHS) const {
544     assert(SE == RHS.SE &&
545            "End iterators don't match between compared partition iterators!");
546 
547     // The observed positions of partitions is marked by the P.SI iterator and
548     // the emptiness of the split slices. The latter is only relevant when
549     // P.SI == SE, as the end iterator will additionally have an empty split
550     // slices list, but the prior may have the same P.SI and a tail of split
551     // slices.
552     if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
553       assert(P.SJ == RHS.P.SJ &&
554              "Same set of slices formed two different sized partitions!");
555       assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
556              "Same slice position with differently sized non-empty split "
557              "slice tails!");
558       return true;
559     }
560     return false;
561   }
562 
563   partition_iterator &operator++() {
564     advance();
565     return *this;
566   }
567 
568   Partition &operator*() { return P; }
569 };
570 
571 /// \brief A forward range over the partitions of the alloca's slices.
572 ///
573 /// This accesses an iterator range over the partitions of the alloca's
574 /// slices. It computes these partitions on the fly based on the overlapping
575 /// offsets of the slices and the ability to split them. It will visit "empty"
576 /// partitions to cover regions of the alloca only accessed via split
577 /// slices.
578 iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
579   return make_range(partition_iterator(begin(), end()),
580                     partition_iterator(end(), end()));
581 }
582 
583 static Value *foldSelectInst(SelectInst &SI) {
584   // If the condition being selected on is a constant or the same value is
585   // being selected between, fold the select. Yes this does (rarely) happen
586   // early on.
587   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
588     return SI.getOperand(1 + CI->isZero());
589   if (SI.getOperand(1) == SI.getOperand(2))
590     return SI.getOperand(1);
591 
592   return nullptr;
593 }
594 
595 /// \brief A helper that folds a PHI node or a select.
596 static Value *foldPHINodeOrSelectInst(Instruction &I) {
597   if (PHINode *PN = dyn_cast<PHINode>(&I)) {
598     // If PN merges together the same value, return that value.
599     return PN->hasConstantValue();
600   }
601   return foldSelectInst(cast<SelectInst>(I));
602 }
603 
604 /// \brief Builder for the alloca slices.
605 ///
606 /// This class builds a set of alloca slices by recursively visiting the uses
607 /// of an alloca and making a slice for each load and store at each offset.
608 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
609   friend class PtrUseVisitor<SliceBuilder>;
610   friend class InstVisitor<SliceBuilder>;
611   typedef PtrUseVisitor<SliceBuilder> Base;
612 
613   const uint64_t AllocSize;
614   AllocaSlices &AS;
615 
616   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
617   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
618 
619   /// \brief Set to de-duplicate dead instructions found in the use walk.
620   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
621 
622 public:
623   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
624       : PtrUseVisitor<SliceBuilder>(DL),
625         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
626 
627 private:
628   void markAsDead(Instruction &I) {
629     if (VisitedDeadInsts.insert(&I).second)
630       AS.DeadUsers.push_back(&I);
631   }
632 
633   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
634                  bool IsSplittable = false) {
635     // Completely skip uses which have a zero size or start either before or
636     // past the end of the allocation.
637     if (Size == 0 || Offset.uge(AllocSize)) {
638       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
639                    << " which has zero size or starts outside of the "
640                    << AllocSize << " byte alloca:\n"
641                    << "    alloca: " << AS.AI << "\n"
642                    << "       use: " << I << "\n");
643       return markAsDead(I);
644     }
645 
646     uint64_t BeginOffset = Offset.getZExtValue();
647     uint64_t EndOffset = BeginOffset + Size;
648 
649     // Clamp the end offset to the end of the allocation. Note that this is
650     // formulated to handle even the case where "BeginOffset + Size" overflows.
651     // This may appear superficially to be something we could ignore entirely,
652     // but that is not so! There may be widened loads or PHI-node uses where
653     // some instructions are dead but not others. We can't completely ignore
654     // them, and so have to record at least the information here.
655     assert(AllocSize >= BeginOffset); // Established above.
656     if (Size > AllocSize - BeginOffset) {
657       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
658                    << " to remain within the " << AllocSize << " byte alloca:\n"
659                    << "    alloca: " << AS.AI << "\n"
660                    << "       use: " << I << "\n");
661       EndOffset = AllocSize;
662     }
663 
664     AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
665   }
666 
667   void visitBitCastInst(BitCastInst &BC) {
668     if (BC.use_empty())
669       return markAsDead(BC);
670 
671     return Base::visitBitCastInst(BC);
672   }
673 
674   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
675     if (GEPI.use_empty())
676       return markAsDead(GEPI);
677 
678     if (SROAStrictInbounds && GEPI.isInBounds()) {
679       // FIXME: This is a manually un-factored variant of the basic code inside
680       // of GEPs with checking of the inbounds invariant specified in the
681       // langref in a very strict sense. If we ever want to enable
682       // SROAStrictInbounds, this code should be factored cleanly into
683       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
684       // by writing out the code here where we have the underlying allocation
685       // size readily available.
686       APInt GEPOffset = Offset;
687       const DataLayout &DL = GEPI.getModule()->getDataLayout();
688       for (gep_type_iterator GTI = gep_type_begin(GEPI),
689                              GTE = gep_type_end(GEPI);
690            GTI != GTE; ++GTI) {
691         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
692         if (!OpC)
693           break;
694 
695         // Handle a struct index, which adds its field offset to the pointer.
696         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
697           unsigned ElementIdx = OpC->getZExtValue();
698           const StructLayout *SL = DL.getStructLayout(STy);
699           GEPOffset +=
700               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
701         } else {
702           // For array or vector indices, scale the index by the size of the
703           // type.
704           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
705           GEPOffset += Index * APInt(Offset.getBitWidth(),
706                                      DL.getTypeAllocSize(GTI.getIndexedType()));
707         }
708 
709         // If this index has computed an intermediate pointer which is not
710         // inbounds, then the result of the GEP is a poison value and we can
711         // delete it and all uses.
712         if (GEPOffset.ugt(AllocSize))
713           return markAsDead(GEPI);
714       }
715     }
716 
717     return Base::visitGetElementPtrInst(GEPI);
718   }
719 
720   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
721                          uint64_t Size, bool IsVolatile) {
722     // We allow splitting of non-volatile loads and stores where the type is an
723     // integer type. These may be used to implement 'memcpy' or other "transfer
724     // of bits" patterns.
725     bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
726 
727     insertUse(I, Offset, Size, IsSplittable);
728   }
729 
730   void visitLoadInst(LoadInst &LI) {
731     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
732            "All simple FCA loads should have been pre-split");
733 
734     if (!IsOffsetKnown)
735       return PI.setAborted(&LI);
736 
737     const DataLayout &DL = LI.getModule()->getDataLayout();
738     uint64_t Size = DL.getTypeStoreSize(LI.getType());
739     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
740   }
741 
742   void visitStoreInst(StoreInst &SI) {
743     Value *ValOp = SI.getValueOperand();
744     if (ValOp == *U)
745       return PI.setEscapedAndAborted(&SI);
746     if (!IsOffsetKnown)
747       return PI.setAborted(&SI);
748 
749     const DataLayout &DL = SI.getModule()->getDataLayout();
750     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
751 
752     // If this memory access can be shown to *statically* extend outside the
753     // bounds of of the allocation, it's behavior is undefined, so simply
754     // ignore it. Note that this is more strict than the generic clamping
755     // behavior of insertUse. We also try to handle cases which might run the
756     // risk of overflow.
757     // FIXME: We should instead consider the pointer to have escaped if this
758     // function is being instrumented for addressing bugs or race conditions.
759     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
760       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
761                    << " which extends past the end of the " << AllocSize
762                    << " byte alloca:\n"
763                    << "    alloca: " << AS.AI << "\n"
764                    << "       use: " << SI << "\n");
765       return markAsDead(SI);
766     }
767 
768     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
769            "All simple FCA stores should have been pre-split");
770     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
771   }
772 
773   void visitMemSetInst(MemSetInst &II) {
774     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
775     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
776     if ((Length && Length->getValue() == 0) ||
777         (IsOffsetKnown && Offset.uge(AllocSize)))
778       // Zero-length mem transfer intrinsics can be ignored entirely.
779       return markAsDead(II);
780 
781     if (!IsOffsetKnown)
782       return PI.setAborted(&II);
783 
784     insertUse(II, Offset, Length ? Length->getLimitedValue()
785                                  : AllocSize - Offset.getLimitedValue(),
786               (bool)Length);
787   }
788 
789   void visitMemTransferInst(MemTransferInst &II) {
790     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
791     if (Length && Length->getValue() == 0)
792       // Zero-length mem transfer intrinsics can be ignored entirely.
793       return markAsDead(II);
794 
795     // Because we can visit these intrinsics twice, also check to see if the
796     // first time marked this instruction as dead. If so, skip it.
797     if (VisitedDeadInsts.count(&II))
798       return;
799 
800     if (!IsOffsetKnown)
801       return PI.setAborted(&II);
802 
803     // This side of the transfer is completely out-of-bounds, and so we can
804     // nuke the entire transfer. However, we also need to nuke the other side
805     // if already added to our partitions.
806     // FIXME: Yet another place we really should bypass this when
807     // instrumenting for ASan.
808     if (Offset.uge(AllocSize)) {
809       SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
810           MemTransferSliceMap.find(&II);
811       if (MTPI != MemTransferSliceMap.end())
812         AS.Slices[MTPI->second].kill();
813       return markAsDead(II);
814     }
815 
816     uint64_t RawOffset = Offset.getLimitedValue();
817     uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
818 
819     // Check for the special case where the same exact value is used for both
820     // source and dest.
821     if (*U == II.getRawDest() && *U == II.getRawSource()) {
822       // For non-volatile transfers this is a no-op.
823       if (!II.isVolatile())
824         return markAsDead(II);
825 
826       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
827     }
828 
829     // If we have seen both source and destination for a mem transfer, then
830     // they both point to the same alloca.
831     bool Inserted;
832     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
833     std::tie(MTPI, Inserted) =
834         MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
835     unsigned PrevIdx = MTPI->second;
836     if (!Inserted) {
837       Slice &PrevP = AS.Slices[PrevIdx];
838 
839       // Check if the begin offsets match and this is a non-volatile transfer.
840       // In that case, we can completely elide the transfer.
841       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
842         PrevP.kill();
843         return markAsDead(II);
844       }
845 
846       // Otherwise we have an offset transfer within the same alloca. We can't
847       // split those.
848       PrevP.makeUnsplittable();
849     }
850 
851     // Insert the use now that we've fixed up the splittable nature.
852     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
853 
854     // Check that we ended up with a valid index in the map.
855     assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
856            "Map index doesn't point back to a slice with this user.");
857   }
858 
859   // Disable SRoA for any intrinsics except for lifetime invariants.
860   // FIXME: What about debug intrinsics? This matches old behavior, but
861   // doesn't make sense.
862   void visitIntrinsicInst(IntrinsicInst &II) {
863     if (!IsOffsetKnown)
864       return PI.setAborted(&II);
865 
866     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
867         II.getIntrinsicID() == Intrinsic::lifetime_end) {
868       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
869       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
870                                Length->getLimitedValue());
871       insertUse(II, Offset, Size, true);
872       return;
873     }
874 
875     Base::visitIntrinsicInst(II);
876   }
877 
878   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
879     // We consider any PHI or select that results in a direct load or store of
880     // the same offset to be a viable use for slicing purposes. These uses
881     // are considered unsplittable and the size is the maximum loaded or stored
882     // size.
883     SmallPtrSet<Instruction *, 4> Visited;
884     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
885     Visited.insert(Root);
886     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
887     const DataLayout &DL = Root->getModule()->getDataLayout();
888     // If there are no loads or stores, the access is dead. We mark that as
889     // a size zero access.
890     Size = 0;
891     do {
892       Instruction *I, *UsedI;
893       std::tie(UsedI, I) = Uses.pop_back_val();
894 
895       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
896         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
897         continue;
898       }
899       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
900         Value *Op = SI->getOperand(0);
901         if (Op == UsedI)
902           return SI;
903         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
904         continue;
905       }
906 
907       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
908         if (!GEP->hasAllZeroIndices())
909           return GEP;
910       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
911                  !isa<SelectInst>(I)) {
912         return I;
913       }
914 
915       for (User *U : I->users())
916         if (Visited.insert(cast<Instruction>(U)).second)
917           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
918     } while (!Uses.empty());
919 
920     return nullptr;
921   }
922 
923   void visitPHINodeOrSelectInst(Instruction &I) {
924     assert(isa<PHINode>(I) || isa<SelectInst>(I));
925     if (I.use_empty())
926       return markAsDead(I);
927 
928     // TODO: We could use SimplifyInstruction here to fold PHINodes and
929     // SelectInsts. However, doing so requires to change the current
930     // dead-operand-tracking mechanism. For instance, suppose neither loading
931     // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
932     // trap either.  However, if we simply replace %U with undef using the
933     // current dead-operand-tracking mechanism, "load (select undef, undef,
934     // %other)" may trap because the select may return the first operand
935     // "undef".
936     if (Value *Result = foldPHINodeOrSelectInst(I)) {
937       if (Result == *U)
938         // If the result of the constant fold will be the pointer, recurse
939         // through the PHI/select as if we had RAUW'ed it.
940         enqueueUsers(I);
941       else
942         // Otherwise the operand to the PHI/select is dead, and we can replace
943         // it with undef.
944         AS.DeadOperands.push_back(U);
945 
946       return;
947     }
948 
949     if (!IsOffsetKnown)
950       return PI.setAborted(&I);
951 
952     // See if we already have computed info on this node.
953     uint64_t &Size = PHIOrSelectSizes[&I];
954     if (!Size) {
955       // This is a new PHI/Select, check for an unsafe use of it.
956       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
957         return PI.setAborted(UnsafeI);
958     }
959 
960     // For PHI and select operands outside the alloca, we can't nuke the entire
961     // phi or select -- the other side might still be relevant, so we special
962     // case them here and use a separate structure to track the operands
963     // themselves which should be replaced with undef.
964     // FIXME: This should instead be escaped in the event we're instrumenting
965     // for address sanitization.
966     if (Offset.uge(AllocSize)) {
967       AS.DeadOperands.push_back(U);
968       return;
969     }
970 
971     insertUse(I, Offset, Size);
972   }
973 
974   void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
975 
976   void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
977 
978   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
979   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
980 };
981 
982 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
983     :
984 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
985       AI(AI),
986 #endif
987       PointerEscapingInstr(nullptr) {
988   SliceBuilder PB(DL, AI, *this);
989   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
990   if (PtrI.isEscaped() || PtrI.isAborted()) {
991     // FIXME: We should sink the escape vs. abort info into the caller nicely,
992     // possibly by just storing the PtrInfo in the AllocaSlices.
993     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
994                                                   : PtrI.getAbortingInst();
995     assert(PointerEscapingInstr && "Did not track a bad instruction");
996     return;
997   }
998 
999   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
1000                               [](const Slice &S) {
1001                                 return S.isDead();
1002                               }),
1003                Slices.end());
1004 
1005 #ifndef NDEBUG
1006   if (SROARandomShuffleSlices) {
1007     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
1008     std::shuffle(Slices.begin(), Slices.end(), MT);
1009   }
1010 #endif
1011 
1012   // Sort the uses. This arranges for the offsets to be in ascending order,
1013   // and the sizes to be in descending order.
1014   std::sort(Slices.begin(), Slices.end());
1015 }
1016 
1017 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1018 
1019 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1020                          StringRef Indent) const {
1021   printSlice(OS, I, Indent);
1022   OS << "\n";
1023   printUse(OS, I, Indent);
1024 }
1025 
1026 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1027                               StringRef Indent) const {
1028   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1029      << " slice #" << (I - begin())
1030      << (I->isSplittable() ? " (splittable)" : "");
1031 }
1032 
1033 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1034                             StringRef Indent) const {
1035   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
1036 }
1037 
1038 void AllocaSlices::print(raw_ostream &OS) const {
1039   if (PointerEscapingInstr) {
1040     OS << "Can't analyze slices for alloca: " << AI << "\n"
1041        << "  A pointer to this alloca escaped by:\n"
1042        << "  " << *PointerEscapingInstr << "\n";
1043     return;
1044   }
1045 
1046   OS << "Slices of alloca: " << AI << "\n";
1047   for (const_iterator I = begin(), E = end(); I != E; ++I)
1048     print(OS, I);
1049 }
1050 
1051 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1052   print(dbgs(), I);
1053 }
1054 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1055 
1056 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1057 
1058 /// Walk the range of a partitioning looking for a common type to cover this
1059 /// sequence of slices.
1060 static Type *findCommonType(AllocaSlices::const_iterator B,
1061                             AllocaSlices::const_iterator E,
1062                             uint64_t EndOffset) {
1063   Type *Ty = nullptr;
1064   bool TyIsCommon = true;
1065   IntegerType *ITy = nullptr;
1066 
1067   // Note that we need to look at *every* alloca slice's Use to ensure we
1068   // always get consistent results regardless of the order of slices.
1069   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1070     Use *U = I->getUse();
1071     if (isa<IntrinsicInst>(*U->getUser()))
1072       continue;
1073     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1074       continue;
1075 
1076     Type *UserTy = nullptr;
1077     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1078       UserTy = LI->getType();
1079     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1080       UserTy = SI->getValueOperand()->getType();
1081     }
1082 
1083     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1084       // If the type is larger than the partition, skip it. We only encounter
1085       // this for split integer operations where we want to use the type of the
1086       // entity causing the split. Also skip if the type is not a byte width
1087       // multiple.
1088       if (UserITy->getBitWidth() % 8 != 0 ||
1089           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1090         continue;
1091 
1092       // Track the largest bitwidth integer type used in this way in case there
1093       // is no common type.
1094       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1095         ITy = UserITy;
1096     }
1097 
1098     // To avoid depending on the order of slices, Ty and TyIsCommon must not
1099     // depend on types skipped above.
1100     if (!UserTy || (Ty && Ty != UserTy))
1101       TyIsCommon = false; // Give up on anything but an iN type.
1102     else
1103       Ty = UserTy;
1104   }
1105 
1106   return TyIsCommon ? Ty : ITy;
1107 }
1108 
1109 /// PHI instructions that use an alloca and are subsequently loaded can be
1110 /// rewritten to load both input pointers in the pred blocks and then PHI the
1111 /// results, allowing the load of the alloca to be promoted.
1112 /// From this:
1113 ///   %P2 = phi [i32* %Alloca, i32* %Other]
1114 ///   %V = load i32* %P2
1115 /// to:
1116 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1117 ///   ...
1118 ///   %V2 = load i32* %Other
1119 ///   ...
1120 ///   %V = phi [i32 %V1, i32 %V2]
1121 ///
1122 /// We can do this to a select if its only uses are loads and if the operands
1123 /// to the select can be loaded unconditionally.
1124 ///
1125 /// FIXME: This should be hoisted into a generic utility, likely in
1126 /// Transforms/Util/Local.h
1127 static bool isSafePHIToSpeculate(PHINode &PN) {
1128   // For now, we can only do this promotion if the load is in the same block
1129   // as the PHI, and if there are no stores between the phi and load.
1130   // TODO: Allow recursive phi users.
1131   // TODO: Allow stores.
1132   BasicBlock *BB = PN.getParent();
1133   unsigned MaxAlign = 0;
1134   bool HaveLoad = false;
1135   for (User *U : PN.users()) {
1136     LoadInst *LI = dyn_cast<LoadInst>(U);
1137     if (!LI || !LI->isSimple())
1138       return false;
1139 
1140     // For now we only allow loads in the same block as the PHI.  This is
1141     // a common case that happens when instcombine merges two loads through
1142     // a PHI.
1143     if (LI->getParent() != BB)
1144       return false;
1145 
1146     // Ensure that there are no instructions between the PHI and the load that
1147     // could store.
1148     for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1149       if (BBI->mayWriteToMemory())
1150         return false;
1151 
1152     MaxAlign = std::max(MaxAlign, LI->getAlignment());
1153     HaveLoad = true;
1154   }
1155 
1156   if (!HaveLoad)
1157     return false;
1158 
1159   const DataLayout &DL = PN.getModule()->getDataLayout();
1160 
1161   // We can only transform this if it is safe to push the loads into the
1162   // predecessor blocks. The only thing to watch out for is that we can't put
1163   // a possibly trapping load in the predecessor if it is a critical edge.
1164   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1165     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1166     Value *InVal = PN.getIncomingValue(Idx);
1167 
1168     // If the value is produced by the terminator of the predecessor (an
1169     // invoke) or it has side-effects, there is no valid place to put a load
1170     // in the predecessor.
1171     if (TI == InVal || TI->mayHaveSideEffects())
1172       return false;
1173 
1174     // If the predecessor has a single successor, then the edge isn't
1175     // critical.
1176     if (TI->getNumSuccessors() == 1)
1177       continue;
1178 
1179     // If this pointer is always safe to load, or if we can prove that there
1180     // is already a load in the block, then we can move the load to the pred
1181     // block.
1182     if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
1183       continue;
1184 
1185     return false;
1186   }
1187 
1188   return true;
1189 }
1190 
1191 static void speculatePHINodeLoads(PHINode &PN) {
1192   DEBUG(dbgs() << "    original: " << PN << "\n");
1193 
1194   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1195   IRBuilderTy PHIBuilder(&PN);
1196   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1197                                         PN.getName() + ".sroa.speculated");
1198 
1199   // Get the AA tags and alignment to use from one of the loads.  It doesn't
1200   // matter which one we get and if any differ.
1201   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1202 
1203   AAMDNodes AATags;
1204   SomeLoad->getAAMetadata(AATags);
1205   unsigned Align = SomeLoad->getAlignment();
1206 
1207   // Rewrite all loads of the PN to use the new PHI.
1208   while (!PN.use_empty()) {
1209     LoadInst *LI = cast<LoadInst>(PN.user_back());
1210     LI->replaceAllUsesWith(NewPN);
1211     LI->eraseFromParent();
1212   }
1213 
1214   // Inject loads into all of the pred blocks.
1215   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1216     BasicBlock *Pred = PN.getIncomingBlock(Idx);
1217     TerminatorInst *TI = Pred->getTerminator();
1218     Value *InVal = PN.getIncomingValue(Idx);
1219     IRBuilderTy PredBuilder(TI);
1220 
1221     LoadInst *Load = PredBuilder.CreateLoad(
1222         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1223     ++NumLoadsSpeculated;
1224     Load->setAlignment(Align);
1225     if (AATags)
1226       Load->setAAMetadata(AATags);
1227     NewPN->addIncoming(Load, Pred);
1228   }
1229 
1230   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
1231   PN.eraseFromParent();
1232 }
1233 
1234 /// Select instructions that use an alloca and are subsequently loaded can be
1235 /// rewritten to load both input pointers and then select between the result,
1236 /// allowing the load of the alloca to be promoted.
1237 /// From this:
1238 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1239 ///   %V = load i32* %P2
1240 /// to:
1241 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1242 ///   %V2 = load i32* %Other
1243 ///   %V = select i1 %cond, i32 %V1, i32 %V2
1244 ///
1245 /// We can do this to a select if its only uses are loads and if the operand
1246 /// to the select can be loaded unconditionally.
1247 static bool isSafeSelectToSpeculate(SelectInst &SI) {
1248   Value *TValue = SI.getTrueValue();
1249   Value *FValue = SI.getFalseValue();
1250   const DataLayout &DL = SI.getModule()->getDataLayout();
1251 
1252   for (User *U : SI.users()) {
1253     LoadInst *LI = dyn_cast<LoadInst>(U);
1254     if (!LI || !LI->isSimple())
1255       return false;
1256 
1257     // Both operands to the select need to be dereferencable, either
1258     // absolutely (e.g. allocas) or at this point because we can see other
1259     // accesses to it.
1260     if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
1261       return false;
1262     if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
1263       return false;
1264   }
1265 
1266   return true;
1267 }
1268 
1269 static void speculateSelectInstLoads(SelectInst &SI) {
1270   DEBUG(dbgs() << "    original: " << SI << "\n");
1271 
1272   IRBuilderTy IRB(&SI);
1273   Value *TV = SI.getTrueValue();
1274   Value *FV = SI.getFalseValue();
1275   // Replace the loads of the select with a select of two loads.
1276   while (!SI.use_empty()) {
1277     LoadInst *LI = cast<LoadInst>(SI.user_back());
1278     assert(LI->isSimple() && "We only speculate simple loads");
1279 
1280     IRB.SetInsertPoint(LI);
1281     LoadInst *TL =
1282         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1283     LoadInst *FL =
1284         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1285     NumLoadsSpeculated += 2;
1286 
1287     // Transfer alignment and AA info if present.
1288     TL->setAlignment(LI->getAlignment());
1289     FL->setAlignment(LI->getAlignment());
1290 
1291     AAMDNodes Tags;
1292     LI->getAAMetadata(Tags);
1293     if (Tags) {
1294       TL->setAAMetadata(Tags);
1295       FL->setAAMetadata(Tags);
1296     }
1297 
1298     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1299                                 LI->getName() + ".sroa.speculated");
1300 
1301     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
1302     LI->replaceAllUsesWith(V);
1303     LI->eraseFromParent();
1304   }
1305   SI.eraseFromParent();
1306 }
1307 
1308 /// \brief Build a GEP out of a base pointer and indices.
1309 ///
1310 /// This will return the BasePtr if that is valid, or build a new GEP
1311 /// instruction using the IRBuilder if GEP-ing is needed.
1312 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1313                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1314   if (Indices.empty())
1315     return BasePtr;
1316 
1317   // A single zero index is a no-op, so check for this and avoid building a GEP
1318   // in that case.
1319   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1320     return BasePtr;
1321 
1322   return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1323                                NamePrefix + "sroa_idx");
1324 }
1325 
1326 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1327 /// TargetTy without changing the offset of the pointer.
1328 ///
1329 /// This routine assumes we've already established a properly offset GEP with
1330 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1331 /// zero-indices down through type layers until we find one the same as
1332 /// TargetTy. If we can't find one with the same type, we at least try to use
1333 /// one with the same size. If none of that works, we just produce the GEP as
1334 /// indicated by Indices to have the correct offset.
1335 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1336                                     Value *BasePtr, Type *Ty, Type *TargetTy,
1337                                     SmallVectorImpl<Value *> &Indices,
1338                                     Twine NamePrefix) {
1339   if (Ty == TargetTy)
1340     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1341 
1342   // Pointer size to use for the indices.
1343   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1344 
1345   // See if we can descend into a struct and locate a field with the correct
1346   // type.
1347   unsigned NumLayers = 0;
1348   Type *ElementTy = Ty;
1349   do {
1350     if (ElementTy->isPointerTy())
1351       break;
1352 
1353     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1354       ElementTy = ArrayTy->getElementType();
1355       Indices.push_back(IRB.getIntN(PtrSize, 0));
1356     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1357       ElementTy = VectorTy->getElementType();
1358       Indices.push_back(IRB.getInt32(0));
1359     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1360       if (STy->element_begin() == STy->element_end())
1361         break; // Nothing left to descend into.
1362       ElementTy = *STy->element_begin();
1363       Indices.push_back(IRB.getInt32(0));
1364     } else {
1365       break;
1366     }
1367     ++NumLayers;
1368   } while (ElementTy != TargetTy);
1369   if (ElementTy != TargetTy)
1370     Indices.erase(Indices.end() - NumLayers, Indices.end());
1371 
1372   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1373 }
1374 
1375 /// \brief Recursively compute indices for a natural GEP.
1376 ///
1377 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1378 /// element types adding appropriate indices for the GEP.
1379 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1380                                        Value *Ptr, Type *Ty, APInt &Offset,
1381                                        Type *TargetTy,
1382                                        SmallVectorImpl<Value *> &Indices,
1383                                        Twine NamePrefix) {
1384   if (Offset == 0)
1385     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1386                                  NamePrefix);
1387 
1388   // We can't recurse through pointer types.
1389   if (Ty->isPointerTy())
1390     return nullptr;
1391 
1392   // We try to analyze GEPs over vectors here, but note that these GEPs are
1393   // extremely poorly defined currently. The long-term goal is to remove GEPing
1394   // over a vector from the IR completely.
1395   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1396     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1397     if (ElementSizeInBits % 8 != 0) {
1398       // GEPs over non-multiple of 8 size vector elements are invalid.
1399       return nullptr;
1400     }
1401     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1402     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1403     if (NumSkippedElements.ugt(VecTy->getNumElements()))
1404       return nullptr;
1405     Offset -= NumSkippedElements * ElementSize;
1406     Indices.push_back(IRB.getInt(NumSkippedElements));
1407     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1408                                     Offset, TargetTy, Indices, NamePrefix);
1409   }
1410 
1411   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1412     Type *ElementTy = ArrTy->getElementType();
1413     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1414     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1415     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1416       return nullptr;
1417 
1418     Offset -= NumSkippedElements * ElementSize;
1419     Indices.push_back(IRB.getInt(NumSkippedElements));
1420     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1421                                     Indices, NamePrefix);
1422   }
1423 
1424   StructType *STy = dyn_cast<StructType>(Ty);
1425   if (!STy)
1426     return nullptr;
1427 
1428   const StructLayout *SL = DL.getStructLayout(STy);
1429   uint64_t StructOffset = Offset.getZExtValue();
1430   if (StructOffset >= SL->getSizeInBytes())
1431     return nullptr;
1432   unsigned Index = SL->getElementContainingOffset(StructOffset);
1433   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1434   Type *ElementTy = STy->getElementType(Index);
1435   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1436     return nullptr; // The offset points into alignment padding.
1437 
1438   Indices.push_back(IRB.getInt32(Index));
1439   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1440                                   Indices, NamePrefix);
1441 }
1442 
1443 /// \brief Get a natural GEP from a base pointer to a particular offset and
1444 /// resulting in a particular type.
1445 ///
1446 /// The goal is to produce a "natural" looking GEP that works with the existing
1447 /// composite types to arrive at the appropriate offset and element type for
1448 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1449 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1450 /// Indices, and setting Ty to the result subtype.
1451 ///
1452 /// If no natural GEP can be constructed, this function returns null.
1453 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1454                                       Value *Ptr, APInt Offset, Type *TargetTy,
1455                                       SmallVectorImpl<Value *> &Indices,
1456                                       Twine NamePrefix) {
1457   PointerType *Ty = cast<PointerType>(Ptr->getType());
1458 
1459   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1460   // an i8.
1461   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1462     return nullptr;
1463 
1464   Type *ElementTy = Ty->getElementType();
1465   if (!ElementTy->isSized())
1466     return nullptr; // We can't GEP through an unsized element.
1467   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1468   if (ElementSize == 0)
1469     return nullptr; // Zero-length arrays can't help us build a natural GEP.
1470   APInt NumSkippedElements = Offset.sdiv(ElementSize);
1471 
1472   Offset -= NumSkippedElements * ElementSize;
1473   Indices.push_back(IRB.getInt(NumSkippedElements));
1474   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1475                                   Indices, NamePrefix);
1476 }
1477 
1478 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1479 /// resulting pointer has PointerTy.
1480 ///
1481 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1482 /// and produces the pointer type desired. Where it cannot, it will try to use
1483 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1484 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1485 /// bitcast to the type.
1486 ///
1487 /// The strategy for finding the more natural GEPs is to peel off layers of the
1488 /// pointer, walking back through bit casts and GEPs, searching for a base
1489 /// pointer from which we can compute a natural GEP with the desired
1490 /// properties. The algorithm tries to fold as many constant indices into
1491 /// a single GEP as possible, thus making each GEP more independent of the
1492 /// surrounding code.
1493 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1494                              APInt Offset, Type *PointerTy, Twine NamePrefix) {
1495   // Even though we don't look through PHI nodes, we could be called on an
1496   // instruction in an unreachable block, which may be on a cycle.
1497   SmallPtrSet<Value *, 4> Visited;
1498   Visited.insert(Ptr);
1499   SmallVector<Value *, 4> Indices;
1500 
1501   // We may end up computing an offset pointer that has the wrong type. If we
1502   // never are able to compute one directly that has the correct type, we'll
1503   // fall back to it, so keep it and the base it was computed from around here.
1504   Value *OffsetPtr = nullptr;
1505   Value *OffsetBasePtr;
1506 
1507   // Remember any i8 pointer we come across to re-use if we need to do a raw
1508   // byte offset.
1509   Value *Int8Ptr = nullptr;
1510   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1511 
1512   Type *TargetTy = PointerTy->getPointerElementType();
1513 
1514   do {
1515     // First fold any existing GEPs into the offset.
1516     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1517       APInt GEPOffset(Offset.getBitWidth(), 0);
1518       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1519         break;
1520       Offset += GEPOffset;
1521       Ptr = GEP->getPointerOperand();
1522       if (!Visited.insert(Ptr).second)
1523         break;
1524     }
1525 
1526     // See if we can perform a natural GEP here.
1527     Indices.clear();
1528     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1529                                            Indices, NamePrefix)) {
1530       // If we have a new natural pointer at the offset, clear out any old
1531       // offset pointer we computed. Unless it is the base pointer or
1532       // a non-instruction, we built a GEP we don't need. Zap it.
1533       if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1534         if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1535           assert(I->use_empty() && "Built a GEP with uses some how!");
1536           I->eraseFromParent();
1537         }
1538       OffsetPtr = P;
1539       OffsetBasePtr = Ptr;
1540       // If we also found a pointer of the right type, we're done.
1541       if (P->getType() == PointerTy)
1542         return P;
1543     }
1544 
1545     // Stash this pointer if we've found an i8*.
1546     if (Ptr->getType()->isIntegerTy(8)) {
1547       Int8Ptr = Ptr;
1548       Int8PtrOffset = Offset;
1549     }
1550 
1551     // Peel off a layer of the pointer and update the offset appropriately.
1552     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1553       Ptr = cast<Operator>(Ptr)->getOperand(0);
1554     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1555       if (GA->isInterposable())
1556         break;
1557       Ptr = GA->getAliasee();
1558     } else {
1559       break;
1560     }
1561     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1562   } while (Visited.insert(Ptr).second);
1563 
1564   if (!OffsetPtr) {
1565     if (!Int8Ptr) {
1566       Int8Ptr = IRB.CreateBitCast(
1567           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1568           NamePrefix + "sroa_raw_cast");
1569       Int8PtrOffset = Offset;
1570     }
1571 
1572     OffsetPtr = Int8PtrOffset == 0
1573                     ? Int8Ptr
1574                     : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1575                                             IRB.getInt(Int8PtrOffset),
1576                                             NamePrefix + "sroa_raw_idx");
1577   }
1578   Ptr = OffsetPtr;
1579 
1580   // On the off chance we were targeting i8*, guard the bitcast here.
1581   if (Ptr->getType() != PointerTy)
1582     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1583 
1584   return Ptr;
1585 }
1586 
1587 /// \brief Compute the adjusted alignment for a load or store from an offset.
1588 static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1589                                      const DataLayout &DL) {
1590   unsigned Alignment;
1591   Type *Ty;
1592   if (auto *LI = dyn_cast<LoadInst>(I)) {
1593     Alignment = LI->getAlignment();
1594     Ty = LI->getType();
1595   } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1596     Alignment = SI->getAlignment();
1597     Ty = SI->getValueOperand()->getType();
1598   } else {
1599     llvm_unreachable("Only loads and stores are allowed!");
1600   }
1601 
1602   if (!Alignment)
1603     Alignment = DL.getABITypeAlignment(Ty);
1604 
1605   return MinAlign(Alignment, Offset);
1606 }
1607 
1608 /// \brief Test whether we can convert a value from the old to the new type.
1609 ///
1610 /// This predicate should be used to guard calls to convertValue in order to
1611 /// ensure that we only try to convert viable values. The strategy is that we
1612 /// will peel off single element struct and array wrappings to get to an
1613 /// underlying value, and convert that value.
1614 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1615   if (OldTy == NewTy)
1616     return true;
1617 
1618   // For integer types, we can't handle any bit-width differences. This would
1619   // break both vector conversions with extension and introduce endianness
1620   // issues when in conjunction with loads and stores.
1621   if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1622     assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1623                cast<IntegerType>(NewTy)->getBitWidth() &&
1624            "We can't have the same bitwidth for different int types");
1625     return false;
1626   }
1627 
1628   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1629     return false;
1630   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1631     return false;
1632 
1633   // We can convert pointers to integers and vice-versa. Same for vectors
1634   // of pointers and integers.
1635   OldTy = OldTy->getScalarType();
1636   NewTy = NewTy->getScalarType();
1637   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1638     if (NewTy->isPointerTy() && OldTy->isPointerTy())
1639       return true;
1640     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1641       return true;
1642     return false;
1643   }
1644 
1645   return true;
1646 }
1647 
1648 /// \brief Generic routine to convert an SSA value to a value of a different
1649 /// type.
1650 ///
1651 /// This will try various different casting techniques, such as bitcasts,
1652 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1653 /// two types for viability with this routine.
1654 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1655                            Type *NewTy) {
1656   Type *OldTy = V->getType();
1657   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1658 
1659   if (OldTy == NewTy)
1660     return V;
1661 
1662   assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1663          "Integer types must be the exact same to convert.");
1664 
1665   // See if we need inttoptr for this type pair. A cast involving both scalars
1666   // and vectors requires and additional bitcast.
1667   if (OldTy->getScalarType()->isIntegerTy() &&
1668       NewTy->getScalarType()->isPointerTy()) {
1669     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1670     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1671       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1672                                 NewTy);
1673 
1674     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1675     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1676       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1677                                 NewTy);
1678 
1679     return IRB.CreateIntToPtr(V, NewTy);
1680   }
1681 
1682   // See if we need ptrtoint for this type pair. A cast involving both scalars
1683   // and vectors requires and additional bitcast.
1684   if (OldTy->getScalarType()->isPointerTy() &&
1685       NewTy->getScalarType()->isIntegerTy()) {
1686     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1687     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1688       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1689                                NewTy);
1690 
1691     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1692     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1693       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1694                                NewTy);
1695 
1696     return IRB.CreatePtrToInt(V, NewTy);
1697   }
1698 
1699   return IRB.CreateBitCast(V, NewTy);
1700 }
1701 
1702 /// \brief Test whether the given slice use can be promoted to a vector.
1703 ///
1704 /// This function is called to test each entry in a partition which is slated
1705 /// for a single slice.
1706 static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1707                                             VectorType *Ty,
1708                                             uint64_t ElementSize,
1709                                             const DataLayout &DL) {
1710   // First validate the slice offsets.
1711   uint64_t BeginOffset =
1712       std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1713   uint64_t BeginIndex = BeginOffset / ElementSize;
1714   if (BeginIndex * ElementSize != BeginOffset ||
1715       BeginIndex >= Ty->getNumElements())
1716     return false;
1717   uint64_t EndOffset =
1718       std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1719   uint64_t EndIndex = EndOffset / ElementSize;
1720   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1721     return false;
1722 
1723   assert(EndIndex > BeginIndex && "Empty vector!");
1724   uint64_t NumElements = EndIndex - BeginIndex;
1725   Type *SliceTy = (NumElements == 1)
1726                       ? Ty->getElementType()
1727                       : VectorType::get(Ty->getElementType(), NumElements);
1728 
1729   Type *SplitIntTy =
1730       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1731 
1732   Use *U = S.getUse();
1733 
1734   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1735     if (MI->isVolatile())
1736       return false;
1737     if (!S.isSplittable())
1738       return false; // Skip any unsplittable intrinsics.
1739   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1740     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1741         II->getIntrinsicID() != Intrinsic::lifetime_end)
1742       return false;
1743   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1744     // Disable vector promotion when there are loads or stores of an FCA.
1745     return false;
1746   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1747     if (LI->isVolatile())
1748       return false;
1749     Type *LTy = LI->getType();
1750     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1751       assert(LTy->isIntegerTy());
1752       LTy = SplitIntTy;
1753     }
1754     if (!canConvertValue(DL, SliceTy, LTy))
1755       return false;
1756   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1757     if (SI->isVolatile())
1758       return false;
1759     Type *STy = SI->getValueOperand()->getType();
1760     if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1761       assert(STy->isIntegerTy());
1762       STy = SplitIntTy;
1763     }
1764     if (!canConvertValue(DL, STy, SliceTy))
1765       return false;
1766   } else {
1767     return false;
1768   }
1769 
1770   return true;
1771 }
1772 
1773 /// \brief Test whether the given alloca partitioning and range of slices can be
1774 /// promoted to a vector.
1775 ///
1776 /// This is a quick test to check whether we can rewrite a particular alloca
1777 /// partition (and its newly formed alloca) into a vector alloca with only
1778 /// whole-vector loads and stores such that it could be promoted to a vector
1779 /// SSA value. We only can ensure this for a limited set of operations, and we
1780 /// don't want to do the rewrites unless we are confident that the result will
1781 /// be promotable, so we have an early test here.
1782 static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
1783   // Collect the candidate types for vector-based promotion. Also track whether
1784   // we have different element types.
1785   SmallVector<VectorType *, 4> CandidateTys;
1786   Type *CommonEltTy = nullptr;
1787   bool HaveCommonEltTy = true;
1788   auto CheckCandidateType = [&](Type *Ty) {
1789     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1790       CandidateTys.push_back(VTy);
1791       if (!CommonEltTy)
1792         CommonEltTy = VTy->getElementType();
1793       else if (CommonEltTy != VTy->getElementType())
1794         HaveCommonEltTy = false;
1795     }
1796   };
1797   // Consider any loads or stores that are the exact size of the slice.
1798   for (const Slice &S : P)
1799     if (S.beginOffset() == P.beginOffset() &&
1800         S.endOffset() == P.endOffset()) {
1801       if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1802         CheckCandidateType(LI->getType());
1803       else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1804         CheckCandidateType(SI->getValueOperand()->getType());
1805     }
1806 
1807   // If we didn't find a vector type, nothing to do here.
1808   if (CandidateTys.empty())
1809     return nullptr;
1810 
1811   // Remove non-integer vector types if we had multiple common element types.
1812   // FIXME: It'd be nice to replace them with integer vector types, but we can't
1813   // do that until all the backends are known to produce good code for all
1814   // integer vector types.
1815   if (!HaveCommonEltTy) {
1816     CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1817                                       [](VectorType *VTy) {
1818                          return !VTy->getElementType()->isIntegerTy();
1819                        }),
1820                        CandidateTys.end());
1821 
1822     // If there were no integer vector types, give up.
1823     if (CandidateTys.empty())
1824       return nullptr;
1825 
1826     // Rank the remaining candidate vector types. This is easy because we know
1827     // they're all integer vectors. We sort by ascending number of elements.
1828     auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1829       assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1830              "Cannot have vector types of different sizes!");
1831       assert(RHSTy->getElementType()->isIntegerTy() &&
1832              "All non-integer types eliminated!");
1833       assert(LHSTy->getElementType()->isIntegerTy() &&
1834              "All non-integer types eliminated!");
1835       return RHSTy->getNumElements() < LHSTy->getNumElements();
1836     };
1837     std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1838     CandidateTys.erase(
1839         std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1840         CandidateTys.end());
1841   } else {
1842 // The only way to have the same element type in every vector type is to
1843 // have the same vector type. Check that and remove all but one.
1844 #ifndef NDEBUG
1845     for (VectorType *VTy : CandidateTys) {
1846       assert(VTy->getElementType() == CommonEltTy &&
1847              "Unaccounted for element type!");
1848       assert(VTy == CandidateTys[0] &&
1849              "Different vector types with the same element type!");
1850     }
1851 #endif
1852     CandidateTys.resize(1);
1853   }
1854 
1855   // Try each vector type, and return the one which works.
1856   auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1857     uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1858 
1859     // While the definition of LLVM vectors is bitpacked, we don't support sizes
1860     // that aren't byte sized.
1861     if (ElementSize % 8)
1862       return false;
1863     assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1864            "vector size not a multiple of element size?");
1865     ElementSize /= 8;
1866 
1867     for (const Slice &S : P)
1868       if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
1869         return false;
1870 
1871     for (const Slice *S : P.splitSliceTails())
1872       if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
1873         return false;
1874 
1875     return true;
1876   };
1877   for (VectorType *VTy : CandidateTys)
1878     if (CheckVectorTypeForPromotion(VTy))
1879       return VTy;
1880 
1881   return nullptr;
1882 }
1883 
1884 /// \brief Test whether a slice of an alloca is valid for integer widening.
1885 ///
1886 /// This implements the necessary checking for the \c isIntegerWideningViable
1887 /// test below on a single slice of the alloca.
1888 static bool isIntegerWideningViableForSlice(const Slice &S,
1889                                             uint64_t AllocBeginOffset,
1890                                             Type *AllocaTy,
1891                                             const DataLayout &DL,
1892                                             bool &WholeAllocaOp) {
1893   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1894 
1895   uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1896   uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1897 
1898   // We can't reasonably handle cases where the load or store extends past
1899   // the end of the alloca's type and into its padding.
1900   if (RelEnd > Size)
1901     return false;
1902 
1903   Use *U = S.getUse();
1904 
1905   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1906     if (LI->isVolatile())
1907       return false;
1908     // We can't handle loads that extend past the allocated memory.
1909     if (DL.getTypeStoreSize(LI->getType()) > Size)
1910       return false;
1911     // Note that we don't count vector loads or stores as whole-alloca
1912     // operations which enable integer widening because we would prefer to use
1913     // vector widening instead.
1914     if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
1915       WholeAllocaOp = true;
1916     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1917       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1918         return false;
1919     } else if (RelBegin != 0 || RelEnd != Size ||
1920                !canConvertValue(DL, AllocaTy, LI->getType())) {
1921       // Non-integer loads need to be convertible from the alloca type so that
1922       // they are promotable.
1923       return false;
1924     }
1925   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1926     Type *ValueTy = SI->getValueOperand()->getType();
1927     if (SI->isVolatile())
1928       return false;
1929     // We can't handle stores that extend past the allocated memory.
1930     if (DL.getTypeStoreSize(ValueTy) > Size)
1931       return false;
1932     // Note that we don't count vector loads or stores as whole-alloca
1933     // operations which enable integer widening because we would prefer to use
1934     // vector widening instead.
1935     if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
1936       WholeAllocaOp = true;
1937     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1938       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1939         return false;
1940     } else if (RelBegin != 0 || RelEnd != Size ||
1941                !canConvertValue(DL, ValueTy, AllocaTy)) {
1942       // Non-integer stores need to be convertible to the alloca type so that
1943       // they are promotable.
1944       return false;
1945     }
1946   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1947     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1948       return false;
1949     if (!S.isSplittable())
1950       return false; // Skip any unsplittable intrinsics.
1951   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1952     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1953         II->getIntrinsicID() != Intrinsic::lifetime_end)
1954       return false;
1955   } else {
1956     return false;
1957   }
1958 
1959   return true;
1960 }
1961 
1962 /// \brief Test whether the given alloca partition's integer operations can be
1963 /// widened to promotable ones.
1964 ///
1965 /// This is a quick test to check whether we can rewrite the integer loads and
1966 /// stores to a particular alloca into wider loads and stores and be able to
1967 /// promote the resulting alloca.
1968 static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
1969                                     const DataLayout &DL) {
1970   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1971   // Don't create integer types larger than the maximum bitwidth.
1972   if (SizeInBits > IntegerType::MAX_INT_BITS)
1973     return false;
1974 
1975   // Don't try to handle allocas with bit-padding.
1976   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1977     return false;
1978 
1979   // We need to ensure that an integer type with the appropriate bitwidth can
1980   // be converted to the alloca type, whatever that is. We don't want to force
1981   // the alloca itself to have an integer type if there is a more suitable one.
1982   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1983   if (!canConvertValue(DL, AllocaTy, IntTy) ||
1984       !canConvertValue(DL, IntTy, AllocaTy))
1985     return false;
1986 
1987   // While examining uses, we ensure that the alloca has a covering load or
1988   // store. We don't want to widen the integer operations only to fail to
1989   // promote due to some other unsplittable entry (which we may make splittable
1990   // later). However, if there are only splittable uses, go ahead and assume
1991   // that we cover the alloca.
1992   // FIXME: We shouldn't consider split slices that happen to start in the
1993   // partition here...
1994   bool WholeAllocaOp =
1995       P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
1996 
1997   for (const Slice &S : P)
1998     if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
1999                                          WholeAllocaOp))
2000       return false;
2001 
2002   for (const Slice *S : P.splitSliceTails())
2003     if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2004                                          WholeAllocaOp))
2005       return false;
2006 
2007   return WholeAllocaOp;
2008 }
2009 
2010 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2011                              IntegerType *Ty, uint64_t Offset,
2012                              const Twine &Name) {
2013   DEBUG(dbgs() << "       start: " << *V << "\n");
2014   IntegerType *IntTy = cast<IntegerType>(V->getType());
2015   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2016          "Element extends past full value");
2017   uint64_t ShAmt = 8 * Offset;
2018   if (DL.isBigEndian())
2019     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2020   if (ShAmt) {
2021     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2022     DEBUG(dbgs() << "     shifted: " << *V << "\n");
2023   }
2024   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2025          "Cannot extract to a larger integer!");
2026   if (Ty != IntTy) {
2027     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2028     DEBUG(dbgs() << "     trunced: " << *V << "\n");
2029   }
2030   return V;
2031 }
2032 
2033 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2034                             Value *V, uint64_t Offset, const Twine &Name) {
2035   IntegerType *IntTy = cast<IntegerType>(Old->getType());
2036   IntegerType *Ty = cast<IntegerType>(V->getType());
2037   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2038          "Cannot insert a larger integer!");
2039   DEBUG(dbgs() << "       start: " << *V << "\n");
2040   if (Ty != IntTy) {
2041     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2042     DEBUG(dbgs() << "    extended: " << *V << "\n");
2043   }
2044   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2045          "Element store outside of alloca store");
2046   uint64_t ShAmt = 8 * Offset;
2047   if (DL.isBigEndian())
2048     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2049   if (ShAmt) {
2050     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2051     DEBUG(dbgs() << "     shifted: " << *V << "\n");
2052   }
2053 
2054   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2055     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2056     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2057     DEBUG(dbgs() << "      masked: " << *Old << "\n");
2058     V = IRB.CreateOr(Old, V, Name + ".insert");
2059     DEBUG(dbgs() << "    inserted: " << *V << "\n");
2060   }
2061   return V;
2062 }
2063 
2064 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2065                             unsigned EndIndex, const Twine &Name) {
2066   VectorType *VecTy = cast<VectorType>(V->getType());
2067   unsigned NumElements = EndIndex - BeginIndex;
2068   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2069 
2070   if (NumElements == VecTy->getNumElements())
2071     return V;
2072 
2073   if (NumElements == 1) {
2074     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2075                                  Name + ".extract");
2076     DEBUG(dbgs() << "     extract: " << *V << "\n");
2077     return V;
2078   }
2079 
2080   SmallVector<Constant *, 8> Mask;
2081   Mask.reserve(NumElements);
2082   for (unsigned i = BeginIndex; i != EndIndex; ++i)
2083     Mask.push_back(IRB.getInt32(i));
2084   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2085                               ConstantVector::get(Mask), Name + ".extract");
2086   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
2087   return V;
2088 }
2089 
2090 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2091                            unsigned BeginIndex, const Twine &Name) {
2092   VectorType *VecTy = cast<VectorType>(Old->getType());
2093   assert(VecTy && "Can only insert a vector into a vector");
2094 
2095   VectorType *Ty = dyn_cast<VectorType>(V->getType());
2096   if (!Ty) {
2097     // Single element to insert.
2098     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2099                                 Name + ".insert");
2100     DEBUG(dbgs() << "     insert: " << *V << "\n");
2101     return V;
2102   }
2103 
2104   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2105          "Too many elements!");
2106   if (Ty->getNumElements() == VecTy->getNumElements()) {
2107     assert(V->getType() == VecTy && "Vector type mismatch");
2108     return V;
2109   }
2110   unsigned EndIndex = BeginIndex + Ty->getNumElements();
2111 
2112   // When inserting a smaller vector into the larger to store, we first
2113   // use a shuffle vector to widen it with undef elements, and then
2114   // a second shuffle vector to select between the loaded vector and the
2115   // incoming vector.
2116   SmallVector<Constant *, 8> Mask;
2117   Mask.reserve(VecTy->getNumElements());
2118   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2119     if (i >= BeginIndex && i < EndIndex)
2120       Mask.push_back(IRB.getInt32(i - BeginIndex));
2121     else
2122       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2123   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2124                               ConstantVector::get(Mask), Name + ".expand");
2125   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
2126 
2127   Mask.clear();
2128   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2129     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2130 
2131   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2132 
2133   DEBUG(dbgs() << "    blend: " << *V << "\n");
2134   return V;
2135 }
2136 
2137 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2138 /// to use a new alloca.
2139 ///
2140 /// Also implements the rewriting to vector-based accesses when the partition
2141 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2142 /// lives here.
2143 class llvm::sroa::AllocaSliceRewriter
2144     : public InstVisitor<AllocaSliceRewriter, bool> {
2145   // Befriend the base class so it can delegate to private visit methods.
2146   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2147   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2148 
2149   const DataLayout &DL;
2150   AllocaSlices &AS;
2151   SROA &Pass;
2152   AllocaInst &OldAI, &NewAI;
2153   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2154   Type *NewAllocaTy;
2155 
2156   // This is a convenience and flag variable that will be null unless the new
2157   // alloca's integer operations should be widened to this integer type due to
2158   // passing isIntegerWideningViable above. If it is non-null, the desired
2159   // integer type will be stored here for easy access during rewriting.
2160   IntegerType *IntTy;
2161 
2162   // If we are rewriting an alloca partition which can be written as pure
2163   // vector operations, we stash extra information here. When VecTy is
2164   // non-null, we have some strict guarantees about the rewritten alloca:
2165   //   - The new alloca is exactly the size of the vector type here.
2166   //   - The accesses all either map to the entire vector or to a single
2167   //     element.
2168   //   - The set of accessing instructions is only one of those handled above
2169   //     in isVectorPromotionViable. Generally these are the same access kinds
2170   //     which are promotable via mem2reg.
2171   VectorType *VecTy;
2172   Type *ElementTy;
2173   uint64_t ElementSize;
2174 
2175   // The original offset of the slice currently being rewritten relative to
2176   // the original alloca.
2177   uint64_t BeginOffset, EndOffset;
2178   // The new offsets of the slice currently being rewritten relative to the
2179   // original alloca.
2180   uint64_t NewBeginOffset, NewEndOffset;
2181 
2182   uint64_t SliceSize;
2183   bool IsSplittable;
2184   bool IsSplit;
2185   Use *OldUse;
2186   Instruction *OldPtr;
2187 
2188   // Track post-rewrite users which are PHI nodes and Selects.
2189   SmallPtrSetImpl<PHINode *> &PHIUsers;
2190   SmallPtrSetImpl<SelectInst *> &SelectUsers;
2191 
2192   // Utility IR builder, whose name prefix is setup for each visited use, and
2193   // the insertion point is set to point to the user.
2194   IRBuilderTy IRB;
2195 
2196 public:
2197   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2198                       AllocaInst &OldAI, AllocaInst &NewAI,
2199                       uint64_t NewAllocaBeginOffset,
2200                       uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2201                       VectorType *PromotableVecTy,
2202                       SmallPtrSetImpl<PHINode *> &PHIUsers,
2203                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
2204       : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2205         NewAllocaBeginOffset(NewAllocaBeginOffset),
2206         NewAllocaEndOffset(NewAllocaEndOffset),
2207         NewAllocaTy(NewAI.getAllocatedType()),
2208         IntTy(IsIntegerPromotable
2209                   ? Type::getIntNTy(
2210                         NewAI.getContext(),
2211                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2212                   : nullptr),
2213         VecTy(PromotableVecTy),
2214         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2215         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2216         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2217         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2218         IRB(NewAI.getContext(), ConstantFolder()) {
2219     if (VecTy) {
2220       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2221              "Only multiple-of-8 sized vector elements are viable");
2222       ++NumVectorized;
2223     }
2224     assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2225   }
2226 
2227   bool visit(AllocaSlices::const_iterator I) {
2228     bool CanSROA = true;
2229     BeginOffset = I->beginOffset();
2230     EndOffset = I->endOffset();
2231     IsSplittable = I->isSplittable();
2232     IsSplit =
2233         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2234     DEBUG(dbgs() << "  rewriting " << (IsSplit ? "split " : ""));
2235     DEBUG(AS.printSlice(dbgs(), I, ""));
2236     DEBUG(dbgs() << "\n");
2237 
2238     // Compute the intersecting offset range.
2239     assert(BeginOffset < NewAllocaEndOffset);
2240     assert(EndOffset > NewAllocaBeginOffset);
2241     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2242     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2243 
2244     SliceSize = NewEndOffset - NewBeginOffset;
2245 
2246     OldUse = I->getUse();
2247     OldPtr = cast<Instruction>(OldUse->get());
2248 
2249     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2250     IRB.SetInsertPoint(OldUserI);
2251     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2252     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2253 
2254     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2255     if (VecTy || IntTy)
2256       assert(CanSROA);
2257     return CanSROA;
2258   }
2259 
2260 private:
2261   // Make sure the other visit overloads are visible.
2262   using Base::visit;
2263 
2264   // Every instruction which can end up as a user must have a rewrite rule.
2265   bool visitInstruction(Instruction &I) {
2266     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2267     llvm_unreachable("No rewrite rule for this instruction!");
2268   }
2269 
2270   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2271     // Note that the offset computation can use BeginOffset or NewBeginOffset
2272     // interchangeably for unsplit slices.
2273     assert(IsSplit || BeginOffset == NewBeginOffset);
2274     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2275 
2276 #ifndef NDEBUG
2277     StringRef OldName = OldPtr->getName();
2278     // Skip through the last '.sroa.' component of the name.
2279     size_t LastSROAPrefix = OldName.rfind(".sroa.");
2280     if (LastSROAPrefix != StringRef::npos) {
2281       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2282       // Look for an SROA slice index.
2283       size_t IndexEnd = OldName.find_first_not_of("0123456789");
2284       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2285         // Strip the index and look for the offset.
2286         OldName = OldName.substr(IndexEnd + 1);
2287         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2288         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2289           // Strip the offset.
2290           OldName = OldName.substr(OffsetEnd + 1);
2291       }
2292     }
2293     // Strip any SROA suffixes as well.
2294     OldName = OldName.substr(0, OldName.find(".sroa_"));
2295 #endif
2296 
2297     return getAdjustedPtr(IRB, DL, &NewAI,
2298                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2299 #ifndef NDEBUG
2300                           Twine(OldName) + "."
2301 #else
2302                           Twine()
2303 #endif
2304                           );
2305   }
2306 
2307   /// \brief Compute suitable alignment to access this slice of the *new*
2308   /// alloca.
2309   ///
2310   /// You can optionally pass a type to this routine and if that type's ABI
2311   /// alignment is itself suitable, this will return zero.
2312   unsigned getSliceAlign(Type *Ty = nullptr) {
2313     unsigned NewAIAlign = NewAI.getAlignment();
2314     if (!NewAIAlign)
2315       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2316     unsigned Align =
2317         MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2318     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2319   }
2320 
2321   unsigned getIndex(uint64_t Offset) {
2322     assert(VecTy && "Can only call getIndex when rewriting a vector");
2323     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2324     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2325     uint32_t Index = RelOffset / ElementSize;
2326     assert(Index * ElementSize == RelOffset);
2327     return Index;
2328   }
2329 
2330   void deleteIfTriviallyDead(Value *V) {
2331     Instruction *I = cast<Instruction>(V);
2332     if (isInstructionTriviallyDead(I))
2333       Pass.DeadInsts.insert(I);
2334   }
2335 
2336   Value *rewriteVectorizedLoadInst() {
2337     unsigned BeginIndex = getIndex(NewBeginOffset);
2338     unsigned EndIndex = getIndex(NewEndOffset);
2339     assert(EndIndex > BeginIndex && "Empty vector!");
2340 
2341     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2342     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2343   }
2344 
2345   Value *rewriteIntegerLoad(LoadInst &LI) {
2346     assert(IntTy && "We cannot insert an integer to the alloca");
2347     assert(!LI.isVolatile());
2348     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2349     V = convertValue(DL, IRB, V, IntTy);
2350     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2351     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2352     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2353       IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2354       V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2355     }
2356     // It is possible that the extracted type is not the load type. This
2357     // happens if there is a load past the end of the alloca, and as
2358     // a consequence the slice is narrower but still a candidate for integer
2359     // lowering. To handle this case, we just zero extend the extracted
2360     // integer.
2361     assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2362            "Can only handle an extract for an overly wide load");
2363     if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2364       V = IRB.CreateZExt(V, LI.getType());
2365     return V;
2366   }
2367 
2368   bool visitLoadInst(LoadInst &LI) {
2369     DEBUG(dbgs() << "    original: " << LI << "\n");
2370     Value *OldOp = LI.getOperand(0);
2371     assert(OldOp == OldPtr);
2372 
2373     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2374                              : LI.getType();
2375     const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
2376     bool IsPtrAdjusted = false;
2377     Value *V;
2378     if (VecTy) {
2379       V = rewriteVectorizedLoadInst();
2380     } else if (IntTy && LI.getType()->isIntegerTy()) {
2381       V = rewriteIntegerLoad(LI);
2382     } else if (NewBeginOffset == NewAllocaBeginOffset &&
2383                NewEndOffset == NewAllocaEndOffset &&
2384                (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2385                 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2386                  TargetTy->isIntegerTy()))) {
2387       LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2388                                               LI.isVolatile(), LI.getName());
2389       if (LI.isVolatile())
2390         NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2391       V = NewLI;
2392 
2393       // If this is an integer load past the end of the slice (which means the
2394       // bytes outside the slice are undef or this load is dead) just forcibly
2395       // fix the integer size with correct handling of endianness.
2396       if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2397         if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2398           if (AITy->getBitWidth() < TITy->getBitWidth()) {
2399             V = IRB.CreateZExt(V, TITy, "load.ext");
2400             if (DL.isBigEndian())
2401               V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2402                                 "endian_shift");
2403           }
2404     } else {
2405       Type *LTy = TargetTy->getPointerTo();
2406       LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2407                                               getSliceAlign(TargetTy),
2408                                               LI.isVolatile(), LI.getName());
2409       if (LI.isVolatile())
2410         NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
2411 
2412       V = NewLI;
2413       IsPtrAdjusted = true;
2414     }
2415     V = convertValue(DL, IRB, V, TargetTy);
2416 
2417     if (IsSplit) {
2418       assert(!LI.isVolatile());
2419       assert(LI.getType()->isIntegerTy() &&
2420              "Only integer type loads and stores are split");
2421       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2422              "Split load isn't smaller than original load");
2423       assert(LI.getType()->getIntegerBitWidth() ==
2424                  DL.getTypeStoreSizeInBits(LI.getType()) &&
2425              "Non-byte-multiple bit width");
2426       // Move the insertion point just past the load so that we can refer to it.
2427       IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2428       // Create a placeholder value with the same type as LI to use as the
2429       // basis for the new value. This allows us to replace the uses of LI with
2430       // the computed value, and then replace the placeholder with LI, leaving
2431       // LI only used for this computation.
2432       Value *Placeholder =
2433           new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2434       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2435                         "insert");
2436       LI.replaceAllUsesWith(V);
2437       Placeholder->replaceAllUsesWith(&LI);
2438       delete Placeholder;
2439     } else {
2440       LI.replaceAllUsesWith(V);
2441     }
2442 
2443     Pass.DeadInsts.insert(&LI);
2444     deleteIfTriviallyDead(OldOp);
2445     DEBUG(dbgs() << "          to: " << *V << "\n");
2446     return !LI.isVolatile() && !IsPtrAdjusted;
2447   }
2448 
2449   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2450     if (V->getType() != VecTy) {
2451       unsigned BeginIndex = getIndex(NewBeginOffset);
2452       unsigned EndIndex = getIndex(NewEndOffset);
2453       assert(EndIndex > BeginIndex && "Empty vector!");
2454       unsigned NumElements = EndIndex - BeginIndex;
2455       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2456       Type *SliceTy = (NumElements == 1)
2457                           ? ElementTy
2458                           : VectorType::get(ElementTy, NumElements);
2459       if (V->getType() != SliceTy)
2460         V = convertValue(DL, IRB, V, SliceTy);
2461 
2462       // Mix in the existing elements.
2463       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2464       V = insertVector(IRB, Old, V, BeginIndex, "vec");
2465     }
2466     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2467     Pass.DeadInsts.insert(&SI);
2468 
2469     (void)Store;
2470     DEBUG(dbgs() << "          to: " << *Store << "\n");
2471     return true;
2472   }
2473 
2474   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2475     assert(IntTy && "We cannot extract an integer from the alloca");
2476     assert(!SI.isVolatile());
2477     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2478       Value *Old =
2479           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2480       Old = convertValue(DL, IRB, Old, IntTy);
2481       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2482       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2483       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2484     }
2485     V = convertValue(DL, IRB, V, NewAllocaTy);
2486     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2487     Pass.DeadInsts.insert(&SI);
2488     (void)Store;
2489     DEBUG(dbgs() << "          to: " << *Store << "\n");
2490     return true;
2491   }
2492 
2493   bool visitStoreInst(StoreInst &SI) {
2494     DEBUG(dbgs() << "    original: " << SI << "\n");
2495     Value *OldOp = SI.getOperand(1);
2496     assert(OldOp == OldPtr);
2497 
2498     Value *V = SI.getValueOperand();
2499 
2500     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2501     // alloca that should be re-examined after promoting this alloca.
2502     if (V->getType()->isPointerTy())
2503       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2504         Pass.PostPromotionWorklist.insert(AI);
2505 
2506     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2507       assert(!SI.isVolatile());
2508       assert(V->getType()->isIntegerTy() &&
2509              "Only integer type loads and stores are split");
2510       assert(V->getType()->getIntegerBitWidth() ==
2511                  DL.getTypeStoreSizeInBits(V->getType()) &&
2512              "Non-byte-multiple bit width");
2513       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2514       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2515                          "extract");
2516     }
2517 
2518     if (VecTy)
2519       return rewriteVectorizedStoreInst(V, SI, OldOp);
2520     if (IntTy && V->getType()->isIntegerTy())
2521       return rewriteIntegerStore(V, SI);
2522 
2523     const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
2524     StoreInst *NewSI;
2525     if (NewBeginOffset == NewAllocaBeginOffset &&
2526         NewEndOffset == NewAllocaEndOffset &&
2527         (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2528          (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2529           V->getType()->isIntegerTy()))) {
2530       // If this is an integer store past the end of slice (and thus the bytes
2531       // past that point are irrelevant or this is unreachable), truncate the
2532       // value prior to storing.
2533       if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2534         if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2535           if (VITy->getBitWidth() > AITy->getBitWidth()) {
2536             if (DL.isBigEndian())
2537               V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2538                                  "endian_shift");
2539             V = IRB.CreateTrunc(V, AITy, "load.trunc");
2540           }
2541 
2542       V = convertValue(DL, IRB, V, NewAllocaTy);
2543       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2544                                      SI.isVolatile());
2545     } else {
2546       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2547       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2548                                      SI.isVolatile());
2549     }
2550     if (SI.isVolatile())
2551       NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
2552     Pass.DeadInsts.insert(&SI);
2553     deleteIfTriviallyDead(OldOp);
2554 
2555     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2556     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2557   }
2558 
2559   /// \brief Compute an integer value from splatting an i8 across the given
2560   /// number of bytes.
2561   ///
2562   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2563   /// call this routine.
2564   /// FIXME: Heed the advice above.
2565   ///
2566   /// \param V The i8 value to splat.
2567   /// \param Size The number of bytes in the output (assuming i8 is one byte)
2568   Value *getIntegerSplat(Value *V, unsigned Size) {
2569     assert(Size > 0 && "Expected a positive number of bytes.");
2570     IntegerType *VTy = cast<IntegerType>(V->getType());
2571     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2572     if (Size == 1)
2573       return V;
2574 
2575     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2576     V = IRB.CreateMul(
2577         IRB.CreateZExt(V, SplatIntTy, "zext"),
2578         ConstantExpr::getUDiv(
2579             Constant::getAllOnesValue(SplatIntTy),
2580             ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2581                                   SplatIntTy)),
2582         "isplat");
2583     return V;
2584   }
2585 
2586   /// \brief Compute a vector splat for a given element value.
2587   Value *getVectorSplat(Value *V, unsigned NumElements) {
2588     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2589     DEBUG(dbgs() << "       splat: " << *V << "\n");
2590     return V;
2591   }
2592 
2593   bool visitMemSetInst(MemSetInst &II) {
2594     DEBUG(dbgs() << "    original: " << II << "\n");
2595     assert(II.getRawDest() == OldPtr);
2596 
2597     // If the memset has a variable size, it cannot be split, just adjust the
2598     // pointer to the new alloca.
2599     if (!isa<Constant>(II.getLength())) {
2600       assert(!IsSplit);
2601       assert(NewBeginOffset == BeginOffset);
2602       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2603       Type *CstTy = II.getAlignmentCst()->getType();
2604       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2605 
2606       deleteIfTriviallyDead(OldPtr);
2607       return false;
2608     }
2609 
2610     // Record this instruction for deletion.
2611     Pass.DeadInsts.insert(&II);
2612 
2613     Type *AllocaTy = NewAI.getAllocatedType();
2614     Type *ScalarTy = AllocaTy->getScalarType();
2615 
2616     // If this doesn't map cleanly onto the alloca type, and that type isn't
2617     // a single value type, just emit a memset.
2618     if (!VecTy && !IntTy &&
2619         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2620          SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2621          !AllocaTy->isSingleValueType() ||
2622          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2623          DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2624       Type *SizeTy = II.getLength()->getType();
2625       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2626       CallInst *New = IRB.CreateMemSet(
2627           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2628           getSliceAlign(), II.isVolatile());
2629       (void)New;
2630       DEBUG(dbgs() << "          to: " << *New << "\n");
2631       return false;
2632     }
2633 
2634     // If we can represent this as a simple value, we have to build the actual
2635     // value to store, which requires expanding the byte present in memset to
2636     // a sensible representation for the alloca type. This is essentially
2637     // splatting the byte to a sufficiently wide integer, splatting it across
2638     // any desired vector width, and bitcasting to the final type.
2639     Value *V;
2640 
2641     if (VecTy) {
2642       // If this is a memset of a vectorized alloca, insert it.
2643       assert(ElementTy == ScalarTy);
2644 
2645       unsigned BeginIndex = getIndex(NewBeginOffset);
2646       unsigned EndIndex = getIndex(NewEndOffset);
2647       assert(EndIndex > BeginIndex && "Empty vector!");
2648       unsigned NumElements = EndIndex - BeginIndex;
2649       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2650 
2651       Value *Splat =
2652           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2653       Splat = convertValue(DL, IRB, Splat, ElementTy);
2654       if (NumElements > 1)
2655         Splat = getVectorSplat(Splat, NumElements);
2656 
2657       Value *Old =
2658           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2659       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2660     } else if (IntTy) {
2661       // If this is a memset on an alloca where we can widen stores, insert the
2662       // set integer.
2663       assert(!II.isVolatile());
2664 
2665       uint64_t Size = NewEndOffset - NewBeginOffset;
2666       V = getIntegerSplat(II.getValue(), Size);
2667 
2668       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2669                     EndOffset != NewAllocaBeginOffset)) {
2670         Value *Old =
2671             IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2672         Old = convertValue(DL, IRB, Old, IntTy);
2673         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2674         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2675       } else {
2676         assert(V->getType() == IntTy &&
2677                "Wrong type for an alloca wide integer!");
2678       }
2679       V = convertValue(DL, IRB, V, AllocaTy);
2680     } else {
2681       // Established these invariants above.
2682       assert(NewBeginOffset == NewAllocaBeginOffset);
2683       assert(NewEndOffset == NewAllocaEndOffset);
2684 
2685       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2686       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2687         V = getVectorSplat(V, AllocaVecTy->getNumElements());
2688 
2689       V = convertValue(DL, IRB, V, AllocaTy);
2690     }
2691 
2692     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2693                                         II.isVolatile());
2694     (void)New;
2695     DEBUG(dbgs() << "          to: " << *New << "\n");
2696     return !II.isVolatile();
2697   }
2698 
2699   bool visitMemTransferInst(MemTransferInst &II) {
2700     // Rewriting of memory transfer instructions can be a bit tricky. We break
2701     // them into two categories: split intrinsics and unsplit intrinsics.
2702 
2703     DEBUG(dbgs() << "    original: " << II << "\n");
2704 
2705     bool IsDest = &II.getRawDestUse() == OldUse;
2706     assert((IsDest && II.getRawDest() == OldPtr) ||
2707            (!IsDest && II.getRawSource() == OldPtr));
2708 
2709     unsigned SliceAlign = getSliceAlign();
2710 
2711     // For unsplit intrinsics, we simply modify the source and destination
2712     // pointers in place. This isn't just an optimization, it is a matter of
2713     // correctness. With unsplit intrinsics we may be dealing with transfers
2714     // within a single alloca before SROA ran, or with transfers that have
2715     // a variable length. We may also be dealing with memmove instead of
2716     // memcpy, and so simply updating the pointers is the necessary for us to
2717     // update both source and dest of a single call.
2718     if (!IsSplittable) {
2719       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2720       if (IsDest)
2721         II.setDest(AdjustedPtr);
2722       else
2723         II.setSource(AdjustedPtr);
2724 
2725       if (II.getAlignment() > SliceAlign) {
2726         Type *CstTy = II.getAlignmentCst()->getType();
2727         II.setAlignment(
2728             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2729       }
2730 
2731       DEBUG(dbgs() << "          to: " << II << "\n");
2732       deleteIfTriviallyDead(OldPtr);
2733       return false;
2734     }
2735     // For split transfer intrinsics we have an incredibly useful assurance:
2736     // the source and destination do not reside within the same alloca, and at
2737     // least one of them does not escape. This means that we can replace
2738     // memmove with memcpy, and we don't need to worry about all manner of
2739     // downsides to splitting and transforming the operations.
2740 
2741     // If this doesn't map cleanly onto the alloca type, and that type isn't
2742     // a single value type, just emit a memcpy.
2743     bool EmitMemCpy =
2744         !VecTy && !IntTy &&
2745         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2746          SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2747          !NewAI.getAllocatedType()->isSingleValueType());
2748 
2749     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2750     // size hasn't been shrunk based on analysis of the viable range, this is
2751     // a no-op.
2752     if (EmitMemCpy && &OldAI == &NewAI) {
2753       // Ensure the start lines up.
2754       assert(NewBeginOffset == BeginOffset);
2755 
2756       // Rewrite the size as needed.
2757       if (NewEndOffset != EndOffset)
2758         II.setLength(ConstantInt::get(II.getLength()->getType(),
2759                                       NewEndOffset - NewBeginOffset));
2760       return false;
2761     }
2762     // Record this instruction for deletion.
2763     Pass.DeadInsts.insert(&II);
2764 
2765     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2766     // alloca that should be re-examined after rewriting this instruction.
2767     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2768     if (AllocaInst *AI =
2769             dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2770       assert(AI != &OldAI && AI != &NewAI &&
2771              "Splittable transfers cannot reach the same alloca on both ends.");
2772       Pass.Worklist.insert(AI);
2773     }
2774 
2775     Type *OtherPtrTy = OtherPtr->getType();
2776     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2777 
2778     // Compute the relative offset for the other pointer within the transfer.
2779     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2780     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2781     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2782                                    OtherOffset.zextOrTrunc(64).getZExtValue());
2783 
2784     if (EmitMemCpy) {
2785       // Compute the other pointer, folding as much as possible to produce
2786       // a single, simple GEP in most cases.
2787       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2788                                 OtherPtr->getName() + ".");
2789 
2790       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2791       Type *SizeTy = II.getLength()->getType();
2792       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2793 
2794       CallInst *New = IRB.CreateMemCpy(
2795           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2796           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2797       (void)New;
2798       DEBUG(dbgs() << "          to: " << *New << "\n");
2799       return false;
2800     }
2801 
2802     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2803                          NewEndOffset == NewAllocaEndOffset;
2804     uint64_t Size = NewEndOffset - NewBeginOffset;
2805     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2806     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2807     unsigned NumElements = EndIndex - BeginIndex;
2808     IntegerType *SubIntTy =
2809         IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2810 
2811     // Reset the other pointer type to match the register type we're going to
2812     // use, but using the address space of the original other pointer.
2813     if (VecTy && !IsWholeAlloca) {
2814       if (NumElements == 1)
2815         OtherPtrTy = VecTy->getElementType();
2816       else
2817         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2818 
2819       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2820     } else if (IntTy && !IsWholeAlloca) {
2821       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2822     } else {
2823       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2824     }
2825 
2826     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2827                                    OtherPtr->getName() + ".");
2828     unsigned SrcAlign = OtherAlign;
2829     Value *DstPtr = &NewAI;
2830     unsigned DstAlign = SliceAlign;
2831     if (!IsDest) {
2832       std::swap(SrcPtr, DstPtr);
2833       std::swap(SrcAlign, DstAlign);
2834     }
2835 
2836     Value *Src;
2837     if (VecTy && !IsWholeAlloca && !IsDest) {
2838       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2839       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2840     } else if (IntTy && !IsWholeAlloca && !IsDest) {
2841       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2842       Src = convertValue(DL, IRB, Src, IntTy);
2843       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2844       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2845     } else {
2846       Src =
2847           IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
2848     }
2849 
2850     if (VecTy && !IsWholeAlloca && IsDest) {
2851       Value *Old =
2852           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2853       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2854     } else if (IntTy && !IsWholeAlloca && IsDest) {
2855       Value *Old =
2856           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2857       Old = convertValue(DL, IRB, Old, IntTy);
2858       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2859       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2860       Src = convertValue(DL, IRB, Src, NewAllocaTy);
2861     }
2862 
2863     StoreInst *Store = cast<StoreInst>(
2864         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
2865     (void)Store;
2866     DEBUG(dbgs() << "          to: " << *Store << "\n");
2867     return !II.isVolatile();
2868   }
2869 
2870   bool visitIntrinsicInst(IntrinsicInst &II) {
2871     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2872            II.getIntrinsicID() == Intrinsic::lifetime_end);
2873     DEBUG(dbgs() << "    original: " << II << "\n");
2874     assert(II.getArgOperand(1) == OldPtr);
2875 
2876     // Record this instruction for deletion.
2877     Pass.DeadInsts.insert(&II);
2878 
2879     ConstantInt *Size =
2880         ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2881                          NewEndOffset - NewBeginOffset);
2882     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2883     Value *New;
2884     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2885       New = IRB.CreateLifetimeStart(Ptr, Size);
2886     else
2887       New = IRB.CreateLifetimeEnd(Ptr, Size);
2888 
2889     (void)New;
2890     DEBUG(dbgs() << "          to: " << *New << "\n");
2891     return true;
2892   }
2893 
2894   bool visitPHINode(PHINode &PN) {
2895     DEBUG(dbgs() << "    original: " << PN << "\n");
2896     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2897     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2898 
2899     // We would like to compute a new pointer in only one place, but have it be
2900     // as local as possible to the PHI. To do that, we re-use the location of
2901     // the old pointer, which necessarily must be in the right position to
2902     // dominate the PHI.
2903     IRBuilderTy PtrBuilder(IRB);
2904     if (isa<PHINode>(OldPtr))
2905       PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
2906     else
2907       PtrBuilder.SetInsertPoint(OldPtr);
2908     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
2909 
2910     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
2911     // Replace the operands which were using the old pointer.
2912     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2913 
2914     DEBUG(dbgs() << "          to: " << PN << "\n");
2915     deleteIfTriviallyDead(OldPtr);
2916 
2917     // PHIs can't be promoted on their own, but often can be speculated. We
2918     // check the speculation outside of the rewriter so that we see the
2919     // fully-rewritten alloca.
2920     PHIUsers.insert(&PN);
2921     return true;
2922   }
2923 
2924   bool visitSelectInst(SelectInst &SI) {
2925     DEBUG(dbgs() << "    original: " << SI << "\n");
2926     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2927            "Pointer isn't an operand!");
2928     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2929     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2930 
2931     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2932     // Replace the operands which were using the old pointer.
2933     if (SI.getOperand(1) == OldPtr)
2934       SI.setOperand(1, NewPtr);
2935     if (SI.getOperand(2) == OldPtr)
2936       SI.setOperand(2, NewPtr);
2937 
2938     DEBUG(dbgs() << "          to: " << SI << "\n");
2939     deleteIfTriviallyDead(OldPtr);
2940 
2941     // Selects can't be promoted on their own, but often can be speculated. We
2942     // check the speculation outside of the rewriter so that we see the
2943     // fully-rewritten alloca.
2944     SelectUsers.insert(&SI);
2945     return true;
2946   }
2947 };
2948 
2949 namespace {
2950 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2951 ///
2952 /// This pass aggressively rewrites all aggregate loads and stores on
2953 /// a particular pointer (or any pointer derived from it which we can identify)
2954 /// with scalar loads and stores.
2955 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2956   // Befriend the base class so it can delegate to private visit methods.
2957   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2958 
2959   /// Queue of pointer uses to analyze and potentially rewrite.
2960   SmallVector<Use *, 8> Queue;
2961 
2962   /// Set to prevent us from cycling with phi nodes and loops.
2963   SmallPtrSet<User *, 8> Visited;
2964 
2965   /// The current pointer use being rewritten. This is used to dig up the used
2966   /// value (as opposed to the user).
2967   Use *U;
2968 
2969 public:
2970   /// Rewrite loads and stores through a pointer and all pointers derived from
2971   /// it.
2972   bool rewrite(Instruction &I) {
2973     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
2974     enqueueUsers(I);
2975     bool Changed = false;
2976     while (!Queue.empty()) {
2977       U = Queue.pop_back_val();
2978       Changed |= visit(cast<Instruction>(U->getUser()));
2979     }
2980     return Changed;
2981   }
2982 
2983 private:
2984   /// Enqueue all the users of the given instruction for further processing.
2985   /// This uses a set to de-duplicate users.
2986   void enqueueUsers(Instruction &I) {
2987     for (Use &U : I.uses())
2988       if (Visited.insert(U.getUser()).second)
2989         Queue.push_back(&U);
2990   }
2991 
2992   // Conservative default is to not rewrite anything.
2993   bool visitInstruction(Instruction &I) { return false; }
2994 
2995   /// \brief Generic recursive split emission class.
2996   template <typename Derived> class OpSplitter {
2997   protected:
2998     /// The builder used to form new instructions.
2999     IRBuilderTy IRB;
3000     /// The indices which to be used with insert- or extractvalue to select the
3001     /// appropriate value within the aggregate.
3002     SmallVector<unsigned, 4> Indices;
3003     /// The indices to a GEP instruction which will move Ptr to the correct slot
3004     /// within the aggregate.
3005     SmallVector<Value *, 4> GEPIndices;
3006     /// The base pointer of the original op, used as a base for GEPing the
3007     /// split operations.
3008     Value *Ptr;
3009 
3010     /// Initialize the splitter with an insertion point, Ptr and start with a
3011     /// single zero GEP index.
3012     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3013         : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3014 
3015   public:
3016     /// \brief Generic recursive split emission routine.
3017     ///
3018     /// This method recursively splits an aggregate op (load or store) into
3019     /// scalar or vector ops. It splits recursively until it hits a single value
3020     /// and emits that single value operation via the template argument.
3021     ///
3022     /// The logic of this routine relies on GEPs and insertvalue and
3023     /// extractvalue all operating with the same fundamental index list, merely
3024     /// formatted differently (GEPs need actual values).
3025     ///
3026     /// \param Ty  The type being split recursively into smaller ops.
3027     /// \param Agg The aggregate value being built up or stored, depending on
3028     /// whether this is splitting a load or a store respectively.
3029     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3030       if (Ty->isSingleValueType())
3031         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3032 
3033       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3034         unsigned OldSize = Indices.size();
3035         (void)OldSize;
3036         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3037              ++Idx) {
3038           assert(Indices.size() == OldSize && "Did not return to the old size");
3039           Indices.push_back(Idx);
3040           GEPIndices.push_back(IRB.getInt32(Idx));
3041           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3042           GEPIndices.pop_back();
3043           Indices.pop_back();
3044         }
3045         return;
3046       }
3047 
3048       if (StructType *STy = dyn_cast<StructType>(Ty)) {
3049         unsigned OldSize = Indices.size();
3050         (void)OldSize;
3051         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3052              ++Idx) {
3053           assert(Indices.size() == OldSize && "Did not return to the old size");
3054           Indices.push_back(Idx);
3055           GEPIndices.push_back(IRB.getInt32(Idx));
3056           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3057           GEPIndices.pop_back();
3058           Indices.pop_back();
3059         }
3060         return;
3061       }
3062 
3063       llvm_unreachable("Only arrays and structs are aggregate loadable types");
3064     }
3065   };
3066 
3067   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3068     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3069         : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3070 
3071     /// Emit a leaf load of a single value. This is called at the leaves of the
3072     /// recursive emission to actually load values.
3073     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3074       assert(Ty->isSingleValueType());
3075       // Load the single value and insert it using the indices.
3076       Value *GEP =
3077           IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
3078       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
3079       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3080       DEBUG(dbgs() << "          to: " << *Load << "\n");
3081     }
3082   };
3083 
3084   bool visitLoadInst(LoadInst &LI) {
3085     assert(LI.getPointerOperand() == *U);
3086     if (!LI.isSimple() || LI.getType()->isSingleValueType())
3087       return false;
3088 
3089     // We have an aggregate being loaded, split it apart.
3090     DEBUG(dbgs() << "    original: " << LI << "\n");
3091     LoadOpSplitter Splitter(&LI, *U);
3092     Value *V = UndefValue::get(LI.getType());
3093     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3094     LI.replaceAllUsesWith(V);
3095     LI.eraseFromParent();
3096     return true;
3097   }
3098 
3099   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3100     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
3101         : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3102 
3103     /// Emit a leaf store of a single value. This is called at the leaves of the
3104     /// recursive emission to actually produce stores.
3105     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3106       assert(Ty->isSingleValueType());
3107       // Extract the single value and store it using the indices.
3108       Value *Store = IRB.CreateStore(
3109           IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3110           IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
3111       (void)Store;
3112       DEBUG(dbgs() << "          to: " << *Store << "\n");
3113     }
3114   };
3115 
3116   bool visitStoreInst(StoreInst &SI) {
3117     if (!SI.isSimple() || SI.getPointerOperand() != *U)
3118       return false;
3119     Value *V = SI.getValueOperand();
3120     if (V->getType()->isSingleValueType())
3121       return false;
3122 
3123     // We have an aggregate being stored, split it apart.
3124     DEBUG(dbgs() << "    original: " << SI << "\n");
3125     StoreOpSplitter Splitter(&SI, *U);
3126     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3127     SI.eraseFromParent();
3128     return true;
3129   }
3130 
3131   bool visitBitCastInst(BitCastInst &BC) {
3132     enqueueUsers(BC);
3133     return false;
3134   }
3135 
3136   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3137     enqueueUsers(GEPI);
3138     return false;
3139   }
3140 
3141   bool visitPHINode(PHINode &PN) {
3142     enqueueUsers(PN);
3143     return false;
3144   }
3145 
3146   bool visitSelectInst(SelectInst &SI) {
3147     enqueueUsers(SI);
3148     return false;
3149   }
3150 };
3151 }
3152 
3153 /// \brief Strip aggregate type wrapping.
3154 ///
3155 /// This removes no-op aggregate types wrapping an underlying type. It will
3156 /// strip as many layers of types as it can without changing either the type
3157 /// size or the allocated size.
3158 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3159   if (Ty->isSingleValueType())
3160     return Ty;
3161 
3162   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3163   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3164 
3165   Type *InnerTy;
3166   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3167     InnerTy = ArrTy->getElementType();
3168   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3169     const StructLayout *SL = DL.getStructLayout(STy);
3170     unsigned Index = SL->getElementContainingOffset(0);
3171     InnerTy = STy->getElementType(Index);
3172   } else {
3173     return Ty;
3174   }
3175 
3176   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3177       TypeSize > DL.getTypeSizeInBits(InnerTy))
3178     return Ty;
3179 
3180   return stripAggregateTypeWrapping(DL, InnerTy);
3181 }
3182 
3183 /// \brief Try to find a partition of the aggregate type passed in for a given
3184 /// offset and size.
3185 ///
3186 /// This recurses through the aggregate type and tries to compute a subtype
3187 /// based on the offset and size. When the offset and size span a sub-section
3188 /// of an array, it will even compute a new array type for that sub-section,
3189 /// and the same for structs.
3190 ///
3191 /// Note that this routine is very strict and tries to find a partition of the
3192 /// type which produces the *exact* right offset and size. It is not forgiving
3193 /// when the size or offset cause either end of type-based partition to be off.
3194 /// Also, this is a best-effort routine. It is reasonable to give up and not
3195 /// return a type if necessary.
3196 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3197                               uint64_t Size) {
3198   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3199     return stripAggregateTypeWrapping(DL, Ty);
3200   if (Offset > DL.getTypeAllocSize(Ty) ||
3201       (DL.getTypeAllocSize(Ty) - Offset) < Size)
3202     return nullptr;
3203 
3204   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3205     // We can't partition pointers...
3206     if (SeqTy->isPointerTy())
3207       return nullptr;
3208 
3209     Type *ElementTy = SeqTy->getElementType();
3210     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3211     uint64_t NumSkippedElements = Offset / ElementSize;
3212     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3213       if (NumSkippedElements >= ArrTy->getNumElements())
3214         return nullptr;
3215     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3216       if (NumSkippedElements >= VecTy->getNumElements())
3217         return nullptr;
3218     }
3219     Offset -= NumSkippedElements * ElementSize;
3220 
3221     // First check if we need to recurse.
3222     if (Offset > 0 || Size < ElementSize) {
3223       // Bail if the partition ends in a different array element.
3224       if ((Offset + Size) > ElementSize)
3225         return nullptr;
3226       // Recurse through the element type trying to peel off offset bytes.
3227       return getTypePartition(DL, ElementTy, Offset, Size);
3228     }
3229     assert(Offset == 0);
3230 
3231     if (Size == ElementSize)
3232       return stripAggregateTypeWrapping(DL, ElementTy);
3233     assert(Size > ElementSize);
3234     uint64_t NumElements = Size / ElementSize;
3235     if (NumElements * ElementSize != Size)
3236       return nullptr;
3237     return ArrayType::get(ElementTy, NumElements);
3238   }
3239 
3240   StructType *STy = dyn_cast<StructType>(Ty);
3241   if (!STy)
3242     return nullptr;
3243 
3244   const StructLayout *SL = DL.getStructLayout(STy);
3245   if (Offset >= SL->getSizeInBytes())
3246     return nullptr;
3247   uint64_t EndOffset = Offset + Size;
3248   if (EndOffset > SL->getSizeInBytes())
3249     return nullptr;
3250 
3251   unsigned Index = SL->getElementContainingOffset(Offset);
3252   Offset -= SL->getElementOffset(Index);
3253 
3254   Type *ElementTy = STy->getElementType(Index);
3255   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3256   if (Offset >= ElementSize)
3257     return nullptr; // The offset points into alignment padding.
3258 
3259   // See if any partition must be contained by the element.
3260   if (Offset > 0 || Size < ElementSize) {
3261     if ((Offset + Size) > ElementSize)
3262       return nullptr;
3263     return getTypePartition(DL, ElementTy, Offset, Size);
3264   }
3265   assert(Offset == 0);
3266 
3267   if (Size == ElementSize)
3268     return stripAggregateTypeWrapping(DL, ElementTy);
3269 
3270   StructType::element_iterator EI = STy->element_begin() + Index,
3271                                EE = STy->element_end();
3272   if (EndOffset < SL->getSizeInBytes()) {
3273     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3274     if (Index == EndIndex)
3275       return nullptr; // Within a single element and its padding.
3276 
3277     // Don't try to form "natural" types if the elements don't line up with the
3278     // expected size.
3279     // FIXME: We could potentially recurse down through the last element in the
3280     // sub-struct to find a natural end point.
3281     if (SL->getElementOffset(EndIndex) != EndOffset)
3282       return nullptr;
3283 
3284     assert(Index < EndIndex);
3285     EE = STy->element_begin() + EndIndex;
3286   }
3287 
3288   // Try to build up a sub-structure.
3289   StructType *SubTy =
3290       StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3291   const StructLayout *SubSL = DL.getStructLayout(SubTy);
3292   if (Size != SubSL->getSizeInBytes())
3293     return nullptr; // The sub-struct doesn't have quite the size needed.
3294 
3295   return SubTy;
3296 }
3297 
3298 /// \brief Pre-split loads and stores to simplify rewriting.
3299 ///
3300 /// We want to break up the splittable load+store pairs as much as
3301 /// possible. This is important to do as a preprocessing step, as once we
3302 /// start rewriting the accesses to partitions of the alloca we lose the
3303 /// necessary information to correctly split apart paired loads and stores
3304 /// which both point into this alloca. The case to consider is something like
3305 /// the following:
3306 ///
3307 ///   %a = alloca [12 x i8]
3308 ///   %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3309 ///   %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3310 ///   %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3311 ///   %iptr1 = bitcast i8* %gep1 to i64*
3312 ///   %iptr2 = bitcast i8* %gep2 to i64*
3313 ///   %fptr1 = bitcast i8* %gep1 to float*
3314 ///   %fptr2 = bitcast i8* %gep2 to float*
3315 ///   %fptr3 = bitcast i8* %gep3 to float*
3316 ///   store float 0.0, float* %fptr1
3317 ///   store float 1.0, float* %fptr2
3318 ///   %v = load i64* %iptr1
3319 ///   store i64 %v, i64* %iptr2
3320 ///   %f1 = load float* %fptr2
3321 ///   %f2 = load float* %fptr3
3322 ///
3323 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3324 /// promote everything so we recover the 2 SSA values that should have been
3325 /// there all along.
3326 ///
3327 /// \returns true if any changes are made.
3328 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3329   DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3330 
3331   // Track the loads and stores which are candidates for pre-splitting here, in
3332   // the order they first appear during the partition scan. These give stable
3333   // iteration order and a basis for tracking which loads and stores we
3334   // actually split.
3335   SmallVector<LoadInst *, 4> Loads;
3336   SmallVector<StoreInst *, 4> Stores;
3337 
3338   // We need to accumulate the splits required of each load or store where we
3339   // can find them via a direct lookup. This is important to cross-check loads
3340   // and stores against each other. We also track the slice so that we can kill
3341   // all the slices that end up split.
3342   struct SplitOffsets {
3343     Slice *S;
3344     std::vector<uint64_t> Splits;
3345   };
3346   SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3347 
3348   // Track loads out of this alloca which cannot, for any reason, be pre-split.
3349   // This is important as we also cannot pre-split stores of those loads!
3350   // FIXME: This is all pretty gross. It means that we can be more aggressive
3351   // in pre-splitting when the load feeding the store happens to come from
3352   // a separate alloca. Put another way, the effectiveness of SROA would be
3353   // decreased by a frontend which just concatenated all of its local allocas
3354   // into one big flat alloca. But defeating such patterns is exactly the job
3355   // SROA is tasked with! Sadly, to not have this discrepancy we would have
3356   // change store pre-splitting to actually force pre-splitting of the load
3357   // that feeds it *and all stores*. That makes pre-splitting much harder, but
3358   // maybe it would make it more principled?
3359   SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3360 
3361   DEBUG(dbgs() << "  Searching for candidate loads and stores\n");
3362   for (auto &P : AS.partitions()) {
3363     for (Slice &S : P) {
3364       Instruction *I = cast<Instruction>(S.getUse()->getUser());
3365       if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3366         // If this is a load we have to track that it can't participate in any
3367         // pre-splitting. If this is a store of a load we have to track that
3368         // that load also can't participate in any pre-splitting.
3369         if (auto *LI = dyn_cast<LoadInst>(I))
3370           UnsplittableLoads.insert(LI);
3371         else if (auto *SI = dyn_cast<StoreInst>(I))
3372           if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3373             UnsplittableLoads.insert(LI);
3374         continue;
3375       }
3376       assert(P.endOffset() > S.beginOffset() &&
3377              "Empty or backwards partition!");
3378 
3379       // Determine if this is a pre-splittable slice.
3380       if (auto *LI = dyn_cast<LoadInst>(I)) {
3381         assert(!LI->isVolatile() && "Cannot split volatile loads!");
3382 
3383         // The load must be used exclusively to store into other pointers for
3384         // us to be able to arbitrarily pre-split it. The stores must also be
3385         // simple to avoid changing semantics.
3386         auto IsLoadSimplyStored = [](LoadInst *LI) {
3387           for (User *LU : LI->users()) {
3388             auto *SI = dyn_cast<StoreInst>(LU);
3389             if (!SI || !SI->isSimple())
3390               return false;
3391           }
3392           return true;
3393         };
3394         if (!IsLoadSimplyStored(LI)) {
3395           UnsplittableLoads.insert(LI);
3396           continue;
3397         }
3398 
3399         Loads.push_back(LI);
3400       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3401         if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3402           // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
3403           continue;
3404         auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3405         if (!StoredLoad || !StoredLoad->isSimple())
3406           continue;
3407         assert(!SI->isVolatile() && "Cannot split volatile stores!");
3408 
3409         Stores.push_back(SI);
3410       } else {
3411         // Other uses cannot be pre-split.
3412         continue;
3413       }
3414 
3415       // Record the initial split.
3416       DEBUG(dbgs() << "    Candidate: " << *I << "\n");
3417       auto &Offsets = SplitOffsetsMap[I];
3418       assert(Offsets.Splits.empty() &&
3419              "Should not have splits the first time we see an instruction!");
3420       Offsets.S = &S;
3421       Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3422     }
3423 
3424     // Now scan the already split slices, and add a split for any of them which
3425     // we're going to pre-split.
3426     for (Slice *S : P.splitSliceTails()) {
3427       auto SplitOffsetsMapI =
3428           SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3429       if (SplitOffsetsMapI == SplitOffsetsMap.end())
3430         continue;
3431       auto &Offsets = SplitOffsetsMapI->second;
3432 
3433       assert(Offsets.S == S && "Found a mismatched slice!");
3434       assert(!Offsets.Splits.empty() &&
3435              "Cannot have an empty set of splits on the second partition!");
3436       assert(Offsets.Splits.back() ==
3437                  P.beginOffset() - Offsets.S->beginOffset() &&
3438              "Previous split does not end where this one begins!");
3439 
3440       // Record each split. The last partition's end isn't needed as the size
3441       // of the slice dictates that.
3442       if (S->endOffset() > P.endOffset())
3443         Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3444     }
3445   }
3446 
3447   // We may have split loads where some of their stores are split stores. For
3448   // such loads and stores, we can only pre-split them if their splits exactly
3449   // match relative to their starting offset. We have to verify this prior to
3450   // any rewriting.
3451   Stores.erase(
3452       std::remove_if(Stores.begin(), Stores.end(),
3453                      [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3454                        // Lookup the load we are storing in our map of split
3455                        // offsets.
3456                        auto *LI = cast<LoadInst>(SI->getValueOperand());
3457                        // If it was completely unsplittable, then we're done,
3458                        // and this store can't be pre-split.
3459                        if (UnsplittableLoads.count(LI))
3460                          return true;
3461 
3462                        auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3463                        if (LoadOffsetsI == SplitOffsetsMap.end())
3464                          return false; // Unrelated loads are definitely safe.
3465                        auto &LoadOffsets = LoadOffsetsI->second;
3466 
3467                        // Now lookup the store's offsets.
3468                        auto &StoreOffsets = SplitOffsetsMap[SI];
3469 
3470                        // If the relative offsets of each split in the load and
3471                        // store match exactly, then we can split them and we
3472                        // don't need to remove them here.
3473                        if (LoadOffsets.Splits == StoreOffsets.Splits)
3474                          return false;
3475 
3476                        DEBUG(dbgs()
3477                              << "    Mismatched splits for load and store:\n"
3478                              << "      " << *LI << "\n"
3479                              << "      " << *SI << "\n");
3480 
3481                        // We've found a store and load that we need to split
3482                        // with mismatched relative splits. Just give up on them
3483                        // and remove both instructions from our list of
3484                        // candidates.
3485                        UnsplittableLoads.insert(LI);
3486                        return true;
3487                      }),
3488       Stores.end());
3489   // Now we have to go *back* through all the stores, because a later store may
3490   // have caused an earlier store's load to become unsplittable and if it is
3491   // unsplittable for the later store, then we can't rely on it being split in
3492   // the earlier store either.
3493   Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
3494                               [&UnsplittableLoads](StoreInst *SI) {
3495                                 auto *LI =
3496                                     cast<LoadInst>(SI->getValueOperand());
3497                                 return UnsplittableLoads.count(LI);
3498                               }),
3499                Stores.end());
3500   // Once we've established all the loads that can't be split for some reason,
3501   // filter any that made it into our list out.
3502   Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
3503                              [&UnsplittableLoads](LoadInst *LI) {
3504                                return UnsplittableLoads.count(LI);
3505                              }),
3506               Loads.end());
3507 
3508 
3509   // If no loads or stores are left, there is no pre-splitting to be done for
3510   // this alloca.
3511   if (Loads.empty() && Stores.empty())
3512     return false;
3513 
3514   // From here on, we can't fail and will be building new accesses, so rig up
3515   // an IR builder.
3516   IRBuilderTy IRB(&AI);
3517 
3518   // Collect the new slices which we will merge into the alloca slices.
3519   SmallVector<Slice, 4> NewSlices;
3520 
3521   // Track any allocas we end up splitting loads and stores for so we iterate
3522   // on them.
3523   SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3524 
3525   // At this point, we have collected all of the loads and stores we can
3526   // pre-split, and the specific splits needed for them. We actually do the
3527   // splitting in a specific order in order to handle when one of the loads in
3528   // the value operand to one of the stores.
3529   //
3530   // First, we rewrite all of the split loads, and just accumulate each split
3531   // load in a parallel structure. We also build the slices for them and append
3532   // them to the alloca slices.
3533   SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3534   std::vector<LoadInst *> SplitLoads;
3535   const DataLayout &DL = AI.getModule()->getDataLayout();
3536   for (LoadInst *LI : Loads) {
3537     SplitLoads.clear();
3538 
3539     IntegerType *Ty = cast<IntegerType>(LI->getType());
3540     uint64_t LoadSize = Ty->getBitWidth() / 8;
3541     assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3542 
3543     auto &Offsets = SplitOffsetsMap[LI];
3544     assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3545            "Slice size should always match load size exactly!");
3546     uint64_t BaseOffset = Offsets.S->beginOffset();
3547     assert(BaseOffset + LoadSize > BaseOffset &&
3548            "Cannot represent alloca access size using 64-bit integers!");
3549 
3550     Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3551     IRB.SetInsertPoint(LI);
3552 
3553     DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
3554 
3555     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3556     int Idx = 0, Size = Offsets.Splits.size();
3557     for (;;) {
3558       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3559       auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3560       LoadInst *PLoad = IRB.CreateAlignedLoad(
3561           getAdjustedPtr(IRB, DL, BasePtr,
3562                          APInt(DL.getPointerSizeInBits(), PartOffset),
3563                          PartPtrTy, BasePtr->getName() + "."),
3564           getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3565           LI->getName());
3566 
3567       // Append this load onto the list of split loads so we can find it later
3568       // to rewrite the stores.
3569       SplitLoads.push_back(PLoad);
3570 
3571       // Now build a new slice for the alloca.
3572       NewSlices.push_back(
3573           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3574                 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3575                 /*IsSplittable*/ false));
3576       DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
3577                    << ", " << NewSlices.back().endOffset() << "): " << *PLoad
3578                    << "\n");
3579 
3580       // See if we've handled all the splits.
3581       if (Idx >= Size)
3582         break;
3583 
3584       // Setup the next partition.
3585       PartOffset = Offsets.Splits[Idx];
3586       ++Idx;
3587       PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3588     }
3589 
3590     // Now that we have the split loads, do the slow walk over all uses of the
3591     // load and rewrite them as split stores, or save the split loads to use
3592     // below if the store is going to be split there anyways.
3593     bool DeferredStores = false;
3594     for (User *LU : LI->users()) {
3595       StoreInst *SI = cast<StoreInst>(LU);
3596       if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3597         DeferredStores = true;
3598         DEBUG(dbgs() << "    Deferred splitting of store: " << *SI << "\n");
3599         continue;
3600       }
3601 
3602       Value *StoreBasePtr = SI->getPointerOperand();
3603       IRB.SetInsertPoint(SI);
3604 
3605       DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
3606 
3607       for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3608         LoadInst *PLoad = SplitLoads[Idx];
3609         uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
3610         auto *PartPtrTy =
3611             PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3612 
3613         StoreInst *PStore = IRB.CreateAlignedStore(
3614             PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3615                                   APInt(DL.getPointerSizeInBits(), PartOffset),
3616                                   PartPtrTy, StoreBasePtr->getName() + "."),
3617             getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3618         (void)PStore;
3619         DEBUG(dbgs() << "      +" << PartOffset << ":" << *PStore << "\n");
3620       }
3621 
3622       // We want to immediately iterate on any allocas impacted by splitting
3623       // this store, and we have to track any promotable alloca (indicated by
3624       // a direct store) as needing to be resplit because it is no longer
3625       // promotable.
3626       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3627         ResplitPromotableAllocas.insert(OtherAI);
3628         Worklist.insert(OtherAI);
3629       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3630                      StoreBasePtr->stripInBoundsOffsets())) {
3631         Worklist.insert(OtherAI);
3632       }
3633 
3634       // Mark the original store as dead.
3635       DeadInsts.insert(SI);
3636     }
3637 
3638     // Save the split loads if there are deferred stores among the users.
3639     if (DeferredStores)
3640       SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3641 
3642     // Mark the original load as dead and kill the original slice.
3643     DeadInsts.insert(LI);
3644     Offsets.S->kill();
3645   }
3646 
3647   // Second, we rewrite all of the split stores. At this point, we know that
3648   // all loads from this alloca have been split already. For stores of such
3649   // loads, we can simply look up the pre-existing split loads. For stores of
3650   // other loads, we split those loads first and then write split stores of
3651   // them.
3652   for (StoreInst *SI : Stores) {
3653     auto *LI = cast<LoadInst>(SI->getValueOperand());
3654     IntegerType *Ty = cast<IntegerType>(LI->getType());
3655     uint64_t StoreSize = Ty->getBitWidth() / 8;
3656     assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3657 
3658     auto &Offsets = SplitOffsetsMap[SI];
3659     assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3660            "Slice size should always match load size exactly!");
3661     uint64_t BaseOffset = Offsets.S->beginOffset();
3662     assert(BaseOffset + StoreSize > BaseOffset &&
3663            "Cannot represent alloca access size using 64-bit integers!");
3664 
3665     Value *LoadBasePtr = LI->getPointerOperand();
3666     Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3667 
3668     DEBUG(dbgs() << "  Splitting store: " << *SI << "\n");
3669 
3670     // Check whether we have an already split load.
3671     auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3672     std::vector<LoadInst *> *SplitLoads = nullptr;
3673     if (SplitLoadsMapI != SplitLoadsMap.end()) {
3674       SplitLoads = &SplitLoadsMapI->second;
3675       assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3676              "Too few split loads for the number of splits in the store!");
3677     } else {
3678       DEBUG(dbgs() << "          of load: " << *LI << "\n");
3679     }
3680 
3681     uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3682     int Idx = 0, Size = Offsets.Splits.size();
3683     for (;;) {
3684       auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3685       auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3686 
3687       // Either lookup a split load or create one.
3688       LoadInst *PLoad;
3689       if (SplitLoads) {
3690         PLoad = (*SplitLoads)[Idx];
3691       } else {
3692         IRB.SetInsertPoint(LI);
3693         PLoad = IRB.CreateAlignedLoad(
3694             getAdjustedPtr(IRB, DL, LoadBasePtr,
3695                            APInt(DL.getPointerSizeInBits(), PartOffset),
3696                            PartPtrTy, LoadBasePtr->getName() + "."),
3697             getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3698             LI->getName());
3699       }
3700 
3701       // And store this partition.
3702       IRB.SetInsertPoint(SI);
3703       StoreInst *PStore = IRB.CreateAlignedStore(
3704           PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
3705                                 APInt(DL.getPointerSizeInBits(), PartOffset),
3706                                 PartPtrTy, StoreBasePtr->getName() + "."),
3707           getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3708 
3709       // Now build a new slice for the alloca.
3710       NewSlices.push_back(
3711           Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3712                 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
3713                 /*IsSplittable*/ false));
3714       DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
3715                    << ", " << NewSlices.back().endOffset() << "): " << *PStore
3716                    << "\n");
3717       if (!SplitLoads) {
3718         DEBUG(dbgs() << "      of split load: " << *PLoad << "\n");
3719       }
3720 
3721       // See if we've finished all the splits.
3722       if (Idx >= Size)
3723         break;
3724 
3725       // Setup the next partition.
3726       PartOffset = Offsets.Splits[Idx];
3727       ++Idx;
3728       PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3729     }
3730 
3731     // We want to immediately iterate on any allocas impacted by splitting
3732     // this load, which is only relevant if it isn't a load of this alloca and
3733     // thus we didn't already split the loads above. We also have to keep track
3734     // of any promotable allocas we split loads on as they can no longer be
3735     // promoted.
3736     if (!SplitLoads) {
3737       if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3738         assert(OtherAI != &AI && "We can't re-split our own alloca!");
3739         ResplitPromotableAllocas.insert(OtherAI);
3740         Worklist.insert(OtherAI);
3741       } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3742                      LoadBasePtr->stripInBoundsOffsets())) {
3743         assert(OtherAI != &AI && "We can't re-split our own alloca!");
3744         Worklist.insert(OtherAI);
3745       }
3746     }
3747 
3748     // Mark the original store as dead now that we've split it up and kill its
3749     // slice. Note that we leave the original load in place unless this store
3750     // was its only use. It may in turn be split up if it is an alloca load
3751     // for some other alloca, but it may be a normal load. This may introduce
3752     // redundant loads, but where those can be merged the rest of the optimizer
3753     // should handle the merging, and this uncovers SSA splits which is more
3754     // important. In practice, the original loads will almost always be fully
3755     // split and removed eventually, and the splits will be merged by any
3756     // trivial CSE, including instcombine.
3757     if (LI->hasOneUse()) {
3758       assert(*LI->user_begin() == SI && "Single use isn't this store!");
3759       DeadInsts.insert(LI);
3760     }
3761     DeadInsts.insert(SI);
3762     Offsets.S->kill();
3763   }
3764 
3765   // Remove the killed slices that have ben pre-split.
3766   AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
3767     return S.isDead();
3768   }), AS.end());
3769 
3770   // Insert our new slices. This will sort and merge them into the sorted
3771   // sequence.
3772   AS.insert(NewSlices);
3773 
3774   DEBUG(dbgs() << "  Pre-split slices:\n");
3775 #ifndef NDEBUG
3776   for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3777     DEBUG(AS.print(dbgs(), I, "    "));
3778 #endif
3779 
3780   // Finally, don't try to promote any allocas that new require re-splitting.
3781   // They have already been added to the worklist above.
3782   PromotableAllocas.erase(
3783       std::remove_if(
3784           PromotableAllocas.begin(), PromotableAllocas.end(),
3785           [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3786       PromotableAllocas.end());
3787 
3788   return true;
3789 }
3790 
3791 /// \brief Rewrite an alloca partition's users.
3792 ///
3793 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3794 /// to rewrite uses of an alloca partition to be conducive for SSA value
3795 /// promotion. If the partition needs a new, more refined alloca, this will
3796 /// build that new alloca, preserving as much type information as possible, and
3797 /// rewrite the uses of the old alloca to point at the new one and have the
3798 /// appropriate new offsets. It also evaluates how successful the rewrite was
3799 /// at enabling promotion and if it was successful queues the alloca to be
3800 /// promoted.
3801 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3802                                    Partition &P) {
3803   // Try to compute a friendly type for this partition of the alloca. This
3804   // won't always succeed, in which case we fall back to a legal integer type
3805   // or an i8 array of an appropriate size.
3806   Type *SliceTy = nullptr;
3807   const DataLayout &DL = AI.getModule()->getDataLayout();
3808   if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3809     if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
3810       SliceTy = CommonUseTy;
3811   if (!SliceTy)
3812     if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
3813                                                  P.beginOffset(), P.size()))
3814       SliceTy = TypePartitionTy;
3815   if ((!SliceTy || (SliceTy->isArrayTy() &&
3816                     SliceTy->getArrayElementType()->isIntegerTy())) &&
3817       DL.isLegalInteger(P.size() * 8))
3818     SliceTy = Type::getIntNTy(*C, P.size() * 8);
3819   if (!SliceTy)
3820     SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3821   assert(DL.getTypeAllocSize(SliceTy) >= P.size());
3822 
3823   bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
3824 
3825   VectorType *VecTy =
3826       IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
3827   if (VecTy)
3828     SliceTy = VecTy;
3829 
3830   // Check for the case where we're going to rewrite to a new alloca of the
3831   // exact same type as the original, and with the same access offsets. In that
3832   // case, re-use the existing alloca, but still run through the rewriter to
3833   // perform phi and select speculation.
3834   AllocaInst *NewAI;
3835   if (SliceTy == AI.getAllocatedType()) {
3836     assert(P.beginOffset() == 0 &&
3837            "Non-zero begin offset but same alloca type");
3838     NewAI = &AI;
3839     // FIXME: We should be able to bail at this point with "nothing changed".
3840     // FIXME: We might want to defer PHI speculation until after here.
3841     // FIXME: return nullptr;
3842   } else {
3843     unsigned Alignment = AI.getAlignment();
3844     if (!Alignment) {
3845       // The minimum alignment which users can rely on when the explicit
3846       // alignment is omitted or zero is that required by the ABI for this
3847       // type.
3848       Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
3849     }
3850     Alignment = MinAlign(Alignment, P.beginOffset());
3851     // If we will get at least this much alignment from the type alone, leave
3852     // the alloca's alignment unconstrained.
3853     if (Alignment <= DL.getABITypeAlignment(SliceTy))
3854       Alignment = 0;
3855     NewAI = new AllocaInst(
3856         SliceTy, nullptr, Alignment,
3857         AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
3858     ++NumNewAllocas;
3859   }
3860 
3861   DEBUG(dbgs() << "Rewriting alloca partition "
3862                << "[" << P.beginOffset() << "," << P.endOffset()
3863                << ") to: " << *NewAI << "\n");
3864 
3865   // Track the high watermark on the worklist as it is only relevant for
3866   // promoted allocas. We will reset it to this point if the alloca is not in
3867   // fact scheduled for promotion.
3868   unsigned PPWOldSize = PostPromotionWorklist.size();
3869   unsigned NumUses = 0;
3870   SmallPtrSet<PHINode *, 8> PHIUsers;
3871   SmallPtrSet<SelectInst *, 8> SelectUsers;
3872 
3873   AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
3874                                P.endOffset(), IsIntegerPromotable, VecTy,
3875                                PHIUsers, SelectUsers);
3876   bool Promotable = true;
3877   for (Slice *S : P.splitSliceTails()) {
3878     Promotable &= Rewriter.visit(S);
3879     ++NumUses;
3880   }
3881   for (Slice &S : P) {
3882     Promotable &= Rewriter.visit(&S);
3883     ++NumUses;
3884   }
3885 
3886   NumAllocaPartitionUses += NumUses;
3887   MaxUsesPerAllocaPartition =
3888       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3889 
3890   // Now that we've processed all the slices in the new partition, check if any
3891   // PHIs or Selects would block promotion.
3892   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3893                                             E = PHIUsers.end();
3894        I != E; ++I)
3895     if (!isSafePHIToSpeculate(**I)) {
3896       Promotable = false;
3897       PHIUsers.clear();
3898       SelectUsers.clear();
3899       break;
3900     }
3901   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3902                                                E = SelectUsers.end();
3903        I != E; ++I)
3904     if (!isSafeSelectToSpeculate(**I)) {
3905       Promotable = false;
3906       PHIUsers.clear();
3907       SelectUsers.clear();
3908       break;
3909     }
3910 
3911   if (Promotable) {
3912     if (PHIUsers.empty() && SelectUsers.empty()) {
3913       // Promote the alloca.
3914       PromotableAllocas.push_back(NewAI);
3915     } else {
3916       // If we have either PHIs or Selects to speculate, add them to those
3917       // worklists and re-queue the new alloca so that we promote in on the
3918       // next iteration.
3919       for (PHINode *PHIUser : PHIUsers)
3920         SpeculatablePHIs.insert(PHIUser);
3921       for (SelectInst *SelectUser : SelectUsers)
3922         SpeculatableSelects.insert(SelectUser);
3923       Worklist.insert(NewAI);
3924     }
3925   } else {
3926     // Drop any post-promotion work items if promotion didn't happen.
3927     while (PostPromotionWorklist.size() > PPWOldSize)
3928       PostPromotionWorklist.pop_back();
3929 
3930     // We couldn't promote and we didn't create a new partition, nothing
3931     // happened.
3932     if (NewAI == &AI)
3933       return nullptr;
3934 
3935     // If we can't promote the alloca, iterate on it to check for new
3936     // refinements exposed by splitting the current alloca. Don't iterate on an
3937     // alloca which didn't actually change and didn't get promoted.
3938     Worklist.insert(NewAI);
3939   }
3940 
3941   return NewAI;
3942 }
3943 
3944 /// \brief Walks the slices of an alloca and form partitions based on them,
3945 /// rewriting each of their uses.
3946 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3947   if (AS.begin() == AS.end())
3948     return false;
3949 
3950   unsigned NumPartitions = 0;
3951   bool Changed = false;
3952   const DataLayout &DL = AI.getModule()->getDataLayout();
3953 
3954   // First try to pre-split loads and stores.
3955   Changed |= presplitLoadsAndStores(AI, AS);
3956 
3957   // Now that we have identified any pre-splitting opportunities, mark any
3958   // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
3959   // to split these during pre-splitting, we want to force them to be
3960   // rewritten into a partition.
3961   bool IsSorted = true;
3962   for (Slice &S : AS) {
3963     if (!S.isSplittable())
3964       continue;
3965     // FIXME: We currently leave whole-alloca splittable loads and stores. This
3966     // used to be the only splittable loads and stores and we need to be
3967     // confident that the above handling of splittable loads and stores is
3968     // completely sufficient before we forcibly disable the remaining handling.
3969     if (S.beginOffset() == 0 &&
3970         S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
3971       continue;
3972     if (isa<LoadInst>(S.getUse()->getUser()) ||
3973         isa<StoreInst>(S.getUse()->getUser())) {
3974       S.makeUnsplittable();
3975       IsSorted = false;
3976     }
3977   }
3978   if (!IsSorted)
3979     std::sort(AS.begin(), AS.end());
3980 
3981   /// \brief Describes the allocas introduced by rewritePartition
3982   /// in order to migrate the debug info.
3983   struct Piece {
3984     AllocaInst *Alloca;
3985     uint64_t Offset;
3986     uint64_t Size;
3987     Piece(AllocaInst *AI, uint64_t O, uint64_t S)
3988       : Alloca(AI), Offset(O), Size(S) {}
3989   };
3990   SmallVector<Piece, 4> Pieces;
3991 
3992   // Rewrite each partition.
3993   for (auto &P : AS.partitions()) {
3994     if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
3995       Changed = true;
3996       if (NewAI != &AI) {
3997         uint64_t SizeOfByte = 8;
3998         uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
3999         // Don't include any padding.
4000         uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4001         Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
4002       }
4003     }
4004     ++NumPartitions;
4005   }
4006 
4007   NumAllocaPartitions += NumPartitions;
4008   MaxPartitionsPerAlloca =
4009       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
4010 
4011   // Migrate debug information from the old alloca to the new alloca(s)
4012   // and the individual partitions.
4013   if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
4014     auto *Var = DbgDecl->getVariable();
4015     auto *Expr = DbgDecl->getExpression();
4016     DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4017     uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
4018     for (auto Piece : Pieces) {
4019       // Create a piece expression describing the new partition or reuse AI's
4020       // expression if there is only one partition.
4021       auto *PieceExpr = Expr;
4022       if (Piece.Size < AllocaSize || Expr->isBitPiece()) {
4023         // If this alloca is already a scalar replacement of a larger aggregate,
4024         // Piece.Offset describes the offset inside the scalar.
4025         uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
4026         uint64_t Start = Offset + Piece.Offset;
4027         uint64_t Size = Piece.Size;
4028         if (Expr->isBitPiece()) {
4029           uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
4030           if (Start >= AbsEnd)
4031             // No need to describe a SROAed padding.
4032             continue;
4033           Size = std::min(Size, AbsEnd - Start);
4034         }
4035         PieceExpr = DIB.createBitPieceExpression(Start, Size);
4036       } else {
4037         assert(Pieces.size() == 1 &&
4038                "partition is as large as original alloca");
4039       }
4040 
4041       // Remove any existing dbg.declare intrinsic describing the same alloca.
4042       if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
4043         OldDDI->eraseFromParent();
4044 
4045       DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
4046                         &AI);
4047     }
4048   }
4049   return Changed;
4050 }
4051 
4052 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
4053 void SROA::clobberUse(Use &U) {
4054   Value *OldV = U;
4055   // Replace the use with an undef value.
4056   U = UndefValue::get(OldV->getType());
4057 
4058   // Check for this making an instruction dead. We have to garbage collect
4059   // all the dead instructions to ensure the uses of any alloca end up being
4060   // minimal.
4061   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4062     if (isInstructionTriviallyDead(OldI)) {
4063       DeadInsts.insert(OldI);
4064     }
4065 }
4066 
4067 /// \brief Analyze an alloca for SROA.
4068 ///
4069 /// This analyzes the alloca to ensure we can reason about it, builds
4070 /// the slices of the alloca, and then hands it off to be split and
4071 /// rewritten as needed.
4072 bool SROA::runOnAlloca(AllocaInst &AI) {
4073   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4074   ++NumAllocasAnalyzed;
4075 
4076   // Special case dead allocas, as they're trivial.
4077   if (AI.use_empty()) {
4078     AI.eraseFromParent();
4079     return true;
4080   }
4081   const DataLayout &DL = AI.getModule()->getDataLayout();
4082 
4083   // Skip alloca forms that this analysis can't handle.
4084   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
4085       DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
4086     return false;
4087 
4088   bool Changed = false;
4089 
4090   // First, split any FCA loads and stores touching this alloca to promote
4091   // better splitting and promotion opportunities.
4092   AggLoadStoreRewriter AggRewriter;
4093   Changed |= AggRewriter.rewrite(AI);
4094 
4095   // Build the slices using a recursive instruction-visiting builder.
4096   AllocaSlices AS(DL, AI);
4097   DEBUG(AS.print(dbgs()));
4098   if (AS.isEscaped())
4099     return Changed;
4100 
4101   // Delete all the dead users of this alloca before splitting and rewriting it.
4102   for (Instruction *DeadUser : AS.getDeadUsers()) {
4103     // Free up everything used by this instruction.
4104     for (Use &DeadOp : DeadUser->operands())
4105       clobberUse(DeadOp);
4106 
4107     // Now replace the uses of this instruction.
4108     DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4109 
4110     // And mark it for deletion.
4111     DeadInsts.insert(DeadUser);
4112     Changed = true;
4113   }
4114   for (Use *DeadOp : AS.getDeadOperands()) {
4115     clobberUse(*DeadOp);
4116     Changed = true;
4117   }
4118 
4119   // No slices to split. Leave the dead alloca for a later pass to clean up.
4120   if (AS.begin() == AS.end())
4121     return Changed;
4122 
4123   Changed |= splitAlloca(AI, AS);
4124 
4125   DEBUG(dbgs() << "  Speculating PHIs\n");
4126   while (!SpeculatablePHIs.empty())
4127     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4128 
4129   DEBUG(dbgs() << "  Speculating Selects\n");
4130   while (!SpeculatableSelects.empty())
4131     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4132 
4133   return Changed;
4134 }
4135 
4136 /// \brief Delete the dead instructions accumulated in this run.
4137 ///
4138 /// Recursively deletes the dead instructions we've accumulated. This is done
4139 /// at the very end to maximize locality of the recursive delete and to
4140 /// minimize the problems of invalidated instruction pointers as such pointers
4141 /// are used heavily in the intermediate stages of the algorithm.
4142 ///
4143 /// We also record the alloca instructions deleted here so that they aren't
4144 /// subsequently handed to mem2reg to promote.
4145 void SROA::deleteDeadInstructions(
4146     SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4147   while (!DeadInsts.empty()) {
4148     Instruction *I = DeadInsts.pop_back_val();
4149     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4150 
4151     I->replaceAllUsesWith(UndefValue::get(I->getType()));
4152 
4153     for (Use &Operand : I->operands())
4154       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4155         // Zero out the operand and see if it becomes trivially dead.
4156         Operand = nullptr;
4157         if (isInstructionTriviallyDead(U))
4158           DeadInsts.insert(U);
4159       }
4160 
4161     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4162       DeletedAllocas.insert(AI);
4163       if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
4164         DbgDecl->eraseFromParent();
4165     }
4166 
4167     ++NumDeleted;
4168     I->eraseFromParent();
4169   }
4170 }
4171 
4172 /// \brief Promote the allocas, using the best available technique.
4173 ///
4174 /// This attempts to promote whatever allocas have been identified as viable in
4175 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
4176 /// This function returns whether any promotion occurred.
4177 bool SROA::promoteAllocas(Function &F) {
4178   if (PromotableAllocas.empty())
4179     return false;
4180 
4181   NumPromoted += PromotableAllocas.size();
4182 
4183   DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4184   PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
4185   PromotableAllocas.clear();
4186   return true;
4187 }
4188 
4189 PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4190                                 AssumptionCache &RunAC) {
4191   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4192   C = &F.getContext();
4193   DT = &RunDT;
4194   AC = &RunAC;
4195 
4196   BasicBlock &EntryBB = F.getEntryBlock();
4197   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4198        I != E; ++I) {
4199     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4200       Worklist.insert(AI);
4201   }
4202 
4203   bool Changed = false;
4204   // A set of deleted alloca instruction pointers which should be removed from
4205   // the list of promotable allocas.
4206   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4207 
4208   do {
4209     while (!Worklist.empty()) {
4210       Changed |= runOnAlloca(*Worklist.pop_back_val());
4211       deleteDeadInstructions(DeletedAllocas);
4212 
4213       // Remove the deleted allocas from various lists so that we don't try to
4214       // continue processing them.
4215       if (!DeletedAllocas.empty()) {
4216         auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4217         Worklist.remove_if(IsInSet);
4218         PostPromotionWorklist.remove_if(IsInSet);
4219         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
4220                                                PromotableAllocas.end(),
4221                                                IsInSet),
4222                                 PromotableAllocas.end());
4223         DeletedAllocas.clear();
4224       }
4225     }
4226 
4227     Changed |= promoteAllocas(F);
4228 
4229     Worklist = PostPromotionWorklist;
4230     PostPromotionWorklist.clear();
4231   } while (!Worklist.empty());
4232 
4233   // FIXME: Even when promoting allocas we should preserve some abstract set of
4234   // CFG-specific analyses.
4235   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
4236 }
4237 
4238 PreservedAnalyses SROA::run(Function &F, AnalysisManager<Function> &AM) {
4239   return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4240                  AM.getResult<AssumptionAnalysis>(F));
4241 }
4242 
4243 /// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4244 ///
4245 /// This is in the llvm namespace purely to allow it to be a friend of the \c
4246 /// SROA pass.
4247 class llvm::sroa::SROALegacyPass : public FunctionPass {
4248   /// The SROA implementation.
4249   SROA Impl;
4250 
4251 public:
4252   SROALegacyPass() : FunctionPass(ID) {
4253     initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4254   }
4255   bool runOnFunction(Function &F) override {
4256     if (skipFunction(F))
4257       return false;
4258 
4259     auto PA = Impl.runImpl(
4260         F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4261         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4262     return !PA.areAllPreserved();
4263   }
4264   void getAnalysisUsage(AnalysisUsage &AU) const override {
4265     AU.addRequired<AssumptionCacheTracker>();
4266     AU.addRequired<DominatorTreeWrapperPass>();
4267     AU.addPreserved<GlobalsAAWrapperPass>();
4268     AU.setPreservesCFG();
4269   }
4270 
4271   const char *getPassName() const override { return "SROA"; }
4272   static char ID;
4273 };
4274 
4275 char SROALegacyPass::ID = 0;
4276 
4277 FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4278 
4279 INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4280                       "Scalar Replacement Of Aggregates", false, false)
4281 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4282 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4283 INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4284                     false, false)
4285