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