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