ScalarReplAggregates.cpp revision 6399b7c51076846942a0c05b4823ca9a8f55b5fc
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
1646  // Walk through the GEP type indices, checking the types that this indexes
1647  // into.
1648  for (; GEPIt != E; ++GEPIt) {
1649    // Ignore struct elements, no extra checking needed for these.
1650    if ((*GEPIt)->isStructTy())
1651      continue;
1652
1653    ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1654    if (!IdxVal)
1655      return MarkUnsafe(Info, GEPI);
1656  }
1657
1658  // Compute the offset due to this GEP and check if the alloca has a
1659  // component element at that offset.
1660  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1661  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1662  if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1663    MarkUnsafe(Info, GEPI);
1664}
1665
1666/// isHomogeneousAggregate - Check if type T is a struct or array containing
1667/// elements of the same type (which is always true for arrays).  If so,
1668/// return true with NumElts and EltTy set to the number of elements and the
1669/// element type, respectively.
1670static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1671                                   Type *&EltTy) {
1672  if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1673    NumElts = AT->getNumElements();
1674    EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1675    return true;
1676  }
1677  if (StructType *ST = dyn_cast<StructType>(T)) {
1678    NumElts = ST->getNumContainedTypes();
1679    EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1680    for (unsigned n = 1; n < NumElts; ++n) {
1681      if (ST->getContainedType(n) != EltTy)
1682        return false;
1683    }
1684    return true;
1685  }
1686  return false;
1687}
1688
1689/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1690/// "homogeneous" aggregates with the same element type and number of elements.
1691static bool isCompatibleAggregate(Type *T1, Type *T2) {
1692  if (T1 == T2)
1693    return true;
1694
1695  unsigned NumElts1, NumElts2;
1696  Type *EltTy1, *EltTy2;
1697  if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1698      isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1699      NumElts1 == NumElts2 &&
1700      EltTy1 == EltTy2)
1701    return true;
1702
1703  return false;
1704}
1705
1706/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1707/// alloca or has an offset and size that corresponds to a component element
1708/// within it.  The offset checked here may have been formed from a GEP with a
1709/// pointer bitcasted to a different type.
1710///
1711/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1712/// unit.  If false, it only allows accesses known to be in a single element.
1713void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1714                           Type *MemOpType, bool isStore,
1715                           AllocaInfo &Info, Instruction *TheAccess,
1716                           bool AllowWholeAccess) {
1717  // Check if this is a load/store of the entire alloca.
1718  if (Offset == 0 && AllowWholeAccess &&
1719      MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1720    // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1721    // loads/stores (which are essentially the same as the MemIntrinsics with
1722    // regard to copying padding between elements).  But, if an alloca is
1723    // flagged as both a source and destination of such operations, we'll need
1724    // to check later for padding between elements.
1725    if (!MemOpType || MemOpType->isIntegerTy()) {
1726      if (isStore)
1727        Info.isMemCpyDst = true;
1728      else
1729        Info.isMemCpySrc = true;
1730      return;
1731    }
1732    // This is also safe for references using a type that is compatible with
1733    // the type of the alloca, so that loads/stores can be rewritten using
1734    // insertvalue/extractvalue.
1735    if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1736      Info.hasSubelementAccess = true;
1737      return;
1738    }
1739  }
1740  // Check if the offset/size correspond to a component within the alloca type.
1741  Type *T = Info.AI->getAllocatedType();
1742  if (TypeHasComponent(T, Offset, MemSize)) {
1743    Info.hasSubelementAccess = true;
1744    return;
1745  }
1746
1747  return MarkUnsafe(Info, TheAccess);
1748}
1749
1750/// TypeHasComponent - Return true if T has a component type with the
1751/// specified offset and size.  If Size is zero, do not check the size.
1752bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1753  Type *EltTy;
1754  uint64_t EltSize;
1755  if (StructType *ST = dyn_cast<StructType>(T)) {
1756    const StructLayout *Layout = TD->getStructLayout(ST);
1757    unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1758    EltTy = ST->getContainedType(EltIdx);
1759    EltSize = TD->getTypeAllocSize(EltTy);
1760    Offset -= Layout->getElementOffset(EltIdx);
1761  } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1762    EltTy = AT->getElementType();
1763    EltSize = TD->getTypeAllocSize(EltTy);
1764    if (Offset >= AT->getNumElements() * EltSize)
1765      return false;
1766    Offset %= EltSize;
1767  } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1768    EltTy = VT->getElementType();
1769    EltSize = TD->getTypeAllocSize(EltTy);
1770    if (Offset >= VT->getNumElements() * EltSize)
1771      return false;
1772    Offset %= EltSize;
1773  } else {
1774    return false;
1775  }
1776  if (Offset == 0 && (Size == 0 || EltSize == Size))
1777    return true;
1778  // Check if the component spans multiple elements.
1779  if (Offset + Size > EltSize)
1780    return false;
1781  return TypeHasComponent(EltTy, Offset, Size);
1782}
1783
1784/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1785/// the instruction I, which references it, to use the separate elements.
1786/// Offset indicates the position within AI that is referenced by this
1787/// instruction.
1788void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1789                                SmallVector<AllocaInst*, 32> &NewElts) {
1790  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1791    Use &TheUse = UI.getUse();
1792    Instruction *User = cast<Instruction>(*UI++);
1793
1794    if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1795      RewriteBitCast(BC, AI, Offset, NewElts);
1796      continue;
1797    }
1798
1799    if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1800      RewriteGEP(GEPI, AI, Offset, NewElts);
1801      continue;
1802    }
1803
1804    if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1805      ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1806      uint64_t MemSize = Length->getZExtValue();
1807      if (Offset == 0 &&
1808          MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1809        RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1810      // Otherwise the intrinsic can only touch a single element and the
1811      // address operand will be updated, so nothing else needs to be done.
1812      continue;
1813    }
1814
1815    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1816      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1817          II->getIntrinsicID() == Intrinsic::lifetime_end) {
1818        RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1819      }
1820      continue;
1821    }
1822
1823    if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1824      Type *LIType = LI->getType();
1825
1826      if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1827        // Replace:
1828        //   %res = load { i32, i32 }* %alloc
1829        // with:
1830        //   %load.0 = load i32* %alloc.0
1831        //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1832        //   %load.1 = load i32* %alloc.1
1833        //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1834        // (Also works for arrays instead of structs)
1835        Value *Insert = UndefValue::get(LIType);
1836        IRBuilder<> Builder(LI);
1837        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1838          Value *Load = Builder.CreateLoad(NewElts[i], "load");
1839          Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1840        }
1841        LI->replaceAllUsesWith(Insert);
1842        DeadInsts.push_back(LI);
1843      } else if (LIType->isIntegerTy() &&
1844                 TD->getTypeAllocSize(LIType) ==
1845                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1846        // If this is a load of the entire alloca to an integer, rewrite it.
1847        RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1848      }
1849      continue;
1850    }
1851
1852    if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1853      Value *Val = SI->getOperand(0);
1854      Type *SIType = Val->getType();
1855      if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1856        // Replace:
1857        //   store { i32, i32 } %val, { i32, i32 }* %alloc
1858        // with:
1859        //   %val.0 = extractvalue { i32, i32 } %val, 0
1860        //   store i32 %val.0, i32* %alloc.0
1861        //   %val.1 = extractvalue { i32, i32 } %val, 1
1862        //   store i32 %val.1, i32* %alloc.1
1863        // (Also works for arrays instead of structs)
1864        IRBuilder<> Builder(SI);
1865        for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1866          Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1867          Builder.CreateStore(Extract, NewElts[i]);
1868        }
1869        DeadInsts.push_back(SI);
1870      } else if (SIType->isIntegerTy() &&
1871                 TD->getTypeAllocSize(SIType) ==
1872                 TD->getTypeAllocSize(AI->getAllocatedType())) {
1873        // If this is a store of the entire alloca from an integer, rewrite it.
1874        RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1875      }
1876      continue;
1877    }
1878
1879    if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1880      // If we have a PHI user of the alloca itself (as opposed to a GEP or
1881      // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
1882      // the new pointer.
1883      if (!isa<AllocaInst>(I)) continue;
1884
1885      assert(Offset == 0 && NewElts[0] &&
1886             "Direct alloca use should have a zero offset");
1887
1888      // If we have a use of the alloca, we know the derived uses will be
1889      // utilizing just the first element of the scalarized result.  Insert a
1890      // bitcast of the first alloca before the user as required.
1891      AllocaInst *NewAI = NewElts[0];
1892      BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1893      NewAI->moveBefore(BCI);
1894      TheUse = BCI;
1895      continue;
1896    }
1897  }
1898}
1899
1900/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1901/// and recursively continue updating all of its uses.
1902void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1903                          SmallVector<AllocaInst*, 32> &NewElts) {
1904  RewriteForScalarRepl(BC, AI, Offset, NewElts);
1905  if (BC->getOperand(0) != AI)
1906    return;
1907
1908  // The bitcast references the original alloca.  Replace its uses with
1909  // references to the alloca containing offset zero (which is normally at
1910  // index zero, but might not be in cases involving structs with elements
1911  // of size zero).
1912  Type *T = AI->getAllocatedType();
1913  uint64_t EltOffset = 0;
1914  Type *IdxTy;
1915  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1916  Instruction *Val = NewElts[Idx];
1917  if (Val->getType() != BC->getDestTy()) {
1918    Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1919    Val->takeName(BC);
1920  }
1921  BC->replaceAllUsesWith(Val);
1922  DeadInsts.push_back(BC);
1923}
1924
1925/// FindElementAndOffset - Return the index of the element containing Offset
1926/// within the specified type, which must be either a struct or an array.
1927/// Sets T to the type of the element and Offset to the offset within that
1928/// element.  IdxTy is set to the type of the index result to be used in a
1929/// GEP instruction.
1930uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
1931                                    Type *&IdxTy) {
1932  uint64_t Idx = 0;
1933  if (StructType *ST = dyn_cast<StructType>(T)) {
1934    const StructLayout *Layout = TD->getStructLayout(ST);
1935    Idx = Layout->getElementContainingOffset(Offset);
1936    T = ST->getContainedType(Idx);
1937    Offset -= Layout->getElementOffset(Idx);
1938    IdxTy = Type::getInt32Ty(T->getContext());
1939    return Idx;
1940  } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1941    T = AT->getElementType();
1942    uint64_t EltSize = TD->getTypeAllocSize(T);
1943    Idx = Offset / EltSize;
1944    Offset -= Idx * EltSize;
1945    IdxTy = Type::getInt64Ty(T->getContext());
1946    return Idx;
1947  }
1948  VectorType *VT = cast<VectorType>(T);
1949  T = VT->getElementType();
1950  uint64_t EltSize = TD->getTypeAllocSize(T);
1951  Idx = Offset / EltSize;
1952  Offset -= Idx * EltSize;
1953  IdxTy = Type::getInt64Ty(T->getContext());
1954  return Idx;
1955}
1956
1957/// RewriteGEP - Check if this GEP instruction moves the pointer across
1958/// elements of the alloca that are being split apart, and if so, rewrite
1959/// the GEP to be relative to the new element.
1960void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1961                      SmallVector<AllocaInst*, 32> &NewElts) {
1962  uint64_t OldOffset = Offset;
1963  SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1964  Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1965
1966  RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1967
1968  Type *T = AI->getAllocatedType();
1969  Type *IdxTy;
1970  uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1971  if (GEPI->getOperand(0) == AI)
1972    OldIdx = ~0ULL; // Force the GEP to be rewritten.
1973
1974  T = AI->getAllocatedType();
1975  uint64_t EltOffset = Offset;
1976  uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1977
1978  // If this GEP does not move the pointer across elements of the alloca
1979  // being split, then it does not needs to be rewritten.
1980  if (Idx == OldIdx)
1981    return;
1982
1983  Type *i32Ty = Type::getInt32Ty(AI->getContext());
1984  SmallVector<Value*, 8> NewArgs;
1985  NewArgs.push_back(Constant::getNullValue(i32Ty));
1986  while (EltOffset != 0) {
1987    uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1988    NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1989  }
1990  Instruction *Val = NewElts[Idx];
1991  if (NewArgs.size() > 1) {
1992    Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
1993    Val->takeName(GEPI);
1994  }
1995  if (Val->getType() != GEPI->getType())
1996    Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1997  GEPI->replaceAllUsesWith(Val);
1998  DeadInsts.push_back(GEPI);
1999}
2000
2001/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2002/// to mark the lifetime of the scalarized memory.
2003void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2004                                    uint64_t Offset,
2005                                    SmallVector<AllocaInst*, 32> &NewElts) {
2006  ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2007  // Put matching lifetime markers on everything from Offset up to
2008  // Offset+OldSize.
2009  Type *AIType = AI->getAllocatedType();
2010  uint64_t NewOffset = Offset;
2011  Type *IdxTy;
2012  uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2013
2014  IRBuilder<> Builder(II);
2015  uint64_t Size = OldSize->getLimitedValue();
2016
2017  if (NewOffset) {
2018    // Splice the first element and index 'NewOffset' bytes in.  SROA will
2019    // split the alloca again later.
2020    Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2021    V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2022
2023    IdxTy = NewElts[Idx]->getAllocatedType();
2024    uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
2025    if (EltSize > Size) {
2026      EltSize = Size;
2027      Size = 0;
2028    } else {
2029      Size -= EltSize;
2030    }
2031    if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2032      Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2033    else
2034      Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2035    ++Idx;
2036  }
2037
2038  for (; Idx != NewElts.size() && Size; ++Idx) {
2039    IdxTy = NewElts[Idx]->getAllocatedType();
2040    uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2041    if (EltSize > Size) {
2042      EltSize = Size;
2043      Size = 0;
2044    } else {
2045      Size -= EltSize;
2046    }
2047    if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2048      Builder.CreateLifetimeStart(NewElts[Idx],
2049                                  Builder.getInt64(EltSize));
2050    else
2051      Builder.CreateLifetimeEnd(NewElts[Idx],
2052                                Builder.getInt64(EltSize));
2053  }
2054  DeadInsts.push_back(II);
2055}
2056
2057/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2058/// Rewrite it to copy or set the elements of the scalarized memory.
2059void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2060                                        AllocaInst *AI,
2061                                        SmallVector<AllocaInst*, 32> &NewElts) {
2062  // If this is a memcpy/memmove, construct the other pointer as the
2063  // appropriate type.  The "Other" pointer is the pointer that goes to memory
2064  // that doesn't have anything to do with the alloca that we are promoting. For
2065  // memset, this Value* stays null.
2066  Value *OtherPtr = 0;
2067  unsigned MemAlignment = MI->getAlignment();
2068  if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2069    if (Inst == MTI->getRawDest())
2070      OtherPtr = MTI->getRawSource();
2071    else {
2072      assert(Inst == MTI->getRawSource());
2073      OtherPtr = MTI->getRawDest();
2074    }
2075  }
2076
2077  // If there is an other pointer, we want to convert it to the same pointer
2078  // type as AI has, so we can GEP through it safely.
2079  if (OtherPtr) {
2080    unsigned AddrSpace =
2081      cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2082
2083    // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
2084    // optimization, but it's also required to detect the corner case where
2085    // both pointer operands are referencing the same memory, and where
2086    // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
2087    // function is only called for mem intrinsics that access the whole
2088    // aggregate, so non-zero GEPs are not an issue here.)
2089    OtherPtr = OtherPtr->stripPointerCasts();
2090
2091    // Copying the alloca to itself is a no-op: just delete it.
2092    if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2093      // This code will run twice for a no-op memcpy -- once for each operand.
2094      // Put only one reference to MI on the DeadInsts list.
2095      for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2096             E = DeadInsts.end(); I != E; ++I)
2097        if (*I == MI) return;
2098      DeadInsts.push_back(MI);
2099      return;
2100    }
2101
2102    // If the pointer is not the right type, insert a bitcast to the right
2103    // type.
2104    Type *NewTy =
2105      PointerType::get(AI->getType()->getElementType(), AddrSpace);
2106
2107    if (OtherPtr->getType() != NewTy)
2108      OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2109  }
2110
2111  // Process each element of the aggregate.
2112  bool SROADest = MI->getRawDest() == Inst;
2113
2114  Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2115
2116  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2117    // If this is a memcpy/memmove, emit a GEP of the other element address.
2118    Value *OtherElt = 0;
2119    unsigned OtherEltAlign = MemAlignment;
2120
2121    if (OtherPtr) {
2122      Value *Idx[2] = { Zero,
2123                      ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2124      OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2125                                              OtherPtr->getName()+"."+Twine(i),
2126                                                   MI);
2127      uint64_t EltOffset;
2128      PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2129      Type *OtherTy = OtherPtrTy->getElementType();
2130      if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2131        EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2132      } else {
2133        Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2134        EltOffset = TD->getTypeAllocSize(EltTy)*i;
2135      }
2136
2137      // The alignment of the other pointer is the guaranteed alignment of the
2138      // element, which is affected by both the known alignment of the whole
2139      // mem intrinsic and the alignment of the element.  If the alignment of
2140      // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2141      // known alignment is just 4 bytes.
2142      OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2143    }
2144
2145    Value *EltPtr = NewElts[i];
2146    Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2147
2148    // If we got down to a scalar, insert a load or store as appropriate.
2149    if (EltTy->isSingleValueType()) {
2150      if (isa<MemTransferInst>(MI)) {
2151        if (SROADest) {
2152          // From Other to Alloca.
2153          Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2154          new StoreInst(Elt, EltPtr, MI);
2155        } else {
2156          // From Alloca to Other.
2157          Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2158          new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2159        }
2160        continue;
2161      }
2162      assert(isa<MemSetInst>(MI));
2163
2164      // If the stored element is zero (common case), just store a null
2165      // constant.
2166      Constant *StoreVal;
2167      if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2168        if (CI->isZero()) {
2169          StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
2170        } else {
2171          // If EltTy is a vector type, get the element type.
2172          Type *ValTy = EltTy->getScalarType();
2173
2174          // Construct an integer with the right value.
2175          unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2176          APInt OneVal(EltSize, CI->getZExtValue());
2177          APInt TotalVal(OneVal);
2178          // Set each byte.
2179          for (unsigned i = 0; 8*i < EltSize; ++i) {
2180            TotalVal = TotalVal.shl(8);
2181            TotalVal |= OneVal;
2182          }
2183
2184          // Convert the integer value to the appropriate type.
2185          StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2186          if (ValTy->isPointerTy())
2187            StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2188          else if (ValTy->isFloatingPointTy())
2189            StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2190          assert(StoreVal->getType() == ValTy && "Type mismatch!");
2191
2192          // If the requested value was a vector constant, create it.
2193          if (EltTy->isVectorTy()) {
2194            unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2195            StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
2196          }
2197        }
2198        new StoreInst(StoreVal, EltPtr, MI);
2199        continue;
2200      }
2201      // Otherwise, if we're storing a byte variable, use a memset call for
2202      // this element.
2203    }
2204
2205    unsigned EltSize = TD->getTypeAllocSize(EltTy);
2206    if (!EltSize)
2207      continue;
2208
2209    IRBuilder<> Builder(MI);
2210
2211    // Finally, insert the meminst for this element.
2212    if (isa<MemSetInst>(MI)) {
2213      Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2214                           MI->isVolatile());
2215    } else {
2216      assert(isa<MemTransferInst>(MI));
2217      Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
2218      Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
2219
2220      if (isa<MemCpyInst>(MI))
2221        Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2222      else
2223        Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2224    }
2225  }
2226  DeadInsts.push_back(MI);
2227}
2228
2229/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2230/// overwrites the entire allocation.  Extract out the pieces of the stored
2231/// integer and store them individually.
2232void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2233                                         SmallVector<AllocaInst*, 32> &NewElts){
2234  // Extract each element out of the integer according to its structure offset
2235  // and store the element value to the individual alloca.
2236  Value *SrcVal = SI->getOperand(0);
2237  Type *AllocaEltTy = AI->getAllocatedType();
2238  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2239
2240  IRBuilder<> Builder(SI);
2241
2242  // Handle tail padding by extending the operand
2243  if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2244    SrcVal = Builder.CreateZExt(SrcVal,
2245                            IntegerType::get(SI->getContext(), AllocaSizeBits));
2246
2247  DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2248               << '\n');
2249
2250  // There are two forms here: AI could be an array or struct.  Both cases
2251  // have different ways to compute the element offset.
2252  if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2253    const StructLayout *Layout = TD->getStructLayout(EltSTy);
2254
2255    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2256      // Get the number of bits to shift SrcVal to get the value.
2257      Type *FieldTy = EltSTy->getElementType(i);
2258      uint64_t Shift = Layout->getElementOffsetInBits(i);
2259
2260      if (TD->isBigEndian())
2261        Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2262
2263      Value *EltVal = SrcVal;
2264      if (Shift) {
2265        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2266        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2267      }
2268
2269      // Truncate down to an integer of the right size.
2270      uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2271
2272      // Ignore zero sized fields like {}, they obviously contain no data.
2273      if (FieldSizeBits == 0) continue;
2274
2275      if (FieldSizeBits != AllocaSizeBits)
2276        EltVal = Builder.CreateTrunc(EltVal,
2277                             IntegerType::get(SI->getContext(), FieldSizeBits));
2278      Value *DestField = NewElts[i];
2279      if (EltVal->getType() == FieldTy) {
2280        // Storing to an integer field of this size, just do it.
2281      } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2282        // Bitcast to the right element type (for fp/vector values).
2283        EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2284      } else {
2285        // Otherwise, bitcast the dest pointer (for aggregates).
2286        DestField = Builder.CreateBitCast(DestField,
2287                                     PointerType::getUnqual(EltVal->getType()));
2288      }
2289      new StoreInst(EltVal, DestField, SI);
2290    }
2291
2292  } else {
2293    ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2294    Type *ArrayEltTy = ATy->getElementType();
2295    uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2296    uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2297
2298    uint64_t Shift;
2299
2300    if (TD->isBigEndian())
2301      Shift = AllocaSizeBits-ElementOffset;
2302    else
2303      Shift = 0;
2304
2305    for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2306      // Ignore zero sized fields like {}, they obviously contain no data.
2307      if (ElementSizeBits == 0) continue;
2308
2309      Value *EltVal = SrcVal;
2310      if (Shift) {
2311        Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2312        EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2313      }
2314
2315      // Truncate down to an integer of the right size.
2316      if (ElementSizeBits != AllocaSizeBits)
2317        EltVal = Builder.CreateTrunc(EltVal,
2318                                     IntegerType::get(SI->getContext(),
2319                                                      ElementSizeBits));
2320      Value *DestField = NewElts[i];
2321      if (EltVal->getType() == ArrayEltTy) {
2322        // Storing to an integer field of this size, just do it.
2323      } else if (ArrayEltTy->isFloatingPointTy() ||
2324                 ArrayEltTy->isVectorTy()) {
2325        // Bitcast to the right element type (for fp/vector values).
2326        EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2327      } else {
2328        // Otherwise, bitcast the dest pointer (for aggregates).
2329        DestField = Builder.CreateBitCast(DestField,
2330                                     PointerType::getUnqual(EltVal->getType()));
2331      }
2332      new StoreInst(EltVal, DestField, SI);
2333
2334      if (TD->isBigEndian())
2335        Shift -= ElementOffset;
2336      else
2337        Shift += ElementOffset;
2338    }
2339  }
2340
2341  DeadInsts.push_back(SI);
2342}
2343
2344/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2345/// an integer.  Load the individual pieces to form the aggregate value.
2346void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2347                                        SmallVector<AllocaInst*, 32> &NewElts) {
2348  // Extract each element out of the NewElts according to its structure offset
2349  // and form the result value.
2350  Type *AllocaEltTy = AI->getAllocatedType();
2351  uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2352
2353  DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2354               << '\n');
2355
2356  // There are two forms here: AI could be an array or struct.  Both cases
2357  // have different ways to compute the element offset.
2358  const StructLayout *Layout = 0;
2359  uint64_t ArrayEltBitOffset = 0;
2360  if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2361    Layout = TD->getStructLayout(EltSTy);
2362  } else {
2363    Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2364    ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2365  }
2366
2367  Value *ResultVal =
2368    Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2369
2370  for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2371    // Load the value from the alloca.  If the NewElt is an aggregate, cast
2372    // the pointer to an integer of the same size before doing the load.
2373    Value *SrcField = NewElts[i];
2374    Type *FieldTy =
2375      cast<PointerType>(SrcField->getType())->getElementType();
2376    uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2377
2378    // Ignore zero sized fields like {}, they obviously contain no data.
2379    if (FieldSizeBits == 0) continue;
2380
2381    IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2382                                                     FieldSizeBits);
2383    if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2384        !FieldTy->isVectorTy())
2385      SrcField = new BitCastInst(SrcField,
2386                                 PointerType::getUnqual(FieldIntTy),
2387                                 "", LI);
2388    SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2389
2390    // If SrcField is a fp or vector of the right size but that isn't an
2391    // integer type, bitcast to an integer so we can shift it.
2392    if (SrcField->getType() != FieldIntTy)
2393      SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2394
2395    // Zero extend the field to be the same size as the final alloca so that
2396    // we can shift and insert it.
2397    if (SrcField->getType() != ResultVal->getType())
2398      SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2399
2400    // Determine the number of bits to shift SrcField.
2401    uint64_t Shift;
2402    if (Layout) // Struct case.
2403      Shift = Layout->getElementOffsetInBits(i);
2404    else  // Array case.
2405      Shift = i*ArrayEltBitOffset;
2406
2407    if (TD->isBigEndian())
2408      Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2409
2410    if (Shift) {
2411      Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2412      SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2413    }
2414
2415    // Don't create an 'or x, 0' on the first iteration.
2416    if (!isa<Constant>(ResultVal) ||
2417        !cast<Constant>(ResultVal)->isNullValue())
2418      ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2419    else
2420      ResultVal = SrcField;
2421  }
2422
2423  // Handle tail padding by truncating the result
2424  if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2425    ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2426
2427  LI->replaceAllUsesWith(ResultVal);
2428  DeadInsts.push_back(LI);
2429}
2430
2431/// HasPadding - Return true if the specified type has any structure or
2432/// alignment padding in between the elements that would be split apart
2433/// by SROA; return false otherwise.
2434static bool HasPadding(Type *Ty, const TargetData &TD) {
2435  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2436    Ty = ATy->getElementType();
2437    return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2438  }
2439
2440  // SROA currently handles only Arrays and Structs.
2441  StructType *STy = cast<StructType>(Ty);
2442  const StructLayout *SL = TD.getStructLayout(STy);
2443  unsigned PrevFieldBitOffset = 0;
2444  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2445    unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2446
2447    // Check to see if there is any padding between this element and the
2448    // previous one.
2449    if (i) {
2450      unsigned PrevFieldEnd =
2451        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2452      if (PrevFieldEnd < FieldBitOffset)
2453        return true;
2454    }
2455    PrevFieldBitOffset = FieldBitOffset;
2456  }
2457  // Check for tail padding.
2458  if (unsigned EltCount = STy->getNumElements()) {
2459    unsigned PrevFieldEnd = PrevFieldBitOffset +
2460      TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2461    if (PrevFieldEnd < SL->getSizeInBits())
2462      return true;
2463  }
2464  return false;
2465}
2466
2467/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2468/// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
2469/// or 1 if safe after canonicalization has been performed.
2470bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2471  // Loop over the use list of the alloca.  We can only transform it if all of
2472  // the users are safe to transform.
2473  AllocaInfo Info(AI);
2474
2475  isSafeForScalarRepl(AI, 0, Info);
2476  if (Info.isUnsafe) {
2477    DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2478    return false;
2479  }
2480
2481  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
2482  // source and destination, we have to be careful.  In particular, the memcpy
2483  // could be moving around elements that live in structure padding of the LLVM
2484  // types, but may actually be used.  In these cases, we refuse to promote the
2485  // struct.
2486  if (Info.isMemCpySrc && Info.isMemCpyDst &&
2487      HasPadding(AI->getAllocatedType(), *TD))
2488    return false;
2489
2490  // If the alloca never has an access to just *part* of it, but is accessed
2491  // via loads and stores, then we should use ConvertToScalarInfo to promote
2492  // the alloca instead of promoting each piece at a time and inserting fission
2493  // and fusion code.
2494  if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2495    // If the struct/array just has one element, use basic SRoA.
2496    if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2497      if (ST->getNumElements() > 1) return false;
2498    } else {
2499      if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2500        return false;
2501    }
2502  }
2503
2504  return true;
2505}
2506
2507
2508
2509/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2510/// some part of a constant global variable.  This intentionally only accepts
2511/// constant expressions because we don't can't rewrite arbitrary instructions.
2512static bool PointsToConstantGlobal(Value *V) {
2513  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2514    return GV->isConstant();
2515  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2516    if (CE->getOpcode() == Instruction::BitCast ||
2517        CE->getOpcode() == Instruction::GetElementPtr)
2518      return PointsToConstantGlobal(CE->getOperand(0));
2519  return false;
2520}
2521
2522/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2523/// pointer to an alloca.  Ignore any reads of the pointer, return false if we
2524/// see any stores or other unknown uses.  If we see pointer arithmetic, keep
2525/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2526/// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
2527/// the alloca, and if the source pointer is a pointer to a constant global, we
2528/// can optimize this.
2529static bool
2530isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2531                               bool isOffset,
2532                               SmallVector<Instruction *, 4> &LifetimeMarkers) {
2533  // We track lifetime intrinsics as we encounter them.  If we decide to go
2534  // ahead and replace the value with the global, this lets the caller quickly
2535  // eliminate the markers.
2536
2537  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2538    User *U = cast<Instruction>(*UI);
2539
2540    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2541      // Ignore non-volatile loads, they are always ok.
2542      if (!LI->isSimple()) return false;
2543      continue;
2544    }
2545
2546    if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2547      // If uses of the bitcast are ok, we are ok.
2548      if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2549                                          LifetimeMarkers))
2550        return false;
2551      continue;
2552    }
2553    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2554      // If the GEP has all zero indices, it doesn't offset the pointer.  If it
2555      // doesn't, it does.
2556      if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2557                                          isOffset || !GEP->hasAllZeroIndices(),
2558                                          LifetimeMarkers))
2559        return false;
2560      continue;
2561    }
2562
2563    if (CallSite CS = U) {
2564      // If this is the function being called then we treat it like a load and
2565      // ignore it.
2566      if (CS.isCallee(UI))
2567        continue;
2568
2569      // If this is a readonly/readnone call site, then we know it is just a
2570      // load (but one that potentially returns the value itself), so we can
2571      // ignore it if we know that the value isn't captured.
2572      unsigned ArgNo = CS.getArgumentNo(UI);
2573      if (CS.onlyReadsMemory() &&
2574          (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
2575        continue;
2576
2577      // If this is being passed as a byval argument, the caller is making a
2578      // copy, so it is only a read of the alloca.
2579      if (CS.isByValArgument(ArgNo))
2580        continue;
2581    }
2582
2583    // Lifetime intrinsics can be handled by the caller.
2584    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2585      if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2586          II->getIntrinsicID() == Intrinsic::lifetime_end) {
2587        assert(II->use_empty() && "Lifetime markers have no result to use!");
2588        LifetimeMarkers.push_back(II);
2589        continue;
2590      }
2591    }
2592
2593    // If this is isn't our memcpy/memmove, reject it as something we can't
2594    // handle.
2595    MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2596    if (MI == 0)
2597      return false;
2598
2599    // If the transfer is using the alloca as a source of the transfer, then
2600    // ignore it since it is a load (unless the transfer is volatile).
2601    if (UI.getOperandNo() == 1) {
2602      if (MI->isVolatile()) return false;
2603      continue;
2604    }
2605
2606    // If we already have seen a copy, reject the second one.
2607    if (TheCopy) return false;
2608
2609    // If the pointer has been offset from the start of the alloca, we can't
2610    // safely handle this.
2611    if (isOffset) return false;
2612
2613    // If the memintrinsic isn't using the alloca as the dest, reject it.
2614    if (UI.getOperandNo() != 0) return false;
2615
2616    // If the source of the memcpy/move is not a constant global, reject it.
2617    if (!PointsToConstantGlobal(MI->getSource()))
2618      return false;
2619
2620    // Otherwise, the transform is safe.  Remember the copy instruction.
2621    TheCopy = MI;
2622  }
2623  return true;
2624}
2625
2626/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2627/// modified by a copy from a constant global.  If we can prove this, we can
2628/// replace any uses of the alloca with uses of the global directly.
2629MemTransferInst *
2630SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2631                                     SmallVector<Instruction*, 4> &ToDelete) {
2632  MemTransferInst *TheCopy = 0;
2633  if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
2634    return TheCopy;
2635  return 0;
2636}
2637