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