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