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