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