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