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