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