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