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