[SROA] Run clang-format over the entire SROA pass as I wrote it before
[oota-llvm.git] / lib / Transforms / Scalar / SROA.cpp
1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This transformation implements the well known scalar replacement of
11 /// aggregates transformation. It tries to identify promotable elements of an
12 /// aggregate alloca, and promote them to registers. It will also try to
13 /// convert uses of an element (or set of elements) of an alloca into a vector
14 /// or bitfield-style integer scalar if appropriate.
15 ///
16 /// It works to do this with minimal slicing of the alloca so that regions
17 /// which are merely transferred in and out of external memory remain unchanged
18 /// and are not decomposed to scalar code.
19 ///
20 /// Because this also performs alloca promotion, it can be thought of as also
21 /// serving the purpose of SSA formation. The algorithm iterates on the
22 /// function until all opportunities for promotion have been realized.
23 ///
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AssumptionTracker.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/PtrUseVisitor.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DIBuilder.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Dominators.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/InstVisitor.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Operator.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/TimeValue.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59
60 #if __cplusplus >= 201103L && !defined(NDEBUG)
61 // We only use this for a debug check in C++11
62 #include <random>
63 #endif
64
65 using namespace llvm;
66
67 #define DEBUG_TYPE "sroa"
68
69 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
70 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
71 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
72 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
73 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
74 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
75 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
76 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
77 STATISTIC(NumDeleted, "Number of instructions deleted");
78 STATISTIC(NumVectorized, "Number of vectorized aggregates");
79
80 /// Hidden option to force the pass to not use DomTree and mem2reg, instead
81 /// forming SSA values through the SSAUpdater infrastructure.
82 static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
83                                      cl::Hidden);
84
85 /// Hidden option to enable randomly shuffling the slices to help uncover
86 /// instability in their order.
87 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
88                                              cl::init(false), cl::Hidden);
89
90 /// Hidden option to experiment with completely strict handling of inbounds
91 /// GEPs.
92 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
93                                         cl::Hidden);
94
95 namespace {
96 /// \brief A custom IRBuilder inserter which prefixes all names if they are
97 /// preserved.
98 template <bool preserveNames = true>
99 class IRBuilderPrefixedInserter
100     : public IRBuilderDefaultInserter<preserveNames> {
101   std::string Prefix;
102
103 public:
104   void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
105
106 protected:
107   void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
108                     BasicBlock::iterator InsertPt) const {
109     IRBuilderDefaultInserter<preserveNames>::InsertHelper(
110         I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
111   }
112 };
113
114 // Specialization for not preserving the name is trivial.
115 template <>
116 class IRBuilderPrefixedInserter<false>
117     : public IRBuilderDefaultInserter<false> {
118 public:
119   void SetNamePrefix(const Twine &P) {}
120 };
121
122 /// \brief Provide a typedef for IRBuilder that drops names in release builds.
123 #ifndef NDEBUG
124 typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
125     IRBuilderTy;
126 #else
127 typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
128     IRBuilderTy;
129 #endif
130 }
131
132 namespace {
133 /// \brief A used slice of an alloca.
134 ///
135 /// This structure represents a slice of an alloca used by some instruction. It
136 /// stores both the begin and end offsets of this use, a pointer to the use
137 /// itself, and a flag indicating whether we can classify the use as splittable
138 /// or not when forming partitions of the alloca.
139 class Slice {
140   /// \brief The beginning offset of the range.
141   uint64_t BeginOffset;
142
143   /// \brief The ending offset, not included in the range.
144   uint64_t EndOffset;
145
146   /// \brief Storage for both the use of this slice and whether it can be
147   /// split.
148   PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
149
150 public:
151   Slice() : BeginOffset(), EndOffset() {}
152   Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
153       : BeginOffset(BeginOffset), EndOffset(EndOffset),
154         UseAndIsSplittable(U, IsSplittable) {}
155
156   uint64_t beginOffset() const { return BeginOffset; }
157   uint64_t endOffset() const { return EndOffset; }
158
159   bool isSplittable() const { return UseAndIsSplittable.getInt(); }
160   void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
161
162   Use *getUse() const { return UseAndIsSplittable.getPointer(); }
163
164   bool isDead() const { return getUse() == nullptr; }
165   void kill() { UseAndIsSplittable.setPointer(nullptr); }
166
167   /// \brief Support for ordering ranges.
168   ///
169   /// This provides an ordering over ranges such that start offsets are
170   /// always increasing, and within equal start offsets, the end offsets are
171   /// decreasing. Thus the spanning range comes first in a cluster with the
172   /// same start position.
173   bool operator<(const Slice &RHS) const {
174     if (beginOffset() < RHS.beginOffset())
175       return true;
176     if (beginOffset() > RHS.beginOffset())
177       return false;
178     if (isSplittable() != RHS.isSplittable())
179       return !isSplittable();
180     if (endOffset() > RHS.endOffset())
181       return true;
182     return false;
183   }
184
185   /// \brief Support comparison with a single offset to allow binary searches.
186   friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
187                                               uint64_t RHSOffset) {
188     return LHS.beginOffset() < RHSOffset;
189   }
190   friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
191                                               const Slice &RHS) {
192     return LHSOffset < RHS.beginOffset();
193   }
194
195   bool operator==(const Slice &RHS) const {
196     return isSplittable() == RHS.isSplittable() &&
197            beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
198   }
199   bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
200 };
201 } // end anonymous namespace
202
203 namespace llvm {
204 template <typename T> struct isPodLike;
205 template <> struct isPodLike<Slice> { static const bool value = true; };
206 }
207
208 namespace {
209 /// \brief Representation of the alloca slices.
210 ///
211 /// This class represents the slices of an alloca which are formed by its
212 /// various uses. If a pointer escapes, we can't fully build a representation
213 /// for the slices used and we reflect that in this structure. The uses are
214 /// stored, sorted by increasing beginning offset and with unsplittable slices
215 /// starting at a particular offset before splittable slices.
216 class AllocaSlices {
217 public:
218   /// \brief Construct the slices of a particular alloca.
219   AllocaSlices(const DataLayout &DL, AllocaInst &AI);
220
221   /// \brief Test whether a pointer to the allocation escapes our analysis.
222   ///
223   /// If this is true, the slices are never fully built and should be
224   /// ignored.
225   bool isEscaped() const { return PointerEscapingInstr; }
226
227   /// \brief Support for iterating over the slices.
228   /// @{
229   typedef SmallVectorImpl<Slice>::iterator iterator;
230   typedef iterator_range<iterator> range;
231   iterator begin() { return Slices.begin(); }
232   iterator end() { return Slices.end(); }
233
234   typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
235   typedef iterator_range<const_iterator> const_range;
236   const_iterator begin() const { return Slices.begin(); }
237   const_iterator end() const { return Slices.end(); }
238   /// @}
239
240   /// \brief Access the dead users for this alloca.
241   ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
242
243   /// \brief Access the dead operands referring to this alloca.
244   ///
245   /// These are operands which have cannot actually be used to refer to the
246   /// alloca as they are outside its range and the user doesn't correct for
247   /// that. These mostly consist of PHI node inputs and the like which we just
248   /// need to replace with undef.
249   ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
250
251 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
252   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
253   void printSlice(raw_ostream &OS, const_iterator I,
254                   StringRef Indent = "  ") const;
255   void printUse(raw_ostream &OS, const_iterator I,
256                 StringRef Indent = "  ") const;
257   void print(raw_ostream &OS) const;
258   void dump(const_iterator I) const;
259   void dump() const;
260 #endif
261
262 private:
263   template <typename DerivedT, typename RetT = void> class BuilderBase;
264   class SliceBuilder;
265   friend class AllocaSlices::SliceBuilder;
266
267 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
268   /// \brief Handle to alloca instruction to simplify method interfaces.
269   AllocaInst &AI;
270 #endif
271
272   /// \brief The instruction responsible for this alloca not having a known set
273   /// of slices.
274   ///
275   /// When an instruction (potentially) escapes the pointer to the alloca, we
276   /// store a pointer to that here and abort trying to form slices of the
277   /// alloca. This will be null if the alloca slices are analyzed successfully.
278   Instruction *PointerEscapingInstr;
279
280   /// \brief The slices of the alloca.
281   ///
282   /// We store a vector of the slices formed by uses of the alloca here. This
283   /// vector is sorted by increasing begin offset, and then the unsplittable
284   /// slices before the splittable ones. See the Slice inner class for more
285   /// details.
286   SmallVector<Slice, 8> Slices;
287
288   /// \brief Instructions which will become dead if we rewrite the alloca.
289   ///
290   /// Note that these are not separated by slice. This is because we expect an
291   /// alloca to be completely rewritten or not rewritten at all. If rewritten,
292   /// all these instructions can simply be removed and replaced with undef as
293   /// they come from outside of the allocated space.
294   SmallVector<Instruction *, 8> DeadUsers;
295
296   /// \brief Operands which will become dead if we rewrite the alloca.
297   ///
298   /// These are operands that in their particular use can be replaced with
299   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
300   /// to PHI nodes and the like. They aren't entirely dead (there might be
301   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
302   /// want to swap this particular input for undef to simplify the use lists of
303   /// the alloca.
304   SmallVector<Use *, 8> DeadOperands;
305 };
306 }
307
308 static Value *foldSelectInst(SelectInst &SI) {
309   // If the condition being selected on is a constant or the same value is
310   // being selected between, fold the select. Yes this does (rarely) happen
311   // early on.
312   if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
313     return SI.getOperand(1 + CI->isZero());
314   if (SI.getOperand(1) == SI.getOperand(2))
315     return SI.getOperand(1);
316
317   return nullptr;
318 }
319
320 /// \brief A helper that folds a PHI node or a select.
321 static Value *foldPHINodeOrSelectInst(Instruction &I) {
322   if (PHINode *PN = dyn_cast<PHINode>(&I)) {
323     // If PN merges together the same value, return that value.
324     return PN->hasConstantValue();
325   }
326   return foldSelectInst(cast<SelectInst>(I));
327 }
328
329 /// \brief Builder for the alloca slices.
330 ///
331 /// This class builds a set of alloca slices by recursively visiting the uses
332 /// of an alloca and making a slice for each load and store at each offset.
333 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
334   friend class PtrUseVisitor<SliceBuilder>;
335   friend class InstVisitor<SliceBuilder>;
336   typedef PtrUseVisitor<SliceBuilder> Base;
337
338   const uint64_t AllocSize;
339   AllocaSlices &AS;
340
341   SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
342   SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
343
344   /// \brief Set to de-duplicate dead instructions found in the use walk.
345   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
346
347 public:
348   SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
349       : PtrUseVisitor<SliceBuilder>(DL),
350         AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
351
352 private:
353   void markAsDead(Instruction &I) {
354     if (VisitedDeadInsts.insert(&I).second)
355       AS.DeadUsers.push_back(&I);
356   }
357
358   void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
359                  bool IsSplittable = false) {
360     // Completely skip uses which have a zero size or start either before or
361     // past the end of the allocation.
362     if (Size == 0 || Offset.uge(AllocSize)) {
363       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
364                    << " which has zero size or starts outside of the "
365                    << AllocSize << " byte alloca:\n"
366                    << "    alloca: " << AS.AI << "\n"
367                    << "       use: " << I << "\n");
368       return markAsDead(I);
369     }
370
371     uint64_t BeginOffset = Offset.getZExtValue();
372     uint64_t EndOffset = BeginOffset + Size;
373
374     // Clamp the end offset to the end of the allocation. Note that this is
375     // formulated to handle even the case where "BeginOffset + Size" overflows.
376     // This may appear superficially to be something we could ignore entirely,
377     // but that is not so! There may be widened loads or PHI-node uses where
378     // some instructions are dead but not others. We can't completely ignore
379     // them, and so have to record at least the information here.
380     assert(AllocSize >= BeginOffset); // Established above.
381     if (Size > AllocSize - BeginOffset) {
382       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
383                    << " to remain within the " << AllocSize << " byte alloca:\n"
384                    << "    alloca: " << AS.AI << "\n"
385                    << "       use: " << I << "\n");
386       EndOffset = AllocSize;
387     }
388
389     AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
390   }
391
392   void visitBitCastInst(BitCastInst &BC) {
393     if (BC.use_empty())
394       return markAsDead(BC);
395
396     return Base::visitBitCastInst(BC);
397   }
398
399   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
400     if (GEPI.use_empty())
401       return markAsDead(GEPI);
402
403     if (SROAStrictInbounds && GEPI.isInBounds()) {
404       // FIXME: This is a manually un-factored variant of the basic code inside
405       // of GEPs with checking of the inbounds invariant specified in the
406       // langref in a very strict sense. If we ever want to enable
407       // SROAStrictInbounds, this code should be factored cleanly into
408       // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
409       // by writing out the code here where we have tho underlying allocation
410       // size readily available.
411       APInt GEPOffset = Offset;
412       for (gep_type_iterator GTI = gep_type_begin(GEPI),
413                              GTE = gep_type_end(GEPI);
414            GTI != GTE; ++GTI) {
415         ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
416         if (!OpC)
417           break;
418
419         // Handle a struct index, which adds its field offset to the pointer.
420         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
421           unsigned ElementIdx = OpC->getZExtValue();
422           const StructLayout *SL = DL.getStructLayout(STy);
423           GEPOffset +=
424               APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
425         } else {
426           // For array or vector indices, scale the index by the size of the
427           // type.
428           APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
429           GEPOffset += Index * APInt(Offset.getBitWidth(),
430                                      DL.getTypeAllocSize(GTI.getIndexedType()));
431         }
432
433         // If this index has computed an intermediate pointer which is not
434         // inbounds, then the result of the GEP is a poison value and we can
435         // delete it and all uses.
436         if (GEPOffset.ugt(AllocSize))
437           return markAsDead(GEPI);
438       }
439     }
440
441     return Base::visitGetElementPtrInst(GEPI);
442   }
443
444   void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
445                          uint64_t Size, bool IsVolatile) {
446     // We allow splitting of loads and stores where the type is an integer type
447     // and cover the entire alloca. This prevents us from splitting over
448     // eagerly.
449     // FIXME: In the great blue eventually, we should eagerly split all integer
450     // loads and stores, and then have a separate step that merges adjacent
451     // alloca partitions into a single partition suitable for integer widening.
452     // Or we should skip the merge step and rely on GVN and other passes to
453     // merge adjacent loads and stores that survive mem2reg.
454     bool IsSplittable =
455         Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
456
457     insertUse(I, Offset, Size, IsSplittable);
458   }
459
460   void visitLoadInst(LoadInst &LI) {
461     assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
462            "All simple FCA loads should have been pre-split");
463
464     if (!IsOffsetKnown)
465       return PI.setAborted(&LI);
466
467     uint64_t Size = DL.getTypeStoreSize(LI.getType());
468     return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
469   }
470
471   void visitStoreInst(StoreInst &SI) {
472     Value *ValOp = SI.getValueOperand();
473     if (ValOp == *U)
474       return PI.setEscapedAndAborted(&SI);
475     if (!IsOffsetKnown)
476       return PI.setAborted(&SI);
477
478     uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
479
480     // If this memory access can be shown to *statically* extend outside the
481     // bounds of of the allocation, it's behavior is undefined, so simply
482     // ignore it. Note that this is more strict than the generic clamping
483     // behavior of insertUse. We also try to handle cases which might run the
484     // risk of overflow.
485     // FIXME: We should instead consider the pointer to have escaped if this
486     // function is being instrumented for addressing bugs or race conditions.
487     if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
488       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
489                    << " which extends past the end of the " << AllocSize
490                    << " byte alloca:\n"
491                    << "    alloca: " << AS.AI << "\n"
492                    << "       use: " << SI << "\n");
493       return markAsDead(SI);
494     }
495
496     assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
497            "All simple FCA stores should have been pre-split");
498     handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
499   }
500
501   void visitMemSetInst(MemSetInst &II) {
502     assert(II.getRawDest() == *U && "Pointer use is not the destination?");
503     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
504     if ((Length && Length->getValue() == 0) ||
505         (IsOffsetKnown && Offset.uge(AllocSize)))
506       // Zero-length mem transfer intrinsics can be ignored entirely.
507       return markAsDead(II);
508
509     if (!IsOffsetKnown)
510       return PI.setAborted(&II);
511
512     insertUse(II, Offset, Length ? Length->getLimitedValue()
513                                  : AllocSize - Offset.getLimitedValue(),
514               (bool)Length);
515   }
516
517   void visitMemTransferInst(MemTransferInst &II) {
518     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
519     if (Length && Length->getValue() == 0)
520       // Zero-length mem transfer intrinsics can be ignored entirely.
521       return markAsDead(II);
522
523     // Because we can visit these intrinsics twice, also check to see if the
524     // first time marked this instruction as dead. If so, skip it.
525     if (VisitedDeadInsts.count(&II))
526       return;
527
528     if (!IsOffsetKnown)
529       return PI.setAborted(&II);
530
531     // This side of the transfer is completely out-of-bounds, and so we can
532     // nuke the entire transfer. However, we also need to nuke the other side
533     // if already added to our partitions.
534     // FIXME: Yet another place we really should bypass this when
535     // instrumenting for ASan.
536     if (Offset.uge(AllocSize)) {
537       SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
538           MemTransferSliceMap.find(&II);
539       if (MTPI != MemTransferSliceMap.end())
540         AS.Slices[MTPI->second].kill();
541       return markAsDead(II);
542     }
543
544     uint64_t RawOffset = Offset.getLimitedValue();
545     uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
546
547     // Check for the special case where the same exact value is used for both
548     // source and dest.
549     if (*U == II.getRawDest() && *U == II.getRawSource()) {
550       // For non-volatile transfers this is a no-op.
551       if (!II.isVolatile())
552         return markAsDead(II);
553
554       return insertUse(II, Offset, Size, /*IsSplittable=*/false);
555     }
556
557     // If we have seen both source and destination for a mem transfer, then
558     // they both point to the same alloca.
559     bool Inserted;
560     SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
561     std::tie(MTPI, Inserted) =
562         MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
563     unsigned PrevIdx = MTPI->second;
564     if (!Inserted) {
565       Slice &PrevP = AS.Slices[PrevIdx];
566
567       // Check if the begin offsets match and this is a non-volatile transfer.
568       // In that case, we can completely elide the transfer.
569       if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
570         PrevP.kill();
571         return markAsDead(II);
572       }
573
574       // Otherwise we have an offset transfer within the same alloca. We can't
575       // split those.
576       PrevP.makeUnsplittable();
577     }
578
579     // Insert the use now that we've fixed up the splittable nature.
580     insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
581
582     // Check that we ended up with a valid index in the map.
583     assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
584            "Map index doesn't point back to a slice with this user.");
585   }
586
587   // Disable SRoA for any intrinsics except for lifetime invariants.
588   // FIXME: What about debug intrinsics? This matches old behavior, but
589   // doesn't make sense.
590   void visitIntrinsicInst(IntrinsicInst &II) {
591     if (!IsOffsetKnown)
592       return PI.setAborted(&II);
593
594     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
595         II.getIntrinsicID() == Intrinsic::lifetime_end) {
596       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
597       uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
598                                Length->getLimitedValue());
599       insertUse(II, Offset, Size, true);
600       return;
601     }
602
603     Base::visitIntrinsicInst(II);
604   }
605
606   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
607     // We consider any PHI or select that results in a direct load or store of
608     // the same offset to be a viable use for slicing purposes. These uses
609     // are considered unsplittable and the size is the maximum loaded or stored
610     // size.
611     SmallPtrSet<Instruction *, 4> Visited;
612     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
613     Visited.insert(Root);
614     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
615     // If there are no loads or stores, the access is dead. We mark that as
616     // a size zero access.
617     Size = 0;
618     do {
619       Instruction *I, *UsedI;
620       std::tie(UsedI, I) = Uses.pop_back_val();
621
622       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
623         Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
624         continue;
625       }
626       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
627         Value *Op = SI->getOperand(0);
628         if (Op == UsedI)
629           return SI;
630         Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
631         continue;
632       }
633
634       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
635         if (!GEP->hasAllZeroIndices())
636           return GEP;
637       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
638                  !isa<SelectInst>(I)) {
639         return I;
640       }
641
642       for (User *U : I->users())
643         if (Visited.insert(cast<Instruction>(U)).second)
644           Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
645     } while (!Uses.empty());
646
647     return nullptr;
648   }
649
650   void visitPHINodeOrSelectInst(Instruction &I) {
651     assert(isa<PHINode>(I) || isa<SelectInst>(I));
652     if (I.use_empty())
653       return markAsDead(I);
654
655     // TODO: We could use SimplifyInstruction here to fold PHINodes and
656     // SelectInsts. However, doing so requires to change the current
657     // dead-operand-tracking mechanism. For instance, suppose neither loading
658     // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
659     // trap either.  However, if we simply replace %U with undef using the
660     // current dead-operand-tracking mechanism, "load (select undef, undef,
661     // %other)" may trap because the select may return the first operand
662     // "undef".
663     if (Value *Result = foldPHINodeOrSelectInst(I)) {
664       if (Result == *U)
665         // If the result of the constant fold will be the pointer, recurse
666         // through the PHI/select as if we had RAUW'ed it.
667         enqueueUsers(I);
668       else
669         // Otherwise the operand to the PHI/select is dead, and we can replace
670         // it with undef.
671         AS.DeadOperands.push_back(U);
672
673       return;
674     }
675
676     if (!IsOffsetKnown)
677       return PI.setAborted(&I);
678
679     // See if we already have computed info on this node.
680     uint64_t &Size = PHIOrSelectSizes[&I];
681     if (!Size) {
682       // This is a new PHI/Select, check for an unsafe use of it.
683       if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
684         return PI.setAborted(UnsafeI);
685     }
686
687     // For PHI and select operands outside the alloca, we can't nuke the entire
688     // phi or select -- the other side might still be relevant, so we special
689     // case them here and use a separate structure to track the operands
690     // themselves which should be replaced with undef.
691     // FIXME: This should instead be escaped in the event we're instrumenting
692     // for address sanitization.
693     if (Offset.uge(AllocSize)) {
694       AS.DeadOperands.push_back(U);
695       return;
696     }
697
698     insertUse(I, Offset, Size);
699   }
700
701   void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
702
703   void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
704
705   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
706   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
707 };
708
709 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
710     :
711 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
712       AI(AI),
713 #endif
714       PointerEscapingInstr(nullptr) {
715   SliceBuilder PB(DL, AI, *this);
716   SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
717   if (PtrI.isEscaped() || PtrI.isAborted()) {
718     // FIXME: We should sink the escape vs. abort info into the caller nicely,
719     // possibly by just storing the PtrInfo in the AllocaSlices.
720     PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
721                                                   : PtrI.getAbortingInst();
722     assert(PointerEscapingInstr && "Did not track a bad instruction");
723     return;
724   }
725
726   Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
727                               [](const Slice &S) {
728                                 return S.isDead();
729                               }),
730                Slices.end());
731
732 #if __cplusplus >= 201103L && !defined(NDEBUG)
733   if (SROARandomShuffleSlices) {
734     std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
735     std::shuffle(Slices.begin(), Slices.end(), MT);
736   }
737 #endif
738
739   // Sort the uses. This arranges for the offsets to be in ascending order,
740   // and the sizes to be in descending order.
741   std::sort(Slices.begin(), Slices.end());
742 }
743
744 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
745
746 void AllocaSlices::print(raw_ostream &OS, const_iterator I,
747                          StringRef Indent) const {
748   printSlice(OS, I, Indent);
749   printUse(OS, I, Indent);
750 }
751
752 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
753                               StringRef Indent) const {
754   OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
755      << " slice #" << (I - begin())
756      << (I->isSplittable() ? " (splittable)" : "") << "\n";
757 }
758
759 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
760                             StringRef Indent) const {
761   OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
762 }
763
764 void AllocaSlices::print(raw_ostream &OS) const {
765   if (PointerEscapingInstr) {
766     OS << "Can't analyze slices for alloca: " << AI << "\n"
767        << "  A pointer to this alloca escaped by:\n"
768        << "  " << *PointerEscapingInstr << "\n";
769     return;
770   }
771
772   OS << "Slices of alloca: " << AI << "\n";
773   for (const_iterator I = begin(), E = end(); I != E; ++I)
774     print(OS, I);
775 }
776
777 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
778   print(dbgs(), I);
779 }
780 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
781
782 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
783
784 namespace {
785 /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
786 ///
787 /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
788 /// the loads and stores of an alloca instruction, as well as updating its
789 /// debug information. This is used when a domtree is unavailable and thus
790 /// mem2reg in its full form can't be used to handle promotion of allocas to
791 /// scalar values.
792 class AllocaPromoter : public LoadAndStorePromoter {
793   AllocaInst &AI;
794   DIBuilder &DIB;
795
796   SmallVector<DbgDeclareInst *, 4> DDIs;
797   SmallVector<DbgValueInst *, 4> DVIs;
798
799 public:
800   AllocaPromoter(const SmallVectorImpl<Instruction *> &Insts, SSAUpdater &S,
801                  AllocaInst &AI, DIBuilder &DIB)
802       : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
803
804   void run(const SmallVectorImpl<Instruction *> &Insts) {
805     // Retain the debug information attached to the alloca for use when
806     // rewriting loads and stores.
807     if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
808       if (auto *DebugNode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
809         for (User *U : DebugNode->users())
810           if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
811             DDIs.push_back(DDI);
812           else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
813             DVIs.push_back(DVI);
814       }
815     }
816
817     LoadAndStorePromoter::run(Insts);
818
819     // While we have the debug information, clear it off of the alloca. The
820     // caller takes care of deleting the alloca.
821     while (!DDIs.empty())
822       DDIs.pop_back_val()->eraseFromParent();
823     while (!DVIs.empty())
824       DVIs.pop_back_val()->eraseFromParent();
825   }
826
827   bool
828   isInstInList(Instruction *I,
829                const SmallVectorImpl<Instruction *> &Insts) const override {
830     Value *Ptr;
831     if (LoadInst *LI = dyn_cast<LoadInst>(I))
832       Ptr = LI->getOperand(0);
833     else
834       Ptr = cast<StoreInst>(I)->getPointerOperand();
835
836     // Only used to detect cycles, which will be rare and quickly found as
837     // we're walking up a chain of defs rather than down through uses.
838     SmallPtrSet<Value *, 4> Visited;
839
840     do {
841       if (Ptr == &AI)
842         return true;
843
844       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
845         Ptr = BCI->getOperand(0);
846       else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
847         Ptr = GEPI->getPointerOperand();
848       else
849         return false;
850
851     } while (Visited.insert(Ptr).second);
852
853     return false;
854   }
855
856   void updateDebugInfo(Instruction *Inst) const override {
857     for (DbgDeclareInst *DDI : DDIs)
858       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
859         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
860       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
861         ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
862     for (DbgValueInst *DVI : DVIs) {
863       Value *Arg = nullptr;
864       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
865         // If an argument is zero extended then use argument directly. The ZExt
866         // may be zapped by an optimization pass in future.
867         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
868           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
869         else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
870           Arg = dyn_cast<Argument>(SExt->getOperand(0));
871         if (!Arg)
872           Arg = SI->getValueOperand();
873       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
874         Arg = LI->getPointerOperand();
875       } else {
876         continue;
877       }
878       Instruction *DbgVal =
879           DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
880                                       DIExpression(DVI->getExpression()), Inst);
881       DbgVal->setDebugLoc(DVI->getDebugLoc());
882     }
883   }
884 };
885 } // end anon namespace
886
887 namespace {
888 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
889 ///
890 /// This pass takes allocations which can be completely analyzed (that is, they
891 /// don't escape) and tries to turn them into scalar SSA values. There are
892 /// a few steps to this process.
893 ///
894 /// 1) It takes allocations of aggregates and analyzes the ways in which they
895 ///    are used to try to split them into smaller allocations, ideally of
896 ///    a single scalar data type. It will split up memcpy and memset accesses
897 ///    as necessary and try to isolate individual scalar accesses.
898 /// 2) It will transform accesses into forms which are suitable for SSA value
899 ///    promotion. This can be replacing a memset with a scalar store of an
900 ///    integer value, or it can involve speculating operations on a PHI or
901 ///    select to be a PHI or select of the results.
902 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
903 ///    onto insert and extract operations on a vector value, and convert them to
904 ///    this form. By doing so, it will enable promotion of vector aggregates to
905 ///    SSA vector values.
906 class SROA : public FunctionPass {
907   const bool RequiresDomTree;
908
909   LLVMContext *C;
910   const DataLayout *DL;
911   DominatorTree *DT;
912   AssumptionTracker *AT;
913
914   /// \brief Worklist of alloca instructions to simplify.
915   ///
916   /// Each alloca in the function is added to this. Each new alloca formed gets
917   /// added to it as well to recursively simplify unless that alloca can be
918   /// directly promoted. Finally, each time we rewrite a use of an alloca other
919   /// the one being actively rewritten, we add it back onto the list if not
920   /// already present to ensure it is re-visited.
921   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
922
923   /// \brief A collection of instructions to delete.
924   /// We try to batch deletions to simplify code and make things a bit more
925   /// efficient.
926   SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
927
928   /// \brief Post-promotion worklist.
929   ///
930   /// Sometimes we discover an alloca which has a high probability of becoming
931   /// viable for SROA after a round of promotion takes place. In those cases,
932   /// the alloca is enqueued here for re-processing.
933   ///
934   /// Note that we have to be very careful to clear allocas out of this list in
935   /// the event they are deleted.
936   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
937
938   /// \brief A collection of alloca instructions we can directly promote.
939   std::vector<AllocaInst *> PromotableAllocas;
940
941   /// \brief A worklist of PHIs to speculate prior to promoting allocas.
942   ///
943   /// All of these PHIs have been checked for the safety of speculation and by
944   /// being speculated will allow promoting allocas currently in the promotable
945   /// queue.
946   SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
947
948   /// \brief A worklist of select instructions to speculate prior to promoting
949   /// allocas.
950   ///
951   /// All of these select instructions have been checked for the safety of
952   /// speculation and by being speculated will allow promoting allocas
953   /// currently in the promotable queue.
954   SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
955
956 public:
957   SROA(bool RequiresDomTree = true)
958       : FunctionPass(ID), RequiresDomTree(RequiresDomTree), C(nullptr),
959         DL(nullptr), DT(nullptr) {
960     initializeSROAPass(*PassRegistry::getPassRegistry());
961   }
962   bool runOnFunction(Function &F) override;
963   void getAnalysisUsage(AnalysisUsage &AU) const override;
964
965   const char *getPassName() const override { return "SROA"; }
966   static char ID;
967
968 private:
969   friend class PHIOrSelectSpeculator;
970   friend class AllocaSliceRewriter;
971
972   bool rewritePartition(AllocaInst &AI, AllocaSlices &AS,
973                         AllocaSlices::iterator B, AllocaSlices::iterator E,
974                         int64_t BeginOffset, int64_t EndOffset,
975                         ArrayRef<AllocaSlices::iterator> SplitUses);
976   bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
977   bool runOnAlloca(AllocaInst &AI);
978   void clobberUse(Use &U);
979   void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
980   bool promoteAllocas(Function &F);
981 };
982 }
983
984 char SROA::ID = 0;
985
986 FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
987   return new SROA(RequiresDomTree);
988 }
989
990 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
991                       false)
992 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
993 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
994 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
995                     false)
996
997 /// Walk the range of a partitioning looking for a common type to cover this
998 /// sequence of slices.
999 static Type *findCommonType(AllocaSlices::const_iterator B,
1000                             AllocaSlices::const_iterator E,
1001                             uint64_t EndOffset) {
1002   Type *Ty = nullptr;
1003   bool TyIsCommon = true;
1004   IntegerType *ITy = nullptr;
1005
1006   // Note that we need to look at *every* alloca slice's Use to ensure we
1007   // always get consistent results regardless of the order of slices.
1008   for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1009     Use *U = I->getUse();
1010     if (isa<IntrinsicInst>(*U->getUser()))
1011       continue;
1012     if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1013       continue;
1014
1015     Type *UserTy = nullptr;
1016     if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1017       UserTy = LI->getType();
1018     } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1019       UserTy = SI->getValueOperand()->getType();
1020     }
1021
1022     if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1023       // If the type is larger than the partition, skip it. We only encounter
1024       // this for split integer operations where we want to use the type of the
1025       // entity causing the split. Also skip if the type is not a byte width
1026       // multiple.
1027       if (UserITy->getBitWidth() % 8 != 0 ||
1028           UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1029         continue;
1030
1031       // Track the largest bitwidth integer type used in this way in case there
1032       // is no common type.
1033       if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1034         ITy = UserITy;
1035     }
1036
1037     // To avoid depending on the order of slices, Ty and TyIsCommon must not
1038     // depend on types skipped above.
1039     if (!UserTy || (Ty && Ty != UserTy))
1040       TyIsCommon = false; // Give up on anything but an iN type.
1041     else
1042       Ty = UserTy;
1043   }
1044
1045   return TyIsCommon ? Ty : ITy;
1046 }
1047
1048 /// PHI instructions that use an alloca and are subsequently loaded can be
1049 /// rewritten to load both input pointers in the pred blocks and then PHI the
1050 /// results, allowing the load of the alloca to be promoted.
1051 /// From this:
1052 ///   %P2 = phi [i32* %Alloca, i32* %Other]
1053 ///   %V = load i32* %P2
1054 /// to:
1055 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1056 ///   ...
1057 ///   %V2 = load i32* %Other
1058 ///   ...
1059 ///   %V = phi [i32 %V1, i32 %V2]
1060 ///
1061 /// We can do this to a select if its only uses are loads and if the operands
1062 /// to the select can be loaded unconditionally.
1063 ///
1064 /// FIXME: This should be hoisted into a generic utility, likely in
1065 /// Transforms/Util/Local.h
1066 static bool isSafePHIToSpeculate(PHINode &PN, const DataLayout *DL = nullptr) {
1067   // For now, we can only do this promotion if the load is in the same block
1068   // as the PHI, and if there are no stores between the phi and load.
1069   // TODO: Allow recursive phi users.
1070   // TODO: Allow stores.
1071   BasicBlock *BB = PN.getParent();
1072   unsigned MaxAlign = 0;
1073   bool HaveLoad = false;
1074   for (User *U : PN.users()) {
1075     LoadInst *LI = dyn_cast<LoadInst>(U);
1076     if (!LI || !LI->isSimple())
1077       return false;
1078
1079     // For now we only allow loads in the same block as the PHI.  This is
1080     // a common case that happens when instcombine merges two loads through
1081     // a PHI.
1082     if (LI->getParent() != BB)
1083       return false;
1084
1085     // Ensure that there are no instructions between the PHI and the load that
1086     // could store.
1087     for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1088       if (BBI->mayWriteToMemory())
1089         return false;
1090
1091     MaxAlign = std::max(MaxAlign, LI->getAlignment());
1092     HaveLoad = true;
1093   }
1094
1095   if (!HaveLoad)
1096     return false;
1097
1098   // We can only transform this if it is safe to push the loads into the
1099   // predecessor blocks. The only thing to watch out for is that we can't put
1100   // a possibly trapping load in the predecessor if it is a critical edge.
1101   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1102     TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1103     Value *InVal = PN.getIncomingValue(Idx);
1104
1105     // If the value is produced by the terminator of the predecessor (an
1106     // invoke) or it has side-effects, there is no valid place to put a load
1107     // in the predecessor.
1108     if (TI == InVal || TI->mayHaveSideEffects())
1109       return false;
1110
1111     // If the predecessor has a single successor, then the edge isn't
1112     // critical.
1113     if (TI->getNumSuccessors() == 1)
1114       continue;
1115
1116     // If this pointer is always safe to load, or if we can prove that there
1117     // is already a load in the block, then we can move the load to the pred
1118     // block.
1119     if (InVal->isDereferenceablePointer(DL) ||
1120         isSafeToLoadUnconditionally(InVal, TI, MaxAlign, DL))
1121       continue;
1122
1123     return false;
1124   }
1125
1126   return true;
1127 }
1128
1129 static void speculatePHINodeLoads(PHINode &PN) {
1130   DEBUG(dbgs() << "    original: " << PN << "\n");
1131
1132   Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1133   IRBuilderTy PHIBuilder(&PN);
1134   PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1135                                         PN.getName() + ".sroa.speculated");
1136
1137   // Get the AA tags and alignment to use from one of the loads.  It doesn't
1138   // matter which one we get and if any differ.
1139   LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1140
1141   AAMDNodes AATags;
1142   SomeLoad->getAAMetadata(AATags);
1143   unsigned Align = SomeLoad->getAlignment();
1144
1145   // Rewrite all loads of the PN to use the new PHI.
1146   while (!PN.use_empty()) {
1147     LoadInst *LI = cast<LoadInst>(PN.user_back());
1148     LI->replaceAllUsesWith(NewPN);
1149     LI->eraseFromParent();
1150   }
1151
1152   // Inject loads into all of the pred blocks.
1153   for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1154     BasicBlock *Pred = PN.getIncomingBlock(Idx);
1155     TerminatorInst *TI = Pred->getTerminator();
1156     Value *InVal = PN.getIncomingValue(Idx);
1157     IRBuilderTy PredBuilder(TI);
1158
1159     LoadInst *Load = PredBuilder.CreateLoad(
1160         InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1161     ++NumLoadsSpeculated;
1162     Load->setAlignment(Align);
1163     if (AATags)
1164       Load->setAAMetadata(AATags);
1165     NewPN->addIncoming(Load, Pred);
1166   }
1167
1168   DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
1169   PN.eraseFromParent();
1170 }
1171
1172 /// Select instructions that use an alloca and are subsequently loaded can be
1173 /// rewritten to load both input pointers and then select between the result,
1174 /// allowing the load of the alloca to be promoted.
1175 /// From this:
1176 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1177 ///   %V = load i32* %P2
1178 /// to:
1179 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1180 ///   %V2 = load i32* %Other
1181 ///   %V = select i1 %cond, i32 %V1, i32 %V2
1182 ///
1183 /// We can do this to a select if its only uses are loads and if the operand
1184 /// to the select can be loaded unconditionally.
1185 static bool isSafeSelectToSpeculate(SelectInst &SI,
1186                                     const DataLayout *DL = nullptr) {
1187   Value *TValue = SI.getTrueValue();
1188   Value *FValue = SI.getFalseValue();
1189   bool TDerefable = TValue->isDereferenceablePointer(DL);
1190   bool FDerefable = FValue->isDereferenceablePointer(DL);
1191
1192   for (User *U : SI.users()) {
1193     LoadInst *LI = dyn_cast<LoadInst>(U);
1194     if (!LI || !LI->isSimple())
1195       return false;
1196
1197     // Both operands to the select need to be dereferencable, either
1198     // absolutely (e.g. allocas) or at this point because we can see other
1199     // accesses to it.
1200     if (!TDerefable &&
1201         !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment(), DL))
1202       return false;
1203     if (!FDerefable &&
1204         !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment(), DL))
1205       return false;
1206   }
1207
1208   return true;
1209 }
1210
1211 static void speculateSelectInstLoads(SelectInst &SI) {
1212   DEBUG(dbgs() << "    original: " << SI << "\n");
1213
1214   IRBuilderTy IRB(&SI);
1215   Value *TV = SI.getTrueValue();
1216   Value *FV = SI.getFalseValue();
1217   // Replace the loads of the select with a select of two loads.
1218   while (!SI.use_empty()) {
1219     LoadInst *LI = cast<LoadInst>(SI.user_back());
1220     assert(LI->isSimple() && "We only speculate simple loads");
1221
1222     IRB.SetInsertPoint(LI);
1223     LoadInst *TL =
1224         IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1225     LoadInst *FL =
1226         IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1227     NumLoadsSpeculated += 2;
1228
1229     // Transfer alignment and AA info if present.
1230     TL->setAlignment(LI->getAlignment());
1231     FL->setAlignment(LI->getAlignment());
1232
1233     AAMDNodes Tags;
1234     LI->getAAMetadata(Tags);
1235     if (Tags) {
1236       TL->setAAMetadata(Tags);
1237       FL->setAAMetadata(Tags);
1238     }
1239
1240     Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1241                                 LI->getName() + ".sroa.speculated");
1242
1243     DEBUG(dbgs() << "          speculated to: " << *V << "\n");
1244     LI->replaceAllUsesWith(V);
1245     LI->eraseFromParent();
1246   }
1247   SI.eraseFromParent();
1248 }
1249
1250 /// \brief Build a GEP out of a base pointer and indices.
1251 ///
1252 /// This will return the BasePtr if that is valid, or build a new GEP
1253 /// instruction using the IRBuilder if GEP-ing is needed.
1254 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1255                        SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1256   if (Indices.empty())
1257     return BasePtr;
1258
1259   // A single zero index is a no-op, so check for this and avoid building a GEP
1260   // in that case.
1261   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1262     return BasePtr;
1263
1264   return IRB.CreateInBoundsGEP(BasePtr, Indices, NamePrefix + "sroa_idx");
1265 }
1266
1267 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1268 /// TargetTy without changing the offset of the pointer.
1269 ///
1270 /// This routine assumes we've already established a properly offset GEP with
1271 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1272 /// zero-indices down through type layers until we find one the same as
1273 /// TargetTy. If we can't find one with the same type, we at least try to use
1274 /// one with the same size. If none of that works, we just produce the GEP as
1275 /// indicated by Indices to have the correct offset.
1276 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1277                                     Value *BasePtr, Type *Ty, Type *TargetTy,
1278                                     SmallVectorImpl<Value *> &Indices,
1279                                     Twine NamePrefix) {
1280   if (Ty == TargetTy)
1281     return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1282
1283   // Pointer size to use for the indices.
1284   unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1285
1286   // See if we can descend into a struct and locate a field with the correct
1287   // type.
1288   unsigned NumLayers = 0;
1289   Type *ElementTy = Ty;
1290   do {
1291     if (ElementTy->isPointerTy())
1292       break;
1293
1294     if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1295       ElementTy = ArrayTy->getElementType();
1296       Indices.push_back(IRB.getIntN(PtrSize, 0));
1297     } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1298       ElementTy = VectorTy->getElementType();
1299       Indices.push_back(IRB.getInt32(0));
1300     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1301       if (STy->element_begin() == STy->element_end())
1302         break; // Nothing left to descend into.
1303       ElementTy = *STy->element_begin();
1304       Indices.push_back(IRB.getInt32(0));
1305     } else {
1306       break;
1307     }
1308     ++NumLayers;
1309   } while (ElementTy != TargetTy);
1310   if (ElementTy != TargetTy)
1311     Indices.erase(Indices.end() - NumLayers, Indices.end());
1312
1313   return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1314 }
1315
1316 /// \brief Recursively compute indices for a natural GEP.
1317 ///
1318 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1319 /// element types adding appropriate indices for the GEP.
1320 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1321                                        Value *Ptr, Type *Ty, APInt &Offset,
1322                                        Type *TargetTy,
1323                                        SmallVectorImpl<Value *> &Indices,
1324                                        Twine NamePrefix) {
1325   if (Offset == 0)
1326     return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1327                                  NamePrefix);
1328
1329   // We can't recurse through pointer types.
1330   if (Ty->isPointerTy())
1331     return nullptr;
1332
1333   // We try to analyze GEPs over vectors here, but note that these GEPs are
1334   // extremely poorly defined currently. The long-term goal is to remove GEPing
1335   // over a vector from the IR completely.
1336   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1337     unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1338     if (ElementSizeInBits % 8 != 0) {
1339       // GEPs over non-multiple of 8 size vector elements are invalid.
1340       return nullptr;
1341     }
1342     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1343     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1344     if (NumSkippedElements.ugt(VecTy->getNumElements()))
1345       return nullptr;
1346     Offset -= NumSkippedElements * ElementSize;
1347     Indices.push_back(IRB.getInt(NumSkippedElements));
1348     return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1349                                     Offset, TargetTy, Indices, NamePrefix);
1350   }
1351
1352   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1353     Type *ElementTy = ArrTy->getElementType();
1354     APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1355     APInt NumSkippedElements = Offset.sdiv(ElementSize);
1356     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1357       return nullptr;
1358
1359     Offset -= NumSkippedElements * ElementSize;
1360     Indices.push_back(IRB.getInt(NumSkippedElements));
1361     return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1362                                     Indices, NamePrefix);
1363   }
1364
1365   StructType *STy = dyn_cast<StructType>(Ty);
1366   if (!STy)
1367     return nullptr;
1368
1369   const StructLayout *SL = DL.getStructLayout(STy);
1370   uint64_t StructOffset = Offset.getZExtValue();
1371   if (StructOffset >= SL->getSizeInBytes())
1372     return nullptr;
1373   unsigned Index = SL->getElementContainingOffset(StructOffset);
1374   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1375   Type *ElementTy = STy->getElementType(Index);
1376   if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1377     return nullptr; // The offset points into alignment padding.
1378
1379   Indices.push_back(IRB.getInt32(Index));
1380   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1381                                   Indices, NamePrefix);
1382 }
1383
1384 /// \brief Get a natural GEP from a base pointer to a particular offset and
1385 /// resulting in a particular type.
1386 ///
1387 /// The goal is to produce a "natural" looking GEP that works with the existing
1388 /// composite types to arrive at the appropriate offset and element type for
1389 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1390 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1391 /// Indices, and setting Ty to the result subtype.
1392 ///
1393 /// If no natural GEP can be constructed, this function returns null.
1394 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1395                                       Value *Ptr, APInt Offset, Type *TargetTy,
1396                                       SmallVectorImpl<Value *> &Indices,
1397                                       Twine NamePrefix) {
1398   PointerType *Ty = cast<PointerType>(Ptr->getType());
1399
1400   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1401   // an i8.
1402   if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1403     return nullptr;
1404
1405   Type *ElementTy = Ty->getElementType();
1406   if (!ElementTy->isSized())
1407     return nullptr; // We can't GEP through an unsized element.
1408   APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1409   if (ElementSize == 0)
1410     return nullptr; // Zero-length arrays can't help us build a natural GEP.
1411   APInt NumSkippedElements = Offset.sdiv(ElementSize);
1412
1413   Offset -= NumSkippedElements * ElementSize;
1414   Indices.push_back(IRB.getInt(NumSkippedElements));
1415   return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1416                                   Indices, NamePrefix);
1417 }
1418
1419 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1420 /// resulting pointer has PointerTy.
1421 ///
1422 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1423 /// and produces the pointer type desired. Where it cannot, it will try to use
1424 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1425 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1426 /// bitcast to the type.
1427 ///
1428 /// The strategy for finding the more natural GEPs is to peel off layers of the
1429 /// pointer, walking back through bit casts and GEPs, searching for a base
1430 /// pointer from which we can compute a natural GEP with the desired
1431 /// properties. The algorithm tries to fold as many constant indices into
1432 /// a single GEP as possible, thus making each GEP more independent of the
1433 /// surrounding code.
1434 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1435                              APInt Offset, Type *PointerTy, Twine NamePrefix) {
1436   // Even though we don't look through PHI nodes, we could be called on an
1437   // instruction in an unreachable block, which may be on a cycle.
1438   SmallPtrSet<Value *, 4> Visited;
1439   Visited.insert(Ptr);
1440   SmallVector<Value *, 4> Indices;
1441
1442   // We may end up computing an offset pointer that has the wrong type. If we
1443   // never are able to compute one directly that has the correct type, we'll
1444   // fall back to it, so keep it around here.
1445   Value *OffsetPtr = nullptr;
1446
1447   // Remember any i8 pointer we come across to re-use if we need to do a raw
1448   // byte offset.
1449   Value *Int8Ptr = nullptr;
1450   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1451
1452   Type *TargetTy = PointerTy->getPointerElementType();
1453
1454   do {
1455     // First fold any existing GEPs into the offset.
1456     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1457       APInt GEPOffset(Offset.getBitWidth(), 0);
1458       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1459         break;
1460       Offset += GEPOffset;
1461       Ptr = GEP->getPointerOperand();
1462       if (!Visited.insert(Ptr).second)
1463         break;
1464     }
1465
1466     // See if we can perform a natural GEP here.
1467     Indices.clear();
1468     if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1469                                            Indices, NamePrefix)) {
1470       if (P->getType() == PointerTy) {
1471         // Zap any offset pointer that we ended up computing in previous rounds.
1472         if (OffsetPtr && OffsetPtr->use_empty())
1473           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1474             I->eraseFromParent();
1475         return P;
1476       }
1477       if (!OffsetPtr) {
1478         OffsetPtr = P;
1479       }
1480     }
1481
1482     // Stash this pointer if we've found an i8*.
1483     if (Ptr->getType()->isIntegerTy(8)) {
1484       Int8Ptr = Ptr;
1485       Int8PtrOffset = Offset;
1486     }
1487
1488     // Peel off a layer of the pointer and update the offset appropriately.
1489     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1490       Ptr = cast<Operator>(Ptr)->getOperand(0);
1491     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1492       if (GA->mayBeOverridden())
1493         break;
1494       Ptr = GA->getAliasee();
1495     } else {
1496       break;
1497     }
1498     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1499   } while (Visited.insert(Ptr).second);
1500
1501   if (!OffsetPtr) {
1502     if (!Int8Ptr) {
1503       Int8Ptr = IRB.CreateBitCast(
1504           Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1505           NamePrefix + "sroa_raw_cast");
1506       Int8PtrOffset = Offset;
1507     }
1508
1509     OffsetPtr = Int8PtrOffset == 0
1510                     ? Int8Ptr
1511                     : IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1512                                             NamePrefix + "sroa_raw_idx");
1513   }
1514   Ptr = OffsetPtr;
1515
1516   // On the off chance we were targeting i8*, guard the bitcast here.
1517   if (Ptr->getType() != PointerTy)
1518     Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1519
1520   return Ptr;
1521 }
1522
1523 /// \brief Test whether we can convert a value from the old to the new type.
1524 ///
1525 /// This predicate should be used to guard calls to convertValue in order to
1526 /// ensure that we only try to convert viable values. The strategy is that we
1527 /// will peel off single element struct and array wrappings to get to an
1528 /// underlying value, and convert that value.
1529 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1530   if (OldTy == NewTy)
1531     return true;
1532   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1533     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1534       if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1535         return true;
1536   if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1537     return false;
1538   if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1539     return false;
1540
1541   // We can convert pointers to integers and vice-versa. Same for vectors
1542   // of pointers and integers.
1543   OldTy = OldTy->getScalarType();
1544   NewTy = NewTy->getScalarType();
1545   if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1546     if (NewTy->isPointerTy() && OldTy->isPointerTy())
1547       return true;
1548     if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1549       return true;
1550     return false;
1551   }
1552
1553   return true;
1554 }
1555
1556 /// \brief Generic routine to convert an SSA value to a value of a different
1557 /// type.
1558 ///
1559 /// This will try various different casting techniques, such as bitcasts,
1560 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1561 /// two types for viability with this routine.
1562 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1563                            Type *NewTy) {
1564   Type *OldTy = V->getType();
1565   assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1566
1567   if (OldTy == NewTy)
1568     return V;
1569
1570   if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1571     if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1572       if (NewITy->getBitWidth() > OldITy->getBitWidth())
1573         return IRB.CreateZExt(V, NewITy);
1574
1575   // See if we need inttoptr for this type pair. A cast involving both scalars
1576   // and vectors requires and additional bitcast.
1577   if (OldTy->getScalarType()->isIntegerTy() &&
1578       NewTy->getScalarType()->isPointerTy()) {
1579     // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1580     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1581       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1582                                 NewTy);
1583
1584     // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1585     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1586       return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1587                                 NewTy);
1588
1589     return IRB.CreateIntToPtr(V, NewTy);
1590   }
1591
1592   // See if we need ptrtoint for this type pair. A cast involving both scalars
1593   // and vectors requires and additional bitcast.
1594   if (OldTy->getScalarType()->isPointerTy() &&
1595       NewTy->getScalarType()->isIntegerTy()) {
1596     // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1597     if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1598       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1599                                NewTy);
1600
1601     // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1602     if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1603       return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1604                                NewTy);
1605
1606     return IRB.CreatePtrToInt(V, NewTy);
1607   }
1608
1609   return IRB.CreateBitCast(V, NewTy);
1610 }
1611
1612 /// \brief Test whether the given slice use can be promoted to a vector.
1613 ///
1614 /// This function is called to test each entry in a partioning which is slated
1615 /// for a single slice.
1616 static bool
1617 isVectorPromotionViableForSlice(const DataLayout &DL, uint64_t SliceBeginOffset,
1618                                 uint64_t SliceEndOffset, VectorType *Ty,
1619                                 uint64_t ElementSize, const Slice &S) {
1620   // First validate the slice offsets.
1621   uint64_t BeginOffset =
1622       std::max(S.beginOffset(), SliceBeginOffset) - SliceBeginOffset;
1623   uint64_t BeginIndex = BeginOffset / ElementSize;
1624   if (BeginIndex * ElementSize != BeginOffset ||
1625       BeginIndex >= Ty->getNumElements())
1626     return false;
1627   uint64_t EndOffset =
1628       std::min(S.endOffset(), SliceEndOffset) - SliceBeginOffset;
1629   uint64_t EndIndex = EndOffset / ElementSize;
1630   if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1631     return false;
1632
1633   assert(EndIndex > BeginIndex && "Empty vector!");
1634   uint64_t NumElements = EndIndex - BeginIndex;
1635   Type *SliceTy = (NumElements == 1)
1636                       ? Ty->getElementType()
1637                       : VectorType::get(Ty->getElementType(), NumElements);
1638
1639   Type *SplitIntTy =
1640       Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1641
1642   Use *U = S.getUse();
1643
1644   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1645     if (MI->isVolatile())
1646       return false;
1647     if (!S.isSplittable())
1648       return false; // Skip any unsplittable intrinsics.
1649   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1650     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1651         II->getIntrinsicID() != Intrinsic::lifetime_end)
1652       return false;
1653   } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1654     // Disable vector promotion when there are loads or stores of an FCA.
1655     return false;
1656   } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1657     if (LI->isVolatile())
1658       return false;
1659     Type *LTy = LI->getType();
1660     if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
1661       assert(LTy->isIntegerTy());
1662       LTy = SplitIntTy;
1663     }
1664     if (!canConvertValue(DL, SliceTy, LTy))
1665       return false;
1666   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1667     if (SI->isVolatile())
1668       return false;
1669     Type *STy = SI->getValueOperand()->getType();
1670     if (SliceBeginOffset > S.beginOffset() || SliceEndOffset < S.endOffset()) {
1671       assert(STy->isIntegerTy());
1672       STy = SplitIntTy;
1673     }
1674     if (!canConvertValue(DL, STy, SliceTy))
1675       return false;
1676   } else {
1677     return false;
1678   }
1679
1680   return true;
1681 }
1682
1683 /// \brief Test whether the given alloca partitioning and range of slices can be
1684 /// promoted to a vector.
1685 ///
1686 /// This is a quick test to check whether we can rewrite a particular alloca
1687 /// partition (and its newly formed alloca) into a vector alloca with only
1688 /// whole-vector loads and stores such that it could be promoted to a vector
1689 /// SSA value. We only can ensure this for a limited set of operations, and we
1690 /// don't want to do the rewrites unless we are confident that the result will
1691 /// be promotable, so we have an early test here.
1692 static VectorType *
1693 isVectorPromotionViable(const DataLayout &DL, uint64_t SliceBeginOffset,
1694                         uint64_t SliceEndOffset,
1695                         AllocaSlices::const_range Slices,
1696                         ArrayRef<AllocaSlices::iterator> SplitUses) {
1697   // Collect the candidate types for vector-based promotion. Also track whether
1698   // we have different element types.
1699   SmallVector<VectorType *, 4> CandidateTys;
1700   Type *CommonEltTy = nullptr;
1701   bool HaveCommonEltTy = true;
1702   auto CheckCandidateType = [&](Type *Ty) {
1703     if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1704       CandidateTys.push_back(VTy);
1705       if (!CommonEltTy)
1706         CommonEltTy = VTy->getElementType();
1707       else if (CommonEltTy != VTy->getElementType())
1708         HaveCommonEltTy = false;
1709     }
1710   };
1711   // Consider any loads or stores that are the exact size of the slice.
1712   for (const auto &S : Slices)
1713     if (S.beginOffset() == SliceBeginOffset &&
1714         S.endOffset() == SliceEndOffset) {
1715       if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1716         CheckCandidateType(LI->getType());
1717       else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1718         CheckCandidateType(SI->getValueOperand()->getType());
1719     }
1720
1721   // If we didn't find a vector type, nothing to do here.
1722   if (CandidateTys.empty())
1723     return nullptr;
1724
1725   // Remove non-integer vector types if we had multiple common element types.
1726   // FIXME: It'd be nice to replace them with integer vector types, but we can't
1727   // do that until all the backends are known to produce good code for all
1728   // integer vector types.
1729   if (!HaveCommonEltTy) {
1730     CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
1731                                       [](VectorType *VTy) {
1732                          return !VTy->getElementType()->isIntegerTy();
1733                        }),
1734                        CandidateTys.end());
1735
1736     // If there were no integer vector types, give up.
1737     if (CandidateTys.empty())
1738       return nullptr;
1739
1740     // Rank the remaining candidate vector types. This is easy because we know
1741     // they're all integer vectors. We sort by ascending number of elements.
1742     auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1743       assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1744              "Cannot have vector types of different sizes!");
1745       assert(RHSTy->getElementType()->isIntegerTy() &&
1746              "All non-integer types eliminated!");
1747       assert(LHSTy->getElementType()->isIntegerTy() &&
1748              "All non-integer types eliminated!");
1749       return RHSTy->getNumElements() < LHSTy->getNumElements();
1750     };
1751     std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1752     CandidateTys.erase(
1753         std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1754         CandidateTys.end());
1755   } else {
1756 // The only way to have the same element type in every vector type is to
1757 // have the same vector type. Check that and remove all but one.
1758 #ifndef NDEBUG
1759     for (VectorType *VTy : CandidateTys) {
1760       assert(VTy->getElementType() == CommonEltTy &&
1761              "Unaccounted for element type!");
1762       assert(VTy == CandidateTys[0] &&
1763              "Different vector types with the same element type!");
1764     }
1765 #endif
1766     CandidateTys.resize(1);
1767   }
1768
1769   // Try each vector type, and return the one which works.
1770   auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1771     uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1772
1773     // While the definition of LLVM vectors is bitpacked, we don't support sizes
1774     // that aren't byte sized.
1775     if (ElementSize % 8)
1776       return false;
1777     assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1778            "vector size not a multiple of element size?");
1779     ElementSize /= 8;
1780
1781     for (const auto &S : Slices)
1782       if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1783                                            VTy, ElementSize, S))
1784         return false;
1785
1786     for (const auto &SI : SplitUses)
1787       if (!isVectorPromotionViableForSlice(DL, SliceBeginOffset, SliceEndOffset,
1788                                            VTy, ElementSize, *SI))
1789         return false;
1790
1791     return true;
1792   };
1793   for (VectorType *VTy : CandidateTys)
1794     if (CheckVectorTypeForPromotion(VTy))
1795       return VTy;
1796
1797   return nullptr;
1798 }
1799
1800 /// \brief Test whether a slice of an alloca is valid for integer widening.
1801 ///
1802 /// This implements the necessary checking for the \c isIntegerWideningViable
1803 /// test below on a single slice of the alloca.
1804 static bool isIntegerWideningViableForSlice(const DataLayout &DL,
1805                                             Type *AllocaTy,
1806                                             uint64_t AllocBeginOffset,
1807                                             uint64_t Size, const Slice &S,
1808                                             bool &WholeAllocaOp) {
1809   uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1810   uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1811
1812   // We can't reasonably handle cases where the load or store extends past
1813   // the end of the aloca's type and into its padding.
1814   if (RelEnd > Size)
1815     return false;
1816
1817   Use *U = S.getUse();
1818
1819   if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1820     if (LI->isVolatile())
1821       return false;
1822     // Note that we don't count vector loads or stores as whole-alloca
1823     // operations which enable integer widening because we would prefer to use
1824     // vector widening instead.
1825     if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
1826       WholeAllocaOp = true;
1827     if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1828       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1829         return false;
1830     } else if (RelBegin != 0 || RelEnd != Size ||
1831                !canConvertValue(DL, AllocaTy, LI->getType())) {
1832       // Non-integer loads need to be convertible from the alloca type so that
1833       // they are promotable.
1834       return false;
1835     }
1836   } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1837     Type *ValueTy = SI->getValueOperand()->getType();
1838     if (SI->isVolatile())
1839       return false;
1840     // Note that we don't count vector loads or stores as whole-alloca
1841     // operations which enable integer widening because we would prefer to use
1842     // vector widening instead.
1843     if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
1844       WholeAllocaOp = true;
1845     if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1846       if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1847         return false;
1848     } else if (RelBegin != 0 || RelEnd != Size ||
1849                !canConvertValue(DL, ValueTy, AllocaTy)) {
1850       // Non-integer stores need to be convertible to the alloca type so that
1851       // they are promotable.
1852       return false;
1853     }
1854   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1855     if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
1856       return false;
1857     if (!S.isSplittable())
1858       return false; // Skip any unsplittable intrinsics.
1859   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1860     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1861         II->getIntrinsicID() != Intrinsic::lifetime_end)
1862       return false;
1863   } else {
1864     return false;
1865   }
1866
1867   return true;
1868 }
1869
1870 /// \brief Test whether the given alloca partition's integer operations can be
1871 /// widened to promotable ones.
1872 ///
1873 /// This is a quick test to check whether we can rewrite the integer loads and
1874 /// stores to a particular alloca into wider loads and stores and be able to
1875 /// promote the resulting alloca.
1876 static bool
1877 isIntegerWideningViable(const DataLayout &DL, Type *AllocaTy,
1878                         uint64_t AllocBeginOffset,
1879                         AllocaSlices::const_range Slices,
1880                         ArrayRef<AllocaSlices::iterator> SplitUses) {
1881   uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
1882   // Don't create integer types larger than the maximum bitwidth.
1883   if (SizeInBits > IntegerType::MAX_INT_BITS)
1884     return false;
1885
1886   // Don't try to handle allocas with bit-padding.
1887   if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
1888     return false;
1889
1890   // We need to ensure that an integer type with the appropriate bitwidth can
1891   // be converted to the alloca type, whatever that is. We don't want to force
1892   // the alloca itself to have an integer type if there is a more suitable one.
1893   Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
1894   if (!canConvertValue(DL, AllocaTy, IntTy) ||
1895       !canConvertValue(DL, IntTy, AllocaTy))
1896     return false;
1897
1898   uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1899
1900   // While examining uses, we ensure that the alloca has a covering load or
1901   // store. We don't want to widen the integer operations only to fail to
1902   // promote due to some other unsplittable entry (which we may make splittable
1903   // later). However, if there are only splittable uses, go ahead and assume
1904   // that we cover the alloca.
1905   bool WholeAllocaOp =
1906       Slices.begin() != Slices.end() ? false : DL.isLegalInteger(SizeInBits);
1907
1908   for (const auto &S : Slices)
1909     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1910                                          S, WholeAllocaOp))
1911       return false;
1912
1913   for (const auto &SI : SplitUses)
1914     if (!isIntegerWideningViableForSlice(DL, AllocaTy, AllocBeginOffset, Size,
1915                                          *SI, WholeAllocaOp))
1916       return false;
1917
1918   return WholeAllocaOp;
1919 }
1920
1921 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1922                              IntegerType *Ty, uint64_t Offset,
1923                              const Twine &Name) {
1924   DEBUG(dbgs() << "       start: " << *V << "\n");
1925   IntegerType *IntTy = cast<IntegerType>(V->getType());
1926   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1927          "Element extends past full value");
1928   uint64_t ShAmt = 8 * Offset;
1929   if (DL.isBigEndian())
1930     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1931   if (ShAmt) {
1932     V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
1933     DEBUG(dbgs() << "     shifted: " << *V << "\n");
1934   }
1935   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1936          "Cannot extract to a larger integer!");
1937   if (Ty != IntTy) {
1938     V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
1939     DEBUG(dbgs() << "     trunced: " << *V << "\n");
1940   }
1941   return V;
1942 }
1943
1944 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
1945                             Value *V, uint64_t Offset, const Twine &Name) {
1946   IntegerType *IntTy = cast<IntegerType>(Old->getType());
1947   IntegerType *Ty = cast<IntegerType>(V->getType());
1948   assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
1949          "Cannot insert a larger integer!");
1950   DEBUG(dbgs() << "       start: " << *V << "\n");
1951   if (Ty != IntTy) {
1952     V = IRB.CreateZExt(V, IntTy, Name + ".ext");
1953     DEBUG(dbgs() << "    extended: " << *V << "\n");
1954   }
1955   assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
1956          "Element store outside of alloca store");
1957   uint64_t ShAmt = 8 * Offset;
1958   if (DL.isBigEndian())
1959     ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
1960   if (ShAmt) {
1961     V = IRB.CreateShl(V, ShAmt, Name + ".shift");
1962     DEBUG(dbgs() << "     shifted: " << *V << "\n");
1963   }
1964
1965   if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
1966     APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
1967     Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
1968     DEBUG(dbgs() << "      masked: " << *Old << "\n");
1969     V = IRB.CreateOr(Old, V, Name + ".insert");
1970     DEBUG(dbgs() << "    inserted: " << *V << "\n");
1971   }
1972   return V;
1973 }
1974
1975 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
1976                             unsigned EndIndex, const Twine &Name) {
1977   VectorType *VecTy = cast<VectorType>(V->getType());
1978   unsigned NumElements = EndIndex - BeginIndex;
1979   assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
1980
1981   if (NumElements == VecTy->getNumElements())
1982     return V;
1983
1984   if (NumElements == 1) {
1985     V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
1986                                  Name + ".extract");
1987     DEBUG(dbgs() << "     extract: " << *V << "\n");
1988     return V;
1989   }
1990
1991   SmallVector<Constant *, 8> Mask;
1992   Mask.reserve(NumElements);
1993   for (unsigned i = BeginIndex; i != EndIndex; ++i)
1994     Mask.push_back(IRB.getInt32(i));
1995   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
1996                               ConstantVector::get(Mask), Name + ".extract");
1997   DEBUG(dbgs() << "     shuffle: " << *V << "\n");
1998   return V;
1999 }
2000
2001 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2002                            unsigned BeginIndex, const Twine &Name) {
2003   VectorType *VecTy = cast<VectorType>(Old->getType());
2004   assert(VecTy && "Can only insert a vector into a vector");
2005
2006   VectorType *Ty = dyn_cast<VectorType>(V->getType());
2007   if (!Ty) {
2008     // Single element to insert.
2009     V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2010                                 Name + ".insert");
2011     DEBUG(dbgs() << "     insert: " << *V << "\n");
2012     return V;
2013   }
2014
2015   assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2016          "Too many elements!");
2017   if (Ty->getNumElements() == VecTy->getNumElements()) {
2018     assert(V->getType() == VecTy && "Vector type mismatch");
2019     return V;
2020   }
2021   unsigned EndIndex = BeginIndex + Ty->getNumElements();
2022
2023   // When inserting a smaller vector into the larger to store, we first
2024   // use a shuffle vector to widen it with undef elements, and then
2025   // a second shuffle vector to select between the loaded vector and the
2026   // incoming vector.
2027   SmallVector<Constant *, 8> Mask;
2028   Mask.reserve(VecTy->getNumElements());
2029   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2030     if (i >= BeginIndex && i < EndIndex)
2031       Mask.push_back(IRB.getInt32(i - BeginIndex));
2032     else
2033       Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2034   V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2035                               ConstantVector::get(Mask), Name + ".expand");
2036   DEBUG(dbgs() << "    shuffle: " << *V << "\n");
2037
2038   Mask.clear();
2039   for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2040     Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2041
2042   V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2043
2044   DEBUG(dbgs() << "    blend: " << *V << "\n");
2045   return V;
2046 }
2047
2048 namespace {
2049 /// \brief Visitor to rewrite instructions using p particular slice of an alloca
2050 /// to use a new alloca.
2051 ///
2052 /// Also implements the rewriting to vector-based accesses when the partition
2053 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2054 /// lives here.
2055 class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
2056   // Befriend the base class so it can delegate to private visit methods.
2057   friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
2058   typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
2059
2060   const DataLayout &DL;
2061   AllocaSlices &AS;
2062   SROA &Pass;
2063   AllocaInst &OldAI, &NewAI;
2064   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2065   Type *NewAllocaTy;
2066
2067   // This is a convenience and flag variable that will be null unless the new
2068   // alloca's integer operations should be widened to this integer type due to
2069   // passing isIntegerWideningViable above. If it is non-null, the desired
2070   // integer type will be stored here for easy access during rewriting.
2071   IntegerType *IntTy;
2072
2073   // If we are rewriting an alloca partition which can be written as pure
2074   // vector operations, we stash extra information here. When VecTy is
2075   // non-null, we have some strict guarantees about the rewritten alloca:
2076   //   - The new alloca is exactly the size of the vector type here.
2077   //   - The accesses all either map to the entire vector or to a single
2078   //     element.
2079   //   - The set of accessing instructions is only one of those handled above
2080   //     in isVectorPromotionViable. Generally these are the same access kinds
2081   //     which are promotable via mem2reg.
2082   VectorType *VecTy;
2083   Type *ElementTy;
2084   uint64_t ElementSize;
2085
2086   // The original offset of the slice currently being rewritten relative to
2087   // the original alloca.
2088   uint64_t BeginOffset, EndOffset;
2089   // The new offsets of the slice currently being rewritten relative to the
2090   // original alloca.
2091   uint64_t NewBeginOffset, NewEndOffset;
2092
2093   uint64_t SliceSize;
2094   bool IsSplittable;
2095   bool IsSplit;
2096   Use *OldUse;
2097   Instruction *OldPtr;
2098
2099   // Track post-rewrite users which are PHI nodes and Selects.
2100   SmallPtrSetImpl<PHINode *> &PHIUsers;
2101   SmallPtrSetImpl<SelectInst *> &SelectUsers;
2102
2103   // Utility IR builder, whose name prefix is setup for each visited use, and
2104   // the insertion point is set to point to the user.
2105   IRBuilderTy IRB;
2106
2107 public:
2108   AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2109                       AllocaInst &OldAI, AllocaInst &NewAI,
2110                       uint64_t NewAllocaBeginOffset,
2111                       uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2112                       VectorType *PromotableVecTy,
2113                       SmallPtrSetImpl<PHINode *> &PHIUsers,
2114                       SmallPtrSetImpl<SelectInst *> &SelectUsers)
2115       : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2116         NewAllocaBeginOffset(NewAllocaBeginOffset),
2117         NewAllocaEndOffset(NewAllocaEndOffset),
2118         NewAllocaTy(NewAI.getAllocatedType()),
2119         IntTy(IsIntegerPromotable
2120                   ? Type::getIntNTy(
2121                         NewAI.getContext(),
2122                         DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2123                   : nullptr),
2124         VecTy(PromotableVecTy),
2125         ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2126         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2127         BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2128         OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2129         IRB(NewAI.getContext(), ConstantFolder()) {
2130     if (VecTy) {
2131       assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2132              "Only multiple-of-8 sized vector elements are viable");
2133       ++NumVectorized;
2134     }
2135     assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2136   }
2137
2138   bool visit(AllocaSlices::const_iterator I) {
2139     bool CanSROA = true;
2140     BeginOffset = I->beginOffset();
2141     EndOffset = I->endOffset();
2142     IsSplittable = I->isSplittable();
2143     IsSplit =
2144         BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2145
2146     // Compute the intersecting offset range.
2147     assert(BeginOffset < NewAllocaEndOffset);
2148     assert(EndOffset > NewAllocaBeginOffset);
2149     NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2150     NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2151
2152     SliceSize = NewEndOffset - NewBeginOffset;
2153
2154     OldUse = I->getUse();
2155     OldPtr = cast<Instruction>(OldUse->get());
2156
2157     Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2158     IRB.SetInsertPoint(OldUserI);
2159     IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2160     IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2161
2162     CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2163     if (VecTy || IntTy)
2164       assert(CanSROA);
2165     return CanSROA;
2166   }
2167
2168 private:
2169   // Make sure the other visit overloads are visible.
2170   using Base::visit;
2171
2172   // Every instruction which can end up as a user must have a rewrite rule.
2173   bool visitInstruction(Instruction &I) {
2174     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2175     llvm_unreachable("No rewrite rule for this instruction!");
2176   }
2177
2178   Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2179     // Note that the offset computation can use BeginOffset or NewBeginOffset
2180     // interchangeably for unsplit slices.
2181     assert(IsSplit || BeginOffset == NewBeginOffset);
2182     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2183
2184 #ifndef NDEBUG
2185     StringRef OldName = OldPtr->getName();
2186     // Skip through the last '.sroa.' component of the name.
2187     size_t LastSROAPrefix = OldName.rfind(".sroa.");
2188     if (LastSROAPrefix != StringRef::npos) {
2189       OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2190       // Look for an SROA slice index.
2191       size_t IndexEnd = OldName.find_first_not_of("0123456789");
2192       if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2193         // Strip the index and look for the offset.
2194         OldName = OldName.substr(IndexEnd + 1);
2195         size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2196         if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2197           // Strip the offset.
2198           OldName = OldName.substr(OffsetEnd + 1);
2199       }
2200     }
2201     // Strip any SROA suffixes as well.
2202     OldName = OldName.substr(0, OldName.find(".sroa_"));
2203 #endif
2204
2205     return getAdjustedPtr(IRB, DL, &NewAI,
2206                           APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
2207 #ifndef NDEBUG
2208                           Twine(OldName) + "."
2209 #else
2210                           Twine()
2211 #endif
2212                           );
2213   }
2214
2215   /// \brief Compute suitable alignment to access this slice of the *new*
2216   /// alloca.
2217   ///
2218   /// You can optionally pass a type to this routine and if that type's ABI
2219   /// alignment is itself suitable, this will return zero.
2220   unsigned getSliceAlign(Type *Ty = nullptr) {
2221     unsigned NewAIAlign = NewAI.getAlignment();
2222     if (!NewAIAlign)
2223       NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2224     unsigned Align =
2225         MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2226     return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2227   }
2228
2229   unsigned getIndex(uint64_t Offset) {
2230     assert(VecTy && "Can only call getIndex when rewriting a vector");
2231     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2232     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2233     uint32_t Index = RelOffset / ElementSize;
2234     assert(Index * ElementSize == RelOffset);
2235     return Index;
2236   }
2237
2238   void deleteIfTriviallyDead(Value *V) {
2239     Instruction *I = cast<Instruction>(V);
2240     if (isInstructionTriviallyDead(I))
2241       Pass.DeadInsts.insert(I);
2242   }
2243
2244   Value *rewriteVectorizedLoadInst() {
2245     unsigned BeginIndex = getIndex(NewBeginOffset);
2246     unsigned EndIndex = getIndex(NewEndOffset);
2247     assert(EndIndex > BeginIndex && "Empty vector!");
2248
2249     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2250     return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2251   }
2252
2253   Value *rewriteIntegerLoad(LoadInst &LI) {
2254     assert(IntTy && "We cannot insert an integer to the alloca");
2255     assert(!LI.isVolatile());
2256     Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2257     V = convertValue(DL, IRB, V, IntTy);
2258     assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2259     uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2260     if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
2261       V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2262                          "extract");
2263     return V;
2264   }
2265
2266   bool visitLoadInst(LoadInst &LI) {
2267     DEBUG(dbgs() << "    original: " << LI << "\n");
2268     Value *OldOp = LI.getOperand(0);
2269     assert(OldOp == OldPtr);
2270
2271     Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2272                              : LI.getType();
2273     bool IsPtrAdjusted = false;
2274     Value *V;
2275     if (VecTy) {
2276       V = rewriteVectorizedLoadInst();
2277     } else if (IntTy && LI.getType()->isIntegerTy()) {
2278       V = rewriteIntegerLoad(LI);
2279     } else if (NewBeginOffset == NewAllocaBeginOffset &&
2280                canConvertValue(DL, NewAllocaTy, LI.getType())) {
2281       V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), LI.isVolatile(),
2282                                 LI.getName());
2283     } else {
2284       Type *LTy = TargetTy->getPointerTo();
2285       V = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2286                                 getSliceAlign(TargetTy), LI.isVolatile(),
2287                                 LI.getName());
2288       IsPtrAdjusted = true;
2289     }
2290     V = convertValue(DL, IRB, V, TargetTy);
2291
2292     if (IsSplit) {
2293       assert(!LI.isVolatile());
2294       assert(LI.getType()->isIntegerTy() &&
2295              "Only integer type loads and stores are split");
2296       assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2297              "Split load isn't smaller than original load");
2298       assert(LI.getType()->getIntegerBitWidth() ==
2299                  DL.getTypeStoreSizeInBits(LI.getType()) &&
2300              "Non-byte-multiple bit width");
2301       // Move the insertion point just past the load so that we can refer to it.
2302       IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
2303       // Create a placeholder value with the same type as LI to use as the
2304       // basis for the new value. This allows us to replace the uses of LI with
2305       // the computed value, and then replace the placeholder with LI, leaving
2306       // LI only used for this computation.
2307       Value *Placeholder =
2308           new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
2309       V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset, "insert");
2310       LI.replaceAllUsesWith(V);
2311       Placeholder->replaceAllUsesWith(&LI);
2312       delete Placeholder;
2313     } else {
2314       LI.replaceAllUsesWith(V);
2315     }
2316
2317     Pass.DeadInsts.insert(&LI);
2318     deleteIfTriviallyDead(OldOp);
2319     DEBUG(dbgs() << "          to: " << *V << "\n");
2320     return !LI.isVolatile() && !IsPtrAdjusted;
2321   }
2322
2323   bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
2324     if (V->getType() != VecTy) {
2325       unsigned BeginIndex = getIndex(NewBeginOffset);
2326       unsigned EndIndex = getIndex(NewEndOffset);
2327       assert(EndIndex > BeginIndex && "Empty vector!");
2328       unsigned NumElements = EndIndex - BeginIndex;
2329       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2330       Type *SliceTy = (NumElements == 1)
2331                           ? ElementTy
2332                           : VectorType::get(ElementTy, NumElements);
2333       if (V->getType() != SliceTy)
2334         V = convertValue(DL, IRB, V, SliceTy);
2335
2336       // Mix in the existing elements.
2337       Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2338       V = insertVector(IRB, Old, V, BeginIndex, "vec");
2339     }
2340     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2341     Pass.DeadInsts.insert(&SI);
2342
2343     (void)Store;
2344     DEBUG(dbgs() << "          to: " << *Store << "\n");
2345     return true;
2346   }
2347
2348   bool rewriteIntegerStore(Value *V, StoreInst &SI) {
2349     assert(IntTy && "We cannot extract an integer from the alloca");
2350     assert(!SI.isVolatile());
2351     if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2352       Value *Old =
2353           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2354       Old = convertValue(DL, IRB, Old, IntTy);
2355       assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2356       uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2357       V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2358     }
2359     V = convertValue(DL, IRB, V, NewAllocaTy);
2360     StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2361     Pass.DeadInsts.insert(&SI);
2362     (void)Store;
2363     DEBUG(dbgs() << "          to: " << *Store << "\n");
2364     return true;
2365   }
2366
2367   bool visitStoreInst(StoreInst &SI) {
2368     DEBUG(dbgs() << "    original: " << SI << "\n");
2369     Value *OldOp = SI.getOperand(1);
2370     assert(OldOp == OldPtr);
2371
2372     Value *V = SI.getValueOperand();
2373
2374     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2375     // alloca that should be re-examined after promoting this alloca.
2376     if (V->getType()->isPointerTy())
2377       if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2378         Pass.PostPromotionWorklist.insert(AI);
2379
2380     if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2381       assert(!SI.isVolatile());
2382       assert(V->getType()->isIntegerTy() &&
2383              "Only integer type loads and stores are split");
2384       assert(V->getType()->getIntegerBitWidth() ==
2385                  DL.getTypeStoreSizeInBits(V->getType()) &&
2386              "Non-byte-multiple bit width");
2387       IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2388       V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset, "extract");
2389     }
2390
2391     if (VecTy)
2392       return rewriteVectorizedStoreInst(V, SI, OldOp);
2393     if (IntTy && V->getType()->isIntegerTy())
2394       return rewriteIntegerStore(V, SI);
2395
2396     StoreInst *NewSI;
2397     if (NewBeginOffset == NewAllocaBeginOffset &&
2398         NewEndOffset == NewAllocaEndOffset &&
2399         canConvertValue(DL, V->getType(), NewAllocaTy)) {
2400       V = convertValue(DL, IRB, V, NewAllocaTy);
2401       NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2402                                      SI.isVolatile());
2403     } else {
2404       Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
2405       NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2406                                      SI.isVolatile());
2407     }
2408     (void)NewSI;
2409     Pass.DeadInsts.insert(&SI);
2410     deleteIfTriviallyDead(OldOp);
2411
2412     DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2413     return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2414   }
2415
2416   /// \brief Compute an integer value from splatting an i8 across the given
2417   /// number of bytes.
2418   ///
2419   /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2420   /// call this routine.
2421   /// FIXME: Heed the advice above.
2422   ///
2423   /// \param V The i8 value to splat.
2424   /// \param Size The number of bytes in the output (assuming i8 is one byte)
2425   Value *getIntegerSplat(Value *V, unsigned Size) {
2426     assert(Size > 0 && "Expected a positive number of bytes.");
2427     IntegerType *VTy = cast<IntegerType>(V->getType());
2428     assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2429     if (Size == 1)
2430       return V;
2431
2432     Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2433     V = IRB.CreateMul(
2434         IRB.CreateZExt(V, SplatIntTy, "zext"),
2435         ConstantExpr::getUDiv(
2436             Constant::getAllOnesValue(SplatIntTy),
2437             ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2438                                   SplatIntTy)),
2439         "isplat");
2440     return V;
2441   }
2442
2443   /// \brief Compute a vector splat for a given element value.
2444   Value *getVectorSplat(Value *V, unsigned NumElements) {
2445     V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2446     DEBUG(dbgs() << "       splat: " << *V << "\n");
2447     return V;
2448   }
2449
2450   bool visitMemSetInst(MemSetInst &II) {
2451     DEBUG(dbgs() << "    original: " << II << "\n");
2452     assert(II.getRawDest() == OldPtr);
2453
2454     // If the memset has a variable size, it cannot be split, just adjust the
2455     // pointer to the new alloca.
2456     if (!isa<Constant>(II.getLength())) {
2457       assert(!IsSplit);
2458       assert(NewBeginOffset == BeginOffset);
2459       II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2460       Type *CstTy = II.getAlignmentCst()->getType();
2461       II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
2462
2463       deleteIfTriviallyDead(OldPtr);
2464       return false;
2465     }
2466
2467     // Record this instruction for deletion.
2468     Pass.DeadInsts.insert(&II);
2469
2470     Type *AllocaTy = NewAI.getAllocatedType();
2471     Type *ScalarTy = AllocaTy->getScalarType();
2472
2473     // If this doesn't map cleanly onto the alloca type, and that type isn't
2474     // a single value type, just emit a memset.
2475     if (!VecTy && !IntTy &&
2476         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2477          SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2478          !AllocaTy->isSingleValueType() ||
2479          !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2480          DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2481       Type *SizeTy = II.getLength()->getType();
2482       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2483       CallInst *New = IRB.CreateMemSet(
2484           getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2485           getSliceAlign(), II.isVolatile());
2486       (void)New;
2487       DEBUG(dbgs() << "          to: " << *New << "\n");
2488       return false;
2489     }
2490
2491     // If we can represent this as a simple value, we have to build the actual
2492     // value to store, which requires expanding the byte present in memset to
2493     // a sensible representation for the alloca type. This is essentially
2494     // splatting the byte to a sufficiently wide integer, splatting it across
2495     // any desired vector width, and bitcasting to the final type.
2496     Value *V;
2497
2498     if (VecTy) {
2499       // If this is a memset of a vectorized alloca, insert it.
2500       assert(ElementTy == ScalarTy);
2501
2502       unsigned BeginIndex = getIndex(NewBeginOffset);
2503       unsigned EndIndex = getIndex(NewEndOffset);
2504       assert(EndIndex > BeginIndex && "Empty vector!");
2505       unsigned NumElements = EndIndex - BeginIndex;
2506       assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2507
2508       Value *Splat =
2509           getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2510       Splat = convertValue(DL, IRB, Splat, ElementTy);
2511       if (NumElements > 1)
2512         Splat = getVectorSplat(Splat, NumElements);
2513
2514       Value *Old =
2515           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2516       V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2517     } else if (IntTy) {
2518       // If this is a memset on an alloca where we can widen stores, insert the
2519       // set integer.
2520       assert(!II.isVolatile());
2521
2522       uint64_t Size = NewEndOffset - NewBeginOffset;
2523       V = getIntegerSplat(II.getValue(), Size);
2524
2525       if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2526                     EndOffset != NewAllocaBeginOffset)) {
2527         Value *Old =
2528             IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2529         Old = convertValue(DL, IRB, Old, IntTy);
2530         uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2531         V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2532       } else {
2533         assert(V->getType() == IntTy &&
2534                "Wrong type for an alloca wide integer!");
2535       }
2536       V = convertValue(DL, IRB, V, AllocaTy);
2537     } else {
2538       // Established these invariants above.
2539       assert(NewBeginOffset == NewAllocaBeginOffset);
2540       assert(NewEndOffset == NewAllocaEndOffset);
2541
2542       V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2543       if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2544         V = getVectorSplat(V, AllocaVecTy->getNumElements());
2545
2546       V = convertValue(DL, IRB, V, AllocaTy);
2547     }
2548
2549     Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2550                                         II.isVolatile());
2551     (void)New;
2552     DEBUG(dbgs() << "          to: " << *New << "\n");
2553     return !II.isVolatile();
2554   }
2555
2556   bool visitMemTransferInst(MemTransferInst &II) {
2557     // Rewriting of memory transfer instructions can be a bit tricky. We break
2558     // them into two categories: split intrinsics and unsplit intrinsics.
2559
2560     DEBUG(dbgs() << "    original: " << II << "\n");
2561
2562     bool IsDest = &II.getRawDestUse() == OldUse;
2563     assert((IsDest && II.getRawDest() == OldPtr) ||
2564            (!IsDest && II.getRawSource() == OldPtr));
2565
2566     unsigned SliceAlign = getSliceAlign();
2567
2568     // For unsplit intrinsics, we simply modify the source and destination
2569     // pointers in place. This isn't just an optimization, it is a matter of
2570     // correctness. With unsplit intrinsics we may be dealing with transfers
2571     // within a single alloca before SROA ran, or with transfers that have
2572     // a variable length. We may also be dealing with memmove instead of
2573     // memcpy, and so simply updating the pointers is the necessary for us to
2574     // update both source and dest of a single call.
2575     if (!IsSplittable) {
2576       Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2577       if (IsDest)
2578         II.setDest(AdjustedPtr);
2579       else
2580         II.setSource(AdjustedPtr);
2581
2582       if (II.getAlignment() > SliceAlign) {
2583         Type *CstTy = II.getAlignmentCst()->getType();
2584         II.setAlignment(
2585             ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
2586       }
2587
2588       DEBUG(dbgs() << "          to: " << II << "\n");
2589       deleteIfTriviallyDead(OldPtr);
2590       return false;
2591     }
2592     // For split transfer intrinsics we have an incredibly useful assurance:
2593     // the source and destination do not reside within the same alloca, and at
2594     // least one of them does not escape. This means that we can replace
2595     // memmove with memcpy, and we don't need to worry about all manner of
2596     // downsides to splitting and transforming the operations.
2597
2598     // If this doesn't map cleanly onto the alloca type, and that type isn't
2599     // a single value type, just emit a memcpy.
2600     bool EmitMemCpy =
2601         !VecTy && !IntTy &&
2602         (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2603          SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2604          !NewAI.getAllocatedType()->isSingleValueType());
2605
2606     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2607     // size hasn't been shrunk based on analysis of the viable range, this is
2608     // a no-op.
2609     if (EmitMemCpy && &OldAI == &NewAI) {
2610       // Ensure the start lines up.
2611       assert(NewBeginOffset == BeginOffset);
2612
2613       // Rewrite the size as needed.
2614       if (NewEndOffset != EndOffset)
2615         II.setLength(ConstantInt::get(II.getLength()->getType(),
2616                                       NewEndOffset - NewBeginOffset));
2617       return false;
2618     }
2619     // Record this instruction for deletion.
2620     Pass.DeadInsts.insert(&II);
2621
2622     // Strip all inbounds GEPs and pointer casts to try to dig out any root
2623     // alloca that should be re-examined after rewriting this instruction.
2624     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2625     if (AllocaInst *AI =
2626             dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2627       assert(AI != &OldAI && AI != &NewAI &&
2628              "Splittable transfers cannot reach the same alloca on both ends.");
2629       Pass.Worklist.insert(AI);
2630     }
2631
2632     Type *OtherPtrTy = OtherPtr->getType();
2633     unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2634
2635     // Compute the relative offset for the other pointer within the transfer.
2636     unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2637     APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2638     unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
2639                                    OtherOffset.zextOrTrunc(64).getZExtValue());
2640
2641     if (EmitMemCpy) {
2642       // Compute the other pointer, folding as much as possible to produce
2643       // a single, simple GEP in most cases.
2644       OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2645                                 OtherPtr->getName() + ".");
2646
2647       Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2648       Type *SizeTy = II.getLength()->getType();
2649       Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2650
2651       CallInst *New = IRB.CreateMemCpy(
2652           IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2653           MinAlign(SliceAlign, OtherAlign), II.isVolatile());
2654       (void)New;
2655       DEBUG(dbgs() << "          to: " << *New << "\n");
2656       return false;
2657     }
2658
2659     bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2660                          NewEndOffset == NewAllocaEndOffset;
2661     uint64_t Size = NewEndOffset - NewBeginOffset;
2662     unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2663     unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2664     unsigned NumElements = EndIndex - BeginIndex;
2665     IntegerType *SubIntTy =
2666         IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2667
2668     // Reset the other pointer type to match the register type we're going to
2669     // use, but using the address space of the original other pointer.
2670     if (VecTy && !IsWholeAlloca) {
2671       if (NumElements == 1)
2672         OtherPtrTy = VecTy->getElementType();
2673       else
2674         OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2675
2676       OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2677     } else if (IntTy && !IsWholeAlloca) {
2678       OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2679     } else {
2680       OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2681     }
2682
2683     Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2684                                    OtherPtr->getName() + ".");
2685     unsigned SrcAlign = OtherAlign;
2686     Value *DstPtr = &NewAI;
2687     unsigned DstAlign = SliceAlign;
2688     if (!IsDest) {
2689       std::swap(SrcPtr, DstPtr);
2690       std::swap(SrcAlign, DstAlign);
2691     }
2692
2693     Value *Src;
2694     if (VecTy && !IsWholeAlloca && !IsDest) {
2695       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2696       Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2697     } else if (IntTy && !IsWholeAlloca && !IsDest) {
2698       Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2699       Src = convertValue(DL, IRB, Src, IntTy);
2700       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2701       Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2702     } else {
2703       Src =
2704           IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
2705     }
2706
2707     if (VecTy && !IsWholeAlloca && IsDest) {
2708       Value *Old =
2709           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2710       Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2711     } else if (IntTy && !IsWholeAlloca && IsDest) {
2712       Value *Old =
2713           IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2714       Old = convertValue(DL, IRB, Old, IntTy);
2715       uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2716       Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
2717       Src = convertValue(DL, IRB, Src, NewAllocaTy);
2718     }
2719
2720     StoreInst *Store = cast<StoreInst>(
2721         IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
2722     (void)Store;
2723     DEBUG(dbgs() << "          to: " << *Store << "\n");
2724     return !II.isVolatile();
2725   }
2726
2727   bool visitIntrinsicInst(IntrinsicInst &II) {
2728     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2729            II.getIntrinsicID() == Intrinsic::lifetime_end);
2730     DEBUG(dbgs() << "    original: " << II << "\n");
2731     assert(II.getArgOperand(1) == OldPtr);
2732
2733     // Record this instruction for deletion.
2734     Pass.DeadInsts.insert(&II);
2735
2736     ConstantInt *Size =
2737         ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2738                          NewEndOffset - NewBeginOffset);
2739     Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2740     Value *New;
2741     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2742       New = IRB.CreateLifetimeStart(Ptr, Size);
2743     else
2744       New = IRB.CreateLifetimeEnd(Ptr, Size);
2745
2746     (void)New;
2747     DEBUG(dbgs() << "          to: " << *New << "\n");
2748     return true;
2749   }
2750
2751   bool visitPHINode(PHINode &PN) {
2752     DEBUG(dbgs() << "    original: " << PN << "\n");
2753     assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
2754     assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
2755
2756     // We would like to compute a new pointer in only one place, but have it be
2757     // as local as possible to the PHI. To do that, we re-use the location of
2758     // the old pointer, which necessarily must be in the right position to
2759     // dominate the PHI.
2760     IRBuilderTy PtrBuilder(IRB);
2761     if (isa<PHINode>(OldPtr))
2762       PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
2763     else
2764       PtrBuilder.SetInsertPoint(OldPtr);
2765     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
2766
2767     Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
2768     // Replace the operands which were using the old pointer.
2769     std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
2770
2771     DEBUG(dbgs() << "          to: " << PN << "\n");
2772     deleteIfTriviallyDead(OldPtr);
2773
2774     // PHIs can't be promoted on their own, but often can be speculated. We
2775     // check the speculation outside of the rewriter so that we see the
2776     // fully-rewritten alloca.
2777     PHIUsers.insert(&PN);
2778     return true;
2779   }
2780
2781   bool visitSelectInst(SelectInst &SI) {
2782     DEBUG(dbgs() << "    original: " << SI << "\n");
2783     assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
2784            "Pointer isn't an operand!");
2785     assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
2786     assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
2787
2788     Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2789     // Replace the operands which were using the old pointer.
2790     if (SI.getOperand(1) == OldPtr)
2791       SI.setOperand(1, NewPtr);
2792     if (SI.getOperand(2) == OldPtr)
2793       SI.setOperand(2, NewPtr);
2794
2795     DEBUG(dbgs() << "          to: " << SI << "\n");
2796     deleteIfTriviallyDead(OldPtr);
2797
2798     // Selects can't be promoted on their own, but often can be speculated. We
2799     // check the speculation outside of the rewriter so that we see the
2800     // fully-rewritten alloca.
2801     SelectUsers.insert(&SI);
2802     return true;
2803   }
2804 };
2805 }
2806
2807 namespace {
2808 /// \brief Visitor to rewrite aggregate loads and stores as scalar.
2809 ///
2810 /// This pass aggressively rewrites all aggregate loads and stores on
2811 /// a particular pointer (or any pointer derived from it which we can identify)
2812 /// with scalar loads and stores.
2813 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2814   // Befriend the base class so it can delegate to private visit methods.
2815   friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2816
2817   const DataLayout &DL;
2818
2819   /// Queue of pointer uses to analyze and potentially rewrite.
2820   SmallVector<Use *, 8> Queue;
2821
2822   /// Set to prevent us from cycling with phi nodes and loops.
2823   SmallPtrSet<User *, 8> Visited;
2824
2825   /// The current pointer use being rewritten. This is used to dig up the used
2826   /// value (as opposed to the user).
2827   Use *U;
2828
2829 public:
2830   AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
2831
2832   /// Rewrite loads and stores through a pointer and all pointers derived from
2833   /// it.
2834   bool rewrite(Instruction &I) {
2835     DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
2836     enqueueUsers(I);
2837     bool Changed = false;
2838     while (!Queue.empty()) {
2839       U = Queue.pop_back_val();
2840       Changed |= visit(cast<Instruction>(U->getUser()));
2841     }
2842     return Changed;
2843   }
2844
2845 private:
2846   /// Enqueue all the users of the given instruction for further processing.
2847   /// This uses a set to de-duplicate users.
2848   void enqueueUsers(Instruction &I) {
2849     for (Use &U : I.uses())
2850       if (Visited.insert(U.getUser()).second)
2851         Queue.push_back(&U);
2852   }
2853
2854   // Conservative default is to not rewrite anything.
2855   bool visitInstruction(Instruction &I) { return false; }
2856
2857   /// \brief Generic recursive split emission class.
2858   template <typename Derived> class OpSplitter {
2859   protected:
2860     /// The builder used to form new instructions.
2861     IRBuilderTy IRB;
2862     /// The indices which to be used with insert- or extractvalue to select the
2863     /// appropriate value within the aggregate.
2864     SmallVector<unsigned, 4> Indices;
2865     /// The indices to a GEP instruction which will move Ptr to the correct slot
2866     /// within the aggregate.
2867     SmallVector<Value *, 4> GEPIndices;
2868     /// The base pointer of the original op, used as a base for GEPing the
2869     /// split operations.
2870     Value *Ptr;
2871
2872     /// Initialize the splitter with an insertion point, Ptr and start with a
2873     /// single zero GEP index.
2874     OpSplitter(Instruction *InsertionPoint, Value *Ptr)
2875         : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
2876
2877   public:
2878     /// \brief Generic recursive split emission routine.
2879     ///
2880     /// This method recursively splits an aggregate op (load or store) into
2881     /// scalar or vector ops. It splits recursively until it hits a single value
2882     /// and emits that single value operation via the template argument.
2883     ///
2884     /// The logic of this routine relies on GEPs and insertvalue and
2885     /// extractvalue all operating with the same fundamental index list, merely
2886     /// formatted differently (GEPs need actual values).
2887     ///
2888     /// \param Ty  The type being split recursively into smaller ops.
2889     /// \param Agg The aggregate value being built up or stored, depending on
2890     /// whether this is splitting a load or a store respectively.
2891     void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2892       if (Ty->isSingleValueType())
2893         return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
2894
2895       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2896         unsigned OldSize = Indices.size();
2897         (void)OldSize;
2898         for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2899              ++Idx) {
2900           assert(Indices.size() == OldSize && "Did not return to the old size");
2901           Indices.push_back(Idx);
2902           GEPIndices.push_back(IRB.getInt32(Idx));
2903           emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2904           GEPIndices.pop_back();
2905           Indices.pop_back();
2906         }
2907         return;
2908       }
2909
2910       if (StructType *STy = dyn_cast<StructType>(Ty)) {
2911         unsigned OldSize = Indices.size();
2912         (void)OldSize;
2913         for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2914              ++Idx) {
2915           assert(Indices.size() == OldSize && "Did not return to the old size");
2916           Indices.push_back(Idx);
2917           GEPIndices.push_back(IRB.getInt32(Idx));
2918           emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2919           GEPIndices.pop_back();
2920           Indices.pop_back();
2921         }
2922         return;
2923       }
2924
2925       llvm_unreachable("Only arrays and structs are aggregate loadable types");
2926     }
2927   };
2928
2929   struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
2930     LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2931         : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
2932
2933     /// Emit a leaf load of a single value. This is called at the leaves of the
2934     /// recursive emission to actually load values.
2935     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2936       assert(Ty->isSingleValueType());
2937       // Load the single value and insert it using the indices.
2938       Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
2939       Value *Load = IRB.CreateLoad(GEP, Name + ".load");
2940       Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2941       DEBUG(dbgs() << "          to: " << *Load << "\n");
2942     }
2943   };
2944
2945   bool visitLoadInst(LoadInst &LI) {
2946     assert(LI.getPointerOperand() == *U);
2947     if (!LI.isSimple() || LI.getType()->isSingleValueType())
2948       return false;
2949
2950     // We have an aggregate being loaded, split it apart.
2951     DEBUG(dbgs() << "    original: " << LI << "\n");
2952     LoadOpSplitter Splitter(&LI, *U);
2953     Value *V = UndefValue::get(LI.getType());
2954     Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
2955     LI.replaceAllUsesWith(V);
2956     LI.eraseFromParent();
2957     return true;
2958   }
2959
2960   struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
2961     StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
2962         : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
2963
2964     /// Emit a leaf store of a single value. This is called at the leaves of the
2965     /// recursive emission to actually produce stores.
2966     void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
2967       assert(Ty->isSingleValueType());
2968       // Extract the single value and store it using the indices.
2969       Value *Store = IRB.CreateStore(
2970           IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2971           IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2972       (void)Store;
2973       DEBUG(dbgs() << "          to: " << *Store << "\n");
2974     }
2975   };
2976
2977   bool visitStoreInst(StoreInst &SI) {
2978     if (!SI.isSimple() || SI.getPointerOperand() != *U)
2979       return false;
2980     Value *V = SI.getValueOperand();
2981     if (V->getType()->isSingleValueType())
2982       return false;
2983
2984     // We have an aggregate being stored, split it apart.
2985     DEBUG(dbgs() << "    original: " << SI << "\n");
2986     StoreOpSplitter Splitter(&SI, *U);
2987     Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
2988     SI.eraseFromParent();
2989     return true;
2990   }
2991
2992   bool visitBitCastInst(BitCastInst &BC) {
2993     enqueueUsers(BC);
2994     return false;
2995   }
2996
2997   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2998     enqueueUsers(GEPI);
2999     return false;
3000   }
3001
3002   bool visitPHINode(PHINode &PN) {
3003     enqueueUsers(PN);
3004     return false;
3005   }
3006
3007   bool visitSelectInst(SelectInst &SI) {
3008     enqueueUsers(SI);
3009     return false;
3010   }
3011 };
3012 }
3013
3014 /// \brief Strip aggregate type wrapping.
3015 ///
3016 /// This removes no-op aggregate types wrapping an underlying type. It will
3017 /// strip as many layers of types as it can without changing either the type
3018 /// size or the allocated size.
3019 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3020   if (Ty->isSingleValueType())
3021     return Ty;
3022
3023   uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3024   uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3025
3026   Type *InnerTy;
3027   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3028     InnerTy = ArrTy->getElementType();
3029   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3030     const StructLayout *SL = DL.getStructLayout(STy);
3031     unsigned Index = SL->getElementContainingOffset(0);
3032     InnerTy = STy->getElementType(Index);
3033   } else {
3034     return Ty;
3035   }
3036
3037   if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3038       TypeSize > DL.getTypeSizeInBits(InnerTy))
3039     return Ty;
3040
3041   return stripAggregateTypeWrapping(DL, InnerTy);
3042 }
3043
3044 /// \brief Try to find a partition of the aggregate type passed in for a given
3045 /// offset and size.
3046 ///
3047 /// This recurses through the aggregate type and tries to compute a subtype
3048 /// based on the offset and size. When the offset and size span a sub-section
3049 /// of an array, it will even compute a new array type for that sub-section,
3050 /// and the same for structs.
3051 ///
3052 /// Note that this routine is very strict and tries to find a partition of the
3053 /// type which produces the *exact* right offset and size. It is not forgiving
3054 /// when the size or offset cause either end of type-based partition to be off.
3055 /// Also, this is a best-effort routine. It is reasonable to give up and not
3056 /// return a type if necessary.
3057 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3058                               uint64_t Size) {
3059   if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3060     return stripAggregateTypeWrapping(DL, Ty);
3061   if (Offset > DL.getTypeAllocSize(Ty) ||
3062       (DL.getTypeAllocSize(Ty) - Offset) < Size)
3063     return nullptr;
3064
3065   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3066     // We can't partition pointers...
3067     if (SeqTy->isPointerTy())
3068       return nullptr;
3069
3070     Type *ElementTy = SeqTy->getElementType();
3071     uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3072     uint64_t NumSkippedElements = Offset / ElementSize;
3073     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
3074       if (NumSkippedElements >= ArrTy->getNumElements())
3075         return nullptr;
3076     } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
3077       if (NumSkippedElements >= VecTy->getNumElements())
3078         return nullptr;
3079     }
3080     Offset -= NumSkippedElements * ElementSize;
3081
3082     // First check if we need to recurse.
3083     if (Offset > 0 || Size < ElementSize) {
3084       // Bail if the partition ends in a different array element.
3085       if ((Offset + Size) > ElementSize)
3086         return nullptr;
3087       // Recurse through the element type trying to peel off offset bytes.
3088       return getTypePartition(DL, ElementTy, Offset, Size);
3089     }
3090     assert(Offset == 0);
3091
3092     if (Size == ElementSize)
3093       return stripAggregateTypeWrapping(DL, ElementTy);
3094     assert(Size > ElementSize);
3095     uint64_t NumElements = Size / ElementSize;
3096     if (NumElements * ElementSize != Size)
3097       return nullptr;
3098     return ArrayType::get(ElementTy, NumElements);
3099   }
3100
3101   StructType *STy = dyn_cast<StructType>(Ty);
3102   if (!STy)
3103     return nullptr;
3104
3105   const StructLayout *SL = DL.getStructLayout(STy);
3106   if (Offset >= SL->getSizeInBytes())
3107     return nullptr;
3108   uint64_t EndOffset = Offset + Size;
3109   if (EndOffset > SL->getSizeInBytes())
3110     return nullptr;
3111
3112   unsigned Index = SL->getElementContainingOffset(Offset);
3113   Offset -= SL->getElementOffset(Index);
3114
3115   Type *ElementTy = STy->getElementType(Index);
3116   uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3117   if (Offset >= ElementSize)
3118     return nullptr; // The offset points into alignment padding.
3119
3120   // See if any partition must be contained by the element.
3121   if (Offset > 0 || Size < ElementSize) {
3122     if ((Offset + Size) > ElementSize)
3123       return nullptr;
3124     return getTypePartition(DL, ElementTy, Offset, Size);
3125   }
3126   assert(Offset == 0);
3127
3128   if (Size == ElementSize)
3129     return stripAggregateTypeWrapping(DL, ElementTy);
3130
3131   StructType::element_iterator EI = STy->element_begin() + Index,
3132                                EE = STy->element_end();
3133   if (EndOffset < SL->getSizeInBytes()) {
3134     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3135     if (Index == EndIndex)
3136       return nullptr; // Within a single element and its padding.
3137
3138     // Don't try to form "natural" types if the elements don't line up with the
3139     // expected size.
3140     // FIXME: We could potentially recurse down through the last element in the
3141     // sub-struct to find a natural end point.
3142     if (SL->getElementOffset(EndIndex) != EndOffset)
3143       return nullptr;
3144
3145     assert(Index < EndIndex);
3146     EE = STy->element_begin() + EndIndex;
3147   }
3148
3149   // Try to build up a sub-structure.
3150   StructType *SubTy =
3151       StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3152   const StructLayout *SubSL = DL.getStructLayout(SubTy);
3153   if (Size != SubSL->getSizeInBytes())
3154     return nullptr; // The sub-struct doesn't have quite the size needed.
3155
3156   return SubTy;
3157 }
3158
3159 /// \brief Rewrite an alloca partition's users.
3160 ///
3161 /// This routine drives both of the rewriting goals of the SROA pass. It tries
3162 /// to rewrite uses of an alloca partition to be conducive for SSA value
3163 /// promotion. If the partition needs a new, more refined alloca, this will
3164 /// build that new alloca, preserving as much type information as possible, and
3165 /// rewrite the uses of the old alloca to point at the new one and have the
3166 /// appropriate new offsets. It also evaluates how successful the rewrite was
3167 /// at enabling promotion and if it was successful queues the alloca to be
3168 /// promoted.
3169 bool SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3170                             AllocaSlices::iterator B, AllocaSlices::iterator E,
3171                             int64_t BeginOffset, int64_t EndOffset,
3172                             ArrayRef<AllocaSlices::iterator> SplitUses) {
3173   assert(BeginOffset < EndOffset);
3174   uint64_t SliceSize = EndOffset - BeginOffset;
3175
3176   // Try to compute a friendly type for this partition of the alloca. This
3177   // won't always succeed, in which case we fall back to a legal integer type
3178   // or an i8 array of an appropriate size.
3179   Type *SliceTy = nullptr;
3180   if (Type *CommonUseTy = findCommonType(B, E, EndOffset))
3181     if (DL->getTypeAllocSize(CommonUseTy) >= SliceSize)
3182       SliceTy = CommonUseTy;
3183   if (!SliceTy)
3184     if (Type *TypePartitionTy = getTypePartition(*DL, AI.getAllocatedType(),
3185                                                  BeginOffset, SliceSize))
3186       SliceTy = TypePartitionTy;
3187   if ((!SliceTy || (SliceTy->isArrayTy() &&
3188                     SliceTy->getArrayElementType()->isIntegerTy())) &&
3189       DL->isLegalInteger(SliceSize * 8))
3190     SliceTy = Type::getIntNTy(*C, SliceSize * 8);
3191   if (!SliceTy)
3192     SliceTy = ArrayType::get(Type::getInt8Ty(*C), SliceSize);
3193   assert(DL->getTypeAllocSize(SliceTy) >= SliceSize);
3194
3195   bool IsIntegerPromotable = isIntegerWideningViable(
3196       *DL, SliceTy, BeginOffset, AllocaSlices::const_range(B, E), SplitUses);
3197
3198   VectorType *VecTy =
3199       IsIntegerPromotable
3200           ? nullptr
3201           : isVectorPromotionViable(*DL, BeginOffset, EndOffset,
3202                                     AllocaSlices::const_range(B, E), SplitUses);
3203   if (VecTy)
3204     SliceTy = VecTy;
3205
3206   // Check for the case where we're going to rewrite to a new alloca of the
3207   // exact same type as the original, and with the same access offsets. In that
3208   // case, re-use the existing alloca, but still run through the rewriter to
3209   // perform phi and select speculation.
3210   AllocaInst *NewAI;
3211   if (SliceTy == AI.getAllocatedType()) {
3212     assert(BeginOffset == 0 && "Non-zero begin offset but same alloca type");
3213     NewAI = &AI;
3214     // FIXME: We should be able to bail at this point with "nothing changed".
3215     // FIXME: We might want to defer PHI speculation until after here.
3216   } else {
3217     unsigned Alignment = AI.getAlignment();
3218     if (!Alignment) {
3219       // The minimum alignment which users can rely on when the explicit
3220       // alignment is omitted or zero is that required by the ABI for this
3221       // type.
3222       Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
3223     }
3224     Alignment = MinAlign(Alignment, BeginOffset);
3225     // If we will get at least this much alignment from the type alone, leave
3226     // the alloca's alignment unconstrained.
3227     if (Alignment <= DL->getABITypeAlignment(SliceTy))
3228       Alignment = 0;
3229     NewAI =
3230         new AllocaInst(SliceTy, nullptr, Alignment,
3231                        AI.getName() + ".sroa." + Twine(B - AS.begin()), &AI);
3232     ++NumNewAllocas;
3233   }
3234
3235   DEBUG(dbgs() << "Rewriting alloca partition "
3236                << "[" << BeginOffset << "," << EndOffset << ") to: " << *NewAI
3237                << "\n");
3238
3239   // Track the high watermark on the worklist as it is only relevant for
3240   // promoted allocas. We will reset it to this point if the alloca is not in
3241   // fact scheduled for promotion.
3242   unsigned PPWOldSize = PostPromotionWorklist.size();
3243   unsigned NumUses = 0;
3244   SmallPtrSet<PHINode *, 8> PHIUsers;
3245   SmallPtrSet<SelectInst *, 8> SelectUsers;
3246
3247   AllocaSliceRewriter Rewriter(*DL, AS, *this, AI, *NewAI, BeginOffset,
3248                                EndOffset, IsIntegerPromotable, VecTy, PHIUsers,
3249                                SelectUsers);
3250   bool Promotable = true;
3251   for (auto &SplitUse : SplitUses) {
3252     DEBUG(dbgs() << "  rewriting split ");
3253     DEBUG(AS.printSlice(dbgs(), SplitUse, ""));
3254     Promotable &= Rewriter.visit(SplitUse);
3255     ++NumUses;
3256   }
3257   for (AllocaSlices::iterator I = B; I != E; ++I) {
3258     DEBUG(dbgs() << "  rewriting ");
3259     DEBUG(AS.printSlice(dbgs(), I, ""));
3260     Promotable &= Rewriter.visit(I);
3261     ++NumUses;
3262   }
3263
3264   NumAllocaPartitionUses += NumUses;
3265   MaxUsesPerAllocaPartition =
3266       std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
3267
3268   // Now that we've processed all the slices in the new partition, check if any
3269   // PHIs or Selects would block promotion.
3270   for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
3271                                             E = PHIUsers.end();
3272        I != E; ++I)
3273     if (!isSafePHIToSpeculate(**I, DL)) {
3274       Promotable = false;
3275       PHIUsers.clear();
3276       SelectUsers.clear();
3277       break;
3278     }
3279   for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
3280                                                E = SelectUsers.end();
3281        I != E; ++I)
3282     if (!isSafeSelectToSpeculate(**I, DL)) {
3283       Promotable = false;
3284       PHIUsers.clear();
3285       SelectUsers.clear();
3286       break;
3287     }
3288
3289   if (Promotable) {
3290     if (PHIUsers.empty() && SelectUsers.empty()) {
3291       // Promote the alloca.
3292       PromotableAllocas.push_back(NewAI);
3293     } else {
3294       // If we have either PHIs or Selects to speculate, add them to those
3295       // worklists and re-queue the new alloca so that we promote in on the
3296       // next iteration.
3297       for (PHINode *PHIUser : PHIUsers)
3298         SpeculatablePHIs.insert(PHIUser);
3299       for (SelectInst *SelectUser : SelectUsers)
3300         SpeculatableSelects.insert(SelectUser);
3301       Worklist.insert(NewAI);
3302     }
3303   } else {
3304     // If we can't promote the alloca, iterate on it to check for new
3305     // refinements exposed by splitting the current alloca. Don't iterate on an
3306     // alloca which didn't actually change and didn't get promoted.
3307     if (NewAI != &AI)
3308       Worklist.insert(NewAI);
3309
3310     // Drop any post-promotion work items if promotion didn't happen.
3311     while (PostPromotionWorklist.size() > PPWOldSize)
3312       PostPromotionWorklist.pop_back();
3313   }
3314
3315   return true;
3316 }
3317
3318 static void
3319 removeFinishedSplitUses(SmallVectorImpl<AllocaSlices::iterator> &SplitUses,
3320                         uint64_t &MaxSplitUseEndOffset, uint64_t Offset) {
3321   if (Offset >= MaxSplitUseEndOffset) {
3322     SplitUses.clear();
3323     MaxSplitUseEndOffset = 0;
3324     return;
3325   }
3326
3327   size_t SplitUsesOldSize = SplitUses.size();
3328   SplitUses.erase(std::remove_if(
3329                       SplitUses.begin(), SplitUses.end(),
3330                       [Offset](const AllocaSlices::iterator &I) {
3331                         return I->endOffset() <= Offset;
3332                       }),
3333                   SplitUses.end());
3334   if (SplitUsesOldSize == SplitUses.size())
3335     return;
3336
3337   // Recompute the max. While this is linear, so is remove_if.
3338   MaxSplitUseEndOffset = 0;
3339   for (AllocaSlices::iterator SplitUse : SplitUses)
3340     MaxSplitUseEndOffset =
3341         std::max(SplitUse->endOffset(), MaxSplitUseEndOffset);
3342 }
3343
3344 /// \brief Walks the slices of an alloca and form partitions based on them,
3345 /// rewriting each of their uses.
3346 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
3347   if (AS.begin() == AS.end())
3348     return false;
3349
3350   unsigned NumPartitions = 0;
3351   bool Changed = false;
3352   SmallVector<AllocaSlices::iterator, 4> SplitUses;
3353   uint64_t MaxSplitUseEndOffset = 0;
3354
3355   uint64_t BeginOffset = AS.begin()->beginOffset();
3356
3357   for (AllocaSlices::iterator SI = AS.begin(), SJ = std::next(SI),
3358                               SE = AS.end();
3359        SI != SE; SI = SJ) {
3360     uint64_t MaxEndOffset = SI->endOffset();
3361
3362     if (!SI->isSplittable()) {
3363       // When we're forming an unsplittable region, it must always start at the
3364       // first slice and will extend through its end.
3365       assert(BeginOffset == SI->beginOffset());
3366
3367       // Form a partition including all of the overlapping slices with this
3368       // unsplittable slice.
3369       while (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3370         if (!SJ->isSplittable())
3371           MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3372         ++SJ;
3373       }
3374     } else {
3375       assert(SI->isSplittable()); // Established above.
3376
3377       // Collect all of the overlapping splittable slices.
3378       while (SJ != SE && SJ->beginOffset() < MaxEndOffset &&
3379              SJ->isSplittable()) {
3380         MaxEndOffset = std::max(MaxEndOffset, SJ->endOffset());
3381         ++SJ;
3382       }
3383
3384       // Back up MaxEndOffset and SJ if we ended the span early when
3385       // encountering an unsplittable slice.
3386       if (SJ != SE && SJ->beginOffset() < MaxEndOffset) {
3387         assert(!SJ->isSplittable());
3388         MaxEndOffset = SJ->beginOffset();
3389       }
3390     }
3391
3392     // Check if we have managed to move the end offset forward yet. If so,
3393     // we'll have to rewrite uses and erase old split uses.
3394     if (BeginOffset < MaxEndOffset) {
3395       // Rewrite a sequence of overlapping slices.
3396       Changed |= rewritePartition(AI, AS, SI, SJ, BeginOffset, MaxEndOffset,
3397                                   SplitUses);
3398       ++NumPartitions;
3399
3400       removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset, MaxEndOffset);
3401     }
3402
3403     // Accumulate all the splittable slices from the [SI,SJ) region which
3404     // overlap going forward.
3405     for (AllocaSlices::iterator SK = SI; SK != SJ; ++SK)
3406       if (SK->isSplittable() && SK->endOffset() > MaxEndOffset) {
3407         SplitUses.push_back(SK);
3408         MaxSplitUseEndOffset = std::max(SK->endOffset(), MaxSplitUseEndOffset);
3409       }
3410
3411     // If we're already at the end and we have no split uses, we're done.
3412     if (SJ == SE && SplitUses.empty())
3413       break;
3414
3415     // If we have no split uses or no gap in offsets, we're ready to move to
3416     // the next slice.
3417     if (SplitUses.empty() || (SJ != SE && MaxEndOffset == SJ->beginOffset())) {
3418       BeginOffset = SJ->beginOffset();
3419       continue;
3420     }
3421
3422     // Even if we have split slices, if the next slice is splittable and the
3423     // split slices reach it, we can simply set up the beginning offset of the
3424     // next iteration to bridge between them.
3425     if (SJ != SE && SJ->isSplittable() &&
3426         MaxSplitUseEndOffset > SJ->beginOffset()) {
3427       BeginOffset = MaxEndOffset;
3428       continue;
3429     }
3430
3431     // Otherwise, we have a tail of split slices. Rewrite them with an empty
3432     // range of slices.
3433     uint64_t PostSplitEndOffset =
3434         SJ == SE ? MaxSplitUseEndOffset : SJ->beginOffset();
3435
3436     Changed |= rewritePartition(AI, AS, SJ, SJ, MaxEndOffset,
3437                                 PostSplitEndOffset, SplitUses);
3438     ++NumPartitions;
3439
3440     if (SJ == SE)
3441       break; // Skip the rest, we don't need to do any cleanup.
3442
3443     removeFinishedSplitUses(SplitUses, MaxSplitUseEndOffset,
3444                             PostSplitEndOffset);
3445
3446     // Now just reset the begin offset for the next iteration.
3447     BeginOffset = SJ->beginOffset();
3448   }
3449
3450   NumAllocaPartitions += NumPartitions;
3451   MaxPartitionsPerAlloca =
3452       std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
3453
3454   return Changed;
3455 }
3456
3457 /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
3458 void SROA::clobberUse(Use &U) {
3459   Value *OldV = U;
3460   // Replace the use with an undef value.
3461   U = UndefValue::get(OldV->getType());
3462
3463   // Check for this making an instruction dead. We have to garbage collect
3464   // all the dead instructions to ensure the uses of any alloca end up being
3465   // minimal.
3466   if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3467     if (isInstructionTriviallyDead(OldI)) {
3468       DeadInsts.insert(OldI);
3469     }
3470 }
3471
3472 /// \brief Analyze an alloca for SROA.
3473 ///
3474 /// This analyzes the alloca to ensure we can reason about it, builds
3475 /// the slices of the alloca, and then hands it off to be split and
3476 /// rewritten as needed.
3477 bool SROA::runOnAlloca(AllocaInst &AI) {
3478   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3479   ++NumAllocasAnalyzed;
3480
3481   // Special case dead allocas, as they're trivial.
3482   if (AI.use_empty()) {
3483     AI.eraseFromParent();
3484     return true;
3485   }
3486
3487   // Skip alloca forms that this analysis can't handle.
3488   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3489       DL->getTypeAllocSize(AI.getAllocatedType()) == 0)
3490     return false;
3491
3492   bool Changed = false;
3493
3494   // First, split any FCA loads and stores touching this alloca to promote
3495   // better splitting and promotion opportunities.
3496   AggLoadStoreRewriter AggRewriter(*DL);
3497   Changed |= AggRewriter.rewrite(AI);
3498
3499   // Build the slices using a recursive instruction-visiting builder.
3500   AllocaSlices AS(*DL, AI);
3501   DEBUG(AS.print(dbgs()));
3502   if (AS.isEscaped())
3503     return Changed;
3504
3505   // Delete all the dead users of this alloca before splitting and rewriting it.
3506   for (Instruction *DeadUser : AS.getDeadUsers()) {
3507     // Free up everything used by this instruction.
3508     for (Use &DeadOp : DeadUser->operands())
3509       clobberUse(DeadOp);
3510
3511     // Now replace the uses of this instruction.
3512     DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
3513
3514     // And mark it for deletion.
3515     DeadInsts.insert(DeadUser);
3516     Changed = true;
3517   }
3518   for (Use *DeadOp : AS.getDeadOperands()) {
3519     clobberUse(*DeadOp);
3520     Changed = true;
3521   }
3522
3523   // No slices to split. Leave the dead alloca for a later pass to clean up.
3524   if (AS.begin() == AS.end())
3525     return Changed;
3526
3527   Changed |= splitAlloca(AI, AS);
3528
3529   DEBUG(dbgs() << "  Speculating PHIs\n");
3530   while (!SpeculatablePHIs.empty())
3531     speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
3532
3533   DEBUG(dbgs() << "  Speculating Selects\n");
3534   while (!SpeculatableSelects.empty())
3535     speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
3536
3537   return Changed;
3538 }
3539
3540 /// \brief Delete the dead instructions accumulated in this run.
3541 ///
3542 /// Recursively deletes the dead instructions we've accumulated. This is done
3543 /// at the very end to maximize locality of the recursive delete and to
3544 /// minimize the problems of invalidated instruction pointers as such pointers
3545 /// are used heavily in the intermediate stages of the algorithm.
3546 ///
3547 /// We also record the alloca instructions deleted here so that they aren't
3548 /// subsequently handed to mem2reg to promote.
3549 void SROA::deleteDeadInstructions(
3550     SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
3551   while (!DeadInsts.empty()) {
3552     Instruction *I = DeadInsts.pop_back_val();
3553     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3554
3555     I->replaceAllUsesWith(UndefValue::get(I->getType()));
3556
3557     for (Use &Operand : I->operands())
3558       if (Instruction *U = dyn_cast<Instruction>(Operand)) {
3559         // Zero out the operand and see if it becomes trivially dead.
3560         Operand = nullptr;
3561         if (isInstructionTriviallyDead(U))
3562           DeadInsts.insert(U);
3563       }
3564
3565     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3566       DeletedAllocas.insert(AI);
3567
3568     ++NumDeleted;
3569     I->eraseFromParent();
3570   }
3571 }
3572
3573 static void enqueueUsersInWorklist(Instruction &I,
3574                                    SmallVectorImpl<Instruction *> &Worklist,
3575                                    SmallPtrSetImpl<Instruction *> &Visited) {
3576   for (User *U : I.users())
3577     if (Visited.insert(cast<Instruction>(U)).second)
3578       Worklist.push_back(cast<Instruction>(U));
3579 }
3580
3581 /// \brief Promote the allocas, using the best available technique.
3582 ///
3583 /// This attempts to promote whatever allocas have been identified as viable in
3584 /// the PromotableAllocas list. If that list is empty, there is nothing to do.
3585 /// If there is a domtree available, we attempt to promote using the full power
3586 /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3587 /// based on the SSAUpdater utilities. This function returns whether any
3588 /// promotion occurred.
3589 bool SROA::promoteAllocas(Function &F) {
3590   if (PromotableAllocas.empty())
3591     return false;
3592
3593   NumPromoted += PromotableAllocas.size();
3594
3595   if (DT && !ForceSSAUpdater) {
3596     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3597     PromoteMemToReg(PromotableAllocas, *DT, nullptr, AT);
3598     PromotableAllocas.clear();
3599     return true;
3600   }
3601
3602   DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3603   SSAUpdater SSA;
3604   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
3605   SmallVector<Instruction *, 64> Insts;
3606
3607   // We need a worklist to walk the uses of each alloca.
3608   SmallVector<Instruction *, 8> Worklist;
3609   SmallPtrSet<Instruction *, 8> Visited;
3610   SmallVector<Instruction *, 32> DeadInsts;
3611
3612   for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3613     AllocaInst *AI = PromotableAllocas[Idx];
3614     Insts.clear();
3615     Worklist.clear();
3616     Visited.clear();
3617
3618     enqueueUsersInWorklist(*AI, Worklist, Visited);
3619
3620     while (!Worklist.empty()) {
3621       Instruction *I = Worklist.pop_back_val();
3622
3623       // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3624       // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3625       // leading to them) here. Eventually it should use them to optimize the
3626       // scalar values produced.
3627       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3628         assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3629                II->getIntrinsicID() == Intrinsic::lifetime_end);
3630         II->eraseFromParent();
3631         continue;
3632       }
3633
3634       // Push the loads and stores we find onto the list. SROA will already
3635       // have validated that all loads and stores are viable candidates for
3636       // promotion.
3637       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3638         assert(LI->getType() == AI->getAllocatedType());
3639         Insts.push_back(LI);
3640         continue;
3641       }
3642       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3643         assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
3644         Insts.push_back(SI);
3645         continue;
3646       }
3647
3648       // For everything else, we know that only no-op bitcasts and GEPs will
3649       // make it this far, just recurse through them and recall them for later
3650       // removal.
3651       DeadInsts.push_back(I);
3652       enqueueUsersInWorklist(*I, Worklist, Visited);
3653     }
3654     AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3655     while (!DeadInsts.empty())
3656       DeadInsts.pop_back_val()->eraseFromParent();
3657     AI->eraseFromParent();
3658   }
3659
3660   PromotableAllocas.clear();
3661   return true;
3662 }
3663
3664 bool SROA::runOnFunction(Function &F) {
3665   if (skipOptnoneFunction(F))
3666     return false;
3667
3668   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3669   C = &F.getContext();
3670   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3671   if (!DLP) {
3672     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
3673     return false;
3674   }
3675   DL = &DLP->getDataLayout();
3676   DominatorTreeWrapperPass *DTWP =
3677       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
3678   DT = DTWP ? &DTWP->getDomTree() : nullptr;
3679   AT = &getAnalysis<AssumptionTracker>();
3680
3681   BasicBlock &EntryBB = F.getEntryBlock();
3682   for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
3683        I != E; ++I)
3684     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3685       Worklist.insert(AI);
3686
3687   bool Changed = false;
3688   // A set of deleted alloca instruction pointers which should be removed from
3689   // the list of promotable allocas.
3690   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3691
3692   do {
3693     while (!Worklist.empty()) {
3694       Changed |= runOnAlloca(*Worklist.pop_back_val());
3695       deleteDeadInstructions(DeletedAllocas);
3696
3697       // Remove the deleted allocas from various lists so that we don't try to
3698       // continue processing them.
3699       if (!DeletedAllocas.empty()) {
3700         auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
3701         Worklist.remove_if(IsInSet);
3702         PostPromotionWorklist.remove_if(IsInSet);
3703         PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3704                                                PromotableAllocas.end(),
3705                                                IsInSet),
3706                                 PromotableAllocas.end());
3707         DeletedAllocas.clear();
3708       }
3709     }
3710
3711     Changed |= promoteAllocas(F);
3712
3713     Worklist = PostPromotionWorklist;
3714     PostPromotionWorklist.clear();
3715   } while (!Worklist.empty());
3716
3717   return Changed;
3718 }
3719
3720 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
3721   AU.addRequired<AssumptionTracker>();
3722   if (RequiresDomTree)
3723     AU.addRequired<DominatorTreeWrapperPass>();
3724   AU.setPreservesCFG();
3725 }