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