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