ScalarReplAggregates.cpp revision dd68912801861273dc3dca33cfc18357213049a4
1//===- ScalarReplAggregates.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//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation.  This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
13// each member (if possible).  Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs.  As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/Module.h"
32#include "llvm/Pass.h"
33#include "llvm/Analysis/DIBuilder.h"
34#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/Loads.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Transforms/Utils/PromoteMemToReg.h"
39#include "llvm/Transforms/Utils/Local.h"
40#include "llvm/Transforms/Utils/SSAUpdater.h"
41#include "llvm/Support/CallSite.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/GetElementPtrTypeIterator.h"
45#include "llvm/Support/IRBuilder.h"
46#include "llvm/Support/MathExtras.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/ADT/SetVector.h"
49#include "llvm/ADT/SmallVector.h"
50#include "llvm/ADT/Statistic.h"
51using namespace llvm;
52
53STATISTIC(NumReplaced,  "Number of allocas broken up");
54STATISTIC(NumPromoted,  "Number of allocas promoted");
55STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
56STATISTIC(NumConverted, "Number of aggregates converted to scalar");
57STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
58
59namespace {
60  struct SROA : public FunctionPass {
61    SROA(int T, bool hasDT, char &ID)
62      : FunctionPass(ID), HasDomTree(hasDT) {
63      if (T == -1)
64        SRThreshold = 128;
65      else
66        SRThreshold = T;
67    }
68
69    bool runOnFunction(Function &F);
70
71    bool performScalarRepl(Function &F);
72    bool performPromotion(Function &F);
73
74  private:
75    bool HasDomTree;
76    TargetData *TD;
77
78    /// DeadInsts - Keep track of instructions we have made dead, so that
79    /// we can remove them after we are done working.
80    SmallVector<Value*, 32> DeadInsts;
81
82    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
83    /// information about the uses.  All these fields are initialized to false
84    /// and set to true when something is learned.
85    struct AllocaInfo {
86      /// The alloca to promote.
87      AllocaInst *AI;
88
89      /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
90      /// looping and avoid redundant work.
91      SmallPtrSet<PHINode*, 8> CheckedPHIs;
92
93      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
94      bool isUnsafe : 1;
95
96      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
97      bool isMemCpySrc : 1;
98
99      /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
100      bool isMemCpyDst : 1;
101
102      /// hasSubelementAccess - This is true if a subelement of the alloca is
103      /// ever accessed, or false if the alloca is only accessed with mem
104      /// intrinsics or load/store that only access the entire alloca at once.
105      bool hasSubelementAccess : 1;
106
107      /// hasALoadOrStore - This is true if there are any loads or stores to it.
108      /// The alloca may just be accessed with memcpy, for example, which would
109      /// not set this.
110      bool hasALoadOrStore : 1;
111
112      explicit AllocaInfo(AllocaInst *ai)
113        : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
114          hasSubelementAccess(false), hasALoadOrStore(false) {}
115    };
116
117    unsigned SRThreshold;
118
119    void MarkUnsafe(AllocaInfo &I, Instruction *User) {
120      I.isUnsafe = true;
121      DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
122    }
123
124    bool isSafeAllocaToScalarRepl(AllocaInst *AI);
125
126    void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
127    void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
128                                         AllocaInfo &Info);
129    void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
130    void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
131                         const Type *MemOpType, bool isStore, AllocaInfo &Info,
132                         Instruction *TheAccess, bool AllowWholeAccess);
133    bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
134    uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
135                                  const Type *&IdxTy);
136
137    void DoScalarReplacement(AllocaInst *AI,
138                             std::vector<AllocaInst*> &WorkList);
139    void DeleteDeadInstructions();
140
141    void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
142                              SmallVector<AllocaInst*, 32> &NewElts);
143    void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
144                        SmallVector<AllocaInst*, 32> &NewElts);
145    void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
146                    SmallVector<AllocaInst*, 32> &NewElts);
147    void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
148                                      AllocaInst *AI,
149                                      SmallVector<AllocaInst*, 32> &NewElts);
150    void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
151                                       SmallVector<AllocaInst*, 32> &NewElts);
152    void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
153                                      SmallVector<AllocaInst*, 32> &NewElts);
154
155    static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
156  };
157
158  // SROA_DT - SROA that uses DominatorTree.
159  struct SROA_DT : public SROA {
160    static char ID;
161  public:
162    SROA_DT(int T = -1) : SROA(T, true, ID) {
163      initializeSROA_DTPass(*PassRegistry::getPassRegistry());
164    }
165
166    // getAnalysisUsage - This pass does not require any passes, but we know it
167    // will not alter the CFG, so say so.
168    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
169      AU.addRequired<DominatorTree>();
170      AU.setPreservesCFG();
171    }
172  };
173
174  // SROA_SSAUp - SROA that uses SSAUpdater.
175  struct SROA_SSAUp : public SROA {
176    static char ID;
177  public:
178    SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
179      initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
180    }
181
182    // getAnalysisUsage - This pass does not require any passes, but we know it
183    // will not alter the CFG, so say so.
184    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
185      AU.setPreservesCFG();
186    }
187  };
188
189}
190
191char SROA_DT::ID = 0;
192char SROA_SSAUp::ID = 0;
193
194INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
195                "Scalar Replacement of Aggregates (DT)", false, false)
196INITIALIZE_PASS_DEPENDENCY(DominatorTree)
197INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
198                "Scalar Replacement of Aggregates (DT)", false, false)
199
200INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
201                      "Scalar Replacement of Aggregates (SSAUp)", false, false)
202INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
203                    "Scalar Replacement of Aggregates (SSAUp)", false, false)
204
205// Public interface to the ScalarReplAggregates pass
206FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
207                                                   bool UseDomTree) {
208  if (UseDomTree)
209    return new SROA_DT(Threshold);
210  return new SROA_SSAUp(Threshold);
211}
212
213
214//===----------------------------------------------------------------------===//
215// Convert To Scalar Optimization.
216//===----------------------------------------------------------------------===//
217
218namespace {
219/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
220/// optimization, which scans the uses of an alloca and determines if it can
221/// rewrite it in terms of a single new alloca that can be mem2reg'd.
222class ConvertToScalarInfo {
223  /// AllocaSize - The size of the alloca being considered in bytes.
224  unsigned AllocaSize;
225  const TargetData &TD;
226
227  /// IsNotTrivial - This is set to true if there is some access to the object
228  /// which means that mem2reg can't promote it.
229  bool IsNotTrivial;
230
231  /// VectorTy - This tracks the type that we should promote the vector to if
232  /// it is possible to turn it into a vector.  This starts out null, and if it
233  /// isn't possible to turn into a vector type, it gets set to VoidTy.
234  const Type *VectorTy;
235
236  /// HadAVector - True if there is at least one vector access to the alloca.
237  /// We don't want to turn random arrays into vectors and use vector element
238  /// insert/extract, but if there are element accesses to something that is
239  /// also declared as a vector, we do want to promote to a vector.
240  bool HadAVector;
241
242  /// HadNonMemTransferAccess - True if there is at least one access to the
243  /// alloca that is not a MemTransferInst.  We don't want to turn structs into
244  /// large integers unless there is some potential for optimization.
245  bool HadNonMemTransferAccess;
246
247public:
248  explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
249    : AllocaSize(Size), TD(td), IsNotTrivial(false), VectorTy(0),
250      HadAVector(false), HadNonMemTransferAccess(false) { }
251
252  AllocaInst *TryConvert(AllocaInst *AI);
253
254private:
255  bool CanConvertToScalar(Value *V, uint64_t Offset);
256  void MergeInType(const Type *In, uint64_t Offset);
257  bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
258  void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
259
260  Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
261                                    uint64_t Offset, IRBuilder<> &Builder);
262  Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
263                                   uint64_t Offset, IRBuilder<> &Builder);
264};
265} // end anonymous namespace.
266
267
268/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
269/// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
270/// alloca if possible or null if not.
271AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
272  // If we can't convert this scalar, or if mem2reg can trivially do it, bail
273  // out.
274  if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
275    return 0;
276
277  // If we were able to find a vector type that can handle this with
278  // insert/extract elements, and if there was at least one use that had
279  // a vector type, promote this to a vector.  We don't want to promote
280  // random stuff that doesn't use vectors (e.g. <9 x double>) because then
281  // we just get a lot of insert/extracts.  If at least one vector is
282  // involved, then we probably really do have a union of vector/array.
283  const Type *NewTy;
284  if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
285    DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
286          << *VectorTy << '\n');
287    NewTy = VectorTy;  // Use the vector type.
288  } else {
289    unsigned BitWidth = AllocaSize * 8;
290    if (!HadAVector && !HadNonMemTransferAccess &&
291        !TD.fitsInLegalInteger(BitWidth))
292      return 0;
293
294    DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
295    // Create and insert the integer alloca.
296    NewTy = IntegerType::get(AI->getContext(), BitWidth);
297  }
298  AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
299  ConvertUsesToScalar(AI, NewAI, 0);
300  return NewAI;
301}
302
303/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
304/// so far at the offset specified by Offset (which is specified in bytes).
305///
306/// There are three cases we handle here:
307///   1) A union of vector types of the same size and potentially its elements.
308///      Here we turn element accesses into insert/extract element operations.
309///      This promotes a <4 x float> with a store of float to the third element
310///      into a <4 x float> that uses insert element.
311///   2) A union of vector types with power-of-2 size differences, e.g. a float,
312///      <2 x float> and <4 x float>.  Here we turn element accesses into insert
313///      and extract element operations, and <2 x float> accesses into a cast to
314///      <2 x double>, an extract, and a cast back to <2 x float>.
315///   3) A fully general blob of memory, which we turn into some (potentially
316///      large) integer type with extract and insert operations where the loads
317///      and stores would mutate the memory.  We mark this by setting VectorTy
318///      to VoidTy.
319void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
320  // If we already decided to turn this into a blob of integer memory, there is
321  // nothing to be done.
322  if (VectorTy && VectorTy->isVoidTy())
323    return;
324
325  // If this could be contributing to a vector, analyze it.
326
327  // If the In type is a vector that is the same size as the alloca, see if it
328  // matches the existing VecTy.
329  if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
330    if (MergeInVectorType(VInTy, Offset))
331      return;
332  } else if (In->isFloatTy() || In->isDoubleTy() ||
333             (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
334              isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
335    // Full width accesses can be ignored, because they can always be turned
336    // into bitcasts.
337    unsigned EltSize = In->getPrimitiveSizeInBits()/8;
338    if (EltSize == AllocaSize)
339      return;
340
341    // If we're accessing something that could be an element of a vector, see
342    // if the implied vector agrees with what we already have and if Offset is
343    // compatible with it.
344    if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
345        (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
346      if (!VectorTy) {
347        VectorTy = VectorType::get(In, AllocaSize/EltSize);
348        return;
349      }
350
351      unsigned CurrentEltSize = cast<VectorType>(VectorTy)->getElementType()
352                                ->getPrimitiveSizeInBits()/8;
353      if (EltSize == CurrentEltSize)
354        return;
355
356      if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
357        return;
358    }
359  }
360
361  // Otherwise, we have a case that we can't handle with an optimized vector
362  // form.  We can still turn this into a large integer.
363  VectorTy = Type::getVoidTy(In->getContext());
364}
365
366/// MergeInVectorType - Handles the vector case of MergeInType, returning true
367/// if the type was successfully merged and false otherwise.
368bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
369                                            uint64_t Offset) {
370  // Remember if we saw a vector type.
371  HadAVector = true;
372
373  // TODO: Support nonzero offsets?
374  if (Offset != 0)
375    return false;
376
377  // Only allow vectors that are a power-of-2 away from the size of the alloca.
378  if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
379    return false;
380
381  // If this the first vector we see, remember the type so that we know the
382  // element size.
383  if (!VectorTy) {
384    VectorTy = VInTy;
385    return true;
386  }
387
388  unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
389  unsigned InBitWidth = VInTy->getBitWidth();
390
391  // Vectors of the same size can be converted using a simple bitcast.
392  if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
393    return true;
394
395  const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType();
396  const Type *InElementTy = cast<VectorType>(VInTy)->getElementType();
397
398  // Do not allow mixed integer and floating-point accesses from vectors of
399  // different sizes.
400  if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
401    return false;
402
403  if (ElementTy->isFloatingPointTy()) {
404    // Only allow floating-point vectors of different sizes if they have the
405    // same element type.
406    // TODO: This could be loosened a bit, but would anything benefit?
407    if (ElementTy != InElementTy)
408      return false;
409
410    // There are no arbitrary-precision floating-point types, which limits the
411    // number of legal vector types with larger element types that we can form
412    // to bitcast and extract a subvector.
413    // TODO: We could support some more cases with mixed fp128 and double here.
414    if (!(BitWidth == 64 || BitWidth == 128) ||
415        !(InBitWidth == 64 || InBitWidth == 128))
416      return false;
417  } else {
418    assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
419                                       "or floating-point.");
420    unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
421    unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
422
423    // Do not allow integer types smaller than a byte or types whose widths are
424    // not a multiple of a byte.
425    if (BitWidth < 8 || InBitWidth < 8 ||
426        BitWidth % 8 != 0 || InBitWidth % 8 != 0)
427      return false;
428  }
429
430  // Pick the largest of the two vector types.
431  if (InBitWidth > BitWidth)
432    VectorTy = VInTy;
433
434  return true;
435}
436
437/// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
438/// its accesses to a single vector type, return true and set VecTy to
439/// the new type.  If we could convert the alloca into a single promotable
440/// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
441/// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
442/// is the current offset from the base of the alloca being analyzed.
443///
444/// If we see at least one access to the value that is as a vector type, set the
445/// SawVec flag.
446bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
447  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
448    Instruction *User = cast<Instruction>(*UI);
449
450    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
451      // Don't break volatile loads.
452      if (LI->isVolatile())
453        return false;
454      // Don't touch MMX operations.
455      if (LI->getType()->isX86_MMXTy())
456        return false;
457      HadNonMemTransferAccess = true;
458      MergeInType(LI->getType(), Offset);
459      continue;
460    }
461
462    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
463      // Storing the pointer, not into the value?
464      if (SI->getOperand(0) == V || SI->isVolatile()) return false;
465      // Don't touch MMX operations.
466      if (SI->getOperand(0)->getType()->isX86_MMXTy())
467        return false;
468      HadNonMemTransferAccess = true;
469      MergeInType(SI->getOperand(0)->getType(), Offset);
470      continue;
471    }
472
473    if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
474      IsNotTrivial = true;  // Can't be mem2reg'd.
475      if (!CanConvertToScalar(BCI, Offset))
476        return false;
477      continue;
478    }
479
480    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
481      // If this is a GEP with a variable indices, we can't handle it.
482      if (!GEP->hasAllConstantIndices())
483        return false;
484
485      // Compute the offset that this GEP adds to the pointer.
486      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
487      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
488                                               &Indices[0], Indices.size());
489      // See if all uses can be converted.
490      if (!CanConvertToScalar(GEP, Offset+GEPOffset))
491        return false;
492      IsNotTrivial = true;  // Can't be mem2reg'd.
493      HadNonMemTransferAccess = true;
494      continue;
495    }
496
497    // If this is a constant sized memset of a constant value (e.g. 0) we can
498    // handle it.
499    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
500      // Store of constant value and constant size.
501      if (!isa<ConstantInt>(MSI->getValue()) ||
502          !isa<ConstantInt>(MSI->getLength()))
503        return false;
504      IsNotTrivial = true;  // Can't be mem2reg'd.
505      HadNonMemTransferAccess = true;
506      continue;
507    }
508
509    // If this is a memcpy or memmove into or out of the whole allocation, we
510    // can handle it like a load or store of the scalar type.
511    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
512      ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
513      if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
514        return false;
515
516      IsNotTrivial = true;  // Can't be mem2reg'd.
517      continue;
518    }
519
520    // Otherwise, we cannot handle this!
521    return false;
522  }
523
524  return true;
525}
526
527/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
528/// directly.  This happens when we are converting an "integer union" to a
529/// single integer scalar, or when we are converting a "vector union" to a
530/// vector with insert/extractelement instructions.
531///
532/// Offset is an offset from the original alloca, in bits that need to be
533/// shifted to the right.  By the end of this, there should be no uses of Ptr.
534void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
535                                              uint64_t Offset) {
536  while (!Ptr->use_empty()) {
537    Instruction *User = cast<Instruction>(Ptr->use_back());
538
539    if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
540      ConvertUsesToScalar(CI, NewAI, Offset);
541      CI->eraseFromParent();
542      continue;
543    }
544
545    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
546      // Compute the offset that this GEP adds to the pointer.
547      SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
548      uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
549                                               &Indices[0], Indices.size());
550      ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
551      GEP->eraseFromParent();
552      continue;
553    }
554
555    IRBuilder<> Builder(User);
556
557    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
558      // The load is a bit extract from NewAI shifted right by Offset bits.
559      Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
560      Value *NewLoadVal
561        = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
562      LI->replaceAllUsesWith(NewLoadVal);
563      LI->eraseFromParent();
564      continue;
565    }
566
567    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
568      assert(SI->getOperand(0) != Ptr && "Consistency error!");
569      Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
570      Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
571                                             Builder);
572      Builder.CreateStore(New, NewAI);
573      SI->eraseFromParent();
574
575      // If the load we just inserted is now dead, then the inserted store
576      // overwrote the entire thing.
577      if (Old->use_empty())
578        Old->eraseFromParent();
579      continue;
580    }
581
582    // If this is a constant sized memset of a constant value (e.g. 0) we can
583    // transform it into a store of the expanded constant value.
584    if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
585      assert(MSI->getRawDest() == Ptr && "Consistency error!");
586      unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
587      if (NumBytes != 0) {
588        unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
589
590        // Compute the value replicated the right number of times.
591        APInt APVal(NumBytes*8, Val);
592
593        // Splat the value if non-zero.
594        if (Val)
595          for (unsigned i = 1; i != NumBytes; ++i)
596            APVal |= APVal << 8;
597
598        Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
599        Value *New = ConvertScalar_InsertValue(
600                                    ConstantInt::get(User->getContext(), APVal),
601                                               Old, Offset, Builder);
602        Builder.CreateStore(New, NewAI);
603
604        // If the load we just inserted is now dead, then the memset overwrote
605        // the entire thing.
606        if (Old->use_empty())
607          Old->eraseFromParent();
608      }
609      MSI->eraseFromParent();
610      continue;
611    }
612
613    // If this is a memcpy or memmove into or out of the whole allocation, we
614    // can handle it like a load or store of the scalar type.
615    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
616      assert(Offset == 0 && "must be store to start of alloca");
617
618      // If the source and destination are both to the same alloca, then this is
619      // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
620      // as appropriate.
621      AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
622
623      if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
624        // Dest must be OrigAI, change this to be a load from the original
625        // pointer (bitcasted), then a store to our new alloca.
626        assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
627        Value *SrcPtr = MTI->getSource();
628        const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
629        const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
630        if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
631          AIPTy = PointerType::get(AIPTy->getElementType(),
632                                   SPTy->getAddressSpace());
633        }
634        SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
635
636        LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
637        SrcVal->setAlignment(MTI->getAlignment());
638        Builder.CreateStore(SrcVal, NewAI);
639      } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
640        // Src must be OrigAI, change this to be a load from NewAI then a store
641        // through the original dest pointer (bitcasted).
642        assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
643        LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
644
645        const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
646        const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
647        if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
648          AIPTy = PointerType::get(AIPTy->getElementType(),
649                                   DPTy->getAddressSpace());
650        }
651        Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
652
653        StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
654        NewStore->setAlignment(MTI->getAlignment());
655      } else {
656        // Noop transfer. Src == Dst
657      }
658
659      MTI->eraseFromParent();
660      continue;
661    }
662
663    llvm_unreachable("Unsupported operation!");
664  }
665}
666
667/// getScaledElementType - Gets a scaled element type for a partial vector
668/// access of an alloca. The input types must be integer or floating-point
669/// scalar or vector types, and the resulting type is an integer, float or
670/// double.
671static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
672                                        unsigned NewBitWidth) {
673  bool IsFP1 = Ty1->isFloatingPointTy() ||
674               (Ty1->isVectorTy() &&
675                cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
676  bool IsFP2 = Ty2->isFloatingPointTy() ||
677               (Ty2->isVectorTy() &&
678                cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
679
680  LLVMContext &Context = Ty1->getContext();
681
682  // Prefer floating-point types over integer types, as integer types may have
683  // been created by earlier scalar replacement.
684  if (IsFP1 || IsFP2) {
685    if (NewBitWidth == 32)
686      return Type::getFloatTy(Context);
687    if (NewBitWidth == 64)
688      return Type::getDoubleTy(Context);
689  }
690
691  return Type::getIntNTy(Context, NewBitWidth);
692}
693
694/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
695/// to another vector of the same element type which has the same allocation
696/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
697static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
698                                      IRBuilder<> &Builder) {
699  const Type *FromType = FromVal->getType();
700  const VectorType *FromVTy = cast<VectorType>(FromType);
701  const VectorType *ToVTy = cast<VectorType>(ToType);
702  assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
703         "Vectors must have the same element type");
704   Value *UnV = UndefValue::get(FromType);
705   unsigned numEltsFrom = FromVTy->getNumElements();
706   unsigned numEltsTo = ToVTy->getNumElements();
707
708   SmallVector<Constant*, 3> Args;
709   const Type* Int32Ty = Builder.getInt32Ty();
710   unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
711   unsigned i;
712   for (i=0; i != minNumElts; ++i)
713     Args.push_back(ConstantInt::get(Int32Ty, i));
714
715   if (i < numEltsTo) {
716     Constant* UnC = UndefValue::get(Int32Ty);
717     for (; i != numEltsTo; ++i)
718       Args.push_back(UnC);
719   }
720   Constant *Mask = ConstantVector::get(Args);
721   return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
722}
723
724/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
725/// or vector value FromVal, extracting the bits from the offset specified by
726/// Offset.  This returns the value, which is of type ToType.
727///
728/// This happens when we are converting an "integer union" to a single
729/// integer scalar, or when we are converting a "vector union" to a vector with
730/// insert/extractelement instructions.
731///
732/// Offset is an offset from the original alloca, in bits that need to be
733/// shifted to the right.
734Value *ConvertToScalarInfo::
735ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
736                           uint64_t Offset, IRBuilder<> &Builder) {
737  // If the load is of the whole new alloca, no conversion is needed.
738  const Type *FromType = FromVal->getType();
739  if (FromType == ToType && Offset == 0)
740    return FromVal;
741
742  // If the result alloca is a vector type, this is either an element
743  // access or a bitcast to another vector type of the same size.
744  if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
745    unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
746    unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
747    if (FromTypeSize == ToTypeSize) {
748      // If the two types have the same primitive size, use a bit cast.
749      // Otherwise, it is two vectors with the same element type that has
750      // the same allocation size but different number of elements so use
751      // a shuffle vector.
752      if (FromType->getPrimitiveSizeInBits() ==
753          ToType->getPrimitiveSizeInBits())
754        return Builder.CreateBitCast(FromVal, ToType, "tmp");
755      else
756        return CreateShuffleVectorCast(FromVal, ToType, Builder);
757    }
758
759    if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
760      assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
761             "of a smaller vector type at a nonzero offset.");
762
763      const Type *CastElementTy = getScaledElementType(FromType, ToType,
764                                                       ToTypeSize * 8);
765      unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
766
767      LLVMContext &Context = FromVal->getContext();
768      const Type *CastTy = VectorType::get(CastElementTy,
769                                           NumCastVectorElements);
770      Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
771
772      unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
773      unsigned Elt = Offset/EltSize;
774      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
775      Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
776                                        Type::getInt32Ty(Context), Elt), "tmp");
777      return Builder.CreateBitCast(Extract, ToType, "tmp");
778    }
779
780    // Otherwise it must be an element access.
781    unsigned Elt = 0;
782    if (Offset) {
783      unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
784      Elt = Offset/EltSize;
785      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
786    }
787    // Return the element extracted out of it.
788    Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
789                    Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
790    if (V->getType() != ToType)
791      V = Builder.CreateBitCast(V, ToType, "tmp");
792    return V;
793  }
794
795  // If ToType is a first class aggregate, extract out each of the pieces and
796  // use insertvalue's to form the FCA.
797  if (const StructType *ST = dyn_cast<StructType>(ToType)) {
798    const StructLayout &Layout = *TD.getStructLayout(ST);
799    Value *Res = UndefValue::get(ST);
800    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
801      Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
802                                        Offset+Layout.getElementOffsetInBits(i),
803                                              Builder);
804      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
805    }
806    return Res;
807  }
808
809  if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
810    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
811    Value *Res = UndefValue::get(AT);
812    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
813      Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
814                                              Offset+i*EltSize, Builder);
815      Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
816    }
817    return Res;
818  }
819
820  // Otherwise, this must be a union that was converted to an integer value.
821  const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
822
823  // If this is a big-endian system and the load is narrower than the
824  // full alloca type, we need to do a shift to get the right bits.
825  int ShAmt = 0;
826  if (TD.isBigEndian()) {
827    // On big-endian machines, the lowest bit is stored at the bit offset
828    // from the pointer given by getTypeStoreSizeInBits.  This matters for
829    // integers with a bitwidth that is not a multiple of 8.
830    ShAmt = TD.getTypeStoreSizeInBits(NTy) -
831            TD.getTypeStoreSizeInBits(ToType) - Offset;
832  } else {
833    ShAmt = Offset;
834  }
835
836  // Note: we support negative bitwidths (with shl) which are not defined.
837  // We do this to support (f.e.) loads off the end of a structure where
838  // only some bits are used.
839  if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
840    FromVal = Builder.CreateLShr(FromVal,
841                                 ConstantInt::get(FromVal->getType(),
842                                                           ShAmt), "tmp");
843  else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
844    FromVal = Builder.CreateShl(FromVal,
845                                ConstantInt::get(FromVal->getType(),
846                                                          -ShAmt), "tmp");
847
848  // Finally, unconditionally truncate the integer to the right width.
849  unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
850  if (LIBitWidth < NTy->getBitWidth())
851    FromVal =
852      Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
853                                                    LIBitWidth), "tmp");
854  else if (LIBitWidth > NTy->getBitWidth())
855    FromVal =
856       Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
857                                                    LIBitWidth), "tmp");
858
859  // If the result is an integer, this is a trunc or bitcast.
860  if (ToType->isIntegerTy()) {
861    // Should be done.
862  } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
863    // Just do a bitcast, we know the sizes match up.
864    FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
865  } else {
866    // Otherwise must be a pointer.
867    FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
868  }
869  assert(FromVal->getType() == ToType && "Didn't convert right?");
870  return FromVal;
871}
872
873/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
874/// or vector value "Old" at the offset specified by Offset.
875///
876/// This happens when we are converting an "integer union" to a
877/// single integer scalar, or when we are converting a "vector union" to a
878/// vector with insert/extractelement instructions.
879///
880/// Offset is an offset from the original alloca, in bits that need to be
881/// shifted to the right.
882Value *ConvertToScalarInfo::
883ConvertScalar_InsertValue(Value *SV, Value *Old,
884                          uint64_t Offset, IRBuilder<> &Builder) {
885  // Convert the stored type to the actual type, shift it left to insert
886  // then 'or' into place.
887  const Type *AllocaType = Old->getType();
888  LLVMContext &Context = Old->getContext();
889
890  if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
891    uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
892    uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
893
894    // Changing the whole vector with memset or with an access of a different
895    // vector type?
896    if (ValSize == VecSize) {
897      // If the two types have the same primitive size, use a bit cast.
898      // Otherwise, it is two vectors with the same element type that has
899      // the same allocation size but different number of elements so use
900      // a shuffle vector.
901      if (VTy->getPrimitiveSizeInBits() ==
902          SV->getType()->getPrimitiveSizeInBits())
903        return Builder.CreateBitCast(SV, AllocaType, "tmp");
904      else
905        return CreateShuffleVectorCast(SV, VTy, Builder);
906    }
907
908    if (isPowerOf2_64(VecSize / ValSize)) {
909      assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
910             "value of a smaller vector type at a nonzero offset.");
911
912      const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
913                                                       ValSize);
914      unsigned NumCastVectorElements = VecSize / ValSize;
915
916      LLVMContext &Context = SV->getContext();
917      const Type *OldCastTy = VectorType::get(CastElementTy,
918                                              NumCastVectorElements);
919      Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
920
921      Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
922
923      unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
924      unsigned Elt = Offset/EltSize;
925      assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
926      Value *Insert =
927        Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
928                                        Type::getInt32Ty(Context), Elt), "tmp");
929      return Builder.CreateBitCast(Insert, AllocaType, "tmp");
930    }
931
932    // Must be an element insertion.
933    assert(SV->getType() == VTy->getElementType());
934    uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
935    unsigned Elt = Offset/EltSize;
936    return Builder.CreateInsertElement(Old, SV,
937                     ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
938                                     "tmp");
939  }
940
941  // If SV is a first-class aggregate value, insert each value recursively.
942  if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
943    const StructLayout &Layout = *TD.getStructLayout(ST);
944    for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
945      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
946      Old = ConvertScalar_InsertValue(Elt, Old,
947                                      Offset+Layout.getElementOffsetInBits(i),
948                                      Builder);
949    }
950    return Old;
951  }
952
953  if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
954    uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
955    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
956      Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
957      Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
958    }
959    return Old;
960  }
961
962  // If SV is a float, convert it to the appropriate integer type.
963  // If it is a pointer, do the same.
964  unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
965  unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
966  unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
967  unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
968  if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
969    SV = Builder.CreateBitCast(SV,
970                            IntegerType::get(SV->getContext(),SrcWidth), "tmp");
971  else if (SV->getType()->isPointerTy())
972    SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
973
974  // Zero extend or truncate the value if needed.
975  if (SV->getType() != AllocaType) {
976    if (SV->getType()->getPrimitiveSizeInBits() <
977             AllocaType->getPrimitiveSizeInBits())
978      SV = Builder.CreateZExt(SV, AllocaType, "tmp");
979    else {
980      // Truncation may be needed if storing more than the alloca can hold
981      // (undefined behavior).
982      SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
983      SrcWidth = DestWidth;
984      SrcStoreWidth = DestStoreWidth;
985    }
986  }
987
988  // If this is a big-endian system and the store is narrower than the
989  // full alloca type, we need to do a shift to get the right bits.
990  int ShAmt = 0;
991  if (TD.isBigEndian()) {
992    // On big-endian machines, the lowest bit is stored at the bit offset
993    // from the pointer given by getTypeStoreSizeInBits.  This matters for
994    // integers with a bitwidth that is not a multiple of 8.
995    ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
996  } else {
997    ShAmt = Offset;
998  }
999
1000  // Note: we support negative bitwidths (with shr) which are not defined.
1001  // We do this to support (f.e.) stores off the end of a structure where
1002  // only some bits in the structure are set.
1003  APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1004  if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1005    SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1006                           ShAmt), "tmp");
1007    Mask <<= ShAmt;
1008  } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1009    SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1010                            -ShAmt), "tmp");
1011    Mask = Mask.lshr(-ShAmt);
1012  }
1013
1014  // Mask out the bits we are about to insert from the old value, and or
1015  // in the new bits.
1016  if (SrcWidth != DestWidth) {
1017    assert(DestWidth > SrcWidth);
1018    Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1019    SV = Builder.CreateOr(Old, SV, "ins");
1020  }
1021  return SV;
1022}
1023
1024
1025//===----------------------------------------------------------------------===//
1026// SRoA Driver
1027//===----------------------------------------------------------------------===//
1028
1029
1030bool SROA::runOnFunction(Function &F) {
1031  TD = getAnalysisIfAvailable<TargetData>();
1032
1033  bool Changed = performPromotion(F);
1034
1035  // FIXME: ScalarRepl currently depends on TargetData more than it
1036  // theoretically needs to. It should be refactored in order to support
1037  // target-independent IR. Until this is done, just skip the actual
1038  // scalar-replacement portion of this pass.
1039  if (!TD) return Changed;
1040
1041  while (1) {
1042    bool LocalChange = performScalarRepl(F);
1043    if (!LocalChange) break;   // No need to repromote if no scalarrepl
1044    Changed = true;
1045    LocalChange = performPromotion(F);
1046    if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
1047  }
1048
1049  return Changed;
1050}
1051
1052namespace {
1053class AllocaPromoter : public LoadAndStorePromoter {
1054  AllocaInst *AI;
1055public:
1056  AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1057                 DbgDeclareInst *DD, DIBuilder *&DB)
1058    : LoadAndStorePromoter(Insts, S, DD, DB), AI(0) {}
1059
1060  void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1061    // Remember which alloca we're promoting (for isInstInList).
1062    this->AI = AI;
1063    LoadAndStorePromoter::run(Insts);
1064    AI->eraseFromParent();
1065  }
1066
1067  virtual bool isInstInList(Instruction *I,
1068                            const SmallVectorImpl<Instruction*> &Insts) const {
1069    if (LoadInst *LI = dyn_cast<LoadInst>(I))
1070      return LI->getOperand(0) == AI;
1071    return cast<StoreInst>(I)->getPointerOperand() == AI;
1072  }
1073};
1074} // end anon namespace
1075
1076/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1077/// subsequently loaded can be rewritten to load both input pointers and then
1078/// select between the result, allowing the load of the alloca to be promoted.
1079/// From this:
1080///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1081///   %V = load i32* %P2
1082/// to:
1083///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1084///   %V2 = load i32* %Other
1085///   %V = select i1 %cond, i32 %V1, i32 %V2
1086///
1087/// We can do this to a select if its only uses are loads and if the operand to
1088/// the select can be loaded unconditionally.
1089static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1090  bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1091  bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1092
1093  for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1094       UI != UE; ++UI) {
1095    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1096    if (LI == 0 || LI->isVolatile()) return false;
1097
1098    // Both operands to the select need to be dereferencable, either absolutely
1099    // (e.g. allocas) or at this point because we can see other accesses to it.
1100    if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1101                                                    LI->getAlignment(), TD))
1102      return false;
1103    if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1104                                                    LI->getAlignment(), TD))
1105      return false;
1106  }
1107
1108  return true;
1109}
1110
1111/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1112/// subsequently loaded can be rewritten to load both input pointers in the pred
1113/// blocks and then PHI the results, allowing the load of the alloca to be
1114/// promoted.
1115/// From this:
1116///   %P2 = phi [i32* %Alloca, i32* %Other]
1117///   %V = load i32* %P2
1118/// to:
1119///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1120///   ...
1121///   %V2 = load i32* %Other
1122///   ...
1123///   %V = phi [i32 %V1, i32 %V2]
1124///
1125/// We can do this to a select if its only uses are loads and if the operand to
1126/// the select can be loaded unconditionally.
1127static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1128  // For now, we can only do this promotion if the load is in the same block as
1129  // the PHI, and if there are no stores between the phi and load.
1130  // TODO: Allow recursive phi users.
1131  // TODO: Allow stores.
1132  BasicBlock *BB = PN->getParent();
1133  unsigned MaxAlign = 0;
1134  for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1135       UI != UE; ++UI) {
1136    LoadInst *LI = dyn_cast<LoadInst>(*UI);
1137    if (LI == 0 || LI->isVolatile()) return false;
1138
1139    // For now we only allow loads in the same block as the PHI.  This is a
1140    // common case that happens when instcombine merges two loads through a PHI.
1141    if (LI->getParent() != BB) return false;
1142
1143    // Ensure that there are no instructions between the PHI and the load that
1144    // could store.
1145    for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1146      if (BBI->mayWriteToMemory())
1147        return false;
1148
1149    MaxAlign = std::max(MaxAlign, LI->getAlignment());
1150  }
1151
1152  // Okay, we know that we have one or more loads in the same block as the PHI.
1153  // We can transform this if it is safe to push the loads into the predecessor
1154  // blocks.  The only thing to watch out for is that we can't put a possibly
1155  // trapping load in the predecessor if it is a critical edge.
1156  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1157    BasicBlock *Pred = PN->getIncomingBlock(i);
1158
1159    // If the predecessor has a single successor, then the edge isn't critical.
1160    if (Pred->getTerminator()->getNumSuccessors() == 1)
1161      continue;
1162
1163    Value *InVal = PN->getIncomingValue(i);
1164
1165    // If the InVal is an invoke in the pred, we can't put a load on the edge.
1166    if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1167      if (II->getParent() == Pred)
1168        return false;
1169
1170    // If this pointer is always safe to load, or if we can prove that there is
1171    // already a load in the block, then we can move the load to the pred block.
1172    if (InVal->isDereferenceablePointer() ||
1173        isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1174      continue;
1175
1176    return false;
1177  }
1178
1179  return true;
1180}
1181
1182
1183/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1184/// direct (non-volatile) loads and stores to it.  If the alloca is close but
1185/// not quite there, this will transform the code to allow promotion.  As such,
1186/// it is a non-pure predicate.
1187static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1188  SetVector<Instruction*, SmallVector<Instruction*, 4>,
1189            SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1190
1191  for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1192       UI != UE; ++UI) {
1193    User *U = *UI;
1194    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1195      if (LI->isVolatile())
1196        return false;
1197      continue;
1198    }
1199
1200    if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1201      if (SI->getOperand(0) == AI || SI->isVolatile())
1202        return false;   // Don't allow a store OF the AI, only INTO the AI.
1203      continue;
1204    }
1205
1206    if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1207      // If the condition being selected on is a constant, fold the select, yes
1208      // this does (rarely) happen early on.
1209      if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1210        Value *Result = SI->getOperand(1+CI->isZero());
1211        SI->replaceAllUsesWith(Result);
1212        SI->eraseFromParent();
1213
1214        // This is very rare and we just scrambled the use list of AI, start
1215        // over completely.
1216        return tryToMakeAllocaBePromotable(AI, TD);
1217      }
1218
1219      // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1220      // loads, then we can transform this by rewriting the select.
1221      if (!isSafeSelectToSpeculate(SI, TD))
1222        return false;
1223
1224      InstsToRewrite.insert(SI);
1225      continue;
1226    }
1227
1228    if (PHINode *PN = dyn_cast<PHINode>(U)) {
1229      if (PN->use_empty()) {  // Dead PHIs can be stripped.
1230        InstsToRewrite.insert(PN);
1231        continue;
1232      }
1233
1234      // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1235      // in the pred blocks, then we can transform this by rewriting the PHI.
1236      if (!isSafePHIToSpeculate(PN, TD))
1237        return false;
1238
1239      InstsToRewrite.insert(PN);
1240      continue;
1241    }
1242
1243    return false;
1244  }
1245
1246  // If there are no instructions to rewrite, then all uses are load/stores and
1247  // we're done!
1248  if (InstsToRewrite.empty())
1249    return true;
1250
1251  // If we have instructions that need to be rewritten for this to be promotable
1252  // take care of it now.
1253  for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1254    if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1255      // Selects in InstsToRewrite only have load uses.  Rewrite each as two
1256      // loads with a new select.
1257      while (!SI->use_empty()) {
1258        LoadInst *LI = cast<LoadInst>(SI->use_back());
1259
1260        IRBuilder<> Builder(LI);
1261        LoadInst *TrueLoad =
1262          Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1263        LoadInst *FalseLoad =
1264          Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1265
1266        // Transfer alignment and TBAA info if present.
1267        TrueLoad->setAlignment(LI->getAlignment());
1268        FalseLoad->setAlignment(LI->getAlignment());
1269        if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1270          TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1271          FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1272        }
1273
1274        Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1275        V->takeName(LI);
1276        LI->replaceAllUsesWith(V);
1277        LI->eraseFromParent();
1278      }
1279
1280      // Now that all the loads are gone, the select is gone too.
1281      SI->eraseFromParent();
1282      continue;
1283    }
1284
1285    // Otherwise, we have a PHI node which allows us to push the loads into the
1286    // predecessors.
1287    PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1288    if (PN->use_empty()) {
1289      PN->eraseFromParent();
1290      continue;
1291    }
1292
1293    const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1294    PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1295                                     PN->getName()+".ld", PN);
1296
1297    // Get the TBAA tag and alignment to use from one of the loads.  It doesn't
1298    // matter which one we get and if any differ, it doesn't matter.
1299    LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1300    MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1301    unsigned Align = SomeLoad->getAlignment();
1302
1303    // Rewrite all loads of the PN to use the new PHI.
1304    while (!PN->use_empty()) {
1305      LoadInst *LI = cast<LoadInst>(PN->use_back());
1306      LI->replaceAllUsesWith(NewPN);
1307      LI->eraseFromParent();
1308    }
1309
1310    // Inject loads into all of the pred blocks.  Keep track of which blocks we
1311    // insert them into in case we have multiple edges from the same block.
1312    DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1313
1314    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1315      BasicBlock *Pred = PN->getIncomingBlock(i);
1316      LoadInst *&Load = InsertedLoads[Pred];
1317      if (Load == 0) {
1318        Load = new LoadInst(PN->getIncomingValue(i),
1319                            PN->getName() + "." + Pred->getName(),
1320                            Pred->getTerminator());
1321        Load->setAlignment(Align);
1322        if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1323      }
1324
1325      NewPN->addIncoming(Load, Pred);
1326    }
1327
1328    PN->eraseFromParent();
1329  }
1330
1331  ++NumAdjusted;
1332  return true;
1333}
1334
1335bool SROA::performPromotion(Function &F) {
1336  std::vector<AllocaInst*> Allocas;
1337  DominatorTree *DT = 0;
1338  if (HasDomTree)
1339    DT = &getAnalysis<DominatorTree>();
1340
1341  BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
1342
1343  bool Changed = false;
1344  SmallVector<Instruction*, 64> Insts;
1345  DIBuilder *DIB = 0;
1346  while (1) {
1347    Allocas.clear();
1348
1349    // Find allocas that are safe to promote, by looking at all instructions in
1350    // the entry node
1351    for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1352      if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
1353        if (tryToMakeAllocaBePromotable(AI, TD))
1354          Allocas.push_back(AI);
1355
1356    if (Allocas.empty()) break;
1357
1358    if (HasDomTree)
1359      PromoteMemToReg(Allocas, *DT);
1360    else {
1361      SSAUpdater SSA;
1362      for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1363        AllocaInst *AI = Allocas[i];
1364
1365        // Build list of instructions to promote.
1366        for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1367             UI != E; ++UI)
1368          Insts.push_back(cast<Instruction>(*UI));
1369
1370        DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
1371        if (DDI && !DIB)
1372          DIB = new DIBuilder(*AI->getParent()->getParent()->getParent());
1373        AllocaPromoter(Insts, SSA, DDI, DIB).run(AI, Insts);
1374        Insts.clear();
1375      }
1376    }
1377    NumPromoted += Allocas.size();
1378    Changed = true;
1379  }
1380
1381  // FIXME: Is there a better way to handle the lazy initialization of DIB
1382  // so that there doesn't need to be an explicit delete?
1383  delete DIB;
1384
1385  return Changed;
1386}
1387
1388
1389/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1390/// SROA.  It must be a struct or array type with a small number of elements.
1391static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1392  const Type *T = AI->getAllocatedType();
1393  // Do not promote any struct into more than 32 separate vars.
1394  if (const StructType *ST = dyn_cast<StructType>(T))
1395    return ST->getNumElements() <= 32;
1396  // Arrays are much less likely to be safe for SROA; only consider
1397  // them if they are very small.
1398  if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1399    return AT->getNumElements() <= 8;
1400  return false;
1401}
1402
1403
1404// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1405// which runs on all of the malloc/alloca instructions in the function, removing
1406// them if they are only used by getelementptr instructions.
1407//
1408bool SROA::performScalarRepl(Function &F) {
1409  std::vector<AllocaInst*> WorkList;
1410
1411  // Scan the entry basic block, adding allocas to the worklist.
1412  BasicBlock &BB = F.getEntryBlock();
1413  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1414    if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1415      WorkList.push_back(A);
1416
1417  // Process the worklist
1418  bool Changed = false;
1419  while (!WorkList.empty()) {
1420    AllocaInst *AI = WorkList.back();
1421    WorkList.pop_back();
1422
1423    // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
1424    // with unused elements.
1425    if (AI->use_empty()) {
1426      AI->eraseFromParent();
1427      Changed = true;
1428      continue;
1429    }
1430
1431    // If this alloca is impossible for us to promote, reject it early.
1432    if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1433      continue;
1434
1435    // Check to see if this allocation is only modified by a memcpy/memmove from
1436    // a constant global.  If this is the case, we can change all users to use
1437    // the constant global instead.  This is commonly produced by the CFE by
1438    // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1439    // is only subsequently read.
1440    if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
1441      DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1442      DEBUG(dbgs() << "  memcpy = " << *TheCopy << '\n');
1443      Constant *TheSrc = cast<Constant>(TheCopy->getSource());
1444      AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1445      TheCopy->eraseFromParent();  // Don't mutate the global.
1446      AI->eraseFromParent();
1447      ++NumGlobals;
1448      Changed = true;
1449      continue;
1450    }
1451
1452    // Check to see if we can perform the core SROA transformation.  We cannot
1453    // transform the allocation instruction if it is an array allocation
1454    // (allocations OF arrays are ok though), and an allocation of a scalar
1455    // value cannot be decomposed at all.
1456    uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1457
1458    // Do not promote [0 x %struct].
1459    if (AllocaSize == 0) continue;
1460
1461    // Do not promote any struct whose size is too big.
1462    if (AllocaSize > SRThreshold) continue;
1463
1464    // If the alloca looks like a good candidate for scalar replacement, and if
1465    // all its users can be transformed, then split up the aggregate into its
1466    // separate elements.
1467    if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1468      DoScalarReplacement(AI, WorkList);
1469      Changed = true;
1470      continue;
1471    }
1472
1473    // If we can turn this aggregate value (potentially with casts) into a
1474    // simple scalar value that can be mem2reg'd into a register value.
1475    // IsNotTrivial tracks whether this is something that mem2reg could have
1476    // promoted itself.  If so, we don't want to transform it needlessly.  Note
1477    // that we can't just check based on the type: the alloca may be of an i32
1478    // but that has pointer arithmetic to set byte 3 of it or something.
1479    if (AllocaInst *NewAI =
1480          ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1481      NewAI->takeName(AI);
1482      AI->eraseFromParent();
1483      ++NumConverted;
1484      Changed = true;
1485      continue;
1486    }
1487
1488    // Otherwise, couldn't process this alloca.
1489  }
1490
1491  return Changed;
1492}
1493
1494/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1495/// predicate, do SROA now.
1496void SROA::DoScalarReplacement(AllocaInst *AI,
1497                               std::vector<AllocaInst*> &WorkList) {
1498  DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1499  SmallVector<AllocaInst*, 32> ElementAllocas;
1500  if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1501    ElementAllocas.reserve(ST->getNumContainedTypes());
1502    for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1503      AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1504                                      AI->getAlignment(),
1505                                      AI->getName() + "." + Twine(i), AI);
1506      ElementAllocas.push_back(NA);
1507      WorkList.push_back(NA);  // Add to worklist for recursive processing
1508    }
1509  } else {
1510    const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1511    ElementAllocas.reserve(AT->getNumElements());
1512    const Type *ElTy = AT->getElementType();
1513    for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1514      AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1515                                      AI->getName() + "." + Twine(i), AI);
1516      ElementAllocas.push_back(NA);
1517      WorkList.push_back(NA);  // Add to worklist for recursive processing
1518    }
1519  }
1520
1521  // Now that we have created the new alloca instructions, rewrite all the
1522  // uses of the old alloca.
1523  RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1524
1525  // Now erase any instructions that were made dead while rewriting the alloca.
1526  DeleteDeadInstructions();
1527  AI->eraseFromParent();
1528
1529  ++NumReplaced;
1530}
1531
1532/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1533/// recursively including all their operands that become trivially dead.
1534void SROA::DeleteDeadInstructions() {
1535  while (!DeadInsts.empty()) {
1536    Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1537
1538    for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1539      if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1540        // Zero out the operand and see if it becomes trivially dead.
1541        // (But, don't add allocas to the dead instruction list -- they are
1542        // already on the worklist and will be deleted separately.)
1543        *OI = 0;
1544        if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1545          DeadInsts.push_back(U);
1546      }
1547
1548    I->eraseFromParent();
1549  }
1550}
1551
1552/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1553/// performing scalar replacement of alloca AI.  The results are flagged in
1554/// the Info parameter.  Offset indicates the position within AI that is
1555/// referenced by this instruction.
1556void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1557                               AllocaInfo &Info) {
1558  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1559    Instruction *User = cast<Instruction>(*UI);
1560
1561    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1562      isSafeForScalarRepl(BC, Offset, Info);
1563    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1564      uint64_t GEPOffset = Offset;
1565      isSafeGEP(GEPI, GEPOffset, Info);
1566      if (!Info.isUnsafe)
1567        isSafeForScalarRepl(GEPI, GEPOffset, Info);
1568    } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1569      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1570      if (Length == 0)
1571        return MarkUnsafe(Info, User);
1572      isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1573                      UI.getOperandNo() == 0, Info, MI,
1574                      true /*AllowWholeAccess*/);
1575    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1576      if (LI->isVolatile())
1577        return MarkUnsafe(Info, User);
1578      const Type *LIType = LI->getType();
1579      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1580                      LIType, false, Info, LI, true /*AllowWholeAccess*/);
1581      Info.hasALoadOrStore = true;
1582
1583    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1584      // Store is ok if storing INTO the pointer, not storing the pointer
1585      if (SI->isVolatile() || SI->getOperand(0) == I)
1586        return MarkUnsafe(Info, User);
1587
1588      const Type *SIType = SI->getOperand(0)->getType();
1589      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1590                      SIType, true, Info, SI, true /*AllowWholeAccess*/);
1591      Info.hasALoadOrStore = true;
1592    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1593      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1594    } else {
1595      return MarkUnsafe(Info, User);
1596    }
1597    if (Info.isUnsafe) return;
1598  }
1599}
1600
1601
1602/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1603/// derived from the alloca, we can often still split the alloca into elements.
1604/// This is useful if we have a large alloca where one element is phi'd
1605/// together somewhere: we can SRoA and promote all the other elements even if
1606/// we end up not being able to promote this one.
1607///
1608/// All we require is that the uses of the PHI do not index into other parts of
1609/// the alloca.  The most important use case for this is single load and stores
1610/// that are PHI'd together, which can happen due to code sinking.
1611void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1612                                           AllocaInfo &Info) {
1613  // If we've already checked this PHI, don't do it again.
1614  if (PHINode *PN = dyn_cast<PHINode>(I))
1615    if (!Info.CheckedPHIs.insert(PN))
1616      return;
1617
1618  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1619    Instruction *User = cast<Instruction>(*UI);
1620
1621    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1622      isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1623    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1624      // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
1625      // but would have to prove that we're staying inside of an element being
1626      // promoted.
1627      if (!GEPI->hasAllZeroIndices())
1628        return MarkUnsafe(Info, User);
1629      isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1630    } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1631      if (LI->isVolatile())
1632        return MarkUnsafe(Info, User);
1633      const Type *LIType = LI->getType();
1634      isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1635                      LIType, false, Info, LI, false /*AllowWholeAccess*/);
1636      Info.hasALoadOrStore = true;
1637
1638    } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1639      // Store is ok if storing INTO the pointer, not storing the pointer
1640      if (SI->isVolatile() || SI->getOperand(0) == I)
1641        return MarkUnsafe(Info, User);
1642
1643      const Type *SIType = SI->getOperand(0)->getType();
1644      isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1645                      SIType, true, Info, SI, false /*AllowWholeAccess*/);
1646      Info.hasALoadOrStore = true;
1647    } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1648      isSafePHISelectUseForScalarRepl(User, Offset, Info);
1649    } else {
1650      return MarkUnsafe(Info, User);
1651    }
1652    if (Info.isUnsafe) return;
1653  }
1654}
1655
1656/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1657/// replacement.  It is safe when all the indices are constant, in-bounds
1658/// references, and when the resulting offset corresponds to an element within
1659/// the alloca type.  The results are flagged in the Info parameter.  Upon
1660/// return, Offset is adjusted as specified by the GEP indices.
1661void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1662                     uint64_t &Offset, AllocaInfo &Info) {
1663  gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1664  if (GEPIt == E)
1665    return;
1666
1667  // Walk through the GEP type indices, checking the types that this indexes
1668  // into.
1669  for (; GEPIt != E; ++GEPIt) {
1670    // Ignore struct elements, no extra checking needed for these.
1671    if ((*GEPIt)->isStructTy())
1672      continue;
1673
1674    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1675    if (!IdxVal)
1676      return MarkUnsafe(Info, GEPI);
1677  }
1678
1679  // Compute the offset due to this GEP and check if the alloca has a
1680  // component element at that offset.
1681  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1682  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1683                                 &Indices[0], Indices.size());
1684  if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1685    MarkUnsafe(Info, GEPI);
1686}
1687
1688/// isHomogeneousAggregate - Check if type T is a struct or array containing
1689/// elements of the same type (which is always true for arrays).  If so,
1690/// return true with NumElts and EltTy set to the number of elements and the
1691/// element type, respectively.
1692static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1693                                   const Type *&EltTy) {
1694  if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1695    NumElts = AT->getNumElements();
1696    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1697    return true;
1698  }
1699  if (const StructType *ST = dyn_cast<StructType>(T)) {
1700    NumElts = ST->getNumContainedTypes();
1701    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1702    for (unsigned n = 1; n < NumElts; ++n) {
1703      if (ST->getContainedType(n) != EltTy)
1704        return false;
1705    }
1706    return true;
1707  }
1708  return false;
1709}
1710
1711/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1712/// "homogeneous" aggregates with the same element type and number of elements.
1713static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1714  if (T1 == T2)
1715    return true;
1716
1717  unsigned NumElts1, NumElts2;
1718  const Type *EltTy1, *EltTy2;
1719  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1720      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1721      NumElts1 == NumElts2 &&
1722      EltTy1 == EltTy2)
1723    return true;
1724
1725  return false;
1726}
1727
1728/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1729/// alloca or has an offset and size that corresponds to a component element
1730/// within it.  The offset checked here may have been formed from a GEP with a
1731/// pointer bitcasted to a different type.
1732///
1733/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1734/// unit.  If false, it only allows accesses known to be in a single element.
1735void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1736                           const Type *MemOpType, bool isStore,
1737                           AllocaInfo &Info, Instruction *TheAccess,
1738                           bool AllowWholeAccess) {
1739  // Check if this is a load/store of the entire alloca.
1740  if (Offset == 0 && AllowWholeAccess &&
1741      MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1742    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1743    // loads/stores (which are essentially the same as the MemIntrinsics with
1744    // regard to copying padding between elements).  But, if an alloca is
1745    // flagged as both a source and destination of such operations, we'll need
1746    // to check later for padding between elements.
1747    if (!MemOpType || MemOpType->isIntegerTy()) {
1748      if (isStore)
1749        Info.isMemCpyDst = true;
1750      else
1751        Info.isMemCpySrc = true;
1752      return;
1753    }
1754    // This is also safe for references using a type that is compatible with
1755    // the type of the alloca, so that loads/stores can be rewritten using
1756    // insertvalue/extractvalue.
1757    if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1758      Info.hasSubelementAccess = true;
1759      return;
1760    }
1761  }
1762  // Check if the offset/size correspond to a component within the alloca type.
1763  const Type *T = Info.AI->getAllocatedType();
1764  if (TypeHasComponent(T, Offset, MemSize)) {
1765    Info.hasSubelementAccess = true;
1766    return;
1767  }
1768
1769  return MarkUnsafe(Info, TheAccess);
1770}
1771
1772/// TypeHasComponent - Return true if T has a component type with the
1773/// specified offset and size.  If Size is zero, do not check the size.
1774bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1775  const Type *EltTy;
1776  uint64_t EltSize;
1777  if (const StructType *ST = dyn_cast<StructType>(T)) {
1778    const StructLayout *Layout = TD->getStructLayout(ST);
1779    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1780    EltTy = ST->getContainedType(EltIdx);
1781    EltSize = TD->getTypeAllocSize(EltTy);
1782    Offset -= Layout->getElementOffset(EltIdx);
1783  } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1784    EltTy = AT->getElementType();
1785    EltSize = TD->getTypeAllocSize(EltTy);
1786    if (Offset >= AT->getNumElements() * EltSize)
1787      return false;
1788    Offset %= EltSize;
1789  } else {
1790    return false;
1791  }
1792  if (Offset == 0 && (Size == 0 || EltSize == Size))
1793    return true;
1794  // Check if the component spans multiple elements.
1795  if (Offset + Size > EltSize)
1796    return false;
1797  return TypeHasComponent(EltTy, Offset, Size);
1798}
1799
1800/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1801/// the instruction I, which references it, to use the separate elements.
1802/// Offset indicates the position within AI that is referenced by this
1803/// instruction.
1804void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1805                                SmallVector<AllocaInst*, 32> &NewElts) {
1806  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1807    Use &TheUse = UI.getUse();
1808    Instruction *User = cast<Instruction>(*UI++);
1809
1810    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1811      RewriteBitCast(BC, AI, Offset, NewElts);
1812      continue;
1813    }
1814
1815    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1816      RewriteGEP(GEPI, AI, Offset, NewElts);
1817      continue;
1818    }
1819
1820    if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1821      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1822      uint64_t MemSize = Length->getZExtValue();
1823      if (Offset == 0 &&
1824          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1825        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1826      // Otherwise the intrinsic can only touch a single element and the
1827      // address operand will be updated, so nothing else needs to be done.
1828      continue;
1829    }
1830
1831    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1832      const Type *LIType = LI->getType();
1833
1834      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1835        // Replace:
1836        //   %res = load { i32, i32 }* %alloc
1837        // with:
1838        //   %load.0 = load i32* %alloc.0
1839        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1840        //   %load.1 = load i32* %alloc.1
1841        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1842        // (Also works for arrays instead of structs)
1843        Value *Insert = UndefValue::get(LIType);
1844        IRBuilder<> Builder(LI);
1845        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1846          Value *Load = Builder.CreateLoad(NewElts[i], "load");
1847          Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1848        }
1849        LI->replaceAllUsesWith(Insert);
1850        DeadInsts.push_back(LI);
1851      } else if (LIType->isIntegerTy() &&
1852                 TD->getTypeAllocSize(LIType) ==
1853                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1854        // If this is a load of the entire alloca to an integer, rewrite it.
1855        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1856      }
1857      continue;
1858    }
1859
1860    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1861      Value *Val = SI->getOperand(0);
1862      const Type *SIType = Val->getType();
1863      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1864        // Replace:
1865        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1866        // with:
1867        //   %val.0 = extractvalue { i32, i32 } %val, 0
1868        //   store i32 %val.0, i32* %alloc.0
1869        //   %val.1 = extractvalue { i32, i32 } %val, 1
1870        //   store i32 %val.1, i32* %alloc.1
1871        // (Also works for arrays instead of structs)
1872        IRBuilder<> Builder(SI);
1873        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1874          Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1875          Builder.CreateStore(Extract, NewElts[i]);
1876        }
1877        DeadInsts.push_back(SI);
1878      } else if (SIType->isIntegerTy() &&
1879                 TD->getTypeAllocSize(SIType) ==
1880                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1881        // If this is a store of the entire alloca from an integer, rewrite it.
1882        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1883      }
1884      continue;
1885    }
1886
1887    if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1888      // If we have a PHI user of the alloca itself (as opposed to a GEP or
1889      // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
1890      // the new pointer.
1891      if (!isa<AllocaInst>(I)) continue;
1892
1893      assert(Offset == 0 && NewElts[0] &&
1894             "Direct alloca use should have a zero offset");
1895
1896      // If we have a use of the alloca, we know the derived uses will be
1897      // utilizing just the first element of the scalarized result.  Insert a
1898      // bitcast of the first alloca before the user as required.
1899      AllocaInst *NewAI = NewElts[0];
1900      BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1901      NewAI->moveBefore(BCI);
1902      TheUse = BCI;
1903      continue;
1904    }
1905  }
1906}
1907
1908/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1909/// and recursively continue updating all of its uses.
1910void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1911                          SmallVector<AllocaInst*, 32> &NewElts) {
1912  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1913  if (BC->getOperand(0) != AI)
1914    return;
1915
1916  // The bitcast references the original alloca.  Replace its uses with
1917  // references to the first new element alloca.
1918  Instruction *Val = NewElts[0];
1919  if (Val->getType() != BC->getDestTy()) {
1920    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1921    Val->takeName(BC);
1922  }
1923  BC->replaceAllUsesWith(Val);
1924  DeadInsts.push_back(BC);
1925}
1926
1927/// FindElementAndOffset - Return the index of the element containing Offset
1928/// within the specified type, which must be either a struct or an array.
1929/// Sets T to the type of the element and Offset to the offset within that
1930/// element.  IdxTy is set to the type of the index result to be used in a
1931/// GEP instruction.
1932uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1933                                    const Type *&IdxTy) {
1934  uint64_t Idx = 0;
1935  if (const StructType *ST = dyn_cast<StructType>(T)) {
1936    const StructLayout *Layout = TD->getStructLayout(ST);
1937    Idx = Layout->getElementContainingOffset(Offset);
1938    T = ST->getContainedType(Idx);
1939    Offset -= Layout->getElementOffset(Idx);
1940    IdxTy = Type::getInt32Ty(T->getContext());
1941    return Idx;
1942  }
1943  const ArrayType *AT = cast<ArrayType>(T);
1944  T = AT->getElementType();
1945  uint64_t EltSize = TD->getTypeAllocSize(T);
1946  Idx = Offset / EltSize;
1947  Offset -= Idx * EltSize;
1948  IdxTy = Type::getInt64Ty(T->getContext());
1949  return Idx;
1950}
1951
1952/// RewriteGEP - Check if this GEP instruction moves the pointer across
1953/// elements of the alloca that are being split apart, and if so, rewrite
1954/// the GEP to be relative to the new element.
1955void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1956                      SmallVector<AllocaInst*, 32> &NewElts) {
1957  uint64_t OldOffset = Offset;
1958  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1959  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1960                                 &Indices[0], Indices.size());
1961
1962  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1963
1964  const Type *T = AI->getAllocatedType();
1965  const Type *IdxTy;
1966  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1967  if (GEPI->getOperand(0) == AI)
1968    OldIdx = ~0ULL; // Force the GEP to be rewritten.
1969
1970  T = AI->getAllocatedType();
1971  uint64_t EltOffset = Offset;
1972  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1973
1974  // If this GEP does not move the pointer across elements of the alloca
1975  // being split, then it does not needs to be rewritten.
1976  if (Idx == OldIdx)
1977    return;
1978
1979  const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1980  SmallVector<Value*, 8> NewArgs;
1981  NewArgs.push_back(Constant::getNullValue(i32Ty));
1982  while (EltOffset != 0) {
1983    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1984    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1985  }
1986  Instruction *Val = NewElts[Idx];
1987  if (NewArgs.size() > 1) {
1988    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1989                                            NewArgs.end(), "", GEPI);
1990    Val->takeName(GEPI);
1991  }
1992  if (Val->getType() != GEPI->getType())
1993    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1994  GEPI->replaceAllUsesWith(Val);
1995  DeadInsts.push_back(GEPI);
1996}
1997
1998/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1999/// Rewrite it to copy or set the elements of the scalarized memory.
2000void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2001                                        AllocaInst *AI,
2002                                        SmallVector<AllocaInst*, 32> &NewElts) {
2003  // If this is a memcpy/memmove, construct the other pointer as the
2004  // appropriate type.  The "Other" pointer is the pointer that goes to memory
2005  // that doesn't have anything to do with the alloca that we are promoting. For
2006  // memset, this Value* stays null.
2007  Value *OtherPtr = 0;
2008  unsigned MemAlignment = MI->getAlignment();
2009  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2010    if (Inst == MTI->getRawDest())
2011      OtherPtr = MTI->getRawSource();
2012    else {
2013      assert(Inst == MTI->getRawSource());
2014      OtherPtr = MTI->getRawDest();
2015    }
2016  }
2017
2018  // If there is an other pointer, we want to convert it to the same pointer
2019  // type as AI has, so we can GEP through it safely.
2020  if (OtherPtr) {
2021    unsigned AddrSpace =
2022      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2023
2024    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
2025    // optimization, but it's also required to detect the corner case where
2026    // both pointer operands are referencing the same memory, and where
2027    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
2028    // function is only called for mem intrinsics that access the whole
2029    // aggregate, so non-zero GEPs are not an issue here.)
2030    OtherPtr = OtherPtr->stripPointerCasts();
2031
2032    // Copying the alloca to itself is a no-op: just delete it.
2033    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2034      // This code will run twice for a no-op memcpy -- once for each operand.
2035      // Put only one reference to MI on the DeadInsts list.
2036      for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2037             E = DeadInsts.end(); I != E; ++I)
2038        if (*I == MI) return;
2039      DeadInsts.push_back(MI);
2040      return;
2041    }
2042
2043    // If the pointer is not the right type, insert a bitcast to the right
2044    // type.
2045    const Type *NewTy =
2046      PointerType::get(AI->getType()->getElementType(), AddrSpace);
2047
2048    if (OtherPtr->getType() != NewTy)
2049      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2050  }
2051
2052  // Process each element of the aggregate.
2053  bool SROADest = MI->getRawDest() == Inst;
2054
2055  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2056
2057  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2058    // If this is a memcpy/memmove, emit a GEP of the other element address.
2059    Value *OtherElt = 0;
2060    unsigned OtherEltAlign = MemAlignment;
2061
2062    if (OtherPtr) {
2063      Value *Idx[2] = { Zero,
2064                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2065      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
2066                                              OtherPtr->getName()+"."+Twine(i),
2067                                                   MI);
2068      uint64_t EltOffset;
2069      const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2070      const Type *OtherTy = OtherPtrTy->getElementType();
2071      if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
2072        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2073      } else {
2074        const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2075        EltOffset = TD->getTypeAllocSize(EltTy)*i;
2076      }
2077
2078      // The alignment of the other pointer is the guaranteed alignment of the
2079      // element, which is affected by both the known alignment of the whole
2080      // mem intrinsic and the alignment of the element.  If the alignment of
2081      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2082      // known alignment is just 4 bytes.
2083      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2084    }
2085
2086    Value *EltPtr = NewElts[i];
2087    const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2088
2089    // If we got down to a scalar, insert a load or store as appropriate.
2090    if (EltTy->isSingleValueType()) {
2091      if (isa<MemTransferInst>(MI)) {
2092        if (SROADest) {
2093          // From Other to Alloca.
2094          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2095          new StoreInst(Elt, EltPtr, MI);
2096        } else {
2097          // From Alloca to Other.
2098          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2099          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2100        }
2101        continue;
2102      }
2103      assert(isa<MemSetInst>(MI));
2104
2105      // If the stored element is zero (common case), just store a null
2106      // constant.
2107      Constant *StoreVal;
2108      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2109        if (CI->isZero()) {
2110          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
2111        } else {
2112          // If EltTy is a vector type, get the element type.
2113          const Type *ValTy = EltTy->getScalarType();
2114
2115          // Construct an integer with the right value.
2116          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2117          APInt OneVal(EltSize, CI->getZExtValue());
2118          APInt TotalVal(OneVal);
2119          // Set each byte.
2120          for (unsigned i = 0; 8*i < EltSize; ++i) {
2121            TotalVal = TotalVal.shl(8);
2122            TotalVal |= OneVal;
2123          }
2124
2125          // Convert the integer value to the appropriate type.
2126          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2127          if (ValTy->isPointerTy())
2128            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2129          else if (ValTy->isFloatingPointTy())
2130            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2131          assert(StoreVal->getType() == ValTy && "Type mismatch!");
2132
2133          // If the requested value was a vector constant, create it.
2134          if (EltTy != ValTy) {
2135            unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2136            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
2137            StoreVal = ConstantVector::get(Elts);
2138          }
2139        }
2140        new StoreInst(StoreVal, EltPtr, MI);
2141        continue;
2142      }
2143      // Otherwise, if we're storing a byte variable, use a memset call for
2144      // this element.
2145    }
2146
2147    unsigned EltSize = TD->getTypeAllocSize(EltTy);
2148
2149    IRBuilder<> Builder(MI);
2150
2151    // Finally, insert the meminst for this element.
2152    if (isa<MemSetInst>(MI)) {
2153      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2154                           MI->isVolatile());
2155    } else {
2156      assert(isa<MemTransferInst>(MI));
2157      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
2158      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
2159
2160      if (isa<MemCpyInst>(MI))
2161        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2162      else
2163        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2164    }
2165  }
2166  DeadInsts.push_back(MI);
2167}
2168
2169/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2170/// overwrites the entire allocation.  Extract out the pieces of the stored
2171/// integer and store them individually.
2172void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2173                                         SmallVector<AllocaInst*, 32> &NewElts){
2174  // Extract each element out of the integer according to its structure offset
2175  // and store the element value to the individual alloca.
2176  Value *SrcVal = SI->getOperand(0);
2177  const Type *AllocaEltTy = AI->getAllocatedType();
2178  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2179
2180  IRBuilder<> Builder(SI);
2181
2182  // Handle tail padding by extending the operand
2183  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2184    SrcVal = Builder.CreateZExt(SrcVal,
2185                            IntegerType::get(SI->getContext(), AllocaSizeBits));
2186
2187  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2188               << '\n');
2189
2190  // There are two forms here: AI could be an array or struct.  Both cases
2191  // have different ways to compute the element offset.
2192  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2193    const StructLayout *Layout = TD->getStructLayout(EltSTy);
2194
2195    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2196      // Get the number of bits to shift SrcVal to get the value.
2197      const Type *FieldTy = EltSTy->getElementType(i);
2198      uint64_t Shift = Layout->getElementOffsetInBits(i);
2199
2200      if (TD->isBigEndian())
2201        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2202
2203      Value *EltVal = SrcVal;
2204      if (Shift) {
2205        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2206        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2207      }
2208
2209      // Truncate down to an integer of the right size.
2210      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2211
2212      // Ignore zero sized fields like {}, they obviously contain no data.
2213      if (FieldSizeBits == 0) continue;
2214
2215      if (FieldSizeBits != AllocaSizeBits)
2216        EltVal = Builder.CreateTrunc(EltVal,
2217                             IntegerType::get(SI->getContext(), FieldSizeBits));
2218      Value *DestField = NewElts[i];
2219      if (EltVal->getType() == FieldTy) {
2220        // Storing to an integer field of this size, just do it.
2221      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2222        // Bitcast to the right element type (for fp/vector values).
2223        EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2224      } else {
2225        // Otherwise, bitcast the dest pointer (for aggregates).
2226        DestField = Builder.CreateBitCast(DestField,
2227                                     PointerType::getUnqual(EltVal->getType()));
2228      }
2229      new StoreInst(EltVal, DestField, SI);
2230    }
2231
2232  } else {
2233    const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2234    const Type *ArrayEltTy = ATy->getElementType();
2235    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2236    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2237
2238    uint64_t Shift;
2239
2240    if (TD->isBigEndian())
2241      Shift = AllocaSizeBits-ElementOffset;
2242    else
2243      Shift = 0;
2244
2245    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2246      // Ignore zero sized fields like {}, they obviously contain no data.
2247      if (ElementSizeBits == 0) continue;
2248
2249      Value *EltVal = SrcVal;
2250      if (Shift) {
2251        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2252        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2253      }
2254
2255      // Truncate down to an integer of the right size.
2256      if (ElementSizeBits != AllocaSizeBits)
2257        EltVal = Builder.CreateTrunc(EltVal,
2258                                     IntegerType::get(SI->getContext(),
2259                                                      ElementSizeBits));
2260      Value *DestField = NewElts[i];
2261      if (EltVal->getType() == ArrayEltTy) {
2262        // Storing to an integer field of this size, just do it.
2263      } else if (ArrayEltTy->isFloatingPointTy() ||
2264                 ArrayEltTy->isVectorTy()) {
2265        // Bitcast to the right element type (for fp/vector values).
2266        EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2267      } else {
2268        // Otherwise, bitcast the dest pointer (for aggregates).
2269        DestField = Builder.CreateBitCast(DestField,
2270                                     PointerType::getUnqual(EltVal->getType()));
2271      }
2272      new StoreInst(EltVal, DestField, SI);
2273
2274      if (TD->isBigEndian())
2275        Shift -= ElementOffset;
2276      else
2277        Shift += ElementOffset;
2278    }
2279  }
2280
2281  DeadInsts.push_back(SI);
2282}
2283
2284/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2285/// an integer.  Load the individual pieces to form the aggregate value.
2286void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2287                                        SmallVector<AllocaInst*, 32> &NewElts) {
2288  // Extract each element out of the NewElts according to its structure offset
2289  // and form the result value.
2290  const Type *AllocaEltTy = AI->getAllocatedType();
2291  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2292
2293  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2294               << '\n');
2295
2296  // There are two forms here: AI could be an array or struct.  Both cases
2297  // have different ways to compute the element offset.
2298  const StructLayout *Layout = 0;
2299  uint64_t ArrayEltBitOffset = 0;
2300  if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2301    Layout = TD->getStructLayout(EltSTy);
2302  } else {
2303    const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2304    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2305  }
2306
2307  Value *ResultVal =
2308    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2309
2310  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2311    // Load the value from the alloca.  If the NewElt is an aggregate, cast
2312    // the pointer to an integer of the same size before doing the load.
2313    Value *SrcField = NewElts[i];
2314    const Type *FieldTy =
2315      cast<PointerType>(SrcField->getType())->getElementType();
2316    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2317
2318    // Ignore zero sized fields like {}, they obviously contain no data.
2319    if (FieldSizeBits == 0) continue;
2320
2321    const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2322                                                     FieldSizeBits);
2323    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2324        !FieldTy->isVectorTy())
2325      SrcField = new BitCastInst(SrcField,
2326                                 PointerType::getUnqual(FieldIntTy),
2327                                 "", LI);
2328    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2329
2330    // If SrcField is a fp or vector of the right size but that isn't an
2331    // integer type, bitcast to an integer so we can shift it.
2332    if (SrcField->getType() != FieldIntTy)
2333      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2334
2335    // Zero extend the field to be the same size as the final alloca so that
2336    // we can shift and insert it.
2337    if (SrcField->getType() != ResultVal->getType())
2338      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2339
2340    // Determine the number of bits to shift SrcField.
2341    uint64_t Shift;
2342    if (Layout) // Struct case.
2343      Shift = Layout->getElementOffsetInBits(i);
2344    else  // Array case.
2345      Shift = i*ArrayEltBitOffset;
2346
2347    if (TD->isBigEndian())
2348      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2349
2350    if (Shift) {
2351      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2352      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2353    }
2354
2355    // Don't create an 'or x, 0' on the first iteration.
2356    if (!isa<Constant>(ResultVal) ||
2357        !cast<Constant>(ResultVal)->isNullValue())
2358      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2359    else
2360      ResultVal = SrcField;
2361  }
2362
2363  // Handle tail padding by truncating the result
2364  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2365    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2366
2367  LI->replaceAllUsesWith(ResultVal);
2368  DeadInsts.push_back(LI);
2369}
2370
2371/// HasPadding - Return true if the specified type has any structure or
2372/// alignment padding in between the elements that would be split apart
2373/// by SROA; return false otherwise.
2374static bool HasPadding(const Type *Ty, const TargetData &TD) {
2375  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2376    Ty = ATy->getElementType();
2377    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2378  }
2379
2380  // SROA currently handles only Arrays and Structs.
2381  const StructType *STy = cast<StructType>(Ty);
2382  const StructLayout *SL = TD.getStructLayout(STy);
2383  unsigned PrevFieldBitOffset = 0;
2384  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2385    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2386
2387    // Check to see if there is any padding between this element and the
2388    // previous one.
2389    if (i) {
2390      unsigned PrevFieldEnd =
2391        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2392      if (PrevFieldEnd < FieldBitOffset)
2393        return true;
2394    }
2395    PrevFieldBitOffset = FieldBitOffset;
2396  }
2397  // Check for tail padding.
2398  if (unsigned EltCount = STy->getNumElements()) {
2399    unsigned PrevFieldEnd = PrevFieldBitOffset +
2400      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2401    if (PrevFieldEnd < SL->getSizeInBits())
2402      return true;
2403  }
2404  return false;
2405}
2406
2407/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2408/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
2409/// or 1 if safe after canonicalization has been performed.
2410bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2411  // Loop over the use list of the alloca.  We can only transform it if all of
2412  // the users are safe to transform.
2413  AllocaInfo Info(AI);
2414
2415  isSafeForScalarRepl(AI, 0, Info);
2416  if (Info.isUnsafe) {
2417    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2418    return false;
2419  }
2420
2421  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
2422  // source and destination, we have to be careful.  In particular, the memcpy
2423  // could be moving around elements that live in structure padding of the LLVM
2424  // types, but may actually be used.  In these cases, we refuse to promote the
2425  // struct.
2426  if (Info.isMemCpySrc && Info.isMemCpyDst &&
2427      HasPadding(AI->getAllocatedType(), *TD))
2428    return false;
2429
2430  // If the alloca never has an access to just *part* of it, but is accessed
2431  // via loads and stores, then we should use ConvertToScalarInfo to promote
2432  // the alloca instead of promoting each piece at a time and inserting fission
2433  // and fusion code.
2434  if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2435    // If the struct/array just has one element, use basic SRoA.
2436    if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2437      if (ST->getNumElements() > 1) return false;
2438    } else {
2439      if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2440        return false;
2441    }
2442  }
2443
2444  return true;
2445}
2446
2447
2448
2449/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2450/// some part of a constant global variable.  This intentionally only accepts
2451/// constant expressions because we don't can't rewrite arbitrary instructions.
2452static bool PointsToConstantGlobal(Value *V) {
2453  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2454    return GV->isConstant();
2455  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2456    if (CE->getOpcode() == Instruction::BitCast ||
2457        CE->getOpcode() == Instruction::GetElementPtr)
2458      return PointsToConstantGlobal(CE->getOperand(0));
2459  return false;
2460}
2461
2462/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2463/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
2464/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
2465/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2466/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
2467/// the alloca, and if the source pointer is a pointer to a constant global, we
2468/// can optimize this.
2469static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2470                                           bool isOffset) {
2471  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2472    User *U = cast<Instruction>(*UI);
2473
2474    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2475      // Ignore non-volatile loads, they are always ok.
2476      if (LI->isVolatile()) return false;
2477      continue;
2478    }
2479
2480    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2481      // If uses of the bitcast are ok, we are ok.
2482      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2483        return false;
2484      continue;
2485    }
2486    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2487      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
2488      // doesn't, it does.
2489      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2490                                         isOffset || !GEP->hasAllZeroIndices()))
2491        return false;
2492      continue;
2493    }
2494
2495    if (CallSite CS = U) {
2496      // If this is the function being called then we treat it like a load and
2497      // ignore it.
2498      if (CS.isCallee(UI))
2499        continue;
2500
2501      // If this is a readonly/readnone call site, then we know it is just a
2502      // load (but one that potentially returns the value itself), so we can
2503      // ignore it if we know that the value isn't captured.
2504      unsigned ArgNo = CS.getArgumentNo(UI);
2505      if (CS.onlyReadsMemory() &&
2506          (CS.getInstruction()->use_empty() ||
2507           CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2508        continue;
2509
2510      // If this is being passed as a byval argument, the caller is making a
2511      // copy, so it is only a read of the alloca.
2512      if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2513        continue;
2514    }
2515
2516    // If this is isn't our memcpy/memmove, reject it as something we can't
2517    // handle.
2518    MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2519    if (MI == 0)
2520      return false;
2521
2522    // If the transfer is using the alloca as a source of the transfer, then
2523    // ignore it since it is a load (unless the transfer is volatile).
2524    if (UI.getOperandNo() == 1) {
2525      if (MI->isVolatile()) return false;
2526      continue;
2527    }
2528
2529    // If we already have seen a copy, reject the second one.
2530    if (TheCopy) return false;
2531
2532    // If the pointer has been offset from the start of the alloca, we can't
2533    // safely handle this.
2534    if (isOffset) return false;
2535
2536    // If the memintrinsic isn't using the alloca as the dest, reject it.
2537    if (UI.getOperandNo() != 0) return false;
2538
2539    // If the source of the memcpy/move is not a constant global, reject it.
2540    if (!PointsToConstantGlobal(MI->getSource()))
2541      return false;
2542
2543    // Otherwise, the transform is safe.  Remember the copy instruction.
2544    TheCopy = MI;
2545  }
2546  return true;
2547}
2548
2549/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2550/// modified by a copy from a constant global.  If we can prove this, we can
2551/// replace any uses of the alloca with uses of the global directly.
2552MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2553  MemTransferInst *TheCopy = 0;
2554  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2555    return TheCopy;
2556  return 0;
2557}
2558