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