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