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