LLVM API Documentation

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