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