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