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
00017 // often interact, especially for C++ programs.  As such, iterating between
00018 // SRoA, then Mem2Reg until we run out of things to promote works well.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #define DEBUG_TYPE "scalarrepl"
00023 #include "llvm/Transforms/Scalar.h"
00024 #include "llvm/Constants.h"
00025 #include "llvm/DerivedTypes.h"
00026 #include "llvm/Function.h"
00027 #include "llvm/GlobalVariable.h"
00028 #include "llvm/Instructions.h"
00029 #include "llvm/IntrinsicInst.h"
00030 #include "llvm/LLVMContext.h"
00031 #include "llvm/Pass.h"
00032 #include "llvm/Analysis/Dominators.h"
00033 #include "llvm/Target/TargetData.h"
00034 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00035 #include "llvm/Transforms/Utils/Local.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/ErrorHandling.h"
00038 #include "llvm/Support/GetElementPtrTypeIterator.h"
00039 #include "llvm/Support/IRBuilder.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include "llvm/Support/Compiler.h"
00042 #include "llvm/ADT/SmallVector.h"
00043 #include "llvm/ADT/Statistic.h"
00044 using namespace llvm;
00045 
00046 STATISTIC(NumReplaced,  "Number of allocas broken up");
00047 STATISTIC(NumPromoted,  "Number of allocas promoted");
00048 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
00049 STATISTIC(NumGlobals,   "Number of allocas copied from constant global");
00050 
00051 namespace {
00052   struct VISIBILITY_HIDDEN SROA : public FunctionPass {
00053     static char ID; // Pass identification, replacement for typeid
00054     explicit SROA(signed T = -1) : FunctionPass(&ID) {
00055       if (T == -1)
00056         SRThreshold = 128;
00057       else
00058         SRThreshold = T;
00059     }
00060 
00061     bool runOnFunction(Function &F);
00062 
00063     bool performScalarRepl(Function &F);
00064     bool performPromotion(Function &F);
00065 
00066     // getAnalysisUsage - This pass does not require any passes, but we know it
00067     // will not alter the CFG, so say so.
00068     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00069       AU.addRequired<DominatorTree>();
00070       AU.addRequired<DominanceFrontier>();
00071       AU.setPreservesCFG();
00072     }
00073 
00074   private:
00075     TargetData *TD;
00076     
00077     /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
00078     /// information about the uses.  All these fields are initialized to false
00079     /// and set to true when something is learned.
00080     struct AllocaInfo {
00081       /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
00082       bool isUnsafe : 1;
00083       
00084       /// needsCleanup - This is set to true if there is some use of the alloca
00085       /// that requires cleanup.
00086       bool needsCleanup : 1;
00087       
00088       /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
00089       bool isMemCpySrc : 1;
00090 
00091       /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
00092       bool isMemCpyDst : 1;
00093 
00094       AllocaInfo()
00095         : isUnsafe(false), needsCleanup(false), 
00096           isMemCpySrc(false), isMemCpyDst(false) {}
00097     };
00098     
00099     unsigned SRThreshold;
00100 
00101     void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
00102 
00103     int isSafeAllocaToScalarRepl(AllocationInst *AI);
00104 
00105     void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
00106                                AllocaInfo &Info);
00107     void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
00108                          AllocaInfo &Info);
00109     void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
00110                                         unsigned OpNo, AllocaInfo &Info);
00111     void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
00112                                         AllocaInfo &Info);
00113     
00114     void DoScalarReplacement(AllocationInst *AI, 
00115                              std::vector<AllocationInst*> &WorkList);
00116     void CleanupGEP(GetElementPtrInst *GEP);
00117     void CleanupAllocaUsers(AllocationInst *AI);
00118     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
00119     
00120     void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
00121                                     SmallVector<AllocaInst*, 32> &NewElts);
00122     
00123     void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
00124                                       AllocationInst *AI,
00125                                       SmallVector<AllocaInst*, 32> &NewElts);
00126     void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
00127                                        SmallVector<AllocaInst*, 32> &NewElts);
00128     void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
00129                                       SmallVector<AllocaInst*, 32> &NewElts);
00130     
00131     bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
00132                             bool &SawVec, uint64_t Offset, unsigned AllocaSize);
00133     void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
00134     Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
00135                                      uint64_t Offset, IRBuilder<> &Builder);
00136     Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
00137                                      uint64_t Offset, IRBuilder<> &Builder);
00138     static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
00139   };
00140 }
00141 
00142 char SROA::ID = 0;
00143 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
00144 
00145 // Public interface to the ScalarReplAggregates pass
00146 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) { 
00147   return new SROA(Threshold);
00148 }
00149 
00150 
00151 bool SROA::runOnFunction(Function &F) {
00152   TD = getAnalysisIfAvailable<TargetData>();
00153 
00154   bool Changed = performPromotion(F);
00155 
00156   // FIXME: ScalarRepl currently depends on TargetData more than it
00157   // theoretically needs to. It should be refactored in order to support
00158   // target-independent IR. Until this is done, just skip the actual
00159   // scalar-replacement portion of this pass.
00160   if (!TD) return Changed;
00161 
00162   while (1) {
00163     bool LocalChange = performScalarRepl(F);
00164     if (!LocalChange) break;   // No need to repromote if no scalarrepl
00165     Changed = true;
00166     LocalChange = performPromotion(F);
00167     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
00168   }
00169 
00170   return Changed;
00171 }
00172 
00173 
00174 bool SROA::performPromotion(Function &F) {
00175   std::vector<AllocaInst*> Allocas;
00176   DominatorTree         &DT = getAnalysis<DominatorTree>();
00177   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
00178 
00179   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
00180 
00181   bool Changed = false;
00182 
00183   while (1) {
00184     Allocas.clear();
00185 
00186     // Find allocas that are safe to promote, by looking at all instructions in
00187     // the entry node
00188     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
00189       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
00190         if (isAllocaPromotable(AI))
00191           Allocas.push_back(AI);
00192 
00193     if (Allocas.empty()) break;
00194 
00195     PromoteMemToReg(Allocas, DT, DF, F.getContext());
00196     NumPromoted += Allocas.size();
00197     Changed = true;
00198   }
00199 
00200   return Changed;
00201 }
00202 
00203 /// getNumSAElements - Return the number of elements in the specific struct or
00204 /// array.
00205 static uint64_t getNumSAElements(const Type *T) {
00206   if (const StructType *ST = dyn_cast<StructType>(T))
00207     return ST->getNumElements();
00208   return cast<ArrayType>(T)->getNumElements();
00209 }
00210 
00211 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
00212 // which runs on all of the malloc/alloca instructions in the function, removing
00213 // them if they are only used by getelementptr instructions.
00214 //
00215 bool SROA::performScalarRepl(Function &F) {
00216   std::vector<AllocationInst*> WorkList;
00217 
00218   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
00219   BasicBlock &BB = F.getEntryBlock();
00220   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
00221     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
00222       WorkList.push_back(A);
00223 
00224   // Process the worklist
00225   bool Changed = false;
00226   while (!WorkList.empty()) {
00227     AllocationInst *AI = WorkList.back();
00228     WorkList.pop_back();
00229     
00230     // Handle dead allocas trivially.  These can be formed by SROA'ing arrays
00231     // with unused elements.
00232     if (AI->use_empty()) {
00233       AI->eraseFromParent();
00234       continue;
00235     }
00236 
00237     // If this alloca is impossible for us to promote, reject it early.
00238     if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
00239       continue;
00240     
00241     // Check to see if this allocation is only modified by a memcpy/memmove from
00242     // a constant global.  If this is the case, we can change all users to use
00243     // the constant global instead.  This is commonly produced by the CFE by
00244     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
00245     // is only subsequently read.
00246     if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
00247       DOUT << "Found alloca equal to global: " << *AI;
00248       DOUT << "  memcpy = " << *TheCopy;
00249       Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
00250       AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
00251       TheCopy->eraseFromParent();  // Don't mutate the global.
00252       AI->eraseFromParent();
00253       ++NumGlobals;
00254       Changed = true;
00255       continue;
00256     }
00257     
00258     // Check to see if we can perform the core SROA transformation.  We cannot
00259     // transform the allocation instruction if it is an array allocation
00260     // (allocations OF arrays are ok though), and an allocation of a scalar
00261     // value cannot be decomposed at all.
00262     uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
00263 
00264     // Do not promote [0 x %struct].
00265     if (AllocaSize == 0) continue;
00266 
00267     // Do not promote any struct whose size is too big.
00268     if (AllocaSize > SRThreshold) continue;
00269 
00270     if ((isa<StructType>(AI->getAllocatedType()) ||
00271          isa<ArrayType>(AI->getAllocatedType())) &&
00272         // Do not promote any struct into more than "32" separate vars.
00273         getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
00274       // Check that all of the users of the allocation are capable of being
00275       // transformed.
00276       switch (isSafeAllocaToScalarRepl(AI)) {
00277       default: llvm_unreachable("Unexpected value!");
00278       case 0:  // Not safe to scalar replace.
00279         break;
00280       case 1:  // Safe, but requires cleanup/canonicalizations first
00281         CleanupAllocaUsers(AI);
00282         // FALL THROUGH.
00283       case 3:  // Safe to scalar replace.
00284         DoScalarReplacement(AI, WorkList);
00285         Changed = true;
00286         continue;
00287       }
00288     }
00289 
00290     // If we can turn this aggregate value (potentially with casts) into a
00291     // simple scalar value that can be mem2reg'd into a register value.
00292     // IsNotTrivial tracks whether this is something that mem2reg could have
00293     // promoted itself.  If so, we don't want to transform it needlessly.  Note
00294     // that we can't just check based on the type: the alloca may be of an i32
00295     // but that has pointer arithmetic to set byte 3 of it or something.
00296     bool IsNotTrivial = false;
00297     const Type *VectorTy = 0;
00298     bool HadAVector = false;
00299     if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector, 
00300                            0, unsigned(AllocaSize)) && IsNotTrivial) {
00301       AllocaInst *NewAI;
00302       // If we were able to find a vector type that can handle this with
00303       // insert/extract elements, and if there was at least one use that had
00304       // a vector type, promote this to a vector.  We don't want to promote
00305       // random stuff that doesn't use vectors (e.g. <9 x double>) because then
00306       // we just get a lot of insert/extracts.  If at least one vector is
00307       // involved, then we probably really do have a union of vector/array.
00308       if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
00309         DOUT << "CONVERT TO VECTOR: " << *AI << "  TYPE = " << *VectorTy <<"\n";
00310         
00311         // Create and insert the vector alloca.
00312         NewAI = new AllocaInst(VectorTy, 0, "",  AI->getParent()->begin());
00313         ConvertUsesToScalar(AI, NewAI, 0);
00314       } else {
00315         DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
00316         
00317         // Create and insert the integer alloca.
00318         const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
00319         NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
00320         ConvertUsesToScalar(AI, NewAI, 0);
00321       }
00322       NewAI->takeName(AI);
00323       AI->eraseFromParent();
00324       ++NumConverted;
00325       Changed = true;
00326       continue;
00327     }
00328     
00329     // Otherwise, couldn't process this alloca.
00330   }
00331 
00332   return Changed;
00333 }
00334 
00335 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
00336 /// predicate, do SROA now.
00337 void SROA::DoScalarReplacement(AllocationInst *AI, 
00338                                std::vector<AllocationInst*> &WorkList) {
00339   DOUT << "Found inst to SROA: " << *AI;
00340   SmallVector<AllocaInst*, 32> ElementAllocas;
00341   if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
00342     ElementAllocas.reserve(ST->getNumContainedTypes());
00343     for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
00344       AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
00345                                       AI->getAlignment(),
00346                                       AI->getName() + "." + Twine(i), AI);
00347       ElementAllocas.push_back(NA);
00348       WorkList.push_back(NA);  // Add to worklist for recursive processing
00349     }
00350   } else {
00351     const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
00352     ElementAllocas.reserve(AT->getNumElements());
00353     const Type *ElTy = AT->getElementType();
00354     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
00355       AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
00356                                       AI->getName() + "." + Twine(i), AI);
00357       ElementAllocas.push_back(NA);
00358       WorkList.push_back(NA);  // Add to worklist for recursive processing
00359     }
00360   }
00361 
00362   // Now that we have created the alloca instructions that we want to use,
00363   // expand the getelementptr instructions to use them.
00364   //
00365   while (!AI->use_empty()) {
00366     Instruction *User = cast<Instruction>(AI->use_back());
00367     if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
00368       RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
00369       BCInst->eraseFromParent();
00370       continue;
00371     }
00372     
00373     // Replace:
00374     //   %res = load { i32, i32 }* %alloc
00375     // with:
00376     //   %load.0 = load i32* %alloc.0
00377     //   %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0 
00378     //   %load.1 = load i32* %alloc.1
00379     //   %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1 
00380     // (Also works for arrays instead of structs)
00381     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
00382       Value *Insert = UndefValue::get(LI->getType());
00383       for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
00384         Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
00385         Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
00386       }
00387       LI->replaceAllUsesWith(Insert);
00388       LI->eraseFromParent();
00389       continue;
00390     }
00391 
00392     // Replace:
00393     //   store { i32, i32 } %val, { i32, i32 }* %alloc
00394     // with:
00395     //   %val.0 = extractvalue { i32, i32 } %val, 0 
00396     //   store i32 %val.0, i32* %alloc.0
00397     //   %val.1 = extractvalue { i32, i32 } %val, 1 
00398     //   store i32 %val.1, i32* %alloc.1
00399     // (Also works for arrays instead of structs)
00400     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00401       Value *Val = SI->getOperand(0);
00402       for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
00403         Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
00404         new StoreInst(Extract, ElementAllocas[i], SI);
00405       }
00406       SI->eraseFromParent();
00407       continue;
00408     }
00409     
00410     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
00411     // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
00412     unsigned Idx =
00413        (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
00414 
00415     assert(Idx < ElementAllocas.size() && "Index out of range?");
00416     AllocaInst *AllocaToUse = ElementAllocas[Idx];
00417 
00418     Value *RepValue;
00419     if (GEPI->getNumOperands() == 3) {
00420       // Do not insert a new getelementptr instruction with zero indices, only
00421       // to have it optimized out later.
00422       RepValue = AllocaToUse;
00423     } else {
00424       // We are indexing deeply into the structure, so we still need a
00425       // getelement ptr instruction to finish the indexing.  This may be
00426       // expanded itself once the worklist is rerun.
00427       //
00428       SmallVector<Value*, 8> NewArgs;
00429       NewArgs.push_back(Constant::getNullValue(
00430                                            Type::getInt32Ty(AI->getContext())));
00431       NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
00432       RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
00433                                            NewArgs.end(), "", GEPI);
00434       RepValue->takeName(GEPI);
00435     }
00436     
00437     // If this GEP is to the start of the aggregate, check for memcpys.
00438     if (Idx == 0 && GEPI->hasAllZeroIndices())
00439       RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
00440 
00441     // Move all of the users over to the new GEP.
00442     GEPI->replaceAllUsesWith(RepValue);
00443     // Delete the old GEP
00444     GEPI->eraseFromParent();
00445   }
00446 
00447   // Finally, delete the Alloca instruction
00448   AI->eraseFromParent();
00449   NumReplaced++;
00450 }
00451 
00452 
00453 /// isSafeElementUse - Check to see if this use is an allowed use for a
00454 /// getelementptr instruction of an array aggregate allocation.  isFirstElt
00455 /// indicates whether Ptr is known to the start of the aggregate.
00456 ///
00457 void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
00458                             AllocaInfo &Info) {
00459   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
00460        I != E; ++I) {
00461     Instruction *User = cast<Instruction>(*I);
00462     switch (User->getOpcode()) {
00463     case Instruction::Load:  break;
00464     case Instruction::Store:
00465       // Store is ok if storing INTO the pointer, not storing the pointer
00466       if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
00467       break;
00468     case Instruction::GetElementPtr: {
00469       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
00470       bool AreAllZeroIndices = isFirstElt;
00471       if (GEP->getNumOperands() > 1) {
00472         if (!isa<ConstantInt>(GEP->getOperand(1)) ||
00473             !cast<ConstantInt>(GEP->getOperand(1))->isZero())
00474           // Using pointer arithmetic to navigate the array.
00475           return MarkUnsafe(Info);
00476        
00477         if (AreAllZeroIndices)
00478           AreAllZeroIndices = GEP->hasAllZeroIndices();
00479       }
00480       isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
00481       if (Info.isUnsafe) return;
00482       break;
00483     }
00484     case Instruction::BitCast:
00485       if (isFirstElt) {
00486         isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
00487         if (Info.isUnsafe) return;
00488         break;
00489       }
00490       DOUT << "  Transformation preventing inst: " << *User;
00491       return MarkUnsafe(Info);
00492     case Instruction::Call:
00493       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
00494         if (isFirstElt) {
00495           isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
00496           if (Info.isUnsafe) return;
00497           break;
00498         }
00499       }
00500       DOUT << "  Transformation preventing inst: " << *User;
00501       return MarkUnsafe(Info);
00502     default:
00503       DOUT << "  Transformation preventing inst: " << *User;
00504       return MarkUnsafe(Info);
00505     }
00506   }
00507   return;  // All users look ok :)
00508 }
00509 
00510 /// AllUsersAreLoads - Return true if all users of this value are loads.
00511 static bool AllUsersAreLoads(Value *Ptr) {
00512   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
00513        I != E; ++I)
00514     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
00515       return false;
00516   return true;
00517 }
00518 
00519 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
00520 /// aggregate allocation.
00521 ///
00522 void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
00523                                  AllocaInfo &Info) {
00524   if (BitCastInst *C = dyn_cast<BitCastInst>(User))
00525     return isSafeUseOfBitCastedAllocation(C, AI, Info);
00526 
00527   if (LoadInst *LI = dyn_cast<LoadInst>(User))
00528     if (!LI->isVolatile())
00529       return;// Loads (returning a first class aggregrate) are always rewritable
00530 
00531   if (StoreInst *SI = dyn_cast<StoreInst>(User))
00532     if (!SI->isVolatile() && SI->getOperand(0) != AI)
00533       return;// Store is ok if storing INTO the pointer, not storing the pointer
00534  
00535   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
00536   if (GEPI == 0)
00537     return MarkUnsafe(Info);
00538 
00539   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
00540 
00541   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
00542   if (I == E ||
00543       I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
00544     return MarkUnsafe(Info);
00545   }
00546 
00547   ++I;
00548   if (I == E) return MarkUnsafe(Info);  // ran out of GEP indices??
00549 
00550   bool IsAllZeroIndices = true;
00551   
00552   // If the first index is a non-constant index into an array, see if we can
00553   // handle it as a special case.
00554   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
00555     if (!isa<ConstantInt>(I.getOperand())) {
00556       IsAllZeroIndices = 0;
00557       uint64_t NumElements = AT->getNumElements();
00558       
00559       // If this is an array index and the index is not constant, we cannot
00560       // promote... that is unless the array has exactly one or two elements in
00561       // it, in which case we CAN promote it, but we have to canonicalize this
00562       // out if this is the only problem.
00563       if ((NumElements == 1 || NumElements == 2) &&
00564           AllUsersAreLoads(GEPI)) {
00565         Info.needsCleanup = true;
00566         return;  // Canonicalization required!
00567       }
00568       return MarkUnsafe(Info);
00569     }
00570   }
00571  
00572   // Walk through the GEP type indices, checking the types that this indexes
00573   // into.
00574   for (; I != E; ++I) {
00575     // Ignore struct elements, no extra checking needed for these.
00576     if (isa<StructType>(*I))
00577       continue;
00578     
00579     ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
00580     if (!IdxVal) return MarkUnsafe(Info);
00581 
00582     // Are all indices still zero?
00583     IsAllZeroIndices &= IdxVal->isZero();
00584     
00585     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
00586       // This GEP indexes an array.  Verify that this is an in-range constant
00587       // integer. Specifically, consider A[0][i]. We cannot know that the user
00588       // isn't doing invalid things like allowing i to index an out-of-range
00589       // subscript that accesses A[1].  Because of this, we have to reject SROA
00590       // of any accesses into structs where any of the components are variables. 
00591       if (IdxVal->getZExtValue() >= AT->getNumElements())
00592         return MarkUnsafe(Info);
00593     } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
00594       if (IdxVal->getZExtValue() >= VT->getNumElements())
00595         return MarkUnsafe(Info);
00596     }
00597   }
00598   
00599   // If there are any non-simple uses of this getelementptr, make sure to reject
00600   // them.
00601   return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
00602 }
00603 
00604 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
00605 /// intrinsic can be promoted by SROA.  At this point, we know that the operand
00606 /// of the memintrinsic is a pointer to the beginning of the allocation.
00607 void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
00608                                           unsigned OpNo, AllocaInfo &Info) {
00609   // If not constant length, give up.
00610   ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
00611   if (!Length) return MarkUnsafe(Info);
00612   
00613   // If not the whole aggregate, give up.
00614   if (Length->getZExtValue() !=
00615       TD->getTypeAllocSize(AI->getType()->getElementType()))
00616     return MarkUnsafe(Info);
00617   
00618   // We only know about memcpy/memset/memmove.
00619   if (!isa<MemIntrinsic>(MI))
00620     return MarkUnsafe(Info);
00621   
00622   // Otherwise, we can transform it.  Determine whether this is a memcpy/set
00623   // into or out of the aggregate.
00624   if (OpNo == 1)
00625     Info.isMemCpyDst = true;
00626   else {
00627     assert(OpNo == 2);
00628     Info.isMemCpySrc = true;
00629   }
00630 }
00631 
00632 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
00633 /// are 
00634 void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
00635                                           AllocaInfo &Info) {
00636   for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
00637        UI != E; ++UI) {
00638     if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
00639       isSafeUseOfBitCastedAllocation(BCU, AI, Info);
00640     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
00641       isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
00642     } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
00643       if (SI->isVolatile())
00644         return MarkUnsafe(Info);
00645       
00646       // If storing the entire alloca in one chunk through a bitcasted pointer
00647       // to integer, we can transform it.  This happens (for example) when you
00648       // cast a {i32,i32}* to i64* and store through it.  This is similar to the
00649       // memcpy case and occurs in various "byval" cases and emulated memcpys.
00650       if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
00651           TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
00652           TD->getTypeAllocSize(AI->getType()->getElementType())) {
00653         Info.isMemCpyDst = true;
00654         continue;
00655       }
00656       return MarkUnsafe(Info);
00657     } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
00658       if (LI->isVolatile())
00659         return MarkUnsafe(Info);
00660 
00661       // If loading the entire alloca in one chunk through a bitcasted pointer
00662       // to integer, we can transform it.  This happens (for example) when you
00663       // cast a {i32,i32}* to i64* and load through it.  This is similar to the
00664       // memcpy case and occurs in various "byval" cases and emulated memcpys.
00665       if (isa<IntegerType>(LI->getType()) &&
00666           TD->getTypeAllocSize(LI->getType()) ==
00667           TD->getTypeAllocSize(AI->getType()->getElementType())) {
00668         Info.isMemCpySrc = true;
00669         continue;
00670       }
00671       return MarkUnsafe(Info);
00672     } else if (isa<DbgInfoIntrinsic>(UI)) {
00673       // If one user is DbgInfoIntrinsic then check if all users are
00674       // DbgInfoIntrinsics.
00675       if (OnlyUsedByDbgInfoIntrinsics(BC)) {
00676         Info.needsCleanup = true;
00677         return;
00678       }
00679       else
00680         MarkUnsafe(Info);
00681     }
00682     else {
00683       return MarkUnsafe(Info);
00684     }
00685     if (Info.isUnsafe) return;
00686   }
00687 }
00688 
00689 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
00690 /// to its first element.  Transform users of the cast to use the new values
00691 /// instead.
00692 void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
00693                                       SmallVector<AllocaInst*, 32> &NewElts) {
00694   Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
00695   while (UI != UE) {
00696     Instruction *User = cast<Instruction>(*UI++);
00697     if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
00698       RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
00699       if (BCU->use_empty()) BCU->eraseFromParent();
00700       continue;
00701     }
00702 
00703     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
00704       // This must be memcpy/memmove/memset of the entire aggregate.
00705       // Split into one per element.
00706       RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
00707       continue;
00708     }
00709       
00710     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00711       // If this is a store of the entire alloca from an integer, rewrite it.
00712       RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
00713       continue;
00714     }
00715 
00716     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
00717       // If this is a load of the entire alloca to an integer, rewrite it.
00718       RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
00719       continue;
00720     }
00721     
00722     // Otherwise it must be some other user of a gep of the first pointer.  Just
00723     // leave these alone.
00724     continue;
00725   }
00726 }
00727 
00728 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
00729 /// Rewrite it to copy or set the elements of the scalarized memory.
00730 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
00731                                         AllocationInst *AI,
00732                                         SmallVector<AllocaInst*, 32> &NewElts) {
00733   
00734   // If this is a memcpy/memmove, construct the other pointer as the
00735   // appropriate type.  The "Other" pointer is the pointer that goes to memory
00736   // that doesn't have anything to do with the alloca that we are promoting. For
00737   // memset, this Value* stays null.
00738   Value *OtherPtr = 0;
00739   LLVMContext &Context = MI->getContext();
00740   unsigned MemAlignment = MI->getAlignment();
00741   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
00742     if (BCInst == MTI->getRawDest())
00743       OtherPtr = MTI->getRawSource();
00744     else {
00745       assert(BCInst == MTI->getRawSource());
00746       OtherPtr = MTI->getRawDest();
00747     }
00748   }
00749   
00750   // If there is an other pointer, we want to convert it to the same pointer
00751   // type as AI has, so we can GEP through it safely.
00752   if (OtherPtr) {
00753     // It is likely that OtherPtr is a bitcast, if so, remove it.
00754     if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
00755       OtherPtr = BC->getOperand(0);
00756     // All zero GEPs are effectively bitcasts.
00757     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
00758       if (GEP->hasAllZeroIndices())
00759         OtherPtr = GEP->getOperand(0);
00760     
00761     if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
00762       if (BCE->getOpcode() == Instruction::BitCast)
00763         OtherPtr = BCE->getOperand(0);
00764     
00765     // If the pointer is not the right type, insert a bitcast to the right
00766     // type.
00767     if (OtherPtr->getType() != AI->getType())
00768       OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
00769                                  MI);
00770   }
00771   
00772   // Process each element of the aggregate.
00773   Value *TheFn = MI->getOperand(0);
00774   const Type *BytePtrTy = MI->getRawDest()->getType();
00775   bool SROADest = MI->getRawDest() == BCInst;
00776   
00777   Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
00778 
00779   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
00780     // If this is a memcpy/memmove, emit a GEP of the other element address.
00781     Value *OtherElt = 0;
00782     unsigned OtherEltAlign = MemAlignment;
00783     
00784     if (OtherPtr) {
00785       Value *Idx[2] = { Zero,
00786                       ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
00787       OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
00788                                            OtherPtr->getNameStr()+"."+Twine(i),
00789                                            MI);
00790       uint64_t EltOffset;
00791       const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
00792       if (const StructType *ST =
00793             dyn_cast<StructType>(OtherPtrTy->getElementType())) {
00794         EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
00795       } else {
00796         const Type *EltTy =
00797           cast<SequentialType>(OtherPtr->getType())->getElementType();
00798         EltOffset = TD->getTypeAllocSize(EltTy)*i;
00799       }
00800       
00801       // The alignment of the other pointer is the guaranteed alignment of the
00802       // element, which is affected by both the known alignment of the whole
00803       // mem intrinsic and the alignment of the element.  If the alignment of
00804       // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
00805       // known alignment is just 4 bytes.
00806       OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
00807     }
00808     
00809     Value *EltPtr = NewElts[i];
00810     const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
00811     
00812     // If we got down to a scalar, insert a load or store as appropriate.
00813     if (EltTy->isSingleValueType()) {
00814       if (isa<MemTransferInst>(MI)) {
00815         if (SROADest) {
00816           // From Other to Alloca.
00817           Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
00818           new StoreInst(Elt, EltPtr, MI);
00819         } else {
00820           // From Alloca to Other.
00821           Value *Elt = new LoadInst(EltPtr, "tmp", MI);
00822           new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
00823         }
00824         continue;
00825       }
00826       assert(isa<MemSetInst>(MI));
00827       
00828       // If the stored element is zero (common case), just store a null
00829       // constant.
00830       Constant *StoreVal;
00831       if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
00832         if (CI->isZero()) {
00833           StoreVal = Constant::getNullValue(EltTy);  // 0.0, null, 0, <0,0>
00834         } else {
00835           // If EltTy is a vector type, get the element type.
00836           const Type *ValTy = EltTy->getScalarType();
00837 
00838           // Construct an integer with the right value.
00839           unsigned EltSize = TD->getTypeSizeInBits(ValTy);
00840           APInt OneVal(EltSize, CI->getZExtValue());
00841           APInt TotalVal(OneVal);
00842           // Set each byte.
00843           for (unsigned i = 0; 8*i < EltSize; ++i) {
00844             TotalVal = TotalVal.shl(8);
00845             TotalVal |= OneVal;
00846           }
00847           
00848           // Convert the integer value to the appropriate type.
00849           StoreVal = ConstantInt::get(Context, TotalVal);
00850           if (isa<PointerType>(ValTy))
00851             StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
00852           else if (ValTy->isFloatingPoint())
00853             StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
00854           assert(StoreVal->getType() == ValTy && "Type mismatch!");
00855           
00856           // If the requested value was a vector constant, create it.
00857           if (EltTy != ValTy) {
00858             unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
00859             SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
00860             StoreVal = ConstantVector::get(&Elts[0], NumElts);
00861           }
00862         }
00863         new StoreInst(StoreVal, EltPtr, MI);
00864         continue;
00865       }
00866       // Otherwise, if we're storing a byte variable, use a memset call for
00867       // this element.
00868     }
00869     
00870     // Cast the element pointer to BytePtrTy.
00871     if (EltPtr->getType() != BytePtrTy)
00872       EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
00873     
00874     // Cast the other pointer (if we have one) to BytePtrTy. 
00875     if (OtherElt && OtherElt->getType() != BytePtrTy)
00876       OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
00877                                  MI);
00878     
00879     unsigned EltSize = TD->getTypeAllocSize(EltTy);
00880     
00881     // Finally, insert the meminst for this element.
00882     if (isa<MemTransferInst>(MI)) {
00883       Value *Ops[] = {
00884         SROADest ? EltPtr : OtherElt,  // Dest ptr
00885         SROADest ? OtherElt : EltPtr,  // Src ptr
00886         ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
00887         // Align
00888         ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
00889       };
00890       CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
00891     } else {
00892       assert(isa<MemSetInst>(MI));
00893       Value *Ops[] = {
00894         EltPtr, MI->getOperand(2),  // Dest, Value,
00895         ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
00896         Zero  // Align
00897       };
00898       CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
00899     }
00900   }
00901   MI->eraseFromParent();
00902 }
00903 
00904 /// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
00905 /// overwrites the entire allocation.  Extract out the pieces of the stored
00906 /// integer and store them individually.
00907 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
00908                                          AllocationInst *AI,
00909                                          SmallVector<AllocaInst*, 32> &NewElts){
00910   // Extract each element out of the integer according to its structure offset
00911   // and store the element value to the individual alloca.
00912   Value *SrcVal = SI->getOperand(0);
00913   const Type *AllocaEltTy = AI->getType()->getElementType();
00914   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
00915   
00916   // If this isn't a store of an integer to the whole alloca, it may be a store
00917   // to the first element.  Just ignore the store in this case and normal SROA
00918   // will handle it.
00919   if (!isa<IntegerType>(SrcVal->getType()) ||
00920       TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
00921     return;
00922   // Handle tail padding by extending the operand
00923   if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
00924     SrcVal = new ZExtInst(SrcVal,
00925                           IntegerType::get(SI->getContext(), AllocaSizeBits), 
00926                           "", SI);
00927 
00928   DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
00929 
00930   // There are two forms here: AI could be an array or struct.  Both cases
00931   // have different ways to compute the element offset.
00932   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
00933     const StructLayout *Layout = TD->getStructLayout(EltSTy);
00934     
00935     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
00936       // Get the number of bits to shift SrcVal to get the value.
00937       const Type *FieldTy = EltSTy->getElementType(i);
00938       uint64_t Shift = Layout->getElementOffsetInBits(i);
00939       
00940       if (TD->isBigEndian())
00941         Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
00942       
00943       Value *EltVal = SrcVal;
00944       if (Shift) {
00945         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
00946         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
00947                                             "sroa.store.elt", SI);
00948       }
00949       
00950       // Truncate down to an integer of the right size.
00951       uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
00952       
00953       // Ignore zero sized fields like {}, they obviously contain no data.
00954       if (FieldSizeBits == 0) continue;
00955       
00956       if (FieldSizeBits != AllocaSizeBits)
00957         EltVal = new TruncInst(EltVal,
00958                              IntegerType::get(SI->getContext(), FieldSizeBits),
00959                               "", SI);
00960       Value *DestField = NewElts[i];
00961       if (EltVal->getType() == FieldTy) {
00962         // Storing to an integer field of this size, just do it.
00963       } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
00964         // Bitcast to the right element type (for fp/vector values).
00965         EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
00966       } else {
00967         // Otherwise, bitcast the dest pointer (for aggregates).
00968         DestField = new BitCastInst(DestField,
00969                               PointerType::getUnqual(EltVal->getType()),
00970                                     "", SI);
00971       }
00972       new StoreInst(EltVal, DestField, SI);
00973     }
00974     
00975   } else {
00976     const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
00977     const Type *ArrayEltTy = ATy->getElementType();
00978     uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
00979     uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
00980 
00981     uint64_t Shift;
00982     
00983     if (TD->isBigEndian())
00984       Shift = AllocaSizeBits-ElementOffset;
00985     else 
00986       Shift = 0;
00987     
00988     for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
00989       // Ignore zero sized fields like {}, they obviously contain no data.
00990       if (ElementSizeBits == 0) continue;
00991       
00992       Value *EltVal = SrcVal;
00993       if (Shift) {
00994         Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
00995         EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
00996                                             "sroa.store.elt", SI);
00997       }
00998       
00999       // Truncate down to an integer of the right size.
01000       if (ElementSizeBits != AllocaSizeBits)
01001         EltVal = new TruncInst(EltVal, 
01002                                IntegerType::get(SI->getContext(), 
01003                                                 ElementSizeBits),"",SI);
01004       Value *DestField = NewElts[i];
01005       if (EltVal->getType() == ArrayEltTy) {
01006         // Storing to an integer field of this size, just do it.
01007       } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
01008         // Bitcast to the right element type (for fp/vector values).
01009         EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
01010       } else {
01011         // Otherwise, bitcast the dest pointer (for aggregates).
01012         DestField = new BitCastInst(DestField,
01013                               PointerType::getUnqual(EltVal->getType()),
01014                                     "", SI);
01015       }
01016       new StoreInst(EltVal, DestField, SI);
01017       
01018       if (TD->isBigEndian())
01019         Shift -= ElementOffset;
01020       else 
01021         Shift += ElementOffset;
01022     }
01023   }
01024   
01025   SI->eraseFromParent();
01026 }
01027 
01028 /// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
01029 /// an integer.  Load the individual pieces to form the aggregate value.
01030 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
01031                                         SmallVector<AllocaInst*, 32> &NewElts) {
01032   // Extract each element out of the NewElts according to its structure offset
01033   // and form the result value.
01034   const Type *AllocaEltTy = AI->getType()->getElementType();
01035   uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
01036   
01037   // If this isn't a load of the whole alloca to an integer, it may be a load
01038   // of the first element.  Just ignore the load in this case and normal SROA
01039   // will handle it.
01040   if (!isa<IntegerType>(LI->getType()) ||
01041       TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
01042     return;
01043   
01044   DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
01045   
01046   // There are two forms here: AI could be an array or struct.  Both cases
01047   // have different ways to compute the element offset.
01048   const StructLayout *Layout = 0;
01049   uint64_t ArrayEltBitOffset = 0;
01050   if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
01051     Layout = TD->getStructLayout(EltSTy);
01052   } else {
01053     const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
01054     ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
01055   }    
01056   
01057   Value *ResultVal = 
01058     Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
01059   
01060   for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
01061     // Load the value from the alloca.  If the NewElt is an aggregate, cast
01062     // the pointer to an integer of the same size before doing the load.
01063     Value *SrcField = NewElts[i];
01064     const Type *FieldTy =
01065       cast<PointerType>(SrcField->getType())->getElementType();
01066     uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
01067     
01068     // Ignore zero sized fields like {}, they obviously contain no data.
01069     if (FieldSizeBits == 0) continue;
01070     
01071     const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(), 
01072                                                      FieldSizeBits);
01073     if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
01074         !isa<VectorType>(FieldTy))
01075       SrcField = new BitCastInst(SrcField,
01076                                  PointerType::getUnqual(FieldIntTy),
01077                                  "", LI);
01078     SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
01079 
01080     // If SrcField is a fp or vector of the right size but that isn't an
01081     // integer type, bitcast to an integer so we can shift it.
01082     if (SrcField->getType() != FieldIntTy)
01083       SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
01084 
01085     // Zero extend the field to be the same size as the final alloca so that
01086     // we can shift and insert it.
01087     if (SrcField->getType() != ResultVal->getType())
01088       SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
01089     
01090     // Determine the number of bits to shift SrcField.
01091     uint64_t Shift;
01092     if (Layout) // Struct case.
01093       Shift = Layout->getElementOffsetInBits(i);
01094     else  // Array case.
01095       Shift = i*ArrayEltBitOffset;
01096     
01097     if (TD->isBigEndian())
01098       Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
01099     
01100     if (Shift) {
01101       Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
01102       SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
01103     }
01104 
01105     ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
01106   }
01107 
01108   // Handle tail padding by truncating the result
01109   if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
01110     ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
01111 
01112   LI->replaceAllUsesWith(ResultVal);
01113   LI->eraseFromParent();
01114 }
01115 
01116 
01117 /// HasPadding - Return true if the specified type has any structure or
01118 /// alignment padding, false otherwise.
01119 static bool HasPadding(const Type *Ty, const TargetData &TD) {
01120   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
01121     const StructLayout *SL = TD.getStructLayout(STy);
01122     unsigned PrevFieldBitOffset = 0;
01123     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01124       unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
01125 
01126       // Padding in sub-elements?
01127       if (HasPadding(STy->getElementType(i), TD))
01128         return true;
01129 
01130       // Check to see if there is any padding between this element and the
01131       // previous one.
01132       if (i) {
01133         unsigned PrevFieldEnd =
01134         PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
01135         if (PrevFieldEnd < FieldBitOffset)
01136           return true;
01137       }
01138 
01139       PrevFieldBitOffset = FieldBitOffset;
01140     }
01141 
01142     //  Check for tail padding.
01143     if (unsigned EltCount = STy->getNumElements()) {
01144       unsigned PrevFieldEnd = PrevFieldBitOffset +
01145                    TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
01146       if (PrevFieldEnd < SL->getSizeInBits())
01147         return true;
01148     }
01149 
01150   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
01151     return HasPadding(ATy->getElementType(), TD);
01152   } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
01153     return HasPadding(VTy->getElementType(), TD);
01154   }
01155   return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
01156 }
01157 
01158 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
01159 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
01160 /// or 1 if safe after canonicalization has been performed.
01161 ///
01162 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
01163   // Loop over the use list of the alloca.  We can only transform it if all of
01164   // the users are safe to transform.
01165   AllocaInfo Info;
01166   
01167   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
01168        I != E; ++I) {
01169     isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
01170     if (Info.isUnsafe) {
01171       DOUT << "Cannot transform: " << *AI << "  due to user: " << **I;
01172       return 0;
01173     }
01174   }
01175   
01176   // Okay, we know all the users are promotable.  If the aggregate is a memcpy
01177   // source and destination, we have to be careful.  In particular, the memcpy
01178   // could be moving around elements that live in structure padding of the LLVM
01179   // types, but may actually be used.  In these cases, we refuse to promote the
01180   // struct.
01181   if (Info.isMemCpySrc && Info.isMemCpyDst &&
01182       HasPadding(AI->getType()->getElementType(), *TD))
01183     return 0;
01184 
01185   // If we require cleanup, return 1, otherwise return 3.
01186   return Info.needsCleanup ? 1 : 3;
01187 }
01188 
01189 /// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
01190 /// is canonicalized here.
01191 void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
01192   gep_type_iterator I = gep_type_begin(GEPI);
01193   ++I;
01194   
01195   const ArrayType *AT = dyn_cast<ArrayType>(*I);
01196   if (!AT) 
01197     return;
01198 
01199   uint64_t NumElements = AT->getNumElements();
01200   
01201   if (isa<ConstantInt>(I.getOperand()))
01202     return;
01203 
01204   if (NumElements == 1) {
01205     GEPI->setOperand(2, 
01206                   Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
01207     return;
01208   } 
01209     
01210   assert(NumElements == 2 && "Unhandled case!");
01211   // All users of the GEP must be loads.  At each use of the GEP, insert
01212   // two loads of the appropriate indexed GEP and select between them.
01213   Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(), 
01214                               Constant::getNullValue(I.getOperand()->getType()),
01215                               "isone");
01216   // Insert the new GEP instructions, which are properly indexed.
01217   SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
01218   Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
01219   Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
01220                                              Indices.begin(),
01221                                              Indices.end(),
01222                                              GEPI->getName()+".0", GEPI);
01223   Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
01224   Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
01225                                             Indices.begin(),
01226                                             Indices.end(),
01227                                             GEPI->getName()+".1", GEPI);
01228   // Replace all loads of the variable index GEP with loads from both
01229   // indexes and a select.
01230   while (!GEPI->use_empty()) {
01231     LoadInst *LI = cast<LoadInst>(GEPI->use_back());
01232     Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
01233     Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
01234     Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
01235     LI->replaceAllUsesWith(R);
01236     LI->eraseFromParent();
01237   }
01238   GEPI->eraseFromParent();
01239 }
01240 
01241 
01242 /// CleanupAllocaUsers - If SROA reported that it can promote the specified
01243 /// allocation, but only if cleaned up, perform the cleanups required.
01244 void SROA::CleanupAllocaUsers(AllocationInst *AI) {
01245   // At this point, we know that the end result will be SROA'd and promoted, so
01246   // we can insert ugly code if required so long as sroa+mem2reg will clean it
01247   // up.
01248   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
01249        UI != E; ) {
01250     User *U = *UI++;
01251     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
01252       CleanupGEP(GEPI);
01253     else {
01254       Instruction *I = cast<Instruction>(U);
01255       SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
01256       if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
01257         // Safe to remove debug info uses.
01258         while (!DbgInUses.empty()) {
01259           DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
01260           DI->eraseFromParent();
01261         }
01262         I->eraseFromParent();
01263       }
01264     }
01265   }
01266 }
01267 
01268 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
01269 /// the offset specified by Offset (which is specified in bytes).
01270 ///
01271 /// There are two cases we handle here:
01272 ///   1) A union of vector types of the same size and potentially its elements.
01273 ///      Here we turn element accesses into insert/extract element operations.
01274 ///      This promotes a <4 x float> with a store of float to the third element
01275 ///      into a <4 x float> that uses insert element.
01276 ///   2) A fully general blob of memory, which we turn into some (potentially
01277 ///      large) integer type with extract and insert operations where the loads
01278 ///      and stores would mutate the memory.
01279 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
01280                         unsigned AllocaSize, const TargetData &TD,
01281                         LLVMContext &Context) {
01282   // If this could be contributing to a vector, analyze it.
01283   if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
01284 
01285     // If the In type is a vector that is the same size as the alloca, see if it
01286     // matches the existing VecTy.
01287     if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
01288       if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
01289         // If we're storing/loading a vector of the right size, allow it as a
01290         // vector.  If this the first vector we see, remember the type so that
01291         // we know the element size.
01292         if (VecTy == 0)
01293           VecTy = VInTy;
01294         return;
01295       }
01296     } else if (In == Type::getFloatTy(Context) ||
01297                In == Type::getDoubleTy(Context) ||
01298                (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
01299                 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
01300       // If we're accessing something that could be an element of a vector, see
01301       // if the implied vector agrees with what we already have and if Offset is
01302       // compatible with it.
01303       unsigned EltSize = In->getPrimitiveSizeInBits()/8;
01304       if (Offset % EltSize == 0 &&
01305           AllocaSize % EltSize == 0 &&
01306           (VecTy == 0 || 
01307            cast<VectorType>(VecTy)->getElementType()
01308                  ->getPrimitiveSizeInBits()/8 == EltSize)) {
01309         if (VecTy == 0)
01310           VecTy = VectorType::get(In, AllocaSize/EltSize);
01311         return;
01312       }
01313     }
01314   }
01315   
01316   // Otherwise, we have a case that we can't handle with an optimized vector
01317   // form.  We can still turn this into a large integer.
01318   VecTy = Type::getVoidTy(Context);
01319 }
01320 
01321 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee and all
01322 /// its accesses to use a to single vector type, return true, and set VecTy to
01323 /// the new type.  If we could convert the alloca into a single promotable
01324 /// integer, return true but set VecTy to VoidTy.  Further, if the use is not a
01325 /// completely trivial use that mem2reg could promote, set IsNotTrivial.  Offset
01326 /// is the current offset from the base of the alloca being analyzed.
01327 ///
01328 /// If we see at least one access to the value that is as a vector type, set the
01329 /// SawVec flag.
01330 ///
01331 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
01332                               bool &SawVec, uint64_t Offset,
01333                               unsigned AllocaSize) {
01334   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
01335     Instruction *User = cast<Instruction>(*UI);
01336     
01337     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01338       // Don't break volatile loads.
01339       if (LI->isVolatile())
01340         return false;
01341       MergeInType(LI->getType(), Offset, VecTy,
01342                   AllocaSize, *TD, V->getContext());
01343       SawVec |= isa<VectorType>(LI->getType());
01344       continue;
01345     }
01346     
01347     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01348       // Storing the pointer, not into the value?
01349       if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
01350       MergeInType(SI->getOperand(0)->getType(), Offset,
01351                   VecTy, AllocaSize, *TD, V->getContext());
01352       SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
01353       continue;
01354     }
01355     
01356     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
01357       if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
01358                               AllocaSize))
01359         return false;
01360       IsNotTrivial = true;
01361       continue;
01362     }
01363 
01364     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
01365       // If this is a GEP with a variable indices, we can't handle it.
01366       if (!GEP->hasAllConstantIndices())
01367         return false;
01368       
01369       // Compute the offset that this GEP adds to the pointer.
01370       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
01371       uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
01372                                                 &Indices[0], Indices.size());
01373       // See if all uses can be converted.
01374       if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
01375                               AllocaSize))
01376         return false;
01377       IsNotTrivial = true;
01378       continue;
01379     }
01380 
01381     // If this is a constant sized memset of a constant value (e.g. 0) we can
01382     // handle it.
01383     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
01384       // Store of constant value and constant size.
01385       if (isa<ConstantInt>(MSI->getValue()) &&
01386           isa<ConstantInt>(MSI->getLength())) {
01387         IsNotTrivial = true;
01388         continue;
01389       }
01390     }
01391 
01392     // If this is a memcpy or memmove into or out of the whole allocation, we
01393     // can handle it like a load or store of the scalar type.
01394     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
01395       if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
01396         if (Len->getZExtValue() == AllocaSize && Offset == 0) {
01397           IsNotTrivial = true;
01398           continue;
01399         }
01400     }
01401     
01402     // Ignore dbg intrinsic.
01403     if (isa<DbgInfoIntrinsic>(User))
01404       continue;
01405 
01406     // Otherwise, we cannot handle this!
01407     return false;
01408   }
01409   
01410   return true;
01411 }
01412 
01413 
01414 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
01415 /// directly.  This happens when we are converting an "integer union" to a
01416 /// single integer scalar, or when we are converting a "vector union" to a
01417 /// vector with insert/extractelement instructions.
01418 ///
01419 /// Offset is an offset from the original alloca, in bits that need to be
01420 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
01421 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
01422   while (!Ptr->use_empty()) {
01423     Instruction *User = cast<Instruction>(Ptr->use_back());
01424 
01425     if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
01426       ConvertUsesToScalar(CI, NewAI, Offset);
01427       CI->eraseFromParent();
01428       continue;
01429     }
01430 
01431     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
01432       // Compute the offset that this GEP adds to the pointer.
01433       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
01434       uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
01435                                                 &Indices[0], Indices.size());
01436       ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
01437       GEP->eraseFromParent();
01438       continue;
01439     }
01440     
01441     IRBuilder<> Builder(User->getParent(), User);
01442     
01443     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01444       // The load is a bit extract from NewAI shifted right by Offset bits.
01445       Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
01446       Value *NewLoadVal
01447         = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
01448       LI->replaceAllUsesWith(NewLoadVal);
01449       LI->eraseFromParent();
01450       continue;
01451     }
01452     
01453     if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
01454       assert(SI->getOperand(0) != Ptr && "Consistency error!");
01455       // FIXME: Remove once builder has Twine API.
01456       Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
01457       Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
01458                                              Builder);
01459       Builder.CreateStore(New, NewAI);
01460       SI->eraseFromParent();
01461       continue;
01462     }
01463     
01464     // If this is a constant sized memset of a constant value (e.g. 0) we can
01465     // transform it into a store of the expanded constant value.
01466     if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
01467       assert(MSI->getRawDest() == Ptr && "Consistency error!");
01468       unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
01469       if (NumBytes != 0) {
01470         unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
01471         
01472         // Compute the value replicated the right number of times.
01473         APInt APVal(NumBytes*8, Val);
01474 
01475         // Splat the value if non-zero.
01476         if (Val)
01477           for (unsigned i = 1; i != NumBytes; ++i)
01478             APVal |= APVal << 8;
01479         
01480         // FIXME: Remove once builder has Twine API.
01481         Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
01482         Value *New = ConvertScalar_InsertValue(
01483                                     ConstantInt::get(User->getContext(), APVal),
01484                                                Old, Offset, Builder);
01485         Builder.CreateStore(New, NewAI);
01486       }
01487       MSI->eraseFromParent();
01488       continue;
01489     }
01490 
01491     // If this is a memcpy or memmove into or out of the whole allocation, we
01492     // can handle it like a load or store of the scalar type.
01493     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
01494       assert(Offset == 0 && "must be store to start of alloca");
01495       
01496       // If the source and destination are both to the same alloca, then this is
01497       // a noop copy-to-self, just delete it.  Otherwise, emit a load and store
01498       // as appropriate.
01499       AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
01500       
01501       if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
01502         // Dest must be OrigAI, change this to be a load from the original
01503         // pointer (bitcasted), then a store to our new alloca.
01504         assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
01505         Value *SrcPtr = MTI->getSource();
01506         SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
01507         
01508         LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
01509         SrcVal->setAlignment(MTI->getAlignment());
01510         Builder.CreateStore(SrcVal, NewAI);
01511       } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
01512         // Src must be OrigAI, change this to be a load from NewAI then a store
01513         // through the original dest pointer (bitcasted).
01514         assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
01515         LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
01516 
01517         Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
01518         StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
01519         NewStore->setAlignment(MTI->getAlignment());
01520       } else {
01521         // Noop transfer. Src == Dst
01522       }
01523           
01524 
01525       MTI->eraseFromParent();
01526       continue;
01527     }
01528     
01529     // If user is a dbg info intrinsic then it is safe to remove it.
01530     if (isa<DbgInfoIntrinsic>(User)) {
01531       User->eraseFromParent();
01532       continue;
01533     }
01534 
01535     llvm_unreachable("Unsupported operation!");
01536   }
01537 }
01538 
01539 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
01540 /// or vector value FromVal, extracting the bits from the offset specified by
01541 /// Offset.  This returns the value, which is of type ToType.
01542 ///
01543 /// This happens when we are converting an "integer union" to a single
01544 /// integer scalar, or when we are converting a "vector union" to a vector with
01545 /// insert/extractelement instructions.
01546 ///
01547 /// Offset is an offset from the original alloca, in bits that need to be
01548 /// shifted to the right.
01549 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
01550                                         uint64_t Offset, IRBuilder<> &Builder) {
01551   // If the load is of the whole new alloca, no conversion is needed.
01552   if (FromVal->getType() == ToType && Offset == 0)
01553     return FromVal;
01554 
01555   // If the result alloca is a vector type, this is either an element
01556   // access or a bitcast to another vector type of the same size.
01557   if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
01558     if (isa<VectorType>(ToType))
01559       return Builder.CreateBitCast(FromVal, ToType, "tmp");
01560 
01561     // Otherwise it must be an element access.
01562     unsigned Elt = 0;
01563     if (Offset) {
01564       unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
01565       Elt = Offset/EltSize;
01566       assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
01567     }
01568     // Return the element extracted out of it.
01569     Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
01570                     Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
01571     if (V->getType() != ToType)
01572       V = Builder.CreateBitCast(V, ToType, "tmp");
01573     return V;
01574   }
01575   
01576   // If ToType is a first class aggregate, extract out each of the pieces and
01577   // use insertvalue's to form the FCA.
01578   if (const StructType *ST = dyn_cast<StructType>(ToType)) {
01579     const StructLayout &Layout = *TD->getStructLayout(ST);
01580     Value *Res = UndefValue::get(ST);
01581     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
01582       Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
01583                                         Offset+Layout.getElementOffsetInBits(i),
01584                                               Builder);
01585       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
01586     }
01587     return Res;
01588   }
01589   
01590   if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
01591     uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
01592     Value *Res = UndefValue::get(AT);
01593     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
01594       Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
01595                                               Offset+i*EltSize, Builder);
01596       Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
01597     }
01598     return Res;
01599   }
01600 
01601   // Otherwise, this must be a union that was converted to an integer value.
01602   const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
01603 
01604   // If this is a big-endian system and the load is narrower than the
01605   // full alloca type, we need to do a shift to get the right bits.
01606   int ShAmt = 0;
01607   if (TD->isBigEndian()) {
01608     // On big-endian machines, the lowest bit is stored at the bit offset
01609     // from the pointer given by getTypeStoreSizeInBits.  This matters for
01610     // integers with a bitwidth that is not a multiple of 8.
01611     ShAmt = TD->getTypeStoreSizeInBits(NTy) -
01612             TD->getTypeStoreSizeInBits(ToType) - Offset;
01613   } else {
01614     ShAmt = Offset;
01615   }
01616 
01617   // Note: we support negative bitwidths (with shl) which are not defined.
01618   // We do this to support (f.e.) loads off the end of a structure where
01619   // only some bits are used.
01620   if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
01621     FromVal = Builder.CreateLShr(FromVal,
01622                                  ConstantInt::get(FromVal->getType(),
01623                                                            ShAmt), "tmp");
01624   else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
01625     FromVal = Builder.CreateShl(FromVal, 
01626                                 ConstantInt::get(FromVal->getType(),
01627                                                           -ShAmt), "tmp");
01628 
01629   // Finally, unconditionally truncate the integer to the right width.
01630   unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
01631   if (LIBitWidth < NTy->getBitWidth())
01632     FromVal =
01633       Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(), 
01634                                                     LIBitWidth), "tmp");
01635   else if (LIBitWidth > NTy->getBitWidth())
01636     FromVal =
01637        Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(), 
01638                                                     LIBitWidth), "tmp");
01639 
01640   // If the result is an integer, this is a trunc or bitcast.
01641   if (isa<IntegerType>(ToType)) {
01642     // Should be done.
01643   } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
01644     // Just do a bitcast, we know the sizes match up.
01645     FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
01646   } else {
01647     // Otherwise must be a pointer.
01648     FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
01649   }
01650   assert(FromVal->getType() == ToType && "Didn't convert right?");
01651   return FromVal;
01652 }
01653 
01654 
01655 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
01656 /// or vector value "Old" at the offset specified by Offset.
01657 ///
01658 /// This happens when we are converting an "integer union" to a
01659 /// single integer scalar, or when we are converting a "vector union" to a
01660 /// vector with insert/extractelement instructions.
01661 ///
01662 /// Offset is an offset from the original alloca, in bits that need to be
01663 /// shifted to the right.
01664 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
01665                                        uint64_t Offset, IRBuilder<> &Builder) {
01666 
01667   // Convert the stored type to the actual type, shift it left to insert
01668   // then 'or' into place.
01669   const Type *AllocaType = Old->getType();
01670   LLVMContext &Context = Old->getContext();
01671 
01672   if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
01673     uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
01674     uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
01675     
01676     // Changing the whole vector with memset or with an access of a different
01677     // vector type?
01678     if (ValSize == VecSize)
01679       return Builder.CreateBitCast(SV, AllocaType, "tmp");
01680 
01681     uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
01682 
01683     // Must be an element insertion.
01684     unsigned Elt = Offset/EltSize;
01685     
01686     if (SV->getType() != VTy->getElementType())
01687       SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
01688     
01689     SV = Builder.CreateInsertElement(Old, SV, 
01690                      ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
01691                                      "tmp");
01692     return SV;
01693   }
01694   
01695   // If SV is a first-class aggregate value, insert each value recursively.
01696   if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
01697     const StructLayout &Layout = *TD->getStructLayout(ST);
01698     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
01699       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
01700       Old = ConvertScalar_InsertValue(Elt, Old, 
01701                                       Offset+Layout.getElementOffsetInBits(i),
01702                                       Builder);
01703     }
01704     return Old;
01705   }
01706   
01707   if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
01708     uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
01709     for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
01710       Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
01711       Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
01712     }
01713     return Old;
01714   }
01715 
01716   // If SV is a float, convert it to the appropriate integer type.
01717   // If it is a pointer, do the same.
01718   unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
01719   unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
01720   unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
01721   unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
01722   if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
01723     SV = Builder.CreateBitCast(SV,
01724                             IntegerType::get(SV->getContext(),SrcWidth), "tmp");
01725   else if (isa<PointerType>(SV->getType()))
01726     SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
01727 
01728   // Zero extend or truncate the value if needed.
01729   if (SV->getType() != AllocaType) {
01730     if (SV->getType()->getPrimitiveSizeInBits() <
01731              AllocaType->getPrimitiveSizeInBits())
01732       SV = Builder.CreateZExt(SV, AllocaType, "tmp");
01733     else {
01734       // Truncation may be needed if storing more than the alloca can hold
01735       // (undefined behavior).
01736       SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
01737       SrcWidth = DestWidth;
01738       SrcStoreWidth = DestStoreWidth;
01739     }
01740   }
01741 
01742   // If this is a big-endian system and the store is narrower than the
01743   // full alloca type, we need to do a shift to get the right bits.
01744   int ShAmt = 0;
01745   if (TD->isBigEndian()) {
01746     // On big-endian machines, the lowest bit is stored at the bit offset
01747     // from the pointer given by getTypeStoreSizeInBits.  This matters for
01748     // integers with a bitwidth that is not a multiple of 8.
01749     ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
01750   } else {
01751     ShAmt = Offset;
01752   }
01753 
01754   // Note: we support negative bitwidths (with shr) which are not defined.
01755   // We do this to support (f.e.) stores off the end of a structure where
01756   // only some bits in the structure are set.
01757   APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
01758   if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
01759     SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
01760                            ShAmt), "tmp");
01761     Mask <<= ShAmt;
01762   } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
01763     SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
01764                             -ShAmt), "tmp");
01765     Mask = Mask.lshr(-ShAmt);
01766   }
01767 
01768   // Mask out the bits we are about to insert from the old value, and or
01769   // in the new bits.
01770   if (SrcWidth != DestWidth) {
01771     assert(DestWidth > SrcWidth);
01772     Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
01773     SV = Builder.CreateOr(Old, SV, "ins");
01774   }
01775   return SV;
01776 }
01777 
01778 
01779 
01780 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
01781 /// some part of a constant global variable.  This intentionally only accepts
01782 /// constant expressions because we don't can't rewrite arbitrary instructions.
01783 static bool PointsToConstantGlobal(Value *V) {
01784   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
01785     return GV->isConstant();
01786   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
01787     if (CE->getOpcode() == Instruction::BitCast || 
01788         CE->getOpcode() == Instruction::GetElementPtr)
01789       return PointsToConstantGlobal(CE->getOperand(0));
01790   return false;
01791 }
01792 
01793 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
01794 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
01795 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
01796 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
01797 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
01798 /// the alloca, and if the source pointer is a pointer to a constant  global, we
01799 /// can optimize this.
01800 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
01801                                            bool isOffset) {
01802   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
01803     if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
01804       // Ignore non-volatile loads, they are always ok.
01805       if (!LI->isVolatile())
01806         continue;
01807     
01808     if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
01809       // If uses of the bitcast are ok, we are ok.
01810       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
01811         return false;
01812       continue;
01813     }
01814     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
01815       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
01816       // doesn't, it does.
01817       if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
01818                                          isOffset || !GEP->hasAllZeroIndices()))
01819         return false;
01820       continue;
01821     }
01822     
01823     // If this is isn't our memcpy/memmove, reject it as something we can't
01824     // handle.
01825     if (!isa<MemTransferInst>(*UI))
01826       return false;
01827 
01828     // If we already have seen a copy, reject the second one.
01829     if (TheCopy) return false;
01830     
01831     // If the pointer has been offset from the start of the alloca, we can't
01832     // safely handle this.
01833     if (isOffset) return false;
01834 
01835     // If the memintrinsic isn't using the alloca as the dest, reject it.
01836     if (UI.getOperandNo() != 1) return false;
01837     
01838     MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
01839     
01840     // If the source of the memcpy/move is not a constant global, reject it.
01841     if (!PointsToConstantGlobal(MI->getOperand(2)))
01842       return false;
01843     
01844     // Otherwise, the transform is safe.  Remember the copy instruction.
01845     TheCopy = MI;
01846   }
01847   return true;
01848 }
01849 
01850 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
01851 /// modified by a copy from a constant global.  If we can prove this, we can
01852 /// replace any uses of the alloca with uses of the global directly.
01853 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
01854   Instruction *TheCopy = 0;
01855   if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
01856     return TheCopy;
01857   return 0;
01858 }