958f9b3705f5852300ab5b87e5907770b3ed01a7
[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/Constants.h"
29 #include "llvm/DIBuilder.h"
30 #include "llvm/DebugInfo.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Function.h"
33 #include "llvm/GlobalVariable.h"
34 #include "llvm/IRBuilder.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/LLVMContext.h"
38 #include "llvm/Module.h"
39 #include "llvm/Operator.h"
40 #include "llvm/Pass.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/TinyPtrVector.h"
46 #include "llvm/Analysis/Dominators.h"
47 #include "llvm/Analysis/Loads.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/ValueHandle.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetData.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
60 #include "llvm/Transforms/Utils/SSAUpdater.h"
61 using namespace llvm;
62
63 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
64 STATISTIC(NumNewAllocas,      "Number of new, smaller allocas introduced");
65 STATISTIC(NumPromoted,        "Number of allocas promoted to SSA values");
66 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
67 STATISTIC(NumDeleted,         "Number of instructions deleted");
68 STATISTIC(NumVectorized,      "Number of vectorized aggregates");
69
70 namespace {
71 /// \brief Alloca partitioning representation.
72 ///
73 /// This class represents a partitioning of an alloca into slices, and
74 /// information about the nature of uses of each slice of the alloca. The goal
75 /// is that this information is sufficient to decide if and how to split the
76 /// alloca apart and replace slices with scalars. It is also intended that this
77 /// structure can capture the relevant information needed both to decide about
78 /// and to enact these transformations.
79 class AllocaPartitioning {
80 public:
81   /// \brief A common base class for representing a half-open byte range.
82   struct ByteRange {
83     /// \brief The beginning offset of the range.
84     uint64_t BeginOffset;
85
86     /// \brief The ending offset, not included in the range.
87     uint64_t EndOffset;
88
89     ByteRange() : BeginOffset(), EndOffset() {}
90     ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
91         : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
92
93     /// \brief Support for ordering ranges.
94     ///
95     /// This provides an ordering over ranges such that start offsets are
96     /// always increasing, and within equal start offsets, the end offsets are
97     /// decreasing. Thus the spanning range comes first in a cluster with the
98     /// same start position.
99     bool operator<(const ByteRange &RHS) const {
100       if (BeginOffset < RHS.BeginOffset) return true;
101       if (BeginOffset > RHS.BeginOffset) return false;
102       if (EndOffset > RHS.EndOffset) return true;
103       return false;
104     }
105
106     /// \brief Support comparison with a single offset to allow binary searches.
107     bool operator<(uint64_t RHSOffset) const {
108       return BeginOffset < RHSOffset;
109     }
110
111     bool operator==(const ByteRange &RHS) const {
112       return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
113     }
114     bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
115   };
116
117   /// \brief A partition of an alloca.
118   ///
119   /// This structure represents a contiguous partition of the alloca. These are
120   /// formed by examining the uses of the alloca. During formation, they may
121   /// overlap but once an AllocaPartitioning is built, the Partitions within it
122   /// are all disjoint.
123   struct Partition : public ByteRange {
124     /// \brief Whether this partition is splittable into smaller partitions.
125     ///
126     /// We flag partitions as splittable when they are formed entirely due to
127     /// accesses by trivially splittable operations such as memset and memcpy.
128     ///
129     /// FIXME: At some point we should consider loads and stores of FCAs to be
130     /// splittable and eagerly split them into scalar values.
131     bool IsSplittable;
132
133     Partition() : ByteRange(), IsSplittable() {}
134     Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
135         : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
136   };
137
138   /// \brief A particular use of a partition of the alloca.
139   ///
140   /// This structure is used to associate uses of a partition with it. They
141   /// mark the range of bytes which are referenced by a particular instruction,
142   /// and includes a handle to the user itself and the pointer value in use.
143   /// The bounds of these uses are determined by intersecting the bounds of the
144   /// memory use itself with a particular partition. As a consequence there is
145   /// intentionally overlap between various uses of the same partition.
146   struct PartitionUse : public ByteRange {
147     /// \brief The user of this range of the alloca.
148     AssertingVH<Instruction> User;
149
150     /// \brief The particular pointer value derived from this alloca in use.
151     AssertingVH<Instruction> Ptr;
152
153     PartitionUse() : ByteRange(), User(), Ptr() {}
154     PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
155                  Instruction *User, Instruction *Ptr)
156         : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
157   };
158
159   /// \brief Construct a partitioning of a particular alloca.
160   ///
161   /// Construction does most of the work for partitioning the alloca. This
162   /// performs the necessary walks of users and builds a partitioning from it.
163   AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
164
165   /// \brief Test whether a pointer to the allocation escapes our analysis.
166   ///
167   /// If this is true, the partitioning is never fully built and should be
168   /// ignored.
169   bool isEscaped() const { return PointerEscapingInstr; }
170
171   /// \brief Support for iterating over the partitions.
172   /// @{
173   typedef SmallVectorImpl<Partition>::iterator iterator;
174   iterator begin() { return Partitions.begin(); }
175   iterator end() { return Partitions.end(); }
176
177   typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
178   const_iterator begin() const { return Partitions.begin(); }
179   const_iterator end() const { return Partitions.end(); }
180   /// @}
181
182   /// \brief Support for iterating over and manipulating a particular
183   /// partition's uses.
184   ///
185   /// The iteration support provided for uses is more limited, but also
186   /// includes some manipulation routines to support rewriting the uses of
187   /// partitions during SROA.
188   /// @{
189   typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
190   use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
191   use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
192   use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
193   use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
194   void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
195     Uses[Idx].insert(UI, U);
196   }
197   void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
198     Uses[I - begin()].insert(UI, U);
199   }
200   void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
201   void use_erase(const_iterator I, use_iterator UI) {
202     Uses[I - begin()].erase(UI);
203   }
204
205   typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
206   const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
207   const_use_iterator use_begin(const_iterator I) const {
208     return Uses[I - begin()].begin();
209   }
210   const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
211   const_use_iterator use_end(const_iterator I) const {
212     return Uses[I - begin()].end();
213   }
214   /// @}
215
216   /// \brief Allow iterating the dead users for this alloca.
217   ///
218   /// These are instructions which will never actually use the alloca as they
219   /// are outside the allocated range. They are safe to replace with undef and
220   /// delete.
221   /// @{
222   typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
223   dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
224   dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
225   /// @}
226
227   /// \brief Allow iterating the dead expressions referring to this alloca.
228   ///
229   /// These are operands which have cannot actually be used to refer to the
230   /// alloca as they are outside its range and the user doesn't correct for
231   /// that. These mostly consist of PHI node inputs and the like which we just
232   /// need to replace with undef.
233   /// @{
234   typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
235   dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
236   dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
237   /// @}
238
239   /// \brief MemTransferInst auxiliary data.
240   /// This struct provides some auxiliary data about memory transfer
241   /// intrinsics such as memcpy and memmove. These intrinsics can use two
242   /// different ranges within the same alloca, and provide other challenges to
243   /// correctly represent. We stash extra data to help us untangle this
244   /// after the partitioning is complete.
245   struct MemTransferOffsets {
246     uint64_t DestBegin, DestEnd;
247     uint64_t SourceBegin, SourceEnd;
248     bool IsSplittable;
249   };
250   MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
251     return MemTransferInstData.lookup(&II);
252   }
253
254   /// \brief Map from a PHI or select operand back to a partition.
255   ///
256   /// When manipulating PHI nodes or selects, they can use more than one
257   /// partition of an alloca. We store a special mapping to allow finding the
258   /// partition referenced by each of these operands, if any.
259   iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
260     SmallDenseMap<std::pair<Instruction *, Value *>,
261                   std::pair<unsigned, unsigned> >::const_iterator MapIt
262       = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
263     if (MapIt == PHIOrSelectOpMap.end())
264       return end();
265
266     return begin() + MapIt->second.first;
267   }
268
269   /// \brief Map from a PHI or select operand back to the specific use of
270   /// a partition.
271   ///
272   /// Similar to mapping these operands back to the partitions, this maps
273   /// directly to the use structure of that partition.
274   use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
275                                                      Value *Op) {
276     SmallDenseMap<std::pair<Instruction *, Value *>,
277                   std::pair<unsigned, unsigned> >::const_iterator MapIt
278       = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
279     assert(MapIt != PHIOrSelectOpMap.end());
280     return Uses[MapIt->second.first].begin() + MapIt->second.second;
281   }
282
283   /// \brief Compute a common type among the uses of a particular partition.
284   ///
285   /// This routines walks all of the uses of a particular partition and tries
286   /// to find a common type between them. Untyped operations such as memset and
287   /// memcpy are ignored.
288   Type *getCommonType(iterator I) const;
289
290   void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
291   void printUsers(raw_ostream &OS, const_iterator I,
292                   StringRef Indent = "  ") const;
293   void print(raw_ostream &OS) const;
294   void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
295   void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
296
297 private:
298   template <typename DerivedT, typename RetT = void> class BuilderBase;
299   class PartitionBuilder;
300   friend class AllocaPartitioning::PartitionBuilder;
301   class UseBuilder;
302   friend class AllocaPartitioning::UseBuilder;
303
304   /// \brief Handle to alloca instruction to simplify method interfaces.
305   AllocaInst &AI;
306
307   /// \brief The instruction responsible for this alloca having no partitioning.
308   ///
309   /// When an instruction (potentially) escapes the pointer to the alloca, we
310   /// store a pointer to that here and abort trying to partition the alloca.
311   /// This will be null if the alloca is partitioned successfully.
312   Instruction *PointerEscapingInstr;
313
314   /// \brief The partitions of the alloca.
315   ///
316   /// We store a vector of the partitions over the alloca here. This vector is
317   /// sorted by increasing begin offset, and then by decreasing end offset. See
318   /// the Partition inner class for more details. Initially (during
319   /// construction) there are overlaps, but we form a disjoint sequence of
320   /// partitions while finishing construction and a fully constructed object is
321   /// expected to always have this as a disjoint space.
322   SmallVector<Partition, 8> Partitions;
323
324   /// \brief The uses of the partitions.
325   ///
326   /// This is essentially a mapping from each partition to a list of uses of
327   /// that partition. The mapping is done with a Uses vector that has the exact
328   /// same number of entries as the partition vector. Each entry is itself
329   /// a vector of the uses.
330   SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
331
332   /// \brief Instructions which will become dead if we rewrite the alloca.
333   ///
334   /// Note that these are not separated by partition. This is because we expect
335   /// a partitioned alloca to be completely rewritten or not rewritten at all.
336   /// If rewritten, all these instructions can simply be removed and replaced
337   /// with undef as they come from outside of the allocated space.
338   SmallVector<Instruction *, 8> DeadUsers;
339
340   /// \brief Operands which will become dead if we rewrite the alloca.
341   ///
342   /// These are operands that in their particular use can be replaced with
343   /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
344   /// to PHI nodes and the like. They aren't entirely dead (there might be
345   /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
346   /// want to swap this particular input for undef to simplify the use lists of
347   /// the alloca.
348   SmallVector<Use *, 8> DeadOperands;
349
350   /// \brief The underlying storage for auxiliary memcpy and memset info.
351   SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
352
353   /// \brief A side datastructure used when building up the partitions and uses.
354   ///
355   /// This mapping is only really used during the initial building of the
356   /// partitioning so that we can retain information about PHI and select nodes
357   /// processed.
358   SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
359
360   /// \brief Auxiliary information for particular PHI or select operands.
361   SmallDenseMap<std::pair<Instruction *, Value *>,
362                 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
363
364   /// \brief A utility routine called from the constructor.
365   ///
366   /// This does what it says on the tin. It is the key of the alloca partition
367   /// splitting and merging. After it is called we have the desired disjoint
368   /// collection of partitions.
369   void splitAndMergePartitions();
370 };
371 }
372
373 template <typename DerivedT, typename RetT>
374 class AllocaPartitioning::BuilderBase
375     : public InstVisitor<DerivedT, RetT> {
376 public:
377   BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
378       : TD(TD),
379         AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
380         P(P) {
381     enqueueUsers(AI, 0);
382   }
383
384 protected:
385   const TargetData &TD;
386   const uint64_t AllocSize;
387   AllocaPartitioning &P;
388
389   struct OffsetUse {
390     Use *U;
391     uint64_t Offset;
392   };
393   SmallVector<OffsetUse, 8> Queue;
394
395   // The active offset and use while visiting.
396   Use *U;
397   uint64_t Offset;
398
399   void enqueueUsers(Instruction &I, uint64_t UserOffset) {
400     SmallPtrSet<User *, 8> UserSet;
401     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
402          UI != UE; ++UI) {
403       if (!UserSet.insert(*UI))
404         continue;
405
406       OffsetUse OU = { &UI.getUse(), UserOffset };
407       Queue.push_back(OU);
408     }
409   }
410
411   bool computeConstantGEPOffset(GetElementPtrInst &GEPI, uint64_t &GEPOffset) {
412     GEPOffset = Offset;
413     for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
414          GTI != GTE; ++GTI) {
415       ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
416       if (!OpC)
417         return false;
418       if (OpC->isZero())
419         continue;
420
421       // Handle a struct index, which adds its field offset to the pointer.
422       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
423         unsigned ElementIdx = OpC->getZExtValue();
424         const StructLayout *SL = TD.getStructLayout(STy);
425         GEPOffset += SL->getElementOffset(ElementIdx);
426         continue;
427       }
428
429       GEPOffset
430         += OpC->getZExtValue() * TD.getTypeAllocSize(GTI.getIndexedType());
431     }
432     return true;
433   }
434
435   Value *foldSelectInst(SelectInst &SI) {
436     // If the condition being selected on is a constant or the same value is
437     // being selected between, fold the select. Yes this does (rarely) happen
438     // early on.
439     if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
440       return SI.getOperand(1+CI->isZero());
441     if (SI.getOperand(1) == SI.getOperand(2)) {
442       assert(*U == SI.getOperand(1));
443       return SI.getOperand(1);
444     }
445     return 0;
446   }
447 };
448
449 /// \brief Builder for the alloca partitioning.
450 ///
451 /// This class builds an alloca partitioning by recursively visiting the uses
452 /// of an alloca and splitting the partitions for each load and store at each
453 /// offset.
454 class AllocaPartitioning::PartitionBuilder
455     : public BuilderBase<PartitionBuilder, bool> {
456   friend class InstVisitor<PartitionBuilder, bool>;
457
458   SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
459
460 public:
461   PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
462       : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
463
464   /// \brief Run the builder over the allocation.
465   bool operator()() {
466     // Note that we have to re-evaluate size on each trip through the loop as
467     // the queue grows at the tail.
468     for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
469       U = Queue[Idx].U;
470       Offset = Queue[Idx].Offset;
471       if (!visit(cast<Instruction>(U->getUser())))
472         return false;
473     }
474     return true;
475   }
476
477 private:
478   bool markAsEscaping(Instruction &I) {
479     P.PointerEscapingInstr = &I;
480     return false;
481   }
482
483   void insertUse(Instruction &I, uint64_t Size, bool IsSplittable = false) {
484     uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
485
486     // Completely skip uses which start outside of the allocation.
487     if (BeginOffset >= AllocSize) {
488       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
489                    << " which starts past the end of the " << AllocSize
490                    << " byte alloca:\n"
491                    << "    alloca: " << P.AI << "\n"
492                    << "       use: " << I << "\n");
493       return;
494     }
495
496     // Clamp the size to the allocation.
497     if (EndOffset > AllocSize) {
498       DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
499                    << " to remain within the " << AllocSize << " byte alloca:\n"
500                    << "    alloca: " << P.AI << "\n"
501                    << "       use: " << I << "\n");
502       EndOffset = AllocSize;
503     }
504
505     // See if we can just add a user onto the last slot currently occupied.
506     if (!P.Partitions.empty() &&
507         P.Partitions.back().BeginOffset == BeginOffset &&
508         P.Partitions.back().EndOffset == EndOffset) {
509       P.Partitions.back().IsSplittable &= IsSplittable;
510       return;
511     }
512
513     Partition New(BeginOffset, EndOffset, IsSplittable);
514     P.Partitions.push_back(New);
515   }
516
517   bool handleLoadOrStore(Type *Ty, Instruction &I) {
518     uint64_t Size = TD.getTypeStoreSize(Ty);
519
520     // If this memory access can be shown to *statically* extend outside the
521     // bounds of of the allocation, it's behavior is undefined, so simply
522     // ignore it. Note that this is more strict than the generic clamping
523     // behavior of insertUse. We also try to handle cases which might run the
524     // risk of overflow.
525     // FIXME: We should instead consider the pointer to have escaped if this
526     // function is being instrumented for addressing bugs or race conditions.
527     if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
528       DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
529                    << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
530                    << " which extends past the end of the " << AllocSize
531                    << " byte alloca:\n"
532                    << "    alloca: " << P.AI << "\n"
533                    << "       use: " << I << "\n");
534       return true;
535     }
536
537     insertUse(I, Size);
538     return true;
539   }
540
541   bool visitBitCastInst(BitCastInst &BC) {
542     enqueueUsers(BC, Offset);
543     return true;
544   }
545
546   bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
547     //unsigned IntPtrWidth = TD->getPointerSizeInBits();
548     //assert(IntPtrWidth == Offset.getBitWidth());
549     uint64_t GEPOffset;
550     if (!computeConstantGEPOffset(GEPI, GEPOffset))
551       return markAsEscaping(GEPI);
552
553     enqueueUsers(GEPI, GEPOffset);
554     return true;
555   }
556
557   bool visitLoadInst(LoadInst &LI) {
558     return handleLoadOrStore(LI.getType(), LI);
559   }
560
561   bool visitStoreInst(StoreInst &SI) {
562     if (SI.getOperand(0) == *U)
563       return markAsEscaping(SI);
564
565     return handleLoadOrStore(SI.getOperand(0)->getType(), SI);
566   }
567
568
569   bool visitMemSetInst(MemSetInst &II) {
570     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
571     insertUse(II, Length ? Length->getZExtValue() : AllocSize - Offset, Length);
572     return true;
573   }
574
575   bool visitMemTransferInst(MemTransferInst &II) {
576     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
577     uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
578     if (!Size)
579       // Zero-length mem transfer intrinsics can be ignored entirely.
580       return true;
581
582     MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
583
584     // Only intrinsics with a constant length can be split.
585     Offsets.IsSplittable = Length;
586
587     if (*U != II.getRawDest()) {
588       assert(*U == II.getRawSource());
589       Offsets.SourceBegin = Offset;
590       Offsets.SourceEnd = Offset + Size;
591     } else {
592       Offsets.DestBegin = Offset;
593       Offsets.DestEnd = Offset + Size;
594     }
595
596     insertUse(II, Size, Offsets.IsSplittable);
597     unsigned NewIdx = P.Partitions.size() - 1;
598
599     SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
600     bool Inserted = false;
601     llvm::tie(PMI, Inserted)
602       = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
603     if (!Inserted && Offsets.IsSplittable) {
604       // We've found a memory transfer intrinsic which refers to the alloca as
605       // both a source and dest. We refuse to split these to simplify splitting
606       // logic. If possible, SROA will still split them into separate allocas
607       // and then re-analyze.
608       Offsets.IsSplittable = false;
609       P.Partitions[PMI->second].IsSplittable = false;
610       P.Partitions[NewIdx].IsSplittable = false;
611     }
612
613     return true;
614   }
615
616   // Disable SRoA for any intrinsics except for lifetime invariants.
617   bool visitIntrinsicInst(IntrinsicInst &II) {
618     if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
619         II.getIntrinsicID() == Intrinsic::lifetime_end) {
620       ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
621       uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
622       insertUse(II, Size, true);
623       return true;
624     }
625
626     return markAsEscaping(II);
627   }
628
629   Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
630     // We consider any PHI or select that results in a direct load or store of
631     // the same offset to be a viable use for partitioning purposes. These uses
632     // are considered unsplittable and the size is the maximum loaded or stored
633     // size.
634     SmallPtrSet<Instruction *, 4> Visited;
635     SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
636     Visited.insert(Root);
637     Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
638     do {
639       Instruction *I, *UsedI;
640       llvm::tie(UsedI, I) = Uses.pop_back_val();
641
642       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
643         Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
644         continue;
645       }
646       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
647         Value *Op = SI->getOperand(0);
648         if (Op == UsedI)
649           return SI;
650         Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
651         continue;
652       }
653
654       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
655         if (!GEP->hasAllZeroIndices())
656           return GEP;
657       } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
658                  !isa<SelectInst>(I)) {
659         return I;
660       }
661
662       for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
663            ++UI)
664         if (Visited.insert(cast<Instruction>(*UI)))
665           Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
666     } while (!Uses.empty());
667
668     return 0;
669   }
670
671   bool visitPHINode(PHINode &PN) {
672     // See if we already have computed info on this node.
673     std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
674     if (PHIInfo.first) {
675       PHIInfo.second = true;
676       insertUse(PN, PHIInfo.first);
677       return true;
678     }
679
680     // Check for an unsafe use of the PHI node.
681     if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
682       return markAsEscaping(*EscapingI);
683
684     insertUse(PN, PHIInfo.first);
685     return true;
686   }
687
688   bool visitSelectInst(SelectInst &SI) {
689     if (Value *Result = foldSelectInst(SI)) {
690       if (Result == *U)
691         // If the result of the constant fold will be the pointer, recurse
692         // through the select as if we had RAUW'ed it.
693         enqueueUsers(SI, Offset);
694
695       return true;
696     }
697
698     // See if we already have computed info on this node.
699     std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
700     if (SelectInfo.first) {
701       SelectInfo.second = true;
702       insertUse(SI, SelectInfo.first);
703       return true;
704     }
705
706     // Check for an unsafe use of the PHI node.
707     if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
708       return markAsEscaping(*EscapingI);
709
710     insertUse(SI, SelectInfo.first);
711     return true;
712   }
713
714   /// \brief Disable SROA entirely if there are unhandled users of the alloca.
715   bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
716 };
717
718
719 /// \brief Use adder for the alloca partitioning.
720 ///
721 /// This class adds the uses of an alloca to all of the partitions which they
722 /// use. For splittable partitions, this can end up doing essentially a linear
723 /// walk of the partitions, but the number of steps remains bounded by the
724 /// total result instruction size:
725 /// - The number of partitions is a result of the number unsplittable
726 ///   instructions using the alloca.
727 /// - The number of users of each partition is at worst the total number of
728 ///   splittable instructions using the alloca.
729 /// Thus we will produce N * M instructions in the end, where N are the number
730 /// of unsplittable uses and M are the number of splittable. This visitor does
731 /// the exact same number of updates to the partitioning.
732 ///
733 /// In the more common case, this visitor will leverage the fact that the
734 /// partition space is pre-sorted, and do a logarithmic search for the
735 /// partition needed, making the total visit a classical ((N + M) * log(N))
736 /// complexity operation.
737 class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
738   friend class InstVisitor<UseBuilder>;
739
740   /// \brief Set to de-duplicate dead instructions found in the use walk.
741   SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
742
743 public:
744   UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
745       : BuilderBase<UseBuilder>(TD, AI, P) {}
746
747   /// \brief Run the builder over the allocation.
748   void operator()() {
749     // Note that we have to re-evaluate size on each trip through the loop as
750     // the queue grows at the tail.
751     for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
752       U = Queue[Idx].U;
753       Offset = Queue[Idx].Offset;
754       this->visit(cast<Instruction>(U->getUser()));
755     }
756   }
757
758 private:
759   void markAsDead(Instruction &I) {
760     if (VisitedDeadInsts.insert(&I))
761       P.DeadUsers.push_back(&I);
762   }
763
764   void insertUse(uint64_t Size, Instruction &User) {
765     uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
766
767     // If the use extends outside of the allocation, record it as a dead use
768     // for elimination later.
769     if (BeginOffset >= AllocSize || Size == 0)
770       return markAsDead(User);
771
772     // Bound the use by the size of the allocation.
773     if (EndOffset > AllocSize)
774       EndOffset = AllocSize;
775
776     // NB: This only works if we have zero overlapping partitions.
777     iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
778     if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
779       B = llvm::prior(B);
780     for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
781          ++I) {
782       PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
783                           std::min(I->EndOffset, EndOffset),
784                           &User, cast<Instruction>(*U));
785       P.Uses[I - P.begin()].push_back(NewUse);
786       if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
787         P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
788           = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
789     }
790   }
791
792   void handleLoadOrStore(Type *Ty, Instruction &I) {
793     uint64_t Size = TD.getTypeStoreSize(Ty);
794
795     // If this memory access can be shown to *statically* extend outside the
796     // bounds of of the allocation, it's behavior is undefined, so simply
797     // ignore it. Note that this is more strict than the generic clamping
798     // behavior of insertUse.
799     if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
800       return markAsDead(I);
801
802     insertUse(Size, I);
803   }
804
805   void visitBitCastInst(BitCastInst &BC) {
806     if (BC.use_empty())
807       return markAsDead(BC);
808
809     enqueueUsers(BC, Offset);
810   }
811
812   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
813     if (GEPI.use_empty())
814       return markAsDead(GEPI);
815
816     //unsigned IntPtrWidth = TD->getPointerSizeInBits();
817     //assert(IntPtrWidth == Offset.getBitWidth());
818     uint64_t GEPOffset;
819     if (!computeConstantGEPOffset(GEPI, GEPOffset))
820       llvm_unreachable("Unable to compute constant offset for use");
821
822     enqueueUsers(GEPI, GEPOffset);
823   }
824
825   void visitLoadInst(LoadInst &LI) {
826     handleLoadOrStore(LI.getType(), LI);
827   }
828
829   void visitStoreInst(StoreInst &SI) {
830     handleLoadOrStore(SI.getOperand(0)->getType(), SI);
831   }
832
833   void visitMemSetInst(MemSetInst &II) {
834     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
835     insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
836   }
837
838   void visitMemTransferInst(MemTransferInst &II) {
839     ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
840     insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
841   }
842
843   void visitIntrinsicInst(IntrinsicInst &II) {
844     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
845            II.getIntrinsicID() == Intrinsic::lifetime_end);
846
847     ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
848     insertUse(std::min(AllocSize - Offset, Length->getLimitedValue()), II);
849   }
850
851   void insertPHIOrSelect(Instruction &User) {
852     uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
853
854     // For PHI and select operands outside the alloca, we can't nuke the entire
855     // phi or select -- the other side might still be relevant, so we special
856     // case them here and use a separate structure to track the operands
857     // themselves which should be replaced with undef.
858     if (Offset >= AllocSize) {
859       P.DeadOperands.push_back(U);
860       return;
861     }
862
863     insertUse(Size, User);
864   }
865   void visitPHINode(PHINode &PN) {
866     if (PN.use_empty())
867       return markAsDead(PN);
868
869     insertPHIOrSelect(PN);
870   }
871   void visitSelectInst(SelectInst &SI) {
872     if (SI.use_empty())
873       return markAsDead(SI);
874
875     if (Value *Result = foldSelectInst(SI)) {
876       if (Result == *U)
877         // If the result of the constant fold will be the pointer, recurse
878         // through the select as if we had RAUW'ed it.
879         enqueueUsers(SI, Offset);
880
881       return;
882     }
883
884     insertPHIOrSelect(SI);
885   }
886
887   /// \brief Unreachable, we've already visited the alloca once.
888   void visitInstruction(Instruction &I) {
889     llvm_unreachable("Unhandled instruction in use builder.");
890   }
891 };
892
893 void AllocaPartitioning::splitAndMergePartitions() {
894   size_t NumDeadPartitions = 0;
895
896   // Track the range of splittable partitions that we pass when accumulating
897   // overlapping unsplittable partitions.
898   uint64_t SplitEndOffset = 0ull;
899
900   Partition New(0ull, 0ull, false);
901
902   for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
903     ++j;
904
905     if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
906       assert(New.BeginOffset == New.EndOffset);
907       New = Partitions[i];
908     } else {
909       assert(New.IsSplittable);
910       New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
911     }
912     assert(New.BeginOffset != New.EndOffset);
913
914     // Scan the overlapping partitions.
915     while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
916       // If the new partition we are forming is splittable, stop at the first
917       // unsplittable partition.
918       if (New.IsSplittable && !Partitions[j].IsSplittable)
919         break;
920
921       // Grow the new partition to include any equally splittable range. 'j' is
922       // always equally splittable when New is splittable, but when New is not
923       // splittable, we may subsume some (or part of some) splitable partition
924       // without growing the new one.
925       if (New.IsSplittable == Partitions[j].IsSplittable) {
926         New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
927       } else {
928         assert(!New.IsSplittable);
929         assert(Partitions[j].IsSplittable);
930         SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
931       }
932
933       Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
934       ++NumDeadPartitions;
935       ++j;
936     }
937
938     // If the new partition is splittable, chop off the end as soon as the
939     // unsplittable subsequent partition starts and ensure we eventually cover
940     // the splittable area.
941     if (j != e && New.IsSplittable) {
942       SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
943       New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
944     }
945
946     // Add the new partition if it differs from the original one and is
947     // non-empty. We can end up with an empty partition here if it was
948     // splittable but there is an unsplittable one that starts at the same
949     // offset.
950     if (New != Partitions[i]) {
951       if (New.BeginOffset != New.EndOffset)
952         Partitions.push_back(New);
953       // Mark the old one for removal.
954       Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
955       ++NumDeadPartitions;
956     }
957
958     New.BeginOffset = New.EndOffset;
959     if (!New.IsSplittable) {
960       New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
961       if (j != e && !Partitions[j].IsSplittable)
962         New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
963       New.IsSplittable = true;
964       // If there is a trailing splittable partition which won't be fused into
965       // the next splittable partition go ahead and add it onto the partitions
966       // list.
967       if (New.BeginOffset < New.EndOffset &&
968           (j == e || !Partitions[j].IsSplittable ||
969            New.EndOffset < Partitions[j].BeginOffset)) {
970         Partitions.push_back(New);
971         New.BeginOffset = New.EndOffset = 0ull;
972       }
973     }
974   }
975
976   // Re-sort the partitions now that they have been split and merged into
977   // disjoint set of partitions. Also remove any of the dead partitions we've
978   // replaced in the process.
979   std::sort(Partitions.begin(), Partitions.end());
980   if (NumDeadPartitions) {
981     assert(Partitions.back().BeginOffset == UINT64_MAX);
982     assert(Partitions.back().EndOffset == UINT64_MAX);
983     assert((ptrdiff_t)NumDeadPartitions ==
984            std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
985   }
986   Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
987 }
988
989 AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
990     : AI(AI), PointerEscapingInstr(0) {
991   PartitionBuilder PB(TD, AI, *this);
992   if (!PB())
993     return;
994
995   if (Partitions.size() > 1) {
996     // Sort the uses. This arranges for the offsets to be in ascending order,
997     // and the sizes to be in descending order.
998     std::sort(Partitions.begin(), Partitions.end());
999
1000     // Intersect splittability for all partitions with equal offsets and sizes.
1001     // Then remove all but the first so that we have a sequence of non-equal but
1002     // potentially overlapping partitions.
1003     for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1004          I = J) {
1005       ++J;
1006       while (J != E && *I == *J) {
1007         I->IsSplittable &= J->IsSplittable;
1008         ++J;
1009       }
1010     }
1011     Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1012                      Partitions.end());
1013
1014     // Split splittable and merge unsplittable partitions into a disjoint set
1015     // of partitions over the used space of the allocation.
1016     splitAndMergePartitions();
1017   }
1018
1019   // Now build up the user lists for each of these disjoint partitions by
1020   // re-walking the recursive users of the alloca.
1021   Uses.resize(Partitions.size());
1022   UseBuilder UB(TD, AI, *this);
1023   UB();
1024   for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1025     std::stable_sort(use_begin(I), use_end(I));
1026 }
1027
1028 Type *AllocaPartitioning::getCommonType(iterator I) const {
1029   Type *Ty = 0;
1030   for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1031     if (isa<MemIntrinsic>(*UI->User))
1032       continue;
1033     if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1034       break;
1035
1036     Type *UserTy = 0;
1037     if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1038       UserTy = LI->getType();
1039     } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1040       UserTy = SI->getValueOperand()->getType();
1041     } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1042       if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1043         UserTy = PtrTy->getElementType();
1044     } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1045       if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1046         UserTy = PtrTy->getElementType();
1047     }
1048
1049     if (Ty && Ty != UserTy)
1050       return 0;
1051
1052     Ty = UserTy;
1053   }
1054   return Ty;
1055 }
1056
1057 void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1058                                StringRef Indent) const {
1059   OS << Indent << "partition #" << (I - begin())
1060      << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1061      << (I->IsSplittable ? " (splittable)" : "")
1062      << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1063      << "\n";
1064 }
1065
1066 void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1067                                     StringRef Indent) const {
1068   for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1069        UI != UE; ++UI) {
1070     OS << Indent << "  [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1071        << "used by: " << *UI->User << "\n";
1072     if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1073       const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1074       bool IsDest;
1075       if (!MTO.IsSplittable)
1076         IsDest = UI->BeginOffset == MTO.DestBegin;
1077       else
1078         IsDest = MTO.DestBegin != 0u;
1079       OS << Indent << "    (original " << (IsDest ? "dest" : "source") << ": "
1080          << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1081          << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1082     }
1083   }
1084 }
1085
1086 void AllocaPartitioning::print(raw_ostream &OS) const {
1087   if (PointerEscapingInstr) {
1088     OS << "No partitioning for alloca: " << AI << "\n"
1089        << "  A pointer to this alloca escaped by:\n"
1090        << "  " << *PointerEscapingInstr << "\n";
1091     return;
1092   }
1093
1094   OS << "Partitioning of alloca: " << AI << "\n";
1095   unsigned Num = 0;
1096   for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1097     print(OS, I);
1098     printUsers(OS, I);
1099   }
1100 }
1101
1102 void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1103 void AllocaPartitioning::dump() const { print(dbgs()); }
1104
1105
1106 namespace {
1107 /// \brief An optimization pass providing Scalar Replacement of Aggregates.
1108 ///
1109 /// This pass takes allocations which can be completely analyzed (that is, they
1110 /// don't escape) and tries to turn them into scalar SSA values. There are
1111 /// a few steps to this process.
1112 ///
1113 /// 1) It takes allocations of aggregates and analyzes the ways in which they
1114 ///    are used to try to split them into smaller allocations, ideally of
1115 ///    a single scalar data type. It will split up memcpy and memset accesses
1116 ///    as necessary and try to isolate invidual scalar accesses.
1117 /// 2) It will transform accesses into forms which are suitable for SSA value
1118 ///    promotion. This can be replacing a memset with a scalar store of an
1119 ///    integer value, or it can involve speculating operations on a PHI or
1120 ///    select to be a PHI or select of the results.
1121 /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1122 ///    onto insert and extract operations on a vector value, and convert them to
1123 ///    this form. By doing so, it will enable promotion of vector aggregates to
1124 ///    SSA vector values.
1125 class SROA : public FunctionPass {
1126   LLVMContext *C;
1127   const TargetData *TD;
1128   DominatorTree *DT;
1129
1130   /// \brief Worklist of alloca instructions to simplify.
1131   ///
1132   /// Each alloca in the function is added to this. Each new alloca formed gets
1133   /// added to it as well to recursively simplify unless that alloca can be
1134   /// directly promoted. Finally, each time we rewrite a use of an alloca other
1135   /// the one being actively rewritten, we add it back onto the list if not
1136   /// already present to ensure it is re-visited.
1137   SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1138
1139   /// \brief A collection of instructions to delete.
1140   /// We try to batch deletions to simplify code and make things a bit more
1141   /// efficient.
1142   SmallVector<Instruction *, 8> DeadInsts;
1143
1144   /// \brief A set to prevent repeatedly marking an instruction split into many
1145   /// uses as dead. Only used to guard insertion into DeadInsts.
1146   SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1147
1148   /// \brief A set of deleted alloca instructions.
1149   ///
1150   /// These pointers are *no longer valid* as they have been deleted. They are
1151   /// used to remove deleted allocas from the list of promotable allocas.
1152   SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
1153
1154   /// \brief A collection of alloca instructions we can directly promote.
1155   std::vector<AllocaInst *> PromotableAllocas;
1156
1157 public:
1158   SROA() : FunctionPass(ID), C(0), TD(0), DT(0) {
1159     initializeSROAPass(*PassRegistry::getPassRegistry());
1160   }
1161   bool runOnFunction(Function &F);
1162   void getAnalysisUsage(AnalysisUsage &AU) const;
1163
1164   const char *getPassName() const { return "SROA"; }
1165   static char ID;
1166
1167 private:
1168   friend class AllocaPartitionRewriter;
1169   friend class AllocaPartitionVectorRewriter;
1170
1171   bool rewriteAllocaPartition(AllocaInst &AI,
1172                               AllocaPartitioning &P,
1173                               AllocaPartitioning::iterator PI);
1174   bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1175   bool runOnAlloca(AllocaInst &AI);
1176   void deleteDeadInstructions();
1177 };
1178 }
1179
1180 char SROA::ID = 0;
1181
1182 FunctionPass *llvm::createSROAPass() {
1183   return new SROA();
1184 }
1185
1186 INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1187                       false, false)
1188 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1189 INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1190                     false, false)
1191
1192 /// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1193 ///
1194 /// If the provided GEP is all-constant, the total byte offset formed by the
1195 /// GEP is computed and Offset is set to it. If the GEP has any non-constant
1196 /// operands, the function returns false and the value of Offset is unmodified.
1197 static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1198                                  APInt &Offset) {
1199   APInt GEPOffset(Offset.getBitWidth(), 0);
1200   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1201        GTI != GTE; ++GTI) {
1202     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1203     if (!OpC)
1204       return false;
1205     if (OpC->isZero()) continue;
1206
1207     // Handle a struct index, which adds its field offset to the pointer.
1208     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1209       unsigned ElementIdx = OpC->getZExtValue();
1210       const StructLayout *SL = TD.getStructLayout(STy);
1211       GEPOffset += APInt(Offset.getBitWidth(),
1212                          SL->getElementOffset(ElementIdx));
1213       continue;
1214     }
1215
1216     APInt TypeSize(Offset.getBitWidth(),
1217                    TD.getTypeAllocSize(GTI.getIndexedType()));
1218     if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1219       assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1220              "vector element size is not a multiple of 8, cannot GEP over it");
1221       TypeSize = VTy->getScalarSizeInBits() / 8;
1222     }
1223
1224     GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1225   }
1226   Offset = GEPOffset;
1227   return true;
1228 }
1229
1230 /// \brief Build a GEP out of a base pointer and indices.
1231 ///
1232 /// This will return the BasePtr if that is valid, or build a new GEP
1233 /// instruction using the IRBuilder if GEP-ing is needed.
1234 static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1235                        SmallVectorImpl<Value *> &Indices,
1236                        const Twine &Prefix) {
1237   if (Indices.empty())
1238     return BasePtr;
1239
1240   // A single zero index is a no-op, so check for this and avoid building a GEP
1241   // in that case.
1242   if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1243     return BasePtr;
1244
1245   return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1246 }
1247
1248 /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1249 /// TargetTy without changing the offset of the pointer.
1250 ///
1251 /// This routine assumes we've already established a properly offset GEP with
1252 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1253 /// zero-indices down through type layers until we find one the same as
1254 /// TargetTy. If we can't find one with the same type, we at least try to use
1255 /// one with the same size. If none of that works, we just produce the GEP as
1256 /// indicated by Indices to have the correct offset.
1257 static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1258                                     Value *BasePtr, Type *Ty, Type *TargetTy,
1259                                     SmallVectorImpl<Value *> &Indices,
1260                                     const Twine &Prefix) {
1261   if (Ty == TargetTy)
1262     return buildGEP(IRB, BasePtr, Indices, Prefix);
1263
1264   // See if we can descend into a struct and locate a field with the correct
1265   // type.
1266   unsigned NumLayers = 0;
1267   Type *ElementTy = Ty;
1268   do {
1269     if (ElementTy->isPointerTy())
1270       break;
1271     if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1272       ElementTy = SeqTy->getElementType();
1273       Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1274     } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1275       ElementTy = *STy->element_begin();
1276       Indices.push_back(IRB.getInt32(0));
1277     } else {
1278       break;
1279     }
1280     ++NumLayers;
1281   } while (ElementTy != TargetTy);
1282   if (ElementTy != TargetTy)
1283     Indices.erase(Indices.end() - NumLayers, Indices.end());
1284
1285   return buildGEP(IRB, BasePtr, Indices, Prefix);
1286 }
1287
1288 /// \brief Recursively compute indices for a natural GEP.
1289 ///
1290 /// This is the recursive step for getNaturalGEPWithOffset that walks down the
1291 /// element types adding appropriate indices for the GEP.
1292 static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1293                                        Value *Ptr, Type *Ty, APInt &Offset,
1294                                        Type *TargetTy,
1295                                        SmallVectorImpl<Value *> &Indices,
1296                                        const Twine &Prefix) {
1297   if (Offset == 0)
1298     return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1299
1300   // We can't recurse through pointer types.
1301   if (Ty->isPointerTy())
1302     return 0;
1303
1304   if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1305     unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1306     if (ElementSizeInBits % 8)
1307       return 0; // GEPs over multiple of 8 size vector elements are invalid.
1308     APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1309     APInt NumSkippedElements = Offset.udiv(ElementSize);
1310     if (NumSkippedElements.ugt(VecTy->getNumElements()))
1311       return 0;
1312     Offset -= NumSkippedElements * ElementSize;
1313     Indices.push_back(IRB.getInt(NumSkippedElements));
1314     return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1315                                     Offset, TargetTy, Indices, Prefix);
1316   }
1317
1318   if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1319     Type *ElementTy = ArrTy->getElementType();
1320     APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1321     APInt NumSkippedElements = Offset.udiv(ElementSize);
1322     if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1323       return 0;
1324
1325     Offset -= NumSkippedElements * ElementSize;
1326     Indices.push_back(IRB.getInt(NumSkippedElements));
1327     return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1328                                     Indices, Prefix);
1329   }
1330
1331   StructType *STy = dyn_cast<StructType>(Ty);
1332   if (!STy)
1333     return 0;
1334
1335   const StructLayout *SL = TD.getStructLayout(STy);
1336   uint64_t StructOffset = Offset.getZExtValue();
1337   if (StructOffset > SL->getSizeInBytes())
1338     return 0;
1339   unsigned Index = SL->getElementContainingOffset(StructOffset);
1340   Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1341   Type *ElementTy = STy->getElementType(Index);
1342   if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1343     return 0; // The offset points into alignment padding.
1344
1345   Indices.push_back(IRB.getInt32(Index));
1346   return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1347                                   Indices, Prefix);
1348 }
1349
1350 /// \brief Get a natural GEP from a base pointer to a particular offset and
1351 /// resulting in a particular type.
1352 ///
1353 /// The goal is to produce a "natural" looking GEP that works with the existing
1354 /// composite types to arrive at the appropriate offset and element type for
1355 /// a pointer. TargetTy is the element type the returned GEP should point-to if
1356 /// possible. We recurse by decreasing Offset, adding the appropriate index to
1357 /// Indices, and setting Ty to the result subtype.
1358 ///
1359 /// If no natural GEP can be constructed, this function returns null.
1360 static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1361                                       Value *Ptr, APInt Offset, Type *TargetTy,
1362                                       SmallVectorImpl<Value *> &Indices,
1363                                       const Twine &Prefix) {
1364   PointerType *Ty = cast<PointerType>(Ptr->getType());
1365
1366   // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1367   // an i8.
1368   if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1369     return 0;
1370
1371   Type *ElementTy = Ty->getElementType();
1372   APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1373   if (ElementSize == 0)
1374     return 0; // Zero-length arrays can't help us build a natural GEP.
1375   APInt NumSkippedElements = Offset.udiv(ElementSize);
1376
1377   Offset -= NumSkippedElements * ElementSize;
1378   Indices.push_back(IRB.getInt(NumSkippedElements));
1379   return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1380                                   Indices, Prefix);
1381 }
1382
1383 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1384 /// resulting pointer has PointerTy.
1385 ///
1386 /// This tries very hard to compute a "natural" GEP which arrives at the offset
1387 /// and produces the pointer type desired. Where it cannot, it will try to use
1388 /// the natural GEP to arrive at the offset and bitcast to the type. Where that
1389 /// fails, it will try to use an existing i8* and GEP to the byte offset and
1390 /// bitcast to the type.
1391 ///
1392 /// The strategy for finding the more natural GEPs is to peel off layers of the
1393 /// pointer, walking back through bit casts and GEPs, searching for a base
1394 /// pointer from which we can compute a natural GEP with the desired
1395 /// properities. The algorithm tries to fold as many constant indices into
1396 /// a single GEP as possible, thus making each GEP more independent of the
1397 /// surrounding code.
1398 static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1399                              Value *Ptr, APInt Offset, Type *PointerTy,
1400                              const Twine &Prefix) {
1401   // Even though we don't look through PHI nodes, we could be called on an
1402   // instruction in an unreachable block, which may be on a cycle.
1403   SmallPtrSet<Value *, 4> Visited;
1404   Visited.insert(Ptr);
1405   SmallVector<Value *, 4> Indices;
1406
1407   // We may end up computing an offset pointer that has the wrong type. If we
1408   // never are able to compute one directly that has the correct type, we'll
1409   // fall back to it, so keep it around here.
1410   Value *OffsetPtr = 0;
1411
1412   // Remember any i8 pointer we come across to re-use if we need to do a raw
1413   // byte offset.
1414   Value *Int8Ptr = 0;
1415   APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1416
1417   Type *TargetTy = PointerTy->getPointerElementType();
1418
1419   do {
1420     // First fold any existing GEPs into the offset.
1421     while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1422       APInt GEPOffset(Offset.getBitWidth(), 0);
1423       if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1424         break;
1425       Offset += GEPOffset;
1426       Ptr = GEP->getPointerOperand();
1427       if (!Visited.insert(Ptr))
1428         break;
1429     }
1430
1431     // See if we can perform a natural GEP here.
1432     Indices.clear();
1433     if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1434                                            Indices, Prefix)) {
1435       if (P->getType() == PointerTy) {
1436         // Zap any offset pointer that we ended up computing in previous rounds.
1437         if (OffsetPtr && OffsetPtr->use_empty())
1438           if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1439             I->eraseFromParent();
1440         return P;
1441       }
1442       if (!OffsetPtr) {
1443         OffsetPtr = P;
1444       }
1445     }
1446
1447     // Stash this pointer if we've found an i8*.
1448     if (Ptr->getType()->isIntegerTy(8)) {
1449       Int8Ptr = Ptr;
1450       Int8PtrOffset = Offset;
1451     }
1452
1453     // Peel off a layer of the pointer and update the offset appropriately.
1454     if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1455       Ptr = cast<Operator>(Ptr)->getOperand(0);
1456     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1457       if (GA->mayBeOverridden())
1458         break;
1459       Ptr = GA->getAliasee();
1460     } else {
1461       break;
1462     }
1463     assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1464   } while (Visited.insert(Ptr));
1465
1466   if (!OffsetPtr) {
1467     if (!Int8Ptr) {
1468       Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1469                                   Prefix + ".raw_cast");
1470       Int8PtrOffset = Offset;
1471     }
1472
1473     OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1474       IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1475                             Prefix + ".raw_idx");
1476   }
1477   Ptr = OffsetPtr;
1478
1479   // On the off chance we were targeting i8*, guard the bitcast here.
1480   if (Ptr->getType() != PointerTy)
1481     Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1482
1483   return Ptr;
1484 }
1485
1486 /// \brief Test whether the given alloca partition can be promoted to a vector.
1487 ///
1488 /// This is a quick test to check whether we can rewrite a particular alloca
1489 /// partition (and its newly formed alloca) into a vector alloca with only
1490 /// whole-vector loads and stores such that it could be promoted to a vector
1491 /// SSA value. We only can ensure this for a limited set of operations, and we
1492 /// don't want to do the rewrites unless we are confident that the result will
1493 /// be promotable, so we have an early test here.
1494 static bool isVectorPromotionViable(const TargetData &TD,
1495                                     Type *AllocaTy,
1496                                     AllocaPartitioning &P,
1497                                     uint64_t PartitionBeginOffset,
1498                                     uint64_t PartitionEndOffset,
1499                                     AllocaPartitioning::const_use_iterator I,
1500                                     AllocaPartitioning::const_use_iterator E) {
1501   VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1502   if (!Ty)
1503     return false;
1504
1505   uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1506   uint64_t ElementSize = Ty->getScalarSizeInBits();
1507
1508   // While the definition of LLVM vectors is bitpacked, we don't support sizes
1509   // that aren't byte sized.
1510   if (ElementSize % 8)
1511     return false;
1512   assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1513   VecSize /= 8;
1514   ElementSize /= 8;
1515
1516   for (; I != E; ++I) {
1517     uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1518     uint64_t BeginIndex = BeginOffset / ElementSize;
1519     if (BeginIndex * ElementSize != BeginOffset ||
1520         BeginIndex >= Ty->getNumElements())
1521       return false;
1522     uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1523     uint64_t EndIndex = EndOffset / ElementSize;
1524     if (EndIndex * ElementSize != EndOffset ||
1525         EndIndex > Ty->getNumElements())
1526       return false;
1527
1528     // FIXME: We should build shuffle vector instructions to handle
1529     // non-element-sized accesses.
1530     if ((EndOffset - BeginOffset) != ElementSize &&
1531         (EndOffset - BeginOffset) != VecSize)
1532       return false;
1533
1534     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1535       if (MI->isVolatile())
1536         return false;
1537       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1538         const AllocaPartitioning::MemTransferOffsets &MTO
1539           = P.getMemTransferOffsets(*MTI);
1540         if (!MTO.IsSplittable)
1541           return false;
1542       }
1543     } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1544       // Disable vector promotion when there are loads or stores of an FCA.
1545       return false;
1546     } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1547       return false;
1548     }
1549   }
1550   return true;
1551 }
1552
1553 namespace {
1554 /// \brief Visitor to rewrite instructions using a partition of an alloca to
1555 /// use a new alloca.
1556 ///
1557 /// Also implements the rewriting to vector-based accesses when the partition
1558 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1559 /// lives here.
1560 class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1561                                                    bool> {
1562   // Befriend the base class so it can delegate to private visit methods.
1563   friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1564
1565   const TargetData &TD;
1566   AllocaPartitioning &P;
1567   SROA &Pass;
1568   AllocaInst &OldAI, &NewAI;
1569   const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1570
1571   // If we are rewriting an alloca partition which can be written as pure
1572   // vector operations, we stash extra information here. When VecTy is
1573   // non-null, we have some strict guarantees about the rewriten alloca:
1574   //   - The new alloca is exactly the size of the vector type here.
1575   //   - The accesses all either map to the entire vector or to a single
1576   //     element.
1577   //   - The set of accessing instructions is only one of those handled above
1578   //     in isVectorPromotionViable. Generally these are the same access kinds
1579   //     which are promotable via mem2reg.
1580   VectorType *VecTy;
1581   Type *ElementTy;
1582   uint64_t ElementSize;
1583
1584   // The offset of the partition user currently being rewritten.
1585   uint64_t BeginOffset, EndOffset;
1586   Instruction *OldPtr;
1587
1588   // The name prefix to use when rewriting instructions for this alloca.
1589   std::string NamePrefix;
1590
1591 public:
1592   AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1593                           AllocaPartitioning::iterator PI,
1594                           SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1595                           uint64_t NewBeginOffset, uint64_t NewEndOffset)
1596     : TD(TD), P(P), Pass(Pass),
1597       OldAI(OldAI), NewAI(NewAI),
1598       NewAllocaBeginOffset(NewBeginOffset),
1599       NewAllocaEndOffset(NewEndOffset),
1600       VecTy(), ElementTy(), ElementSize(),
1601       BeginOffset(), EndOffset() {
1602   }
1603
1604   /// \brief Visit the users of the alloca partition and rewrite them.
1605   bool visitUsers(AllocaPartitioning::const_use_iterator I,
1606                   AllocaPartitioning::const_use_iterator E) {
1607     if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1608                                 NewAllocaBeginOffset, NewAllocaEndOffset,
1609                                 I, E)) {
1610       ++NumVectorized;
1611       VecTy = cast<VectorType>(NewAI.getAllocatedType());
1612       ElementTy = VecTy->getElementType();
1613       assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1614              "Only multiple-of-8 sized vector elements are viable");
1615       ElementSize = VecTy->getScalarSizeInBits() / 8;
1616     }
1617     bool CanSROA = true;
1618     for (; I != E; ++I) {
1619       BeginOffset = I->BeginOffset;
1620       EndOffset = I->EndOffset;
1621       OldPtr = I->Ptr;
1622       NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1623       CanSROA &= visit(I->User);
1624     }
1625     if (VecTy) {
1626       assert(CanSROA);
1627       VecTy = 0;
1628       ElementTy = 0;
1629       ElementSize = 0;
1630     }
1631     return CanSROA;
1632   }
1633
1634 private:
1635   // Every instruction which can end up as a user must have a rewrite rule.
1636   bool visitInstruction(Instruction &I) {
1637     DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
1638     llvm_unreachable("No rewrite rule for this instruction!");
1639   }
1640
1641   Twine getName(const Twine &Suffix) {
1642     return NamePrefix + Suffix;
1643   }
1644
1645   Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1646     assert(BeginOffset >= NewAllocaBeginOffset);
1647     APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1648     return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1649   }
1650
1651   ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1652     assert(VecTy && "Can only call getIndex when rewriting a vector");
1653     uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1654     assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1655     uint32_t Index = RelOffset / ElementSize;
1656     assert(Index * ElementSize == RelOffset);
1657     return IRB.getInt32(Index);
1658   }
1659
1660   void deleteIfTriviallyDead(Value *V) {
1661     Instruction *I = cast<Instruction>(V);
1662     if (isInstructionTriviallyDead(I))
1663       Pass.DeadInsts.push_back(I);
1664   }
1665
1666   Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1667     if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1668       return IRB.CreateIntToPtr(V, Ty);
1669     if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1670       return IRB.CreatePtrToInt(V, Ty);
1671
1672     return IRB.CreateBitCast(V, Ty);
1673   }
1674
1675   bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1676     Value *Result;
1677     if (LI.getType() == VecTy->getElementType() ||
1678         BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1679       Result
1680         = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1681                                    getIndex(IRB, BeginOffset),
1682                                    getName(".extract"));
1683     } else {
1684       Result = IRB.CreateLoad(&NewAI, getName(".load"));
1685     }
1686     if (Result->getType() != LI.getType())
1687       Result = getValueCast(IRB, Result, LI.getType());
1688     LI.replaceAllUsesWith(Result);
1689     Pass.DeadInsts.push_back(&LI);
1690
1691     DEBUG(dbgs() << "          to: " << *Result << "\n");
1692     return true;
1693   }
1694
1695   bool visitLoadInst(LoadInst &LI) {
1696     DEBUG(dbgs() << "    original: " << LI << "\n");
1697     Value *OldOp = LI.getOperand(0);
1698     assert(OldOp == OldPtr);
1699     IRBuilder<> IRB(&LI);
1700
1701     if (VecTy)
1702       return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1703
1704     Value *NewPtr = getAdjustedAllocaPtr(IRB,
1705                                          LI.getPointerOperand()->getType());
1706     LI.setOperand(0, NewPtr);
1707     DEBUG(dbgs() << "          to: " << LI << "\n");
1708
1709     deleteIfTriviallyDead(OldOp);
1710     return NewPtr == &NewAI && !LI.isVolatile();
1711   }
1712
1713   bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1714                                   Value *OldOp) {
1715     Value *V = SI.getValueOperand();
1716     if (V->getType() == ElementTy ||
1717         BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1718       if (V->getType() != ElementTy)
1719         V = getValueCast(IRB, V, ElementTy);
1720       V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1721                                   getIndex(IRB, BeginOffset),
1722                                   getName(".insert"));
1723     } else if (V->getType() != VecTy) {
1724       V = getValueCast(IRB, V, VecTy);
1725     }
1726     StoreInst *Store = IRB.CreateStore(V, &NewAI);
1727     Pass.DeadInsts.push_back(&SI);
1728
1729     (void)Store;
1730     DEBUG(dbgs() << "          to: " << *Store << "\n");
1731     return true;
1732   }
1733
1734   bool visitStoreInst(StoreInst &SI) {
1735     DEBUG(dbgs() << "    original: " << SI << "\n");
1736     Value *OldOp = SI.getOperand(1);
1737     assert(OldOp == OldPtr);
1738     IRBuilder<> IRB(&SI);
1739
1740     if (VecTy)
1741       return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1742
1743     Value *NewPtr = getAdjustedAllocaPtr(IRB,
1744                                          SI.getPointerOperand()->getType());
1745     SI.setOperand(1, NewPtr);
1746     DEBUG(dbgs() << "          to: " << SI << "\n");
1747
1748     deleteIfTriviallyDead(OldOp);
1749     return NewPtr == &NewAI && !SI.isVolatile();
1750   }
1751
1752   bool visitMemSetInst(MemSetInst &II) {
1753     DEBUG(dbgs() << "    original: " << II << "\n");
1754     IRBuilder<> IRB(&II);
1755     assert(II.getRawDest() == OldPtr);
1756
1757     // If the memset has a variable size, it cannot be split, just adjust the
1758     // pointer to the new alloca.
1759     if (!isa<Constant>(II.getLength())) {
1760       II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1761       deleteIfTriviallyDead(OldPtr);
1762       return false;
1763     }
1764
1765     // Record this instruction for deletion.
1766     if (Pass.DeadSplitInsts.insert(&II))
1767       Pass.DeadInsts.push_back(&II);
1768
1769     Type *AllocaTy = NewAI.getAllocatedType();
1770     Type *ScalarTy = AllocaTy->getScalarType();
1771
1772     // If this doesn't map cleanly onto the alloca type, and that type isn't
1773     // a single value type, just emit a memset.
1774     if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1775                    EndOffset != NewAllocaEndOffset ||
1776                    !AllocaTy->isSingleValueType() ||
1777                    !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1778       Type *SizeTy = II.getLength()->getType();
1779       Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1780
1781       CallInst *New
1782         = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1783                                                 II.getRawDest()->getType()),
1784                            II.getValue(), Size, II.getAlignment(),
1785                            II.isVolatile());
1786       (void)New;
1787       DEBUG(dbgs() << "          to: " << *New << "\n");
1788       return false;
1789     }
1790
1791     // If we can represent this as a simple value, we have to build the actual
1792     // value to store, which requires expanding the byte present in memset to
1793     // a sensible representation for the alloca type. This is essentially
1794     // splatting the byte to a sufficiently wide integer, bitcasting to the
1795     // desired scalar type, and splatting it across any desired vector type.
1796     Value *V = II.getValue();
1797     IntegerType *VTy = cast<IntegerType>(V->getType());
1798     Type *IntTy = Type::getIntNTy(VTy->getContext(),
1799                                   TD.getTypeSizeInBits(ScalarTy));
1800     if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1801       V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1802                         ConstantExpr::getUDiv(
1803                           Constant::getAllOnesValue(IntTy),
1804                           ConstantExpr::getZExt(
1805                             Constant::getAllOnesValue(V->getType()),
1806                             IntTy)),
1807                         getName(".isplat"));
1808     if (V->getType() != ScalarTy) {
1809       if (ScalarTy->isPointerTy())
1810         V = IRB.CreateIntToPtr(V, ScalarTy);
1811       else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1812         V = IRB.CreateBitCast(V, ScalarTy);
1813       else if (ScalarTy->isIntegerTy())
1814         llvm_unreachable("Computed different integer types with equal widths");
1815       else
1816         llvm_unreachable("Invalid scalar type");
1817     }
1818
1819     // If this is an element-wide memset of a vectorizable alloca, insert it.
1820     if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1821                   EndOffset < NewAllocaEndOffset)) {
1822       StoreInst *Store = IRB.CreateStore(
1823         IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1824                                 getIndex(IRB, BeginOffset),
1825                                 getName(".insert")),
1826         &NewAI);
1827       (void)Store;
1828       DEBUG(dbgs() << "          to: " << *Store << "\n");
1829       return true;
1830     }
1831
1832     // Splat to a vector if needed.
1833     if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1834       VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1835       V = IRB.CreateShuffleVector(
1836         IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1837                                 IRB.getInt32(0), getName(".vsplat.insert")),
1838         UndefValue::get(SplatSourceTy),
1839         ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1840         getName(".vsplat.shuffle"));
1841       assert(V->getType() == VecTy);
1842     }
1843
1844     Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1845     (void)New;
1846     DEBUG(dbgs() << "          to: " << *New << "\n");
1847     return !II.isVolatile();
1848   }
1849
1850   bool visitMemTransferInst(MemTransferInst &II) {
1851     // Rewriting of memory transfer instructions can be a bit tricky. We break
1852     // them into two categories: split intrinsics and unsplit intrinsics.
1853
1854     DEBUG(dbgs() << "    original: " << II << "\n");
1855     IRBuilder<> IRB(&II);
1856
1857     assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1858     bool IsDest = II.getRawDest() == OldPtr;
1859
1860     const AllocaPartitioning::MemTransferOffsets &MTO
1861       = P.getMemTransferOffsets(II);
1862
1863     // For unsplit intrinsics, we simply modify the source and destination
1864     // pointers in place. This isn't just an optimization, it is a matter of
1865     // correctness. With unsplit intrinsics we may be dealing with transfers
1866     // within a single alloca before SROA ran, or with transfers that have
1867     // a variable length. We may also be dealing with memmove instead of
1868     // memcpy, and so simply updating the pointers is the necessary for us to
1869     // update both source and dest of a single call.
1870     if (!MTO.IsSplittable) {
1871       Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1872       if (IsDest)
1873         II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1874       else
1875         II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1876
1877       DEBUG(dbgs() << "          to: " << II << "\n");
1878       deleteIfTriviallyDead(OldOp);
1879       return false;
1880     }
1881     // For split transfer intrinsics we have an incredibly useful assurance:
1882     // the source and destination do not reside within the same alloca, and at
1883     // least one of them does not escape. This means that we can replace
1884     // memmove with memcpy, and we don't need to worry about all manner of
1885     // downsides to splitting and transforming the operations.
1886
1887     // Compute the relative offset within the transfer.
1888     unsigned IntPtrWidth = TD.getPointerSizeInBits();
1889     APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
1890                                                        : MTO.SourceBegin));
1891
1892     // If this doesn't map cleanly onto the alloca type, and that type isn't
1893     // a single value type, just emit a memcpy.
1894     bool EmitMemCpy
1895       = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
1896                    EndOffset != NewAllocaEndOffset ||
1897                    !NewAI.getAllocatedType()->isSingleValueType());
1898
1899     // If we're just going to emit a memcpy, the alloca hasn't changed, and the
1900     // size hasn't been shrunk based on analysis of the viable range, this is
1901     // a no-op.
1902     if (EmitMemCpy && &OldAI == &NewAI) {
1903       uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
1904       uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
1905       // Ensure the start lines up.
1906       assert(BeginOffset == OrigBegin);
1907
1908       // Rewrite the size as needed.
1909       if (EndOffset != OrigEnd)
1910         II.setLength(ConstantInt::get(II.getLength()->getType(),
1911                                       EndOffset - BeginOffset));
1912       return false;
1913     }
1914     // Record this instruction for deletion.
1915     if (Pass.DeadSplitInsts.insert(&II))
1916       Pass.DeadInsts.push_back(&II);
1917
1918     bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
1919                                      EndOffset < NewAllocaEndOffset);
1920
1921     Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
1922                               : II.getRawDest()->getType();
1923     if (!EmitMemCpy)
1924       OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
1925                                    : NewAI.getType();
1926
1927     // Compute the other pointer, folding as much as possible to produce
1928     // a single, simple GEP in most cases.
1929     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
1930     OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
1931                               getName("." + OtherPtr->getName()));
1932
1933     // Strip all inbounds GEPs and pointer casts to try to dig out any root
1934     // alloca that should be re-examined after rewriting this instruction.
1935     if (AllocaInst *AI
1936           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
1937       Pass.Worklist.insert(AI);
1938
1939     if (EmitMemCpy) {
1940       Value *OurPtr
1941         = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
1942                                            : II.getRawSource()->getType());
1943       Type *SizeTy = II.getLength()->getType();
1944       Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1945
1946       CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
1947                                        IsDest ? OtherPtr : OurPtr,
1948                                        Size, II.getAlignment(),
1949                                        II.isVolatile());
1950       (void)New;
1951       DEBUG(dbgs() << "          to: " << *New << "\n");
1952       return false;
1953     }
1954
1955     Value *SrcPtr = OtherPtr;
1956     Value *DstPtr = &NewAI;
1957     if (!IsDest)
1958       std::swap(SrcPtr, DstPtr);
1959
1960     Value *Src;
1961     if (IsVectorElement && !IsDest) {
1962       // We have to extract rather than load.
1963       Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
1964                                                     getName(".copyload")),
1965                                      getIndex(IRB, BeginOffset),
1966                                      getName(".copyextract"));
1967     } else {
1968       Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
1969     }
1970
1971     if (IsVectorElement && IsDest) {
1972       // We have to insert into a loaded copy before storing.
1973       Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
1974                                     Src, getIndex(IRB, BeginOffset),
1975                                     getName(".insert"));
1976     }
1977
1978     Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
1979     (void)Store;
1980     DEBUG(dbgs() << "          to: " << *Store << "\n");
1981     return !II.isVolatile();
1982   }
1983
1984   bool visitIntrinsicInst(IntrinsicInst &II) {
1985     assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
1986            II.getIntrinsicID() == Intrinsic::lifetime_end);
1987     DEBUG(dbgs() << "    original: " << II << "\n");
1988     IRBuilder<> IRB(&II);
1989     assert(II.getArgOperand(1) == OldPtr);
1990
1991     // Record this instruction for deletion.
1992     if (Pass.DeadSplitInsts.insert(&II))
1993       Pass.DeadInsts.push_back(&II);
1994
1995     ConstantInt *Size
1996       = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
1997                          EndOffset - BeginOffset);
1998     Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
1999     Value *New;
2000     if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2001       New = IRB.CreateLifetimeStart(Ptr, Size);
2002     else
2003       New = IRB.CreateLifetimeEnd(Ptr, Size);
2004
2005     DEBUG(dbgs() << "          to: " << *New << "\n");
2006     return true;
2007   }
2008
2009   /// PHI instructions that use an alloca and are subsequently loaded can be
2010   /// rewritten to load both input pointers in the pred blocks and then PHI the
2011   /// results, allowing the load of the alloca to be promoted.
2012   /// From this:
2013   ///   %P2 = phi [i32* %Alloca, i32* %Other]
2014   ///   %V = load i32* %P2
2015   /// to:
2016   ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
2017   ///   ...
2018   ///   %V2 = load i32* %Other
2019   ///   ...
2020   ///   %V = phi [i32 %V1, i32 %V2]
2021   ///
2022   /// We can do this to a select if its only uses are loads and if the operand
2023   /// to the select can be loaded unconditionally.
2024   ///
2025   /// FIXME: This should be hoisted into a generic utility, likely in
2026   /// Transforms/Util/Local.h
2027   bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2028     // For now, we can only do this promotion if the load is in the same block
2029     // as the PHI, and if there are no stores between the phi and load.
2030     // TODO: Allow recursive phi users.
2031     // TODO: Allow stores.
2032     BasicBlock *BB = PN.getParent();
2033     unsigned MaxAlign = 0;
2034     for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2035          UI != UE; ++UI) {
2036       LoadInst *LI = dyn_cast<LoadInst>(*UI);
2037       if (LI == 0 || !LI->isSimple()) return false;
2038
2039       // For now we only allow loads in the same block as the PHI.  This is
2040       // a common case that happens when instcombine merges two loads through
2041       // a PHI.
2042       if (LI->getParent() != BB) return false;
2043
2044       // Ensure that there are no instructions between the PHI and the load that
2045       // could store.
2046       for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2047         if (BBI->mayWriteToMemory())
2048           return false;
2049
2050       MaxAlign = std::max(MaxAlign, LI->getAlignment());
2051       Loads.push_back(LI);
2052     }
2053
2054     // We can only transform this if it is safe to push the loads into the
2055     // predecessor blocks. The only thing to watch out for is that we can't put
2056     // a possibly trapping load in the predecessor if it is a critical edge.
2057     for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2058          ++Idx) {
2059       TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2060       Value *InVal = PN.getIncomingValue(Idx);
2061
2062       // If the value is produced by the terminator of the predecessor (an
2063       // invoke) or it has side-effects, there is no valid place to put a load
2064       // in the predecessor.
2065       if (TI == InVal || TI->mayHaveSideEffects())
2066         return false;
2067
2068       // If the predecessor has a single successor, then the edge isn't
2069       // critical.
2070       if (TI->getNumSuccessors() == 1)
2071         continue;
2072
2073       // If this pointer is always safe to load, or if we can prove that there
2074       // is already a load in the block, then we can move the load to the pred
2075       // block.
2076       if (InVal->isDereferenceablePointer() ||
2077           isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2078         continue;
2079
2080       return false;
2081     }
2082
2083     return true;
2084   }
2085
2086   bool visitPHINode(PHINode &PN) {
2087     DEBUG(dbgs() << "    original: " << PN << "\n");
2088     // We would like to compute a new pointer in only one place, but have it be
2089     // as local as possible to the PHI. To do that, we re-use the location of
2090     // the old pointer, which necessarily must be in the right position to
2091     // dominate the PHI.
2092     IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2093
2094     SmallVector<LoadInst *, 4> Loads;
2095     if (!isSafePHIToSpeculate(PN, Loads)) {
2096       Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2097       // Replace the operands which were using the old pointer.
2098       User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2099       for (; OI != OE; ++OI)
2100         if (*OI == OldPtr)
2101           *OI = NewPtr;
2102
2103       DEBUG(dbgs() << "          to: " << PN << "\n");
2104       deleteIfTriviallyDead(OldPtr);
2105       return false;
2106     }
2107     assert(!Loads.empty());
2108
2109     Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2110     IRBuilder<> PHIBuilder(&PN);
2111     PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2112     NewPN->takeName(&PN);
2113
2114     // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
2115     // matter which one we get and if any differ, it doesn't matter.
2116     LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2117     MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2118     unsigned Align = SomeLoad->getAlignment();
2119     Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2120
2121     // Rewrite all loads of the PN to use the new PHI.
2122     do {
2123       LoadInst *LI = Loads.pop_back_val();
2124       LI->replaceAllUsesWith(NewPN);
2125       Pass.DeadInsts.push_back(LI);
2126     } while (!Loads.empty());
2127
2128     // Inject loads into all of the pred blocks.
2129     for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2130       BasicBlock *Pred = PN.getIncomingBlock(Idx);
2131       TerminatorInst *TI = Pred->getTerminator();
2132       Value *InVal = PN.getIncomingValue(Idx);
2133       IRBuilder<> PredBuilder(TI);
2134
2135       // Map the value to the new alloca pointer if this was the old alloca
2136       // pointer.
2137       bool ThisOperand = InVal == OldPtr;
2138       if (ThisOperand)
2139         InVal = NewPtr;
2140
2141       LoadInst *Load
2142         = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2143                                                 Pred->getName()));
2144       ++NumLoadsSpeculated;
2145       Load->setAlignment(Align);
2146       if (TBAATag)
2147         Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2148       NewPN->addIncoming(Load, Pred);
2149
2150       if (ThisOperand)
2151         continue;
2152       Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2153       if (!OtherPtr)
2154         // No uses to rewrite.
2155         continue;
2156
2157       // Try to lookup and rewrite any partition uses corresponding to this phi
2158       // input.
2159       AllocaPartitioning::iterator PI
2160         = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2161       if (PI != P.end()) {
2162         // If the other pointer is within the partitioning, replace the PHI in
2163         // its uses with the load we just speculated, or add another load for
2164         // it to rewrite if we've already replaced the PHI.
2165         AllocaPartitioning::use_iterator UI
2166           = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2167         if (isa<PHINode>(*UI->User))
2168           UI->User = Load;
2169         else {
2170           AllocaPartitioning::PartitionUse OtherUse = *UI;
2171           OtherUse.User = Load;
2172           P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2173                        OtherUse);
2174         }
2175       }
2176     }
2177     DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
2178     return NewPtr == &NewAI;
2179   }
2180
2181   /// Select instructions that use an alloca and are subsequently loaded can be
2182   /// rewritten to load both input pointers and then select between the result,
2183   /// allowing the load of the alloca to be promoted.
2184   /// From this:
2185   ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2186   ///   %V = load i32* %P2
2187   /// to:
2188   ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
2189   ///   %V2 = load i32* %Other
2190   ///   %V = select i1 %cond, i32 %V1, i32 %V2
2191   ///
2192   /// We can do this to a select if its only uses are loads and if the operand
2193   /// to the select can be loaded unconditionally.
2194   bool isSafeSelectToSpeculate(SelectInst &SI,
2195                                SmallVectorImpl<LoadInst *> &Loads) {
2196     Value *TValue = SI.getTrueValue();
2197     Value *FValue = SI.getFalseValue();
2198     bool TDerefable = TValue->isDereferenceablePointer();
2199     bool FDerefable = FValue->isDereferenceablePointer();
2200
2201     for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2202          UI != UE; ++UI) {
2203       LoadInst *LI = dyn_cast<LoadInst>(*UI);
2204       if (LI == 0 || !LI->isSimple()) return false;
2205
2206       // Both operands to the select need to be dereferencable, either
2207       // absolutely (e.g. allocas) or at this point because we can see other
2208       // accesses to it.
2209       if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2210                                                       LI->getAlignment(), &TD))
2211         return false;
2212       if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2213                                                       LI->getAlignment(), &TD))
2214         return false;
2215       Loads.push_back(LI);
2216     }
2217
2218     return true;
2219   }
2220
2221   bool visitSelectInst(SelectInst &SI) {
2222     DEBUG(dbgs() << "    original: " << SI << "\n");
2223     IRBuilder<> IRB(&SI);
2224
2225     // Find the operand we need to rewrite here.
2226     bool IsTrueVal = SI.getTrueValue() == OldPtr;
2227     if (IsTrueVal)
2228       assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2229     else
2230       assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2231     Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2232
2233     // If the select isn't safe to speculate, just use simple logic to emit it.
2234     SmallVector<LoadInst *, 4> Loads;
2235     if (!isSafeSelectToSpeculate(SI, Loads)) {
2236       SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2237       DEBUG(dbgs() << "          to: " << SI << "\n");
2238       deleteIfTriviallyDead(OldPtr);
2239       return false;
2240     }
2241
2242     Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2243     AllocaPartitioning::iterator PI
2244       = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2245     AllocaPartitioning::PartitionUse OtherUse;
2246     if (PI != P.end()) {
2247       // If the other pointer is within the partitioning, remove the select
2248       // from its uses. We'll add in the new loads below.
2249       AllocaPartitioning::use_iterator UI
2250         = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2251       OtherUse = *UI;
2252       P.use_erase(PI, UI);
2253     }
2254
2255     Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2256     Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2257     // Replace the loads of the select with a select of two loads.
2258     while (!Loads.empty()) {
2259       LoadInst *LI = Loads.pop_back_val();
2260
2261       IRB.SetInsertPoint(LI);
2262       LoadInst *TL =
2263         IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2264       LoadInst *FL =
2265         IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2266       NumLoadsSpeculated += 2;
2267       if (PI != P.end()) {
2268         LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2269         assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2270         OtherUse.User = OtherLoad;
2271         P.use_insert(PI, P.use_end(PI), OtherUse);
2272       }
2273
2274       // Transfer alignment and TBAA info if present.
2275       TL->setAlignment(LI->getAlignment());
2276       FL->setAlignment(LI->getAlignment());
2277       if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2278         TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2279         FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2280       }
2281
2282       Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2283       V->takeName(LI);
2284       DEBUG(dbgs() << "          speculated to: " << *V << "\n");
2285       LI->replaceAllUsesWith(V);
2286       Pass.DeadInsts.push_back(LI);
2287     }
2288     if (PI != P.end())
2289       std::stable_sort(P.use_begin(PI), P.use_end(PI));
2290
2291     deleteIfTriviallyDead(OldPtr);
2292     return NewPtr == &NewAI;
2293   }
2294
2295 };
2296 }
2297
2298 /// \brief Try to find a partition of the aggregate type passed in for a given
2299 /// offset and size.
2300 ///
2301 /// This recurses through the aggregate type and tries to compute a subtype
2302 /// based on the offset and size. When the offset and size span a sub-section
2303 /// of an array, it will even compute a new array type for that sub-section.
2304 static Type *getTypePartition(const TargetData &TD, Type *Ty,
2305                               uint64_t Offset, uint64_t Size) {
2306   if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2307     return Ty;
2308
2309   if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2310     // We can't partition pointers...
2311     if (SeqTy->isPointerTy())
2312       return 0;
2313
2314     Type *ElementTy = SeqTy->getElementType();
2315     uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2316     uint64_t NumSkippedElements = Offset / ElementSize;
2317     if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2318       if (NumSkippedElements >= ArrTy->getNumElements())
2319         return 0;
2320     if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2321       if (NumSkippedElements >= VecTy->getNumElements())
2322         return 0;
2323     Offset -= NumSkippedElements * ElementSize;
2324
2325     // First check if we need to recurse.
2326     if (Offset > 0 || Size < ElementSize) {
2327       // Bail if the partition ends in a different array element.
2328       if ((Offset + Size) > ElementSize)
2329         return 0;
2330       // Recurse through the element type trying to peel off offset bytes.
2331       return getTypePartition(TD, ElementTy, Offset, Size);
2332     }
2333     assert(Offset == 0);
2334
2335     if (Size == ElementSize)
2336       return ElementTy;
2337     assert(Size > ElementSize);
2338     uint64_t NumElements = Size / ElementSize;
2339     if (NumElements * ElementSize != Size)
2340       return 0;
2341     return ArrayType::get(ElementTy, NumElements);
2342   }
2343
2344   StructType *STy = dyn_cast<StructType>(Ty);
2345   if (!STy)
2346     return 0;
2347
2348   const StructLayout *SL = TD.getStructLayout(STy);
2349   if (Offset > SL->getSizeInBytes())
2350     return 0;
2351   uint64_t EndOffset = Offset + Size;
2352   if (EndOffset > SL->getSizeInBytes())
2353     return 0;
2354
2355   unsigned Index = SL->getElementContainingOffset(Offset);
2356   if (SL->getElementOffset(Index) != Offset)
2357     return 0; // Inside of padding.
2358   Offset -= SL->getElementOffset(Index);
2359
2360   Type *ElementTy = STy->getElementType(Index);
2361   uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2362   if (Offset >= ElementSize)
2363     return 0; // The offset points into alignment padding.
2364
2365   // See if any partition must be contained by the element.
2366   if (Offset > 0 || Size < ElementSize) {
2367     if ((Offset + Size) > ElementSize)
2368       return 0;
2369     // Bail if this is a poniter element, we can't recurse through them.
2370     if (ElementTy->isPointerTy())
2371       return 0;
2372     return getTypePartition(TD, ElementTy, Offset, Size);
2373   }
2374   assert(Offset == 0);
2375
2376   if (Size == ElementSize)
2377     return ElementTy;
2378
2379   StructType::element_iterator EI = STy->element_begin() + Index,
2380                                EE = STy->element_end();
2381   if (EndOffset < SL->getSizeInBytes()) {
2382     unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2383     if (Index == EndIndex)
2384       return 0; // Within a single element and its padding.
2385     assert(Index < EndIndex);
2386     assert(Index + EndIndex <= STy->getNumElements());
2387     EE = STy->element_begin() + EndIndex;
2388   }
2389
2390   // Try to build up a sub-structure.
2391   SmallVector<Type *, 4> ElementTys;
2392   do {
2393     ElementTys.push_back(*EI++);
2394   } while (EI != EE);
2395   StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2396                                       STy->isPacked());
2397   const StructLayout *SubSL = TD.getStructLayout(SubTy);
2398   if (Size == SubSL->getSizeInBytes())
2399     return SubTy;
2400
2401   // FIXME: We could potentially recurse down through the last element in the
2402   // sub-struct to find a natural end point.
2403   return 0;
2404 }
2405
2406 /// \brief Rewrite an alloca partition's users.
2407 ///
2408 /// This routine drives both of the rewriting goals of the SROA pass. It tries
2409 /// to rewrite uses of an alloca partition to be conducive for SSA value
2410 /// promotion. If the partition needs a new, more refined alloca, this will
2411 /// build that new alloca, preserving as much type information as possible, and
2412 /// rewrite the uses of the old alloca to point at the new one and have the
2413 /// appropriate new offsets. It also evaluates how successful the rewrite was
2414 /// at enabling promotion and if it was successful queues the alloca to be
2415 /// promoted.
2416 bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2417                                   AllocaPartitioning &P,
2418                                   AllocaPartitioning::iterator PI) {
2419   uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2420   if (P.use_begin(PI) == P.use_end(PI))
2421     return false; // No live uses left of this partition.
2422
2423   // Try to compute a friendly type for this partition of the alloca. This
2424   // won't always succeed, in which case we fall back to a legal integer type
2425   // or an i8 array of an appropriate size.
2426   Type *AllocaTy = 0;
2427   if (Type *PartitionTy = P.getCommonType(PI))
2428     if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2429       AllocaTy = PartitionTy;
2430   if (!AllocaTy)
2431     if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2432                                              PI->BeginOffset, AllocaSize))
2433       AllocaTy = PartitionTy;
2434   if ((!AllocaTy ||
2435        (AllocaTy->isArrayTy() &&
2436         AllocaTy->getArrayElementType()->isIntegerTy())) &&
2437       TD->isLegalInteger(AllocaSize * 8))
2438     AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2439   if (!AllocaTy)
2440     AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
2441
2442   // Check for the case where we're going to rewrite to a new alloca of the
2443   // exact same type as the original, and with the same access offsets. In that
2444   // case, re-use the existing alloca, but still run through the rewriter to
2445   // performe phi and select speculation.
2446   AllocaInst *NewAI;
2447   if (AllocaTy == AI.getAllocatedType()) {
2448     assert(PI->BeginOffset == 0 &&
2449            "Non-zero begin offset but same alloca type");
2450     assert(PI == P.begin() && "Begin offset is zero on later partition");
2451     NewAI = &AI;
2452   } else {
2453     // FIXME: The alignment here is overly conservative -- we could in many
2454     // cases get away with much weaker alignment constraints.
2455     NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2456                            AI.getName() + ".sroa." + Twine(PI - P.begin()),
2457                            &AI);
2458     ++NumNewAllocas;
2459   }
2460
2461   DEBUG(dbgs() << "Rewriting alloca partition "
2462                << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2463                << *NewAI << "\n");
2464
2465   AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2466                                    PI->BeginOffset, PI->EndOffset);
2467   DEBUG(dbgs() << "  rewriting ");
2468   DEBUG(P.print(dbgs(), PI, ""));
2469   if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2470     DEBUG(dbgs() << "  and queuing for promotion\n");
2471     PromotableAllocas.push_back(NewAI);
2472   } else if (NewAI != &AI) {
2473     // If we can't promote the alloca, iterate on it to check for new
2474     // refinements exposed by splitting the current alloca. Don't iterate on an
2475     // alloca which didn't actually change and didn't get promoted.
2476     Worklist.insert(NewAI);
2477   }
2478   return true;
2479 }
2480
2481 /// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2482 bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2483   bool Changed = false;
2484   for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2485        ++PI)
2486     Changed |= rewriteAllocaPartition(AI, P, PI);
2487
2488   return Changed;
2489 }
2490
2491 /// \brief Analyze an alloca for SROA.
2492 ///
2493 /// This analyzes the alloca to ensure we can reason about it, builds
2494 /// a partitioning of the alloca, and then hands it off to be split and
2495 /// rewritten as needed.
2496 bool SROA::runOnAlloca(AllocaInst &AI) {
2497   DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2498   ++NumAllocasAnalyzed;
2499
2500   // Special case dead allocas, as they're trivial.
2501   if (AI.use_empty()) {
2502     AI.eraseFromParent();
2503     return true;
2504   }
2505
2506   // Skip alloca forms that this analysis can't handle.
2507   if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2508       TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2509     return false;
2510
2511   // First check if this is a non-aggregate type that we should simply promote.
2512   if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2513     DEBUG(dbgs() << "  Trivially scalar type, queuing for promotion...\n");
2514     PromotableAllocas.push_back(&AI);
2515     return false;
2516   }
2517
2518   // Build the partition set using a recursive instruction-visiting builder.
2519   AllocaPartitioning P(*TD, AI);
2520   DEBUG(P.print(dbgs()));
2521   if (P.isEscaped())
2522     return false;
2523
2524   // No partitions to split. Leave the dead alloca for a later pass to clean up.
2525   if (P.begin() == P.end())
2526     return false;
2527
2528   // Delete all the dead users of this alloca before splitting and rewriting it.
2529   bool Changed = false;
2530   for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2531                                               DE = P.dead_user_end();
2532        DI != DE; ++DI) {
2533     Changed = true;
2534     (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2535     DeadInsts.push_back(*DI);
2536   }
2537   for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2538                                             DE = P.dead_op_end();
2539        DO != DE; ++DO) {
2540     Value *OldV = **DO;
2541     // Clobber the use with an undef value.
2542     **DO = UndefValue::get(OldV->getType());
2543     if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2544       if (isInstructionTriviallyDead(OldI)) {
2545         Changed = true;
2546         DeadInsts.push_back(OldI);
2547       }
2548   }
2549
2550   return splitAlloca(AI, P) || Changed;
2551 }
2552
2553 void SROA::deleteDeadInstructions() {
2554   DeadSplitInsts.clear();
2555   while (!DeadInsts.empty()) {
2556     Instruction *I = DeadInsts.pop_back_val();
2557     DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2558
2559     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2560       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2561         // Zero out the operand and see if it becomes trivially dead.
2562         *OI = 0;
2563         if (isInstructionTriviallyDead(U))
2564           DeadInsts.push_back(U);
2565       }
2566
2567     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2568       DeletedAllocas.insert(AI);
2569
2570     ++NumDeleted;
2571     I->eraseFromParent();
2572   }
2573 }
2574
2575 namespace {
2576   /// \brief A predicate to test whether an alloca belongs to a set.
2577   class IsAllocaInSet {
2578     typedef SmallPtrSet<AllocaInst *, 4> SetType;
2579     const SetType &Set;
2580
2581   public:
2582     IsAllocaInSet(const SetType &Set) : Set(Set) {}
2583     bool operator()(AllocaInst *AI) { return Set.count(AI); }
2584   };
2585 }
2586
2587 bool SROA::runOnFunction(Function &F) {
2588   DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2589   C = &F.getContext();
2590   TD = getAnalysisIfAvailable<TargetData>();
2591   if (!TD) {
2592     DEBUG(dbgs() << "  Skipping SROA -- no target data!\n");
2593     return false;
2594   }
2595   DT = &getAnalysis<DominatorTree>();
2596
2597   BasicBlock &EntryBB = F.getEntryBlock();
2598   for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
2599        I != E; ++I)
2600     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2601       Worklist.insert(AI);
2602
2603   bool Changed = false;
2604   while (!Worklist.empty()) {
2605     Changed |= runOnAlloca(*Worklist.pop_back_val());
2606     deleteDeadInstructions();
2607     if (!DeletedAllocas.empty()) {
2608       PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
2609                                              PromotableAllocas.end(),
2610                                              IsAllocaInSet(DeletedAllocas)),
2611                               PromotableAllocas.end());
2612       DeletedAllocas.clear();
2613     }
2614   }
2615
2616   if (!PromotableAllocas.empty()) {
2617     DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2618     PromoteMemToReg(PromotableAllocas, *DT);
2619     Changed = true;
2620     NumPromoted += PromotableAllocas.size();
2621     PromotableAllocas.clear();
2622   }
2623
2624   return Changed;
2625 }
2626
2627 void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
2628   AU.addRequired<DominatorTree>();
2629   AU.setPreservesCFG();
2630 }