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