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