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