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