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