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