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