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