LLVM API Documentation

ScalarReplAggregates.cpp
Go to the documentation of this file.
00001 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This transformation implements the well known scalar replacement of
00011 // aggregates transformation.  This xform breaks up alloca instructions of
00012 // aggregate type (structure or array) into individual alloca instructions for
00013 // each member (if possible).  Then, if possible, it transforms the individual
00014 // alloca instructions into nice clean scalar SSA form.
00015 //
00016 // This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
00017 // often interact, especially for C++ programs.  As such, iterating between
00018 // SRoA, then Mem2Reg until we run out of things to promote works well.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #include "llvm/Transforms/Scalar.h"
00023 #include "llvm/ADT/SetVector.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/Analysis/AssumptionCache.h"
00027 #include "llvm/Analysis/Loads.h"
00028 #include "llvm/Analysis/ValueTracking.h"
00029 #include "llvm/IR/CallSite.h"
00030 #include "llvm/IR/Constants.h"
00031 #include "llvm/IR/DIBuilder.h"
00032 #include "llvm/IR/DataLayout.h"
00033 #include "llvm/IR/DebugInfo.h"
00034 #include "llvm/IR/DerivedTypes.h"
00035 #include "llvm/IR/Dominators.h"
00036 #include "llvm/IR/Function.h"
00037 #include "llvm/IR/GetElementPtrTypeIterator.h"
00038 #include "llvm/IR/GlobalVariable.h"
00039 #include "llvm/IR/IRBuilder.h"
00040 #include "llvm/IR/Instructions.h"
00041 #include "llvm/IR/IntrinsicInst.h"
00042 #include "llvm/IR/LLVMContext.h"
00043 #include "llvm/IR/Module.h"
00044 #include "llvm/IR/Operator.h"
00045 #include "llvm/Pass.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/ErrorHandling.h"
00048 #include "llvm/Support/MathExtras.h"
00049 #include "llvm/Support/raw_ostream.h"
00050 #include "llvm/Transforms/Utils/Local.h"
00051 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00052 #include "llvm/Transforms/Utils/SSAUpdater.h"
00053 using namespace llvm;
00054 
00055 #define DEBUG_TYPE "scalarrepl"
00056 
00057 STATISTIC(NumReplaced,  "Number of allocas broken up");
00058 STATISTIC(NumPromoted,  "Number of allocas promoted");
00059 STATISTIC(NumAdjusted,  "Number of scalar allocas adjusted to allow promotion");
00060 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
00061 
00062 namespace {
00063   struct SROA : public FunctionPass {
00064     SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
00065       : FunctionPass(ID), HasDomTree(hasDT) {
00066       if (T == -1)
00067         SRThreshold = 128;
00068       else
00069         SRThreshold = T;
00070       if (ST == -1)
00071         StructMemberThreshold = 32;
00072       else
00073         StructMemberThreshold = ST;
00074       if (AT == -1)
00075         ArrayElementThreshold = 8;
00076       else
00077         ArrayElementThreshold = AT;
00078       if (SLT == -1)
00079         // Do not limit the scalar integer load size if no threshold is given.
00080         ScalarLoadThreshold = -1;
00081       else
00082         ScalarLoadThreshold = SLT;
00083     }
00084 
00085     bool runOnFunction(Function &F) override;
00086 
00087     bool performScalarRepl(Function &F);
00088     bool performPromotion(Function &F);
00089 
00090   private:
00091     bool HasDomTree;
00092     const DataLayout *DL;
00093 
00094     /// DeadInsts - Keep track of instructions we have made dead, so that
00095     /// we can remove them after we are done working.
00096     SmallVector<Value*, 32> DeadInsts;
00097 
00098     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
00099     /// information about the uses.  All these fields are initialized to false
00100     /// and set to true when something is learned.
00101     struct AllocaInfo {
00102       /// The alloca to promote.
00103       AllocaInst *AI;
00104 
00105       /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
00106       /// looping and avoid redundant work.
00107       SmallPtrSet<PHINode*, 8> CheckedPHIs;
00108 
00109       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
00110       bool isUnsafe : 1;
00111 
00112       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
00113       bool isMemCpySrc : 1;
00114 
00115       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
00116       bool isMemCpyDst : 1;
00117 
00118       /// hasSubelementAccess - This is true if a subelement of the alloca is
00119       /// ever accessed, or false if the alloca is only accessed with mem
00120       /// intrinsics or load/store that only access the entire alloca at once.
00121       bool hasSubelementAccess : 1;
00122 
00123       /// hasALoadOrStore - This is true if there are any loads or stores to it.
00124       /// The alloca may just be accessed with memcpy, for example, which would
00125       /// not set this.
00126       bool hasALoadOrStore : 1;
00127 
00128       explicit AllocaInfo(AllocaInst *ai)
00129         : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
00130           hasSubelementAccess(false), hasALoadOrStore(false) {}
00131     };
00132 
00133     /// SRThreshold - The maximum alloca size to considered for SROA.
00134     unsigned SRThreshold;
00135 
00136     /// StructMemberThreshold - The maximum number of members a struct can
00137     /// contain to be considered for SROA.
00138     unsigned StructMemberThreshold;
00139 
00140     /// ArrayElementThreshold - The maximum number of elements an array can
00141     /// have to be considered for SROA.
00142     unsigned ArrayElementThreshold;
00143 
00144     /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
00145     /// converting to scalar
00146     unsigned ScalarLoadThreshold;
00147 
00148     void MarkUnsafe(AllocaInfo &I, Instruction *User) {
00149       I.isUnsafe = true;
00150       DEBUG(dbgs() << "  Transformation preventing inst: " << *User << '\n');
00151     }
00152 
00153     bool isSafeAllocaToScalarRepl(AllocaInst *AI);
00154 
00155     void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
00156     void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
00157                                          AllocaInfo &Info);
00158     void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
00159     void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
00160                          Type *MemOpType, bool isStore, AllocaInfo &Info,
00161                          Instruction *TheAccess, bool AllowWholeAccess);
00162     bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
00163     uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
00164                                   Type *&IdxTy);
00165 
00166     void DoScalarReplacement(AllocaInst *AI,
00167                              std::vector<AllocaInst*> &WorkList);
00168     void DeleteDeadInstructions();
00169 
00170     void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
00171                               SmallVectorImpl<AllocaInst *> &NewElts);
00172     void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
00173                         SmallVectorImpl<AllocaInst *> &NewElts);
00174     void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
00175                     SmallVectorImpl<AllocaInst *> &NewElts);
00176     void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
00177                                   uint64_t Offset,
00178                                   SmallVectorImpl<AllocaInst *> &NewElts);
00179     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
00180                                       AllocaInst *AI,
00181                                       SmallVectorImpl<AllocaInst *> &NewElts);
00182     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
00183                                        SmallVectorImpl<AllocaInst *> &NewElts);
00184     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
00185                                       SmallVectorImpl<AllocaInst *> &NewElts);
00186     bool ShouldAttemptScalarRepl(AllocaInst *AI);
00187   };
00188 
00189   // SROA_DT - SROA that uses DominatorTree.
00190   struct SROA_DT : public SROA {
00191     static char ID;
00192   public:
00193     SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
00194         SROA(T, true, ID, ST, AT, SLT) {
00195       initializeSROA_DTPass(*PassRegistry::getPassRegistry());
00196     }
00197 
00198     // getAnalysisUsage - This pass does not require any passes, but we know it
00199     // will not alter the CFG, so say so.
00200     void getAnalysisUsage(AnalysisUsage &AU) const override {
00201       AU.addRequired<AssumptionCacheTracker>();
00202       AU.addRequired<DominatorTreeWrapperPass>();
00203       AU.setPreservesCFG();
00204     }
00205   };
00206 
00207   // SROA_SSAUp - SROA that uses SSAUpdater.
00208   struct SROA_SSAUp : public SROA {
00209     static char ID;
00210   public:
00211     SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
00212         SROA(T, false, ID, ST, AT, SLT) {
00213       initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
00214     }
00215 
00216     // getAnalysisUsage - This pass does not require any passes, but we know it
00217     // will not alter the CFG, so say so.
00218     void getAnalysisUsage(AnalysisUsage &AU) const override {
00219       AU.addRequired<AssumptionCacheTracker>();
00220       AU.setPreservesCFG();
00221     }
00222   };
00223 
00224 }
00225 
00226 char SROA_DT::ID = 0;
00227 char SROA_SSAUp::ID = 0;
00228 
00229 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
00230                 "Scalar Replacement of Aggregates (DT)", false, false)
00231 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00232 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00233 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
00234                 "Scalar Replacement of Aggregates (DT)", false, false)
00235 
00236 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
00237                       "Scalar Replacement of Aggregates (SSAUp)", false, false)
00238 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00239 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
00240                     "Scalar Replacement of Aggregates (SSAUp)", false, false)
00241 
00242 // Public interface to the ScalarReplAggregates pass
00243 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
00244                                                    bool UseDomTree,
00245                                                    int StructMemberThreshold,
00246                                                    int ArrayElementThreshold,
00247                                                    int ScalarLoadThreshold) {
00248   if (UseDomTree)
00249     return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
00250                        ScalarLoadThreshold);
00251   return new SROA_SSAUp(Threshold, StructMemberThreshold,
00252                         ArrayElementThreshold, ScalarLoadThreshold);
00253 }
00254 
00255 
00256 //===----------------------------------------------------------------------===//
00257 // Convert To Scalar Optimization.
00258 //===----------------------------------------------------------------------===//
00259 
00260 namespace {
00261 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
00262 /// optimization, which scans the uses of an alloca and determines if it can
00263 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
00264 class ConvertToScalarInfo {
00265   /// AllocaSize - The size of the alloca being considered in bytes.
00266   unsigned AllocaSize;
00267   const DataLayout &DL;
00268   unsigned ScalarLoadThreshold;
00269 
00270   /// IsNotTrivial - This is set to true if there is some access to the object
00271   /// which means that mem2reg can't promote it.
00272   bool IsNotTrivial;
00273 
00274   /// ScalarKind - Tracks the kind of alloca being considered for promotion,
00275   /// computed based on the uses of the alloca rather than the LLVM type system.
00276   enum {
00277     Unknown,
00278 
00279     // Accesses via GEPs that are consistent with element access of a vector
00280     // type. This will not be converted into a vector unless there is a later
00281     // access using an actual vector type.
00282     ImplicitVector,
00283 
00284     // Accesses via vector operations and GEPs that are consistent with the
00285     // layout of a vector type.
00286     Vector,
00287 
00288     // An integer bag-of-bits with bitwise operations for insertion and
00289     // extraction. Any combination of types can be converted into this kind
00290     // of scalar.
00291     Integer
00292   } ScalarKind;
00293 
00294   /// VectorTy - This tracks the type that we should promote the vector to if
00295   /// it is possible to turn it into a vector.  This starts out null, and if it
00296   /// isn't possible to turn into a vector type, it gets set to VoidTy.
00297   VectorType *VectorTy;
00298 
00299   /// HadNonMemTransferAccess - True if there is at least one access to the
00300   /// alloca that is not a MemTransferInst.  We don't want to turn structs into
00301   /// large integers unless there is some potential for optimization.
00302   bool HadNonMemTransferAccess;
00303 
00304   /// HadDynamicAccess - True if some element of this alloca was dynamic.
00305   /// We don't yet have support for turning a dynamic access into a large
00306   /// integer.
00307   bool HadDynamicAccess;
00308 
00309 public:
00310   explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
00311                                unsigned SLT)
00312     : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
00313     ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
00314     HadDynamicAccess(false) { }
00315 
00316   AllocaInst *TryConvert(AllocaInst *AI);
00317 
00318 private:
00319   bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
00320   void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
00321   bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
00322   void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
00323                            Value *NonConstantIdx);
00324 
00325   Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
00326                                     uint64_t Offset, Value* NonConstantIdx,
00327                                     IRBuilder<> &Builder);
00328   Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
00329                                    uint64_t Offset, Value* NonConstantIdx,
00330                                    IRBuilder<> &Builder);
00331 };
00332 } // end anonymous namespace.
00333 
00334 
00335 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
00336 /// rewrite it to be a new alloca which is mem2reg'able.  This returns the new
00337 /// alloca if possible or null if not.
00338 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
00339   // If we can't convert this scalar, or if mem2reg can trivially do it, bail
00340   // out.
00341   if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
00342     return nullptr;
00343 
00344   // If an alloca has only memset / memcpy uses, it may still have an Unknown
00345   // ScalarKind. Treat it as an Integer below.
00346   if (ScalarKind == Unknown)
00347     ScalarKind = Integer;
00348 
00349   if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
00350     ScalarKind = Integer;
00351 
00352   // If we were able to find a vector type that can handle this with
00353   // insert/extract elements, and if there was at least one use that had
00354   // a vector type, promote this to a vector.  We don't want to promote
00355   // random stuff that doesn't use vectors (e.g. <9 x double>) because then
00356   // we just get a lot of insert/extracts.  If at least one vector is
00357   // involved, then we probably really do have a union of vector/array.
00358   Type *NewTy;
00359   if (ScalarKind == Vector) {
00360     assert(VectorTy && "Missing type for vector scalar.");
00361     DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n  TYPE = "
00362           << *VectorTy << '\n');
00363     NewTy = VectorTy;  // Use the vector type.
00364   } else {
00365     unsigned BitWidth = AllocaSize * 8;
00366 
00367     // Do not convert to scalar integer if the alloca size exceeds the
00368     // scalar load threshold.
00369     if (BitWidth > ScalarLoadThreshold)
00370       return nullptr;
00371 
00372     if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
00373         !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
00374       return nullptr;
00375     // Dynamic accesses on integers aren't yet supported.  They need us to shift
00376     // by a dynamic amount which could be difficult to work out as we might not
00377     // know whether to use a left or right shift.
00378     if (ScalarKind == Integer && HadDynamicAccess)
00379       return nullptr;
00380 
00381     DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
00382     // Create and insert the integer alloca.
00383     NewTy = IntegerType::get(AI->getContext(), BitWidth);
00384   }
00385   AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
00386                                      AI->getParent()->begin());
00387   ConvertUsesToScalar(AI, NewAI, 0, nullptr);
00388   return NewAI;
00389 }
00390 
00391 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
00392 /// (VectorTy) so far at the offset specified by Offset (which is specified in
00393 /// bytes).
00394 ///
00395 /// There are two cases we handle here:
00396 ///   1) A union of vector types of the same size and potentially its elements.
00397 ///      Here we turn element accesses into insert/extract element operations.
00398 ///      This promotes a <4 x float> with a store of float to the third element
00399 ///      into a <4 x float> that uses insert element.
00400 ///   2) A fully general blob of memory, which we turn into some (potentially
00401 ///      large) integer type with extract and insert operations where the loads
00402 ///      and stores would mutate the memory.  We mark this by setting VectorTy
00403 ///      to VoidTy.
00404 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
00405                                                     uint64_t Offset) {
00406   // If we already decided to turn this into a blob of integer memory, there is
00407   // nothing to be done.
00408   if (ScalarKind == Integer)
00409     return;
00410 
00411   // If this could be contributing to a vector, analyze it.
00412 
00413   // If the In type is a vector that is the same size as the alloca, see if it
00414   // matches the existing VecTy.
00415   if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
00416     if (MergeInVectorType(VInTy, Offset))
00417       return;
00418   } else if (In->isFloatTy() || In->isDoubleTy() ||
00419              (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
00420               isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
00421     // Full width accesses can be ignored, because they can always be turned
00422     // into bitcasts.
00423     unsigned EltSize = In->getPrimitiveSizeInBits()/8;
00424     if (EltSize == AllocaSize)
00425       return;
00426 
00427     // If we're accessing something that could be an element of a vector, see
00428     // if the implied vector agrees with what we already have and if Offset is
00429     // compatible with it.
00430     if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
00431         (!VectorTy || EltSize == VectorTy->getElementType()
00432                                          ->getPrimitiveSizeInBits()/8)) {
00433       if (!VectorTy) {
00434         ScalarKind = ImplicitVector;
00435         VectorTy = VectorType::get(In, AllocaSize/EltSize);
00436       }
00437       return;
00438     }
00439   }
00440 
00441   // Otherwise, we have a case that we can't handle with an optimized vector
00442   // form.  We can still turn this into a large integer.
00443   ScalarKind = Integer;
00444 }
00445 
00446 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
00447 /// returning true if the type was successfully merged and false otherwise.
00448 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
00449                                             uint64_t Offset) {
00450   if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
00451     // If we're storing/loading a vector of the right size, allow it as a
00452     // vector.  If this the first vector we see, remember the type so that
00453     // we know the element size. If this is a subsequent access, ignore it
00454     // even if it is a differing type but the same size. Worst case we can
00455     // bitcast the resultant vectors.
00456     if (!VectorTy)
00457       VectorTy = VInTy;
00458     ScalarKind = Vector;
00459     return true;
00460   }
00461 
00462   return false;
00463 }
00464 
00465 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
00466 /// its accesses to a single vector type, return true and set VecTy to
00467 /// the new type.  If we could convert the alloca into a single promotable
00468 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
00469 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
00470 /// is the current offset from the base of the alloca being analyzed.
00471 ///
00472 /// If we see at least one access to the value that is as a vector type, set the
00473 /// SawVec flag.
00474 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
00475                                              Value* NonConstantIdx) {
00476   for (User *U : V->users()) {
00477     Instruction *UI = cast<Instruction>(U);
00478 
00479     if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
00480       // Don't break volatile loads.
00481       if (!LI->isSimple())
00482         return false;
00483       // Don't touch MMX operations.
00484       if (LI->getType()->isX86_MMXTy())
00485         return false;
00486       HadNonMemTransferAccess = true;
00487       MergeInTypeForLoadOrStore(LI->getType(), Offset);
00488       continue;
00489     }
00490 
00491     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
00492       // Storing the pointer, not into the value?
00493       if (SI->getOperand(0) == V || !SI->isSimple()) return false;
00494       // Don't touch MMX operations.
00495       if (SI->getOperand(0)->getType()->isX86_MMXTy())
00496         return false;
00497       HadNonMemTransferAccess = true;
00498       MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
00499       continue;
00500     }
00501 
00502     if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
00503       if (!onlyUsedByLifetimeMarkers(BCI))
00504         IsNotTrivial = true;  // Can't be mem2reg'd.
00505       if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
00506         return false;
00507       continue;
00508     }
00509 
00510     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
00511       // If this is a GEP with a variable indices, we can't handle it.
00512       PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
00513       if (!PtrTy)
00514         return false;
00515 
00516       // Compute the offset that this GEP adds to the pointer.
00517       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
00518       Value *GEPNonConstantIdx = nullptr;
00519       if (!GEP->hasAllConstantIndices()) {
00520         if (!isa<VectorType>(PtrTy->getElementType()))
00521           return false;
00522         if (NonConstantIdx)
00523           return false;
00524         GEPNonConstantIdx = Indices.pop_back_val();
00525         if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
00526           return false;
00527         HadDynamicAccess = true;
00528       } else
00529         GEPNonConstantIdx = NonConstantIdx;
00530       uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
00531                                                Indices);
00532       // See if all uses can be converted.
00533       if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
00534         return false;
00535       IsNotTrivial = true;  // Can't be mem2reg'd.
00536       HadNonMemTransferAccess = true;
00537       continue;
00538     }
00539 
00540     // If this is a constant sized memset of a constant value (e.g. 0) we can
00541     // handle it.
00542     if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
00543       // Store to dynamic index.
00544       if (NonConstantIdx)
00545         return false;
00546       // Store of constant value.
00547       if (!isa<ConstantInt>(MSI->getValue()))
00548         return false;
00549 
00550       // Store of constant size.
00551       ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
00552       if (!Len)
00553         return false;
00554 
00555       // If the size differs from the alloca, we can only convert the alloca to
00556       // an integer bag-of-bits.
00557       // FIXME: This should handle all of the cases that are currently accepted
00558       // as vector element insertions.
00559       if (Len->getZExtValue() != AllocaSize || Offset != 0)
00560         ScalarKind = Integer;
00561 
00562       IsNotTrivial = true;  // Can't be mem2reg'd.
00563       HadNonMemTransferAccess = true;
00564       continue;
00565     }
00566 
00567     // If this is a memcpy or memmove into or out of the whole allocation, we
00568     // can handle it like a load or store of the scalar type.
00569     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
00570       // Store to dynamic index.
00571       if (NonConstantIdx)
00572         return false;
00573       ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
00574       if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
00575         return false;
00576 
00577       IsNotTrivial = true;  // Can't be mem2reg'd.
00578       continue;
00579     }
00580 
00581     // If this is a lifetime intrinsic, we can handle it.
00582     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
00583       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00584           II->getIntrinsicID() == Intrinsic::lifetime_end) {
00585         continue;
00586       }
00587     }
00588 
00589     // Otherwise, we cannot handle this!
00590     return false;
00591   }
00592 
00593   return true;
00594 }
00595 
00596 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
00597 /// directly.  This happens when we are converting an "integer union" to a
00598 /// single integer scalar, or when we are converting a "vector union" to a
00599 /// vector with insert/extractelement instructions.
00600 ///
00601 /// Offset is an offset from the original alloca, in bits that need to be
00602 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
00603 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
00604                                               uint64_t Offset,
00605                                               Value* NonConstantIdx) {
00606   while (!Ptr->use_empty()) {
00607     Instruction *User = cast<Instruction>(Ptr->user_back());
00608 
00609     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
00610       ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
00611       CI->eraseFromParent();
00612       continue;
00613     }
00614 
00615     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
00616       // Compute the offset that this GEP adds to the pointer.
00617       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
00618       Value* GEPNonConstantIdx = nullptr;
00619       if (!GEP->hasAllConstantIndices()) {
00620         assert(!NonConstantIdx &&
00621                "Dynamic GEP reading from dynamic GEP unsupported");
00622         GEPNonConstantIdx = Indices.pop_back_val();
00623       } else
00624         GEPNonConstantIdx = NonConstantIdx;
00625       uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
00626                                                Indices);
00627       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
00628       GEP->eraseFromParent();
00629       continue;
00630     }
00631 
00632     IRBuilder<> Builder(User);
00633 
00634     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
00635       // The load is a bit extract from NewAI shifted right by Offset bits.
00636       Value *LoadedVal = Builder.CreateLoad(NewAI);
00637       Value *NewLoadVal
00638         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
00639                                      NonConstantIdx, Builder);
00640       LI->replaceAllUsesWith(NewLoadVal);
00641       LI->eraseFromParent();
00642       continue;
00643     }
00644 
00645     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00646       assert(SI->getOperand(0) != Ptr && "Consistency error!");
00647       Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
00648       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
00649                                              NonConstantIdx, Builder);
00650       Builder.CreateStore(New, NewAI);
00651       SI->eraseFromParent();
00652 
00653       // If the load we just inserted is now dead, then the inserted store
00654       // overwrote the entire thing.
00655       if (Old->use_empty())
00656         Old->eraseFromParent();
00657       continue;
00658     }
00659 
00660     // If this is a constant sized memset of a constant value (e.g. 0) we can
00661     // transform it into a store of the expanded constant value.
00662     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
00663       assert(MSI->getRawDest() == Ptr && "Consistency error!");
00664       assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
00665       int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
00666       if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
00667         unsigned NumBytes = static_cast<unsigned>(SNumBytes);
00668         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
00669 
00670         // Compute the value replicated the right number of times.
00671         APInt APVal(NumBytes*8, Val);
00672 
00673         // Splat the value if non-zero.
00674         if (Val)
00675           for (unsigned i = 1; i != NumBytes; ++i)
00676             APVal |= APVal << 8;
00677 
00678         Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
00679         Value *New = ConvertScalar_InsertValue(
00680                                     ConstantInt::get(User->getContext(), APVal),
00681                                                Old, Offset, nullptr, Builder);
00682         Builder.CreateStore(New, NewAI);
00683 
00684         // If the load we just inserted is now dead, then the memset overwrote
00685         // the entire thing.
00686         if (Old->use_empty())
00687           Old->eraseFromParent();
00688       }
00689       MSI->eraseFromParent();
00690       continue;
00691     }
00692 
00693     // If this is a memcpy or memmove into or out of the whole allocation, we
00694     // can handle it like a load or store of the scalar type.
00695     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
00696       assert(Offset == 0 && "must be store to start of alloca");
00697       assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
00698 
00699       // If the source and destination are both to the same alloca, then this is
00700       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
00701       // as appropriate.
00702       AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
00703 
00704       if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
00705         // Dest must be OrigAI, change this to be a load from the original
00706         // pointer (bitcasted), then a store to our new alloca.
00707         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
00708         Value *SrcPtr = MTI->getSource();
00709         PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
00710         PointerType* AIPTy = cast<PointerType>(NewAI->getType());
00711         if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
00712           AIPTy = PointerType::get(AIPTy->getElementType(),
00713                                    SPTy->getAddressSpace());
00714         }
00715         SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
00716 
00717         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
00718         SrcVal->setAlignment(MTI->getAlignment());
00719         Builder.CreateStore(SrcVal, NewAI);
00720       } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
00721         // Src must be OrigAI, change this to be a load from NewAI then a store
00722         // through the original dest pointer (bitcasted).
00723         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
00724         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
00725 
00726         PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
00727         PointerType* AIPTy = cast<PointerType>(NewAI->getType());
00728         if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
00729           AIPTy = PointerType::get(AIPTy->getElementType(),
00730                                    DPTy->getAddressSpace());
00731         }
00732         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
00733 
00734         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
00735         NewStore->setAlignment(MTI->getAlignment());
00736       } else {
00737         // Noop transfer. Src == Dst
00738       }
00739 
00740       MTI->eraseFromParent();
00741       continue;
00742     }
00743 
00744     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
00745       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00746           II->getIntrinsicID() == Intrinsic::lifetime_end) {
00747         // There's no need to preserve these, as the resulting alloca will be
00748         // converted to a register anyways.
00749         II->eraseFromParent();
00750         continue;
00751       }
00752     }
00753 
00754     llvm_unreachable("Unsupported operation!");
00755   }
00756 }
00757 
00758 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
00759 /// or vector value FromVal, extracting the bits from the offset specified by
00760 /// Offset.  This returns the value, which is of type ToType.
00761 ///
00762 /// This happens when we are converting an "integer union" to a single
00763 /// integer scalar, or when we are converting a "vector union" to a vector with
00764 /// insert/extractelement instructions.
00765 ///
00766 /// Offset is an offset from the original alloca, in bits that need to be
00767 /// shifted to the right.
00768 Value *ConvertToScalarInfo::
00769 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
00770                            uint64_t Offset, Value* NonConstantIdx,
00771                            IRBuilder<> &Builder) {
00772   // If the load is of the whole new alloca, no conversion is needed.
00773   Type *FromType = FromVal->getType();
00774   if (FromType == ToType && Offset == 0)
00775     return FromVal;
00776 
00777   // If the result alloca is a vector type, this is either an element
00778   // access or a bitcast to another vector type of the same size.
00779   if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
00780     unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
00781     unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
00782     if (FromTypeSize == ToTypeSize)
00783         return Builder.CreateBitCast(FromVal, ToType);
00784 
00785     // Otherwise it must be an element access.
00786     unsigned Elt = 0;
00787     if (Offset) {
00788       unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
00789       Elt = Offset/EltSize;
00790       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
00791     }
00792     // Return the element extracted out of it.
00793     Value *Idx;
00794     if (NonConstantIdx) {
00795       if (Elt)
00796         Idx = Builder.CreateAdd(NonConstantIdx,
00797                                 Builder.getInt32(Elt),
00798                                 "dyn.offset");
00799       else
00800         Idx = NonConstantIdx;
00801     } else
00802       Idx = Builder.getInt32(Elt);
00803     Value *V = Builder.CreateExtractElement(FromVal, Idx);
00804     if (V->getType() != ToType)
00805       V = Builder.CreateBitCast(V, ToType);
00806     return V;
00807   }
00808 
00809   // If ToType is a first class aggregate, extract out each of the pieces and
00810   // use insertvalue's to form the FCA.
00811   if (StructType *ST = dyn_cast<StructType>(ToType)) {
00812     assert(!NonConstantIdx &&
00813            "Dynamic indexing into struct types not supported");
00814     const StructLayout &Layout = *DL.getStructLayout(ST);
00815     Value *Res = UndefValue::get(ST);
00816     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
00817       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
00818                                         Offset+Layout.getElementOffsetInBits(i),
00819                                               nullptr, Builder);
00820       Res = Builder.CreateInsertValue(Res, Elt, i);
00821     }
00822     return Res;
00823   }
00824 
00825   if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
00826     assert(!NonConstantIdx &&
00827            "Dynamic indexing into array types not supported");
00828     uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
00829     Value *Res = UndefValue::get(AT);
00830     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
00831       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
00832                                               Offset+i*EltSize, nullptr,
00833                                               Builder);
00834       Res = Builder.CreateInsertValue(Res, Elt, i);
00835     }
00836     return Res;
00837   }
00838 
00839   // Otherwise, this must be a union that was converted to an integer value.
00840   IntegerType *NTy = cast<IntegerType>(FromVal->getType());
00841 
00842   // If this is a big-endian system and the load is narrower than the
00843   // full alloca type, we need to do a shift to get the right bits.
00844   int ShAmt = 0;
00845   if (DL.isBigEndian()) {
00846     // On big-endian machines, the lowest bit is stored at the bit offset
00847     // from the pointer given by getTypeStoreSizeInBits.  This matters for
00848     // integers with a bitwidth that is not a multiple of 8.
00849     ShAmt = DL.getTypeStoreSizeInBits(NTy) -
00850             DL.getTypeStoreSizeInBits(ToType) - Offset;
00851   } else {
00852     ShAmt = Offset;
00853   }
00854 
00855   // Note: we support negative bitwidths (with shl) which are not defined.
00856   // We do this to support (f.e.) loads off the end of a structure where
00857   // only some bits are used.
00858   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
00859     FromVal = Builder.CreateLShr(FromVal,
00860                                  ConstantInt::get(FromVal->getType(), ShAmt));
00861   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
00862     FromVal = Builder.CreateShl(FromVal,
00863                                 ConstantInt::get(FromVal->getType(), -ShAmt));
00864 
00865   // Finally, unconditionally truncate the integer to the right width.
00866   unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
00867   if (LIBitWidth < NTy->getBitWidth())
00868     FromVal =
00869       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
00870                                                     LIBitWidth));
00871   else if (LIBitWidth > NTy->getBitWidth())
00872     FromVal =
00873        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
00874                                                     LIBitWidth));
00875 
00876   // If the result is an integer, this is a trunc or bitcast.
00877   if (ToType->isIntegerTy()) {
00878     // Should be done.
00879   } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
00880     // Just do a bitcast, we know the sizes match up.
00881     FromVal = Builder.CreateBitCast(FromVal, ToType);
00882   } else {
00883     // Otherwise must be a pointer.
00884     FromVal = Builder.CreateIntToPtr(FromVal, ToType);
00885   }
00886   assert(FromVal->getType() == ToType && "Didn't convert right?");
00887   return FromVal;
00888 }
00889 
00890 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
00891 /// or vector value "Old" at the offset specified by Offset.
00892 ///
00893 /// This happens when we are converting an "integer union" to a
00894 /// single integer scalar, or when we are converting a "vector union" to a
00895 /// vector with insert/extractelement instructions.
00896 ///
00897 /// Offset is an offset from the original alloca, in bits that need to be
00898 /// shifted to the right.
00899 ///
00900 /// NonConstantIdx is an index value if there was a GEP with a non-constant
00901 /// index value.  If this is 0 then all GEPs used to find this insert address
00902 /// are constant.
00903 Value *ConvertToScalarInfo::
00904 ConvertScalar_InsertValue(Value *SV, Value *Old,
00905                           uint64_t Offset, Value* NonConstantIdx,
00906                           IRBuilder<> &Builder) {
00907   // Convert the stored type to the actual type, shift it left to insert
00908   // then 'or' into place.
00909   Type *AllocaType = Old->getType();
00910   LLVMContext &Context = Old->getContext();
00911 
00912   if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
00913     uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
00914     uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
00915 
00916     // Changing the whole vector with memset or with an access of a different
00917     // vector type?
00918     if (ValSize == VecSize)
00919         return Builder.CreateBitCast(SV, AllocaType);
00920 
00921     // Must be an element insertion.
00922     Type *EltTy = VTy->getElementType();
00923     if (SV->getType() != EltTy)
00924       SV = Builder.CreateBitCast(SV, EltTy);
00925     uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
00926     unsigned Elt = Offset/EltSize;
00927     Value *Idx;
00928     if (NonConstantIdx) {
00929       if (Elt)
00930         Idx = Builder.CreateAdd(NonConstantIdx,
00931                                 Builder.getInt32(Elt),
00932                                 "dyn.offset");
00933       else
00934         Idx = NonConstantIdx;
00935     } else
00936       Idx = Builder.getInt32(Elt);
00937     return Builder.CreateInsertElement(Old, SV, Idx);
00938   }
00939 
00940   // If SV is a first-class aggregate value, insert each value recursively.
00941   if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
00942     assert(!NonConstantIdx &&
00943            "Dynamic indexing into struct types not supported");
00944     const StructLayout &Layout = *DL.getStructLayout(ST);
00945     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
00946       Value *Elt = Builder.CreateExtractValue(SV, i);
00947       Old = ConvertScalar_InsertValue(Elt, Old,
00948                                       Offset+Layout.getElementOffsetInBits(i),
00949                                       nullptr, Builder);
00950     }
00951     return Old;
00952   }
00953 
00954   if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
00955     assert(!NonConstantIdx &&
00956            "Dynamic indexing into array types not supported");
00957     uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
00958     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
00959       Value *Elt = Builder.CreateExtractValue(SV, i);
00960       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
00961                                       Builder);
00962     }
00963     return Old;
00964   }
00965 
00966   // If SV is a float, convert it to the appropriate integer type.
00967   // If it is a pointer, do the same.
00968   unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
00969   unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
00970   unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
00971   unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
00972   if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
00973     SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
00974   else if (SV->getType()->isPointerTy())
00975     SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
00976 
00977   // Zero extend or truncate the value if needed.
00978   if (SV->getType() != AllocaType) {
00979     if (SV->getType()->getPrimitiveSizeInBits() <
00980              AllocaType->getPrimitiveSizeInBits())
00981       SV = Builder.CreateZExt(SV, AllocaType);
00982     else {
00983       // Truncation may be needed if storing more than the alloca can hold
00984       // (undefined behavior).
00985       SV = Builder.CreateTrunc(SV, AllocaType);
00986       SrcWidth = DestWidth;
00987       SrcStoreWidth = DestStoreWidth;
00988     }
00989   }
00990 
00991   // If this is a big-endian system and the store is narrower than the
00992   // full alloca type, we need to do a shift to get the right bits.
00993   int ShAmt = 0;
00994   if (DL.isBigEndian()) {
00995     // On big-endian machines, the lowest bit is stored at the bit offset
00996     // from the pointer given by getTypeStoreSizeInBits.  This matters for
00997     // integers with a bitwidth that is not a multiple of 8.
00998     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
00999   } else {
01000     ShAmt = Offset;
01001   }
01002 
01003   // Note: we support negative bitwidths (with shr) which are not defined.
01004   // We do this to support (f.e.) stores off the end of a structure where
01005   // only some bits in the structure are set.
01006   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
01007   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
01008     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
01009     Mask <<= ShAmt;
01010   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
01011     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
01012     Mask = Mask.lshr(-ShAmt);
01013   }
01014 
01015   // Mask out the bits we are about to insert from the old value, and or
01016   // in the new bits.
01017   if (SrcWidth != DestWidth) {
01018     assert(DestWidth > SrcWidth);
01019     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
01020     SV = Builder.CreateOr(Old, SV, "ins");
01021   }
01022   return SV;
01023 }
01024 
01025 
01026 //===----------------------------------------------------------------------===//
01027 // SRoA Driver
01028 //===----------------------------------------------------------------------===//
01029 
01030 
01031 bool SROA::runOnFunction(Function &F) {
01032   if (skipOptnoneFunction(F))
01033     return false;
01034 
01035   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01036   DL = DLP ? &DLP->getDataLayout() : nullptr;
01037 
01038   bool Changed = performPromotion(F);
01039 
01040   // FIXME: ScalarRepl currently depends on DataLayout more than it
01041   // theoretically needs to. It should be refactored in order to support
01042   // target-independent IR. Until this is done, just skip the actual
01043   // scalar-replacement portion of this pass.
01044   if (!DL) return Changed;
01045 
01046   while (1) {
01047     bool LocalChange = performScalarRepl(F);
01048     if (!LocalChange) break;   // No need to repromote if no scalarrepl
01049     Changed = true;
01050     LocalChange = performPromotion(F);
01051     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
01052   }
01053 
01054   return Changed;
01055 }
01056 
01057 namespace {
01058 class AllocaPromoter : public LoadAndStorePromoter {
01059   AllocaInst *AI;
01060   DIBuilder *DIB;
01061   SmallVector<DbgDeclareInst *, 4> DDIs;
01062   SmallVector<DbgValueInst *, 4> DVIs;
01063 public:
01064   AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
01065                  DIBuilder *DB)
01066     : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
01067 
01068   void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
01069     // Remember which alloca we're promoting (for isInstInList).
01070     this->AI = AI;
01071     if (auto *L = LocalAsMetadata::getIfExists(AI)) {
01072       if (auto *DebugNode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
01073         for (User *U : DebugNode->users())
01074           if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01075             DDIs.push_back(DDI);
01076           else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
01077             DVIs.push_back(DVI);
01078       }
01079     }
01080 
01081     LoadAndStorePromoter::run(Insts);
01082     AI->eraseFromParent();
01083     for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
01084            E = DDIs.end(); I != E; ++I) {
01085       DbgDeclareInst *DDI = *I;
01086       DDI->eraseFromParent();
01087     }
01088     for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
01089            E = DVIs.end(); I != E; ++I) {
01090       DbgValueInst *DVI = *I;
01091       DVI->eraseFromParent();
01092     }
01093   }
01094 
01095   bool isInstInList(Instruction *I,
01096                     const SmallVectorImpl<Instruction*> &Insts) const override {
01097     if (LoadInst *LI = dyn_cast<LoadInst>(I))
01098       return LI->getOperand(0) == AI;
01099     return cast<StoreInst>(I)->getPointerOperand() == AI;
01100   }
01101 
01102   void updateDebugInfo(Instruction *Inst) const override {
01103     for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
01104            E = DDIs.end(); I != E; ++I) {
01105       DbgDeclareInst *DDI = *I;
01106       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
01107         ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
01108       else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
01109         ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
01110     }
01111     for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
01112            E = DVIs.end(); I != E; ++I) {
01113       DbgValueInst *DVI = *I;
01114       Value *Arg = nullptr;
01115       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
01116         // If an argument is zero extended then use argument directly. The ZExt
01117         // may be zapped by an optimization pass in future.
01118         if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
01119           Arg = dyn_cast<Argument>(ZExt->getOperand(0));
01120         if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01121           Arg = dyn_cast<Argument>(SExt->getOperand(0));
01122         if (!Arg)
01123           Arg = SI->getOperand(0);
01124       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
01125         Arg = LI->getOperand(0);
01126       } else {
01127         continue;
01128       }
01129       Instruction *DbgVal = DIB->insertDbgValueIntrinsic(
01130           Arg, 0, DIVariable(DVI->getVariable()),
01131           DIExpression(DVI->getExpression()), Inst);
01132       DbgVal->setDebugLoc(DVI->getDebugLoc());
01133     }
01134   }
01135 };
01136 } // end anon namespace
01137 
01138 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
01139 /// subsequently loaded can be rewritten to load both input pointers and then
01140 /// select between the result, allowing the load of the alloca to be promoted.
01141 /// From this:
01142 ///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
01143 ///   %V = load i32* %P2
01144 /// to:
01145 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01146 ///   %V2 = load i32* %Other
01147 ///   %V = select i1 %cond, i32 %V1, i32 %V2
01148 ///
01149 /// We can do this to a select if its only uses are loads and if the operand to
01150 /// the select can be loaded unconditionally.
01151 static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
01152   bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(DL);
01153   bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(DL);
01154 
01155   for (User *U : SI->users()) {
01156     LoadInst *LI = dyn_cast<LoadInst>(U);
01157     if (!LI || !LI->isSimple()) return false;
01158 
01159     // Both operands to the select need to be dereferencable, either absolutely
01160     // (e.g. allocas) or at this point because we can see other accesses to it.
01161     if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
01162                                                     LI->getAlignment(), DL))
01163       return false;
01164     if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
01165                                                     LI->getAlignment(), DL))
01166       return false;
01167   }
01168 
01169   return true;
01170 }
01171 
01172 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
01173 /// subsequently loaded can be rewritten to load both input pointers in the pred
01174 /// blocks and then PHI the results, allowing the load of the alloca to be
01175 /// promoted.
01176 /// From this:
01177 ///   %P2 = phi [i32* %Alloca, i32* %Other]
01178 ///   %V = load i32* %P2
01179 /// to:
01180 ///   %V1 = load i32* %Alloca      -> will be mem2reg'd
01181 ///   ...
01182 ///   %V2 = load i32* %Other
01183 ///   ...
01184 ///   %V = phi [i32 %V1, i32 %V2]
01185 ///
01186 /// We can do this to a select if its only uses are loads and if the operand to
01187 /// the select can be loaded unconditionally.
01188 static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
01189   // For now, we can only do this promotion if the load is in the same block as
01190   // the PHI, and if there are no stores between the phi and load.
01191   // TODO: Allow recursive phi users.
01192   // TODO: Allow stores.
01193   BasicBlock *BB = PN->getParent();
01194   unsigned MaxAlign = 0;
01195   for (User *U : PN->users()) {
01196     LoadInst *LI = dyn_cast<LoadInst>(U);
01197     if (!LI || !LI->isSimple()) return false;
01198 
01199     // For now we only allow loads in the same block as the PHI.  This is a
01200     // common case that happens when instcombine merges two loads through a PHI.
01201     if (LI->getParent() != BB) return false;
01202 
01203     // Ensure that there are no instructions between the PHI and the load that
01204     // could store.
01205     for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
01206       if (BBI->mayWriteToMemory())
01207         return false;
01208 
01209     MaxAlign = std::max(MaxAlign, LI->getAlignment());
01210   }
01211 
01212   // Okay, we know that we have one or more loads in the same block as the PHI.
01213   // We can transform this if it is safe to push the loads into the predecessor
01214   // blocks.  The only thing to watch out for is that we can't put a possibly
01215   // trapping load in the predecessor if it is a critical edge.
01216   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01217     BasicBlock *Pred = PN->getIncomingBlock(i);
01218     Value *InVal = PN->getIncomingValue(i);
01219 
01220     // If the terminator of the predecessor has side-effects (an invoke),
01221     // there is no safe place to put a load in the predecessor.
01222     if (Pred->getTerminator()->mayHaveSideEffects())
01223       return false;
01224 
01225     // If the value is produced by the terminator of the predecessor
01226     // (an invoke), there is no valid place to put a load in the predecessor.
01227     if (Pred->getTerminator() == InVal)
01228       return false;
01229 
01230     // If the predecessor has a single successor, then the edge isn't critical.
01231     if (Pred->getTerminator()->getNumSuccessors() == 1)
01232       continue;
01233 
01234     // If this pointer is always safe to load, or if we can prove that there is
01235     // already a load in the block, then we can move the load to the pred block.
01236     if (InVal->isDereferenceablePointer(DL) ||
01237         isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
01238       continue;
01239 
01240     return false;
01241   }
01242 
01243   return true;
01244 }
01245 
01246 
01247 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
01248 /// direct (non-volatile) loads and stores to it.  If the alloca is close but
01249 /// not quite there, this will transform the code to allow promotion.  As such,
01250 /// it is a non-pure predicate.
01251 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
01252   SetVector<Instruction*, SmallVector<Instruction*, 4>,
01253             SmallPtrSet<Instruction*, 4> > InstsToRewrite;
01254   for (User *U : AI->users()) {
01255     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
01256       if (!LI->isSimple())
01257         return false;
01258       continue;
01259     }
01260 
01261     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
01262       if (SI->getOperand(0) == AI || !SI->isSimple())
01263         return false;   // Don't allow a store OF the AI, only INTO the AI.
01264       continue;
01265     }
01266 
01267     if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
01268       // If the condition being selected on is a constant, fold the select, yes
01269       // this does (rarely) happen early on.
01270       if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
01271         Value *Result = SI->getOperand(1+CI->isZero());
01272         SI->replaceAllUsesWith(Result);
01273         SI->eraseFromParent();
01274 
01275         // This is very rare and we just scrambled the use list of AI, start
01276         // over completely.
01277         return tryToMakeAllocaBePromotable(AI, DL);
01278       }
01279 
01280       // If it is safe to turn "load (select c, AI, ptr)" into a select of two
01281       // loads, then we can transform this by rewriting the select.
01282       if (!isSafeSelectToSpeculate(SI, DL))
01283         return false;
01284 
01285       InstsToRewrite.insert(SI);
01286       continue;
01287     }
01288 
01289     if (PHINode *PN = dyn_cast<PHINode>(U)) {
01290       if (PN->use_empty()) {  // Dead PHIs can be stripped.
01291         InstsToRewrite.insert(PN);
01292         continue;
01293       }
01294 
01295       // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
01296       // in the pred blocks, then we can transform this by rewriting the PHI.
01297       if (!isSafePHIToSpeculate(PN, DL))
01298         return false;
01299 
01300       InstsToRewrite.insert(PN);
01301       continue;
01302     }
01303 
01304     if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
01305       if (onlyUsedByLifetimeMarkers(BCI)) {
01306         InstsToRewrite.insert(BCI);
01307         continue;
01308       }
01309     }
01310 
01311     return false;
01312   }
01313 
01314   // If there are no instructions to rewrite, then all uses are load/stores and
01315   // we're done!
01316   if (InstsToRewrite.empty())
01317     return true;
01318 
01319   // If we have instructions that need to be rewritten for this to be promotable
01320   // take care of it now.
01321   for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
01322     if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
01323       // This could only be a bitcast used by nothing but lifetime intrinsics.
01324       for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
01325            I != E;)
01326         cast<Instruction>(*I++)->eraseFromParent();
01327       BCI->eraseFromParent();
01328       continue;
01329     }
01330 
01331     if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
01332       // Selects in InstsToRewrite only have load uses.  Rewrite each as two
01333       // loads with a new select.
01334       while (!SI->use_empty()) {
01335         LoadInst *LI = cast<LoadInst>(SI->user_back());
01336 
01337         IRBuilder<> Builder(LI);
01338         LoadInst *TrueLoad =
01339           Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
01340         LoadInst *FalseLoad =
01341           Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
01342 
01343         // Transfer alignment and AA info if present.
01344         TrueLoad->setAlignment(LI->getAlignment());
01345         FalseLoad->setAlignment(LI->getAlignment());
01346 
01347         AAMDNodes Tags;
01348         LI->getAAMetadata(Tags);
01349         if (Tags) {
01350           TrueLoad->setAAMetadata(Tags);
01351           FalseLoad->setAAMetadata(Tags);
01352         }
01353 
01354         Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
01355         V->takeName(LI);
01356         LI->replaceAllUsesWith(V);
01357         LI->eraseFromParent();
01358       }
01359 
01360       // Now that all the loads are gone, the select is gone too.
01361       SI->eraseFromParent();
01362       continue;
01363     }
01364 
01365     // Otherwise, we have a PHI node which allows us to push the loads into the
01366     // predecessors.
01367     PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
01368     if (PN->use_empty()) {
01369       PN->eraseFromParent();
01370       continue;
01371     }
01372 
01373     Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
01374     PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
01375                                      PN->getName()+".ld", PN);
01376 
01377     // Get the AA tags and alignment to use from one of the loads.  It doesn't
01378     // matter which one we get and if any differ, it doesn't matter.
01379     LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
01380 
01381     AAMDNodes AATags;
01382     SomeLoad->getAAMetadata(AATags);
01383     unsigned Align = SomeLoad->getAlignment();
01384 
01385     // Rewrite all loads of the PN to use the new PHI.
01386     while (!PN->use_empty()) {
01387       LoadInst *LI = cast<LoadInst>(PN->user_back());
01388       LI->replaceAllUsesWith(NewPN);
01389       LI->eraseFromParent();
01390     }
01391 
01392     // Inject loads into all of the pred blocks.  Keep track of which blocks we
01393     // insert them into in case we have multiple edges from the same block.
01394     DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
01395 
01396     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01397       BasicBlock *Pred = PN->getIncomingBlock(i);
01398       LoadInst *&Load = InsertedLoads[Pred];
01399       if (!Load) {
01400         Load = new LoadInst(PN->getIncomingValue(i),
01401                             PN->getName() + "." + Pred->getName(),
01402                             Pred->getTerminator());
01403         Load->setAlignment(Align);
01404         if (AATags) Load->setAAMetadata(AATags);
01405       }
01406 
01407       NewPN->addIncoming(Load, Pred);
01408     }
01409 
01410     PN->eraseFromParent();
01411   }
01412 
01413   ++NumAdjusted;
01414   return true;
01415 }
01416 
01417 bool SROA::performPromotion(Function &F) {
01418   std::vector<AllocaInst*> Allocas;
01419   DominatorTree *DT = nullptr;
01420   if (HasDomTree)
01421     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01422   AssumptionCache &AC =
01423       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
01424 
01425   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
01426   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
01427   bool Changed = false;
01428   SmallVector<Instruction*, 64> Insts;
01429   while (1) {
01430     Allocas.clear();
01431 
01432     // Find allocas that are safe to promote, by looking at all instructions in
01433     // the entry node
01434     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
01435       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
01436         if (tryToMakeAllocaBePromotable(AI, DL))
01437           Allocas.push_back(AI);
01438 
01439     if (Allocas.empty()) break;
01440 
01441     if (HasDomTree)
01442       PromoteMemToReg(Allocas, *DT, nullptr, &AC);
01443     else {
01444       SSAUpdater SSA;
01445       for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
01446         AllocaInst *AI = Allocas[i];
01447 
01448         // Build list of instructions to promote.
01449         for (User *U : AI->users())
01450           Insts.push_back(cast<Instruction>(U));
01451         AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
01452         Insts.clear();
01453       }
01454     }
01455     NumPromoted += Allocas.size();
01456     Changed = true;
01457   }
01458 
01459   return Changed;
01460 }
01461 
01462 
01463 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
01464 /// SROA.  It must be a struct or array type with a small number of elements.
01465 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
01466   Type *T = AI->getAllocatedType();
01467   // Do not promote any struct that has too many members.
01468   if (StructType *ST = dyn_cast<StructType>(T))
01469     return ST->getNumElements() <= StructMemberThreshold;
01470   // Do not promote any array that has too many elements.
01471   if (ArrayType *AT = dyn_cast<ArrayType>(T))
01472     return AT->getNumElements() <= ArrayElementThreshold;
01473   return false;
01474 }
01475 
01476 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
01477 // which runs on all of the alloca instructions in the entry block, removing
01478 // them if they are only used by getelementptr instructions.
01479 //
01480 bool SROA::performScalarRepl(Function &F) {
01481   std::vector<AllocaInst*> WorkList;
01482 
01483   // Scan the entry basic block, adding allocas to the worklist.
01484   BasicBlock &BB = F.getEntryBlock();
01485   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
01486     if (AllocaInst *A = dyn_cast<AllocaInst>(I))
01487       WorkList.push_back(A);
01488 
01489   // Process the worklist
01490   bool Changed = false;
01491   while (!WorkList.empty()) {
01492     AllocaInst *AI = WorkList.back();
01493     WorkList.pop_back();
01494 
01495     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
01496     // with unused elements.
01497     if (AI->use_empty()) {
01498       AI->eraseFromParent();
01499       Changed = true;
01500       continue;
01501     }
01502 
01503     // If this alloca is impossible for us to promote, reject it early.
01504     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
01505       continue;
01506 
01507     // Check to see if we can perform the core SROA transformation.  We cannot
01508     // transform the allocation instruction if it is an array allocation
01509     // (allocations OF arrays are ok though), and an allocation of a scalar
01510     // value cannot be decomposed at all.
01511     uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
01512 
01513     // Do not promote [0 x %struct].
01514     if (AllocaSize == 0) continue;
01515 
01516     // Do not promote any struct whose size is too big.
01517     if (AllocaSize > SRThreshold) continue;
01518 
01519     // If the alloca looks like a good candidate for scalar replacement, and if
01520     // all its users can be transformed, then split up the aggregate into its
01521     // separate elements.
01522     if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
01523       DoScalarReplacement(AI, WorkList);
01524       Changed = true;
01525       continue;
01526     }
01527 
01528     // If we can turn this aggregate value (potentially with casts) into a
01529     // simple scalar value that can be mem2reg'd into a register value.
01530     // IsNotTrivial tracks whether this is something that mem2reg could have
01531     // promoted itself.  If so, we don't want to transform it needlessly.  Note
01532     // that we can't just check based on the type: the alloca may be of an i32
01533     // but that has pointer arithmetic to set byte 3 of it or something.
01534     if (AllocaInst *NewAI = ConvertToScalarInfo(
01535               (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
01536       NewAI->takeName(AI);
01537       AI->eraseFromParent();
01538       ++NumConverted;
01539       Changed = true;
01540       continue;
01541     }
01542 
01543     // Otherwise, couldn't process this alloca.
01544   }
01545 
01546   return Changed;
01547 }
01548 
01549 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
01550 /// predicate, do SROA now.
01551 void SROA::DoScalarReplacement(AllocaInst *AI,
01552                                std::vector<AllocaInst*> &WorkList) {
01553   DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
01554   SmallVector<AllocaInst*, 32> ElementAllocas;
01555   if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
01556     ElementAllocas.reserve(ST->getNumContainedTypes());
01557     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
01558       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
01559                                       AI->getAlignment(),
01560                                       AI->getName() + "." + Twine(i), AI);
01561       ElementAllocas.push_back(NA);
01562       WorkList.push_back(NA);  // Add to worklist for recursive processing
01563     }
01564   } else {
01565     ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
01566     ElementAllocas.reserve(AT->getNumElements());
01567     Type *ElTy = AT->getElementType();
01568     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
01569       AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
01570                                       AI->getName() + "." + Twine(i), AI);
01571       ElementAllocas.push_back(NA);
01572       WorkList.push_back(NA);  // Add to worklist for recursive processing
01573     }
01574   }
01575 
01576   // Now that we have created the new alloca instructions, rewrite all the
01577   // uses of the old alloca.
01578   RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
01579 
01580   // Now erase any instructions that were made dead while rewriting the alloca.
01581   DeleteDeadInstructions();
01582   AI->eraseFromParent();
01583 
01584   ++NumReplaced;
01585 }
01586 
01587 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
01588 /// recursively including all their operands that become trivially dead.
01589 void SROA::DeleteDeadInstructions() {
01590   while (!DeadInsts.empty()) {
01591     Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
01592 
01593     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
01594       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
01595         // Zero out the operand and see if it becomes trivially dead.
01596         // (But, don't add allocas to the dead instruction list -- they are
01597         // already on the worklist and will be deleted separately.)
01598         *OI = nullptr;
01599         if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
01600           DeadInsts.push_back(U);
01601       }
01602 
01603     I->eraseFromParent();
01604   }
01605 }
01606 
01607 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
01608 /// performing scalar replacement of alloca AI.  The results are flagged in
01609 /// the Info parameter.  Offset indicates the position within AI that is
01610 /// referenced by this instruction.
01611 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
01612                                AllocaInfo &Info) {
01613   for (Use &U : I->uses()) {
01614     Instruction *User = cast<Instruction>(U.getUser());
01615 
01616     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
01617       isSafeForScalarRepl(BC, Offset, Info);
01618     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01619       uint64_t GEPOffset = Offset;
01620       isSafeGEP(GEPI, GEPOffset, Info);
01621       if (!Info.isUnsafe)
01622         isSafeForScalarRepl(GEPI, GEPOffset, Info);
01623     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
01624       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
01625       if (!Length || Length->isNegative())
01626         return MarkUnsafe(Info, User);
01627 
01628       isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
01629                       U.getOperandNo() == 0, Info, MI,
01630                       true /*AllowWholeAccess*/);
01631     } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01632       if (!LI->isSimple())
01633         return MarkUnsafe(Info, User);
01634       Type *LIType = LI->getType();
01635       isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
01636                       LIType, false, Info, LI, true /*AllowWholeAccess*/);
01637       Info.hasALoadOrStore = true;
01638 
01639     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01640       // Store is ok if storing INTO the pointer, not storing the pointer
01641       if (!SI->isSimple() || SI->getOperand(0) == I)
01642         return MarkUnsafe(Info, User);
01643 
01644       Type *SIType = SI->getOperand(0)->getType();
01645       isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
01646                       SIType, true, Info, SI, true /*AllowWholeAccess*/);
01647       Info.hasALoadOrStore = true;
01648     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
01649       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01650           II->getIntrinsicID() != Intrinsic::lifetime_end)
01651         return MarkUnsafe(Info, User);
01652     } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
01653       isSafePHISelectUseForScalarRepl(User, Offset, Info);
01654     } else {
01655       return MarkUnsafe(Info, User);
01656     }
01657     if (Info.isUnsafe) return;
01658   }
01659 }
01660 
01661 
01662 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
01663 /// derived from the alloca, we can often still split the alloca into elements.
01664 /// This is useful if we have a large alloca where one element is phi'd
01665 /// together somewhere: we can SRoA and promote all the other elements even if
01666 /// we end up not being able to promote this one.
01667 ///
01668 /// All we require is that the uses of the PHI do not index into other parts of
01669 /// the alloca.  The most important use case for this is single load and stores
01670 /// that are PHI'd together, which can happen due to code sinking.
01671 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
01672                                            AllocaInfo &Info) {
01673   // If we've already checked this PHI, don't do it again.
01674   if (PHINode *PN = dyn_cast<PHINode>(I))
01675     if (!Info.CheckedPHIs.insert(PN).second)
01676       return;
01677 
01678   for (User *U : I->users()) {
01679     Instruction *UI = cast<Instruction>(U);
01680 
01681     if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
01682       isSafePHISelectUseForScalarRepl(BC, Offset, Info);
01683     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
01684       // Only allow "bitcast" GEPs for simplicity.  We could generalize this,
01685       // but would have to prove that we're staying inside of an element being
01686       // promoted.
01687       if (!GEPI->hasAllZeroIndices())
01688         return MarkUnsafe(Info, UI);
01689       isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
01690     } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
01691       if (!LI->isSimple())
01692         return MarkUnsafe(Info, UI);
01693       Type *LIType = LI->getType();
01694       isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
01695                       LIType, false, Info, LI, false /*AllowWholeAccess*/);
01696       Info.hasALoadOrStore = true;
01697 
01698     } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
01699       // Store is ok if storing INTO the pointer, not storing the pointer
01700       if (!SI->isSimple() || SI->getOperand(0) == I)
01701         return MarkUnsafe(Info, UI);
01702 
01703       Type *SIType = SI->getOperand(0)->getType();
01704       isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
01705                       SIType, true, Info, SI, false /*AllowWholeAccess*/);
01706       Info.hasALoadOrStore = true;
01707     } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
01708       isSafePHISelectUseForScalarRepl(UI, Offset, Info);
01709     } else {
01710       return MarkUnsafe(Info, UI);
01711     }
01712     if (Info.isUnsafe) return;
01713   }
01714 }
01715 
01716 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
01717 /// replacement.  It is safe when all the indices are constant, in-bounds
01718 /// references, and when the resulting offset corresponds to an element within
01719 /// the alloca type.  The results are flagged in the Info parameter.  Upon
01720 /// return, Offset is adjusted as specified by the GEP indices.
01721 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
01722                      uint64_t &Offset, AllocaInfo &Info) {
01723   gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
01724   if (GEPIt == E)
01725     return;
01726   bool NonConstant = false;
01727   unsigned NonConstantIdxSize = 0;
01728 
01729   // Walk through the GEP type indices, checking the types that this indexes
01730   // into.
01731   for (; GEPIt != E; ++GEPIt) {
01732     // Ignore struct elements, no extra checking needed for these.
01733     if ((*GEPIt)->isStructTy())
01734       continue;
01735 
01736     ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
01737     if (!IdxVal)
01738       return MarkUnsafe(Info, GEPI);
01739   }
01740 
01741   // Compute the offset due to this GEP and check if the alloca has a
01742   // component element at that offset.
01743   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
01744   // If this GEP is non-constant then the last operand must have been a
01745   // dynamic index into a vector.  Pop this now as it has no impact on the
01746   // constant part of the offset.
01747   if (NonConstant)
01748     Indices.pop_back();
01749   Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
01750   if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
01751                         NonConstantIdxSize))
01752     MarkUnsafe(Info, GEPI);
01753 }
01754 
01755 /// isHomogeneousAggregate - Check if type T is a struct or array containing
01756 /// elements of the same type (which is always true for arrays).  If so,
01757 /// return true with NumElts and EltTy set to the number of elements and the
01758 /// element type, respectively.
01759 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
01760                                    Type *&EltTy) {
01761   if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
01762     NumElts = AT->getNumElements();
01763     EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
01764     return true;
01765   }
01766   if (StructType *ST = dyn_cast<StructType>(T)) {
01767     NumElts = ST->getNumContainedTypes();
01768     EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
01769     for (unsigned n = 1; n < NumElts; ++n) {
01770       if (ST->getContainedType(n) != EltTy)
01771         return false;
01772     }
01773     return true;
01774   }
01775   return false;
01776 }
01777 
01778 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
01779 /// "homogeneous" aggregates with the same element type and number of elements.
01780 static bool isCompatibleAggregate(Type *T1, Type *T2) {
01781   if (T1 == T2)
01782     return true;
01783 
01784   unsigned NumElts1, NumElts2;
01785   Type *EltTy1, *EltTy2;
01786   if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
01787       isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
01788       NumElts1 == NumElts2 &&
01789       EltTy1 == EltTy2)
01790     return true;
01791 
01792   return false;
01793 }
01794 
01795 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
01796 /// alloca or has an offset and size that corresponds to a component element
01797 /// within it.  The offset checked here may have been formed from a GEP with a
01798 /// pointer bitcasted to a different type.
01799 ///
01800 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
01801 /// unit.  If false, it only allows accesses known to be in a single element.
01802 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
01803                            Type *MemOpType, bool isStore,
01804                            AllocaInfo &Info, Instruction *TheAccess,
01805                            bool AllowWholeAccess) {
01806   // Check if this is a load/store of the entire alloca.
01807   if (Offset == 0 && AllowWholeAccess &&
01808       MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
01809     // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
01810     // loads/stores (which are essentially the same as the MemIntrinsics with
01811     // regard to copying padding between elements).  But, if an alloca is
01812     // flagged as both a source and destination of such operations, we'll need
01813     // to check later for padding between elements.
01814     if (!MemOpType || MemOpType->isIntegerTy()) {
01815       if (isStore)
01816         Info.isMemCpyDst = true;
01817       else
01818         Info.isMemCpySrc = true;
01819       return;
01820     }
01821     // This is also safe for references using a type that is compatible with
01822     // the type of the alloca, so that loads/stores can be rewritten using
01823     // insertvalue/extractvalue.
01824     if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
01825       Info.hasSubelementAccess = true;
01826       return;
01827     }
01828   }
01829   // Check if the offset/size correspond to a component within the alloca type.
01830   Type *T = Info.AI->getAllocatedType();
01831   if (TypeHasComponent(T, Offset, MemSize)) {
01832     Info.hasSubelementAccess = true;
01833     return;
01834   }
01835 
01836   return MarkUnsafe(Info, TheAccess);
01837 }
01838 
01839 /// TypeHasComponent - Return true if T has a component type with the
01840 /// specified offset and size.  If Size is zero, do not check the size.
01841 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
01842   Type *EltTy;
01843   uint64_t EltSize;
01844   if (StructType *ST = dyn_cast<StructType>(T)) {
01845     const StructLayout *Layout = DL->getStructLayout(ST);
01846     unsigned EltIdx = Layout->getElementContainingOffset(Offset);
01847     EltTy = ST->getContainedType(EltIdx);
01848     EltSize = DL->getTypeAllocSize(EltTy);
01849     Offset -= Layout->getElementOffset(EltIdx);
01850   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
01851     EltTy = AT->getElementType();
01852     EltSize = DL->getTypeAllocSize(EltTy);
01853     if (Offset >= AT->getNumElements() * EltSize)
01854       return false;
01855     Offset %= EltSize;
01856   } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
01857     EltTy = VT->getElementType();
01858     EltSize = DL->getTypeAllocSize(EltTy);
01859     if (Offset >= VT->getNumElements() * EltSize)
01860       return false;
01861     Offset %= EltSize;
01862   } else {
01863     return false;
01864   }
01865   if (Offset == 0 && (Size == 0 || EltSize == Size))
01866     return true;
01867   // Check if the component spans multiple elements.
01868   if (Offset + Size > EltSize)
01869     return false;
01870   return TypeHasComponent(EltTy, Offset, Size);
01871 }
01872 
01873 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
01874 /// the instruction I, which references it, to use the separate elements.
01875 /// Offset indicates the position within AI that is referenced by this
01876 /// instruction.
01877 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
01878                                 SmallVectorImpl<AllocaInst *> &NewElts) {
01879   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
01880     Use &TheUse = *UI++;
01881     Instruction *User = cast<Instruction>(TheUse.getUser());
01882 
01883     if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
01884       RewriteBitCast(BC, AI, Offset, NewElts);
01885       continue;
01886     }
01887 
01888     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01889       RewriteGEP(GEPI, AI, Offset, NewElts);
01890       continue;
01891     }
01892 
01893     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
01894       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
01895       uint64_t MemSize = Length->getZExtValue();
01896       if (Offset == 0 &&
01897           MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
01898         RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
01899       // Otherwise the intrinsic can only touch a single element and the
01900       // address operand will be updated, so nothing else needs to be done.
01901       continue;
01902     }
01903 
01904     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
01905       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
01906           II->getIntrinsicID() == Intrinsic::lifetime_end) {
01907         RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
01908       }
01909       continue;
01910     }
01911 
01912     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01913       Type *LIType = LI->getType();
01914 
01915       if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
01916         // Replace:
01917         //   %res = load { i32, i32 }* %alloc
01918         // with:
01919         //   %load.0 = load i32* %alloc.0
01920         //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
01921         //   %load.1 = load i32* %alloc.1
01922         //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
01923         // (Also works for arrays instead of structs)
01924         Value *Insert = UndefValue::get(LIType);
01925         IRBuilder<> Builder(LI);
01926         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01927           Value *Load = Builder.CreateLoad(NewElts[i], "load");
01928           Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
01929         }
01930         LI->replaceAllUsesWith(Insert);
01931         DeadInsts.push_back(LI);
01932       } else if (LIType->isIntegerTy() &&
01933                  DL->getTypeAllocSize(LIType) ==
01934                  DL->getTypeAllocSize(AI->getAllocatedType())) {
01935         // If this is a load of the entire alloca to an integer, rewrite it.
01936         RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
01937       }
01938       continue;
01939     }
01940 
01941     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01942       Value *Val = SI->getOperand(0);
01943       Type *SIType = Val->getType();
01944       if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
01945         // Replace:
01946         //   store { i32, i32 } %val, { i32, i32 }* %alloc
01947         // with:
01948         //   %val.0 = extractvalue { i32, i32 } %val, 0
01949         //   store i32 %val.0, i32* %alloc.0
01950         //   %val.1 = extractvalue { i32, i32 } %val, 1
01951         //   store i32 %val.1, i32* %alloc.1
01952         // (Also works for arrays instead of structs)
01953         IRBuilder<> Builder(SI);
01954         for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01955           Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
01956           Builder.CreateStore(Extract, NewElts[i]);
01957         }
01958         DeadInsts.push_back(SI);
01959       } else if (SIType->isIntegerTy() &&
01960                  DL->getTypeAllocSize(SIType) ==
01961                  DL->getTypeAllocSize(AI->getAllocatedType())) {
01962         // If this is a store of the entire alloca from an integer, rewrite it.
01963         RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
01964       }
01965       continue;
01966     }
01967 
01968     if (isa<SelectInst>(User) || isa<PHINode>(User)) {
01969       // If we have a PHI user of the alloca itself (as opposed to a GEP or
01970       // bitcast) we have to rewrite it.  GEP and bitcast uses will be RAUW'd to
01971       // the new pointer.
01972       if (!isa<AllocaInst>(I)) continue;
01973 
01974       assert(Offset == 0 && NewElts[0] &&
01975              "Direct alloca use should have a zero offset");
01976 
01977       // If we have a use of the alloca, we know the derived uses will be
01978       // utilizing just the first element of the scalarized result.  Insert a
01979       // bitcast of the first alloca before the user as required.
01980       AllocaInst *NewAI = NewElts[0];
01981       BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
01982       NewAI->moveBefore(BCI);
01983       TheUse = BCI;
01984       continue;
01985     }
01986   }
01987 }
01988 
01989 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
01990 /// and recursively continue updating all of its uses.
01991 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
01992                           SmallVectorImpl<AllocaInst *> &NewElts) {
01993   RewriteForScalarRepl(BC, AI, Offset, NewElts);
01994   if (BC->getOperand(0) != AI)
01995     return;
01996 
01997   // The bitcast references the original alloca.  Replace its uses with
01998   // references to the alloca containing offset zero (which is normally at
01999   // index zero, but might not be in cases involving structs with elements
02000   // of size zero).
02001   Type *T = AI->getAllocatedType();
02002   uint64_t EltOffset = 0;
02003   Type *IdxTy;
02004   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
02005   Instruction *Val = NewElts[Idx];
02006   if (Val->getType() != BC->getDestTy()) {
02007     Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
02008     Val->takeName(BC);
02009   }
02010   BC->replaceAllUsesWith(Val);
02011   DeadInsts.push_back(BC);
02012 }
02013 
02014 /// FindElementAndOffset - Return the index of the element containing Offset
02015 /// within the specified type, which must be either a struct or an array.
02016 /// Sets T to the type of the element and Offset to the offset within that
02017 /// element.  IdxTy is set to the type of the index result to be used in a
02018 /// GEP instruction.
02019 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
02020                                     Type *&IdxTy) {
02021   uint64_t Idx = 0;
02022   if (StructType *ST = dyn_cast<StructType>(T)) {
02023     const StructLayout *Layout = DL->getStructLayout(ST);
02024     Idx = Layout->getElementContainingOffset(Offset);
02025     T = ST->getContainedType(Idx);
02026     Offset -= Layout->getElementOffset(Idx);
02027     IdxTy = Type::getInt32Ty(T->getContext());
02028     return Idx;
02029   } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
02030     T = AT->getElementType();
02031     uint64_t EltSize = DL->getTypeAllocSize(T);
02032     Idx = Offset / EltSize;
02033     Offset -= Idx * EltSize;
02034     IdxTy = Type::getInt64Ty(T->getContext());
02035     return Idx;
02036   }
02037   VectorType *VT = cast<VectorType>(T);
02038   T = VT->getElementType();
02039   uint64_t EltSize = DL->getTypeAllocSize(T);
02040   Idx = Offset / EltSize;
02041   Offset -= Idx * EltSize;
02042   IdxTy = Type::getInt64Ty(T->getContext());
02043   return Idx;
02044 }
02045 
02046 /// RewriteGEP - Check if this GEP instruction moves the pointer across
02047 /// elements of the alloca that are being split apart, and if so, rewrite
02048 /// the GEP to be relative to the new element.
02049 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
02050                       SmallVectorImpl<AllocaInst *> &NewElts) {
02051   uint64_t OldOffset = Offset;
02052   SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
02053   // If the GEP was dynamic then it must have been a dynamic vector lookup.
02054   // In this case, it must be the last GEP operand which is dynamic so keep that
02055   // aside until we've found the constant GEP offset then add it back in at the
02056   // end.
02057   Value* NonConstantIdx = nullptr;
02058   if (!GEPI->hasAllConstantIndices())
02059     NonConstantIdx = Indices.pop_back_val();
02060   Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
02061 
02062   RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
02063 
02064   Type *T = AI->getAllocatedType();
02065   Type *IdxTy;
02066   uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
02067   if (GEPI->getOperand(0) == AI)
02068     OldIdx = ~0ULL; // Force the GEP to be rewritten.
02069 
02070   T = AI->getAllocatedType();
02071   uint64_t EltOffset = Offset;
02072   uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
02073 
02074   // If this GEP does not move the pointer across elements of the alloca
02075   // being split, then it does not needs to be rewritten.
02076   if (Idx == OldIdx)
02077     return;
02078 
02079   Type *i32Ty = Type::getInt32Ty(AI->getContext());
02080   SmallVector<Value*, 8> NewArgs;
02081   NewArgs.push_back(Constant::getNullValue(i32Ty));
02082   while (EltOffset != 0) {
02083     uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
02084     NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
02085   }
02086   if (NonConstantIdx) {
02087     Type* GepTy = T;
02088     // This GEP has a dynamic index.  We need to add "i32 0" to index through
02089     // any structs or arrays in the original type until we get to the vector
02090     // to index.
02091     while (!isa<VectorType>(GepTy)) {
02092       NewArgs.push_back(Constant::getNullValue(i32Ty));
02093       GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
02094     }
02095     NewArgs.push_back(NonConstantIdx);
02096   }
02097   Instruction *Val = NewElts[Idx];
02098   if (NewArgs.size() > 1) {
02099     Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
02100     Val->takeName(GEPI);
02101   }
02102   if (Val->getType() != GEPI->getType())
02103     Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
02104   GEPI->replaceAllUsesWith(Val);
02105   DeadInsts.push_back(GEPI);
02106 }
02107 
02108 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
02109 /// to mark the lifetime of the scalarized memory.
02110 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
02111                                     uint64_t Offset,
02112                                     SmallVectorImpl<AllocaInst *> &NewElts) {
02113   ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
02114   // Put matching lifetime markers on everything from Offset up to
02115   // Offset+OldSize.
02116   Type *AIType = AI->getAllocatedType();
02117   uint64_t NewOffset = Offset;
02118   Type *IdxTy;
02119   uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
02120 
02121   IRBuilder<> Builder(II);
02122   uint64_t Size = OldSize->getLimitedValue();
02123 
02124   if (NewOffset) {
02125     // Splice the first element and index 'NewOffset' bytes in.  SROA will
02126     // split the alloca again later.
02127     unsigned AS = AI->getType()->getAddressSpace();
02128     Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
02129     V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
02130 
02131     IdxTy = NewElts[Idx]->getAllocatedType();
02132     uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
02133     if (EltSize > Size) {
02134       EltSize = Size;
02135       Size = 0;
02136     } else {
02137       Size -= EltSize;
02138     }
02139     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
02140       Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
02141     else
02142       Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
02143     ++Idx;
02144   }
02145 
02146   for (; Idx != NewElts.size() && Size; ++Idx) {
02147     IdxTy = NewElts[Idx]->getAllocatedType();
02148     uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
02149     if (EltSize > Size) {
02150       EltSize = Size;
02151       Size = 0;
02152     } else {
02153       Size -= EltSize;
02154     }
02155     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
02156       Builder.CreateLifetimeStart(NewElts[Idx],
02157                                   Builder.getInt64(EltSize));
02158     else
02159       Builder.CreateLifetimeEnd(NewElts[Idx],
02160                                 Builder.getInt64(EltSize));
02161   }
02162   DeadInsts.push_back(II);
02163 }
02164 
02165 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
02166 /// Rewrite it to copy or set the elements of the scalarized memory.
02167 void
02168 SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
02169                                    AllocaInst *AI,
02170                                    SmallVectorImpl<AllocaInst *> &NewElts) {
02171   // If this is a memcpy/memmove, construct the other pointer as the
02172   // appropriate type.  The "Other" pointer is the pointer that goes to memory
02173   // that doesn't have anything to do with the alloca that we are promoting. For
02174   // memset, this Value* stays null.
02175   Value *OtherPtr = nullptr;
02176   unsigned MemAlignment = MI->getAlignment();
02177   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
02178     if (Inst == MTI->getRawDest())
02179       OtherPtr = MTI->getRawSource();
02180     else {
02181       assert(Inst == MTI->getRawSource());
02182       OtherPtr = MTI->getRawDest();
02183     }
02184   }
02185 
02186   // If there is an other pointer, we want to convert it to the same pointer
02187   // type as AI has, so we can GEP through it safely.
02188   if (OtherPtr) {
02189     unsigned AddrSpace =
02190       cast<PointerType>(OtherPtr->getType())->getAddressSpace();
02191 
02192     // Remove bitcasts and all-zero GEPs from OtherPtr.  This is an
02193     // optimization, but it's also required to detect the corner case where
02194     // both pointer operands are referencing the same memory, and where
02195     // OtherPtr may be a bitcast or GEP that currently being rewritten.  (This
02196     // function is only called for mem intrinsics that access the whole
02197     // aggregate, so non-zero GEPs are not an issue here.)
02198     OtherPtr = OtherPtr->stripPointerCasts();
02199 
02200     // Copying the alloca to itself is a no-op: just delete it.
02201     if (OtherPtr == AI || OtherPtr == NewElts[0]) {
02202       // This code will run twice for a no-op memcpy -- once for each operand.
02203       // Put only one reference to MI on the DeadInsts list.
02204       for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
02205              E = DeadInsts.end(); I != E; ++I)
02206         if (*I == MI) return;
02207       DeadInsts.push_back(MI);
02208       return;
02209     }
02210 
02211     // If the pointer is not the right type, insert a bitcast to the right
02212     // type.
02213     Type *NewTy =
02214       PointerType::get(AI->getType()->getElementType(), AddrSpace);
02215 
02216     if (OtherPtr->getType() != NewTy)
02217       OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
02218   }
02219 
02220   // Process each element of the aggregate.
02221   bool SROADest = MI->getRawDest() == Inst;
02222 
02223   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
02224 
02225   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02226     // If this is a memcpy/memmove, emit a GEP of the other element address.
02227     Value *OtherElt = nullptr;
02228     unsigned OtherEltAlign = MemAlignment;
02229 
02230     if (OtherPtr) {
02231       Value *Idx[2] = { Zero,
02232                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
02233       OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
02234                                               OtherPtr->getName()+"."+Twine(i),
02235                                                    MI);
02236       uint64_t EltOffset;
02237       PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
02238       Type *OtherTy = OtherPtrTy->getElementType();
02239       if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
02240         EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
02241       } else {
02242         Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
02243         EltOffset = DL->getTypeAllocSize(EltTy)*i;
02244       }
02245 
02246       // The alignment of the other pointer is the guaranteed alignment of the
02247       // element, which is affected by both the known alignment of the whole
02248       // mem intrinsic and the alignment of the element.  If the alignment of
02249       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
02250       // known alignment is just 4 bytes.
02251       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
02252     }
02253 
02254     Value *EltPtr = NewElts[i];
02255     Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
02256 
02257     // If we got down to a scalar, insert a load or store as appropriate.
02258     if (EltTy->isSingleValueType()) {
02259       if (isa<MemTransferInst>(MI)) {
02260         if (SROADest) {
02261           // From Other to Alloca.
02262           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
02263           new StoreInst(Elt, EltPtr, MI);
02264         } else {
02265           // From Alloca to Other.
02266           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
02267           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
02268         }
02269         continue;
02270       }
02271       assert(isa<MemSetInst>(MI));
02272 
02273       // If the stored element is zero (common case), just store a null
02274       // constant.
02275       Constant *StoreVal;
02276       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
02277         if (CI->isZero()) {
02278           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
02279         } else {
02280           // If EltTy is a vector type, get the element type.
02281           Type *ValTy = EltTy->getScalarType();
02282 
02283           // Construct an integer with the right value.
02284           unsigned EltSize = DL->getTypeSizeInBits(ValTy);
02285           APInt OneVal(EltSize, CI->getZExtValue());
02286           APInt TotalVal(OneVal);
02287           // Set each byte.
02288           for (unsigned i = 0; 8*i < EltSize; ++i) {
02289             TotalVal = TotalVal.shl(8);
02290             TotalVal |= OneVal;
02291           }
02292 
02293           // Convert the integer value to the appropriate type.
02294           StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
02295           if (ValTy->isPointerTy())
02296             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
02297           else if (ValTy->isFloatingPointTy())
02298             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
02299           assert(StoreVal->getType() == ValTy && "Type mismatch!");
02300 
02301           // If the requested value was a vector constant, create it.
02302           if (EltTy->isVectorTy()) {
02303             unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
02304             StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
02305           }
02306         }
02307         new StoreInst(StoreVal, EltPtr, MI);
02308         continue;
02309       }
02310       // Otherwise, if we're storing a byte variable, use a memset call for
02311       // this element.
02312     }
02313 
02314     unsigned EltSize = DL->getTypeAllocSize(EltTy);
02315     if (!EltSize)
02316       continue;
02317 
02318     IRBuilder<> Builder(MI);
02319 
02320     // Finally, insert the meminst for this element.
02321     if (isa<MemSetInst>(MI)) {
02322       Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
02323                            MI->isVolatile());
02324     } else {
02325       assert(isa<MemTransferInst>(MI));
02326       Value *Dst = SROADest ? EltPtr : OtherElt;  // Dest ptr
02327       Value *Src = SROADest ? OtherElt : EltPtr;  // Src ptr
02328 
02329       if (isa<MemCpyInst>(MI))
02330         Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
02331       else
02332         Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
02333     }
02334   }
02335   DeadInsts.push_back(MI);
02336 }
02337 
02338 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
02339 /// overwrites the entire allocation.  Extract out the pieces of the stored
02340 /// integer and store them individually.
02341 void
02342 SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
02343                                     SmallVectorImpl<AllocaInst *> &NewElts) {
02344   // Extract each element out of the integer according to its structure offset
02345   // and store the element value to the individual alloca.
02346   Value *SrcVal = SI->getOperand(0);
02347   Type *AllocaEltTy = AI->getAllocatedType();
02348   uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
02349 
02350   IRBuilder<> Builder(SI);
02351 
02352   // Handle tail padding by extending the operand
02353   if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
02354     SrcVal = Builder.CreateZExt(SrcVal,
02355                             IntegerType::get(SI->getContext(), AllocaSizeBits));
02356 
02357   DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
02358                << '\n');
02359 
02360   // There are two forms here: AI could be an array or struct.  Both cases
02361   // have different ways to compute the element offset.
02362   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
02363     const StructLayout *Layout = DL->getStructLayout(EltSTy);
02364 
02365     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02366       // Get the number of bits to shift SrcVal to get the value.
02367       Type *FieldTy = EltSTy->getElementType(i);
02368       uint64_t Shift = Layout->getElementOffsetInBits(i);
02369 
02370       if (DL->isBigEndian())
02371         Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
02372 
02373       Value *EltVal = SrcVal;
02374       if (Shift) {
02375         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
02376         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
02377       }
02378 
02379       // Truncate down to an integer of the right size.
02380       uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
02381 
02382       // Ignore zero sized fields like {}, they obviously contain no data.
02383       if (FieldSizeBits == 0) continue;
02384 
02385       if (FieldSizeBits != AllocaSizeBits)
02386         EltVal = Builder.CreateTrunc(EltVal,
02387                              IntegerType::get(SI->getContext(), FieldSizeBits));
02388       Value *DestField = NewElts[i];
02389       if (EltVal->getType() == FieldTy) {
02390         // Storing to an integer field of this size, just do it.
02391       } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
02392         // Bitcast to the right element type (for fp/vector values).
02393         EltVal = Builder.CreateBitCast(EltVal, FieldTy);
02394       } else {
02395         // Otherwise, bitcast the dest pointer (for aggregates).
02396         DestField = Builder.CreateBitCast(DestField,
02397                                      PointerType::getUnqual(EltVal->getType()));
02398       }
02399       new StoreInst(EltVal, DestField, SI);
02400     }
02401 
02402   } else {
02403     ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
02404     Type *ArrayEltTy = ATy->getElementType();
02405     uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
02406     uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
02407 
02408     uint64_t Shift;
02409 
02410     if (DL->isBigEndian())
02411       Shift = AllocaSizeBits-ElementOffset;
02412     else
02413       Shift = 0;
02414 
02415     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02416       // Ignore zero sized fields like {}, they obviously contain no data.
02417       if (ElementSizeBits == 0) continue;
02418 
02419       Value *EltVal = SrcVal;
02420       if (Shift) {
02421         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
02422         EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
02423       }
02424 
02425       // Truncate down to an integer of the right size.
02426       if (ElementSizeBits != AllocaSizeBits)
02427         EltVal = Builder.CreateTrunc(EltVal,
02428                                      IntegerType::get(SI->getContext(),
02429                                                       ElementSizeBits));
02430       Value *DestField = NewElts[i];
02431       if (EltVal->getType() == ArrayEltTy) {
02432         // Storing to an integer field of this size, just do it.
02433       } else if (ArrayEltTy->isFloatingPointTy() ||
02434                  ArrayEltTy->isVectorTy()) {
02435         // Bitcast to the right element type (for fp/vector values).
02436         EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
02437       } else {
02438         // Otherwise, bitcast the dest pointer (for aggregates).
02439         DestField = Builder.CreateBitCast(DestField,
02440                                      PointerType::getUnqual(EltVal->getType()));
02441       }
02442       new StoreInst(EltVal, DestField, SI);
02443 
02444       if (DL->isBigEndian())
02445         Shift -= ElementOffset;
02446       else
02447         Shift += ElementOffset;
02448     }
02449   }
02450 
02451   DeadInsts.push_back(SI);
02452 }
02453 
02454 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
02455 /// an integer.  Load the individual pieces to form the aggregate value.
02456 void
02457 SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
02458                                    SmallVectorImpl<AllocaInst *> &NewElts) {
02459   // Extract each element out of the NewElts according to its structure offset
02460   // and form the result value.
02461   Type *AllocaEltTy = AI->getAllocatedType();
02462   uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
02463 
02464   DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
02465                << '\n');
02466 
02467   // There are two forms here: AI could be an array or struct.  Both cases
02468   // have different ways to compute the element offset.
02469   const StructLayout *Layout = nullptr;
02470   uint64_t ArrayEltBitOffset = 0;
02471   if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
02472     Layout = DL->getStructLayout(EltSTy);
02473   } else {
02474     Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
02475     ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
02476   }
02477 
02478   Value *ResultVal =
02479     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
02480 
02481   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
02482     // Load the value from the alloca.  If the NewElt is an aggregate, cast
02483     // the pointer to an integer of the same size before doing the load.
02484     Value *SrcField = NewElts[i];
02485     Type *FieldTy =
02486       cast<PointerType>(SrcField->getType())->getElementType();
02487     uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
02488 
02489     // Ignore zero sized fields like {}, they obviously contain no data.
02490     if (FieldSizeBits == 0) continue;
02491 
02492     IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
02493                                                      FieldSizeBits);
02494     if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
02495         !FieldTy->isVectorTy())
02496       SrcField = new BitCastInst(SrcField,
02497                                  PointerType::getUnqual(FieldIntTy),
02498                                  "", LI);
02499     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
02500 
02501     // If SrcField is a fp or vector of the right size but that isn't an
02502     // integer type, bitcast to an integer so we can shift it.
02503     if (SrcField->getType() != FieldIntTy)
02504       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
02505 
02506     // Zero extend the field to be the same size as the final alloca so that
02507     // we can shift and insert it.
02508     if (SrcField->getType() != ResultVal->getType())
02509       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
02510 
02511     // Determine the number of bits to shift SrcField.
02512     uint64_t Shift;
02513     if (Layout) // Struct case.
02514       Shift = Layout->getElementOffsetInBits(i);
02515     else  // Array case.
02516       Shift = i*ArrayEltBitOffset;
02517 
02518     if (DL->isBigEndian())
02519       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
02520 
02521     if (Shift) {
02522       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
02523       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
02524     }
02525 
02526     // Don't create an 'or x, 0' on the first iteration.
02527     if (!isa<Constant>(ResultVal) ||
02528         !cast<Constant>(ResultVal)->isNullValue())
02529       ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
02530     else
02531       ResultVal = SrcField;
02532   }
02533 
02534   // Handle tail padding by truncating the result
02535   if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
02536     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
02537 
02538   LI->replaceAllUsesWith(ResultVal);
02539   DeadInsts.push_back(LI);
02540 }
02541 
02542 /// HasPadding - Return true if the specified type has any structure or
02543 /// alignment padding in between the elements that would be split apart
02544 /// by SROA; return false otherwise.
02545 static bool HasPadding(Type *Ty, const DataLayout &DL) {
02546   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
02547     Ty = ATy->getElementType();
02548     return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
02549   }
02550 
02551   // SROA currently handles only Arrays and Structs.
02552   StructType *STy = cast<StructType>(Ty);
02553   const StructLayout *SL = DL.getStructLayout(STy);
02554   unsigned PrevFieldBitOffset = 0;
02555   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02556     unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
02557 
02558     // Check to see if there is any padding between this element and the
02559     // previous one.
02560     if (i) {
02561       unsigned PrevFieldEnd =
02562         PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
02563       if (PrevFieldEnd < FieldBitOffset)
02564         return true;
02565     }
02566     PrevFieldBitOffset = FieldBitOffset;
02567   }
02568   // Check for tail padding.
02569   if (unsigned EltCount = STy->getNumElements()) {
02570     unsigned PrevFieldEnd = PrevFieldBitOffset +
02571       DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
02572     if (PrevFieldEnd < SL->getSizeInBits())
02573       return true;
02574   }
02575   return false;
02576 }
02577 
02578 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
02579 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
02580 /// or 1 if safe after canonicalization has been performed.
02581 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
02582   // Loop over the use list of the alloca.  We can only transform it if all of
02583   // the users are safe to transform.
02584   AllocaInfo Info(AI);
02585 
02586   isSafeForScalarRepl(AI, 0, Info);
02587   if (Info.isUnsafe) {
02588     DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
02589     return false;
02590   }
02591 
02592   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
02593   // source and destination, we have to be careful.  In particular, the memcpy
02594   // could be moving around elements that live in structure padding of the LLVM
02595   // types, but may actually be used.  In these cases, we refuse to promote the
02596   // struct.
02597   if (Info.isMemCpySrc && Info.isMemCpyDst &&
02598       HasPadding(AI->getAllocatedType(), *DL))
02599     return false;
02600 
02601   // If the alloca never has an access to just *part* of it, but is accessed
02602   // via loads and stores, then we should use ConvertToScalarInfo to promote
02603   // the alloca instead of promoting each piece at a time and inserting fission
02604   // and fusion code.
02605   if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
02606     // If the struct/array just has one element, use basic SRoA.
02607     if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
02608       if (ST->getNumElements() > 1) return false;
02609     } else {
02610       if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
02611         return false;
02612     }
02613   }
02614 
02615   return true;
02616 }