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