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