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