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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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 #include "llvm/Transforms/Scalar.h"
00023 #include "llvm/Constants.h"
00024 #include "llvm/DerivedTypes.h"
00025 #include "llvm/Function.h"
00026 #include "llvm/Pass.h"
00027 #include "llvm/Instructions.h"
00028 #include "llvm/Analysis/Dominators.h"
00029 #include "llvm/Target/TargetData.h"
00030 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/GetElementPtrTypeIterator.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/Visibility.h"
00035 #include "llvm/ADT/Statistic.h"
00036 #include "llvm/ADT/StringExtras.h"
00037 #include <iostream>
00038 using namespace llvm;
00039 
00040 namespace {
00041   Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
00042   Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
00043   Statistic<> NumConverted("scalarrepl",
00044                            "Number of aggregates converted to scalar");
00045 
00046   struct VISIBILITY_HIDDEN SROA : public FunctionPass {
00047     bool runOnFunction(Function &F);
00048 
00049     bool performScalarRepl(Function &F);
00050     bool performPromotion(Function &F);
00051 
00052     // getAnalysisUsage - This pass does not require any passes, but we know it
00053     // will not alter the CFG, so say so.
00054     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00055       AU.addRequired<DominatorTree>();
00056       AU.addRequired<DominanceFrontier>();
00057       AU.addRequired<TargetData>();
00058       AU.setPreservesCFG();
00059     }
00060 
00061   private:
00062     int isSafeElementUse(Value *Ptr);
00063     int isSafeUseOfAllocation(Instruction *User);
00064     int isSafeAllocaToScalarRepl(AllocationInst *AI);
00065     void CanonicalizeAllocaUsers(AllocationInst *AI);
00066     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
00067     
00068     const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
00069     void ConvertToScalar(AllocationInst *AI, const Type *Ty);
00070     void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
00071   };
00072 
00073   RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
00074 }
00075 
00076 // Public interface to the ScalarReplAggregates pass
00077 FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); }
00078 
00079 
00080 bool SROA::runOnFunction(Function &F) {
00081   bool Changed = performPromotion(F);
00082   while (1) {
00083     bool LocalChange = performScalarRepl(F);
00084     if (!LocalChange) break;   // No need to repromote if no scalarrepl
00085     Changed = true;
00086     LocalChange = performPromotion(F);
00087     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
00088   }
00089 
00090   return Changed;
00091 }
00092 
00093 
00094 bool SROA::performPromotion(Function &F) {
00095   std::vector<AllocaInst*> Allocas;
00096   const TargetData &TD = getAnalysis<TargetData>();
00097   DominatorTree     &DT = getAnalysis<DominatorTree>();
00098   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
00099 
00100   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
00101 
00102   bool Changed = false;
00103 
00104   while (1) {
00105     Allocas.clear();
00106 
00107     // Find allocas that are safe to promote, by looking at all instructions in
00108     // the entry node
00109     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
00110       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
00111         if (isAllocaPromotable(AI, TD))
00112           Allocas.push_back(AI);
00113 
00114     if (Allocas.empty()) break;
00115 
00116     PromoteMemToReg(Allocas, DT, DF, TD);
00117     NumPromoted += Allocas.size();
00118     Changed = true;
00119   }
00120 
00121   return Changed;
00122 }
00123 
00124 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
00125 // which runs on all of the malloc/alloca instructions in the function, removing
00126 // them if they are only used by getelementptr instructions.
00127 //
00128 bool SROA::performScalarRepl(Function &F) {
00129   std::vector<AllocationInst*> WorkList;
00130 
00131   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
00132   BasicBlock &BB = F.getEntryBlock();
00133   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
00134     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
00135       WorkList.push_back(A);
00136 
00137   // Process the worklist
00138   bool Changed = false;
00139   while (!WorkList.empty()) {
00140     AllocationInst *AI = WorkList.back();
00141     WorkList.pop_back();
00142     
00143     // If we can turn this aggregate value (potentially with casts) into a
00144     // simple scalar value that can be mem2reg'd into a register value.
00145     bool IsNotTrivial = false;
00146     if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
00147       if (IsNotTrivial && ActualType != Type::VoidTy) {
00148         ConvertToScalar(AI, ActualType);
00149         Changed = true;
00150         continue;
00151       }
00152 
00153     // We cannot transform the allocation instruction if it is an array
00154     // allocation (allocations OF arrays are ok though), and an allocation of a
00155     // scalar value cannot be decomposed at all.
00156     //
00157     if (AI->isArrayAllocation() ||
00158         (!isa<StructType>(AI->getAllocatedType()) &&
00159          !isa<ArrayType>(AI->getAllocatedType()))) continue;
00160 
00161     // Check that all of the users of the allocation are capable of being
00162     // transformed.
00163     switch (isSafeAllocaToScalarRepl(AI)) {
00164     default: assert(0 && "Unexpected value!");
00165     case 0:  // Not safe to scalar replace.
00166       continue;
00167     case 1:  // Safe, but requires cleanup/canonicalizations first
00168       CanonicalizeAllocaUsers(AI);
00169     case 3:  // Safe to scalar replace.
00170       break;
00171     }
00172 
00173     DEBUG(std::cerr << "Found inst to xform: " << *AI);
00174     Changed = true;
00175 
00176     std::vector<AllocaInst*> ElementAllocas;
00177     if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
00178       ElementAllocas.reserve(ST->getNumContainedTypes());
00179       for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
00180         AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 
00181                                         AI->getAlignment(),
00182                                         AI->getName() + "." + utostr(i), AI);
00183         ElementAllocas.push_back(NA);
00184         WorkList.push_back(NA);  // Add to worklist for recursive processing
00185       }
00186     } else {
00187       const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
00188       ElementAllocas.reserve(AT->getNumElements());
00189       const Type *ElTy = AT->getElementType();
00190       for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
00191         AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
00192                                         AI->getName() + "." + utostr(i), AI);
00193         ElementAllocas.push_back(NA);
00194         WorkList.push_back(NA);  // Add to worklist for recursive processing
00195       }
00196     }
00197 
00198     // Now that we have created the alloca instructions that we want to use,
00199     // expand the getelementptr instructions to use them.
00200     //
00201     while (!AI->use_empty()) {
00202       Instruction *User = cast<Instruction>(AI->use_back());
00203       GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
00204       // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
00205       unsigned Idx =
00206          (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
00207 
00208       assert(Idx < ElementAllocas.size() && "Index out of range?");
00209       AllocaInst *AllocaToUse = ElementAllocas[Idx];
00210 
00211       Value *RepValue;
00212       if (GEPI->getNumOperands() == 3) {
00213         // Do not insert a new getelementptr instruction with zero indices, only
00214         // to have it optimized out later.
00215         RepValue = AllocaToUse;
00216       } else {
00217         // We are indexing deeply into the structure, so we still need a
00218         // getelement ptr instruction to finish the indexing.  This may be
00219         // expanded itself once the worklist is rerun.
00220         //
00221         std::string OldName = GEPI->getName();  // Steal the old name.
00222         std::vector<Value*> NewArgs;
00223         NewArgs.push_back(Constant::getNullValue(Type::IntTy));
00224         NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
00225         GEPI->setName("");
00226         RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
00227       }
00228 
00229       // Move all of the users over to the new GEP.
00230       GEPI->replaceAllUsesWith(RepValue);
00231       // Delete the old GEP
00232       GEPI->eraseFromParent();
00233     }
00234 
00235     // Finally, delete the Alloca instruction
00236     AI->getParent()->getInstList().erase(AI);
00237     NumReplaced++;
00238   }
00239 
00240   return Changed;
00241 }
00242 
00243 
00244 /// isSafeElementUse - Check to see if this use is an allowed use for a
00245 /// getelementptr instruction of an array aggregate allocation.
00246 ///
00247 int SROA::isSafeElementUse(Value *Ptr) {
00248   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
00249        I != E; ++I) {
00250     Instruction *User = cast<Instruction>(*I);
00251     switch (User->getOpcode()) {
00252     case Instruction::Load:  break;
00253     case Instruction::Store:
00254       // Store is ok if storing INTO the pointer, not storing the pointer
00255       if (User->getOperand(0) == Ptr) return 0;
00256       break;
00257     case Instruction::GetElementPtr: {
00258       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
00259       if (GEP->getNumOperands() > 1) {
00260         if (!isa<Constant>(GEP->getOperand(1)) ||
00261             !cast<Constant>(GEP->getOperand(1))->isNullValue())
00262           return 0;  // Using pointer arithmetic to navigate the array...
00263       }
00264       if (!isSafeElementUse(GEP)) return 0;
00265       break;
00266     }
00267     default:
00268       DEBUG(std::cerr << "  Transformation preventing inst: " << *User);
00269       return 0;
00270     }
00271   }
00272   return 3;  // All users look ok :)
00273 }
00274 
00275 /// AllUsersAreLoads - Return true if all users of this value are loads.
00276 static bool AllUsersAreLoads(Value *Ptr) {
00277   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
00278        I != E; ++I)
00279     if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
00280       return false;
00281   return true;
00282 }
00283 
00284 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
00285 /// aggregate allocation.
00286 ///
00287 int SROA::isSafeUseOfAllocation(Instruction *User) {
00288   if (!isa<GetElementPtrInst>(User)) return 0;
00289 
00290   GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
00291   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
00292 
00293   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
00294   if (I == E ||
00295       I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
00296     return 0;
00297 
00298   ++I;
00299   if (I == E) return 0;  // ran out of GEP indices??
00300 
00301   // If this is a use of an array allocation, do a bit more checking for sanity.
00302   if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
00303     uint64_t NumElements = AT->getNumElements();
00304 
00305     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
00306       // Check to make sure that index falls within the array.  If not,
00307       // something funny is going on, so we won't do the optimization.
00308       //
00309       if (cast<ConstantInt>(GEPI->getOperand(2))->getRawValue() >= NumElements)
00310         return 0;
00311 
00312       // We cannot scalar repl this level of the array unless any array
00313       // sub-indices are in-range constants.  In particular, consider:
00314       // A[0][i].  We cannot know that the user isn't doing invalid things like
00315       // allowing i to index an out-of-range subscript that accesses A[1].
00316       //
00317       // Scalar replacing *just* the outer index of the array is probably not
00318       // going to be a win anyway, so just give up.
00319       for (++I; I != E && isa<ArrayType>(*I); ++I) {
00320         const ArrayType *SubArrayTy = cast<ArrayType>(*I);
00321         uint64_t NumElements = SubArrayTy->getNumElements();
00322         if (!isa<ConstantInt>(I.getOperand())) return 0;
00323         if (cast<ConstantInt>(I.getOperand())->getRawValue() >= NumElements)
00324           return 0;
00325       }
00326       
00327     } else {
00328       // If this is an array index and the index is not constant, we cannot
00329       // promote... that is unless the array has exactly one or two elements in
00330       // it, in which case we CAN promote it, but we have to canonicalize this
00331       // out if this is the only problem.
00332       if ((NumElements == 1 || NumElements == 2) &&
00333           AllUsersAreLoads(GEPI))
00334         return 1;  // Canonicalization required!
00335       return 0;
00336     }
00337   }
00338 
00339   // If there are any non-simple uses of this getelementptr, make sure to reject
00340   // them.
00341   return isSafeElementUse(GEPI);
00342 }
00343 
00344 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
00345 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
00346 /// or 1 if safe after canonicalization has been performed.
00347 ///
00348 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
00349   // Loop over the use list of the alloca.  We can only transform it if all of
00350   // the users are safe to transform.
00351   //
00352   int isSafe = 3;
00353   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
00354        I != E; ++I) {
00355     isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I));
00356     if (isSafe == 0) {
00357       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
00358             << **I);
00359       return 0;
00360     }
00361   }
00362   // If we require cleanup, isSafe is now 1, otherwise it is 3.
00363   return isSafe;
00364 }
00365 
00366 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
00367 /// allocation, but only if cleaned up, perform the cleanups required.
00368 void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
00369   // At this point, we know that the end result will be SROA'd and promoted, so
00370   // we can insert ugly code if required so long as sroa+mem2reg will clean it
00371   // up.
00372   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
00373        UI != E; ) {
00374     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++);
00375     gep_type_iterator I = gep_type_begin(GEPI);
00376     ++I;
00377 
00378     if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
00379       uint64_t NumElements = AT->getNumElements();
00380 
00381       if (!isa<ConstantInt>(I.getOperand())) {
00382         if (NumElements == 1) {
00383           GEPI->setOperand(2, Constant::getNullValue(Type::IntTy));
00384         } else {
00385           assert(NumElements == 2 && "Unhandled case!");
00386           // All users of the GEP must be loads.  At each use of the GEP, insert
00387           // two loads of the appropriate indexed GEP and select between them.
00388           Value *IsOne = BinaryOperator::createSetNE(I.getOperand(),
00389                               Constant::getNullValue(I.getOperand()->getType()),
00390                                                      "isone", GEPI);
00391           // Insert the new GEP instructions, which are properly indexed.
00392           std::vector<Value*> Indices(GEPI->op_begin()+1, GEPI->op_end());
00393           Indices[1] = Constant::getNullValue(Type::IntTy);
00394           Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
00395                                                  GEPI->getName()+".0", GEPI);
00396           Indices[1] = ConstantInt::get(Type::IntTy, 1);
00397           Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices,
00398                                                 GEPI->getName()+".1", GEPI);
00399           // Replace all loads of the variable index GEP with loads from both
00400           // indexes and a select.
00401           while (!GEPI->use_empty()) {
00402             LoadInst *LI = cast<LoadInst>(GEPI->use_back());
00403             Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
00404             Value *One  = new LoadInst(OneIdx , LI->getName()+".1", LI);
00405             Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI);
00406             LI->replaceAllUsesWith(R);
00407             LI->eraseFromParent();
00408           }
00409           GEPI->eraseFromParent();
00410         }
00411       }
00412     }
00413   }
00414 }
00415 
00416 /// MergeInType - Add the 'In' type to the accumulated type so far.  If the
00417 /// types are incompatible, return true, otherwise update Accum and return
00418 /// false.
00419 ///
00420 /// There are two cases we handle here:
00421 ///   1) An effectively integer union, where the pieces are stored into as
00422 ///      smaller integers (common with byte swap and other idioms).
00423 ///   2) A union of a vector and its elements.  Here we turn element accesses
00424 ///      into insert/extract element operations.
00425 static bool MergeInType(const Type *In, const Type *&Accum) {
00426   // If this is our first type, just use it.
00427   const PackedType *PTy;
00428   if (Accum == Type::VoidTy || In == Accum) {
00429     Accum = In;
00430   } else if (In->isIntegral() && Accum->isIntegral()) {   // integer union.
00431     // Otherwise pick whichever type is larger.
00432     if (In->getTypeID() > Accum->getTypeID())
00433       Accum = In;
00434   } else if ((PTy = dyn_cast<PackedType>(Accum)) && 
00435              PTy->getElementType() == In) {
00436     // Accum is a vector, and we are accessing an element: ok.
00437   } else if ((PTy = dyn_cast<PackedType>(In)) && 
00438              PTy->getElementType() == Accum) {
00439     // In is a vector, and accum is an element: ok, remember In.
00440     Accum = In;
00441   } else {
00442     return true;
00443   }
00444   return false;
00445 }
00446 
00447 /// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least
00448 /// as big as the specified type.  If there is no suitable type, this returns
00449 /// null.
00450 const Type *getUIntAtLeastAsBitAs(unsigned NumBits) {
00451   if (NumBits > 64) return 0;
00452   if (NumBits > 32) return Type::ULongTy;
00453   if (NumBits > 16) return Type::UIntTy;
00454   if (NumBits > 8) return Type::UShortTy;
00455   return Type::UByteTy;    
00456 }
00457 
00458 /// CanConvertToScalar - V is a pointer.  If we can convert the pointee to a
00459 /// single scalar integer type, return that type.  Further, if the use is not
00460 /// a completely trivial use that mem2reg could promote, set IsNotTrivial.  If
00461 /// there are no uses of this pointer, return Type::VoidTy to differentiate from
00462 /// failure.
00463 ///
00464 const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
00465   const Type *UsedType = Type::VoidTy; // No uses, no forced type.
00466   const TargetData &TD = getAnalysis<TargetData>();
00467   const PointerType *PTy = cast<PointerType>(V->getType());
00468 
00469   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
00470     Instruction *User = cast<Instruction>(*UI);
00471     
00472     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
00473       if (MergeInType(LI->getType(), UsedType))
00474         return 0;
00475       
00476     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00477       // Storing the pointer, not the into the value?
00478       if (SI->getOperand(0) == V) return 0;
00479       
00480       // NOTE: We could handle storing of FP imms into integers here!
00481       
00482       if (MergeInType(SI->getOperand(0)->getType(), UsedType))
00483         return 0;
00484     } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
00485       if (!isa<PointerType>(CI->getType())) return 0;
00486       IsNotTrivial = true;
00487       const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
00488       if (!SubTy || MergeInType(SubTy, UsedType)) return 0;
00489     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
00490       // Check to see if this is stepping over an element: GEP Ptr, int C
00491       if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
00492         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getRawValue();
00493         unsigned ElSize = TD.getTypeSize(PTy->getElementType());
00494         unsigned BitOffset = Idx*ElSize*8;
00495         if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
00496         
00497         IsNotTrivial = true;
00498         const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
00499         if (SubElt == 0) return 0;
00500         if (SubElt != Type::VoidTy && SubElt->isInteger()) {
00501           const Type *NewTy = 
00502             getUIntAtLeastAsBitAs(SubElt->getPrimitiveSizeInBits()+BitOffset);
00503           if (NewTy == 0 || MergeInType(NewTy, UsedType)) return 0;
00504           continue;
00505         }
00506       } else if (GEP->getNumOperands() == 3 && 
00507                  isa<ConstantInt>(GEP->getOperand(1)) &&
00508                  isa<ConstantInt>(GEP->getOperand(2)) &&
00509                  cast<Constant>(GEP->getOperand(1))->isNullValue()) {
00510         // We are stepping into an element, e.g. a structure or an array:
00511         // GEP Ptr, int 0, uint C
00512         const Type *AggTy = PTy->getElementType();
00513         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
00514         
00515         if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
00516           if (Idx >= ATy->getNumElements()) return 0;  // Out of range.
00517         } else if (const PackedType *PackedTy = dyn_cast<PackedType>(AggTy)) {
00518           // Getting an element of the packed vector.
00519           if (Idx >= PackedTy->getNumElements()) return 0;  // Out of range.
00520 
00521           // Merge in the packed type.
00522           if (MergeInType(PackedTy, UsedType)) return 0;
00523           
00524           const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
00525           if (SubTy == 0) return 0;
00526           
00527           if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType))
00528             return 0;
00529 
00530           // We'll need to change this to an insert/extract element operation.
00531           IsNotTrivial = true;
00532           continue;    // Everything looks ok
00533           
00534         } else if (isa<StructType>(AggTy)) {
00535           // Structs are always ok.
00536         } else {
00537           return 0;
00538         }
00539         const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8);
00540         if (NTy == 0 || MergeInType(NTy, UsedType)) return 0;
00541         const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
00542         if (SubTy == 0) return 0;
00543         if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType))
00544           return 0;
00545         continue;    // Everything looks ok
00546       }
00547       return 0;
00548     } else {
00549       // Cannot handle this!
00550       return 0;
00551     }
00552   }
00553   
00554   return UsedType;
00555 }
00556 
00557 /// ConvertToScalar - The specified alloca passes the CanConvertToScalar
00558 /// predicate and is non-trivial.  Convert it to something that can be trivially
00559 /// promoted into a register by mem2reg.
00560 void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
00561   DEBUG(std::cerr << "CONVERT TO SCALAR: " << *AI << "  TYPE = "
00562                   << *ActualTy << "\n");
00563   ++NumConverted;
00564   
00565   BasicBlock *EntryBlock = AI->getParent();
00566   assert(EntryBlock == &EntryBlock->getParent()->front() &&
00567          "Not in the entry block!");
00568   EntryBlock->getInstList().remove(AI);  // Take the alloca out of the program.
00569   
00570   if (ActualTy->isInteger())
00571     ActualTy = ActualTy->getUnsignedVersion();
00572   
00573   // Create and insert the alloca.
00574   AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
00575                                      EntryBlock->begin());
00576   ConvertUsesToScalar(AI, NewAI, 0);
00577   delete AI;
00578 }
00579 
00580 
00581 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
00582 /// directly.  This happens when we are converting an "integer union" to a
00583 /// single integer scalar, or when we are converting a "vector union" to a
00584 /// vector with insert/extractelement instructions.
00585 ///
00586 /// Offset is an offset from the original alloca, in bits that need to be
00587 /// shifted to the right.  By the end of this, there should be no uses of Ptr.
00588 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
00589   bool isVectorInsert = isa<PackedType>(NewAI->getType()->getElementType());
00590   while (!Ptr->use_empty()) {
00591     Instruction *User = cast<Instruction>(Ptr->use_back());
00592     
00593     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
00594       // The load is a bit extract from NewAI shifted right by Offset bits.
00595       Value *NV = new LoadInst(NewAI, LI->getName(), LI);
00596       if (NV->getType() != LI->getType()) {
00597         if (const PackedType *PTy = dyn_cast<PackedType>(NV->getType())) {
00598           // Must be an element access.
00599           unsigned Elt = Offset/PTy->getElementType()->getPrimitiveSizeInBits();
00600           NV = new ExtractElementInst(NV, ConstantUInt::get(Type::UIntTy, Elt),
00601                                       "tmp", LI);
00602         } else {
00603           assert(NV->getType()->isInteger() && "Unknown promotion!");
00604           if (Offset && Offset < NV->getType()->getPrimitiveSizeInBits())
00605             NV = new ShiftInst(Instruction::Shr, NV,
00606                                ConstantUInt::get(Type::UByteTy, Offset),
00607                                LI->getName(), LI);
00608           NV = new CastInst(NV, LI->getType(), LI->getName(), LI);
00609         }
00610       }
00611       LI->replaceAllUsesWith(NV);
00612       LI->eraseFromParent();
00613     } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00614       assert(SI->getOperand(0) != Ptr && "Consistency error!");
00615 
00616       // Convert the stored type to the actual type, shift it left to insert
00617       // then 'or' into place.
00618       Value *SV = SI->getOperand(0);
00619       const Type *AllocaType = NewAI->getType()->getElementType();
00620       if (SV->getType() != AllocaType) {
00621         Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
00622         
00623         if (const PackedType *PTy = dyn_cast<PackedType>(AllocaType)) {
00624           // Must be an element insertion.
00625           unsigned Elt = Offset/PTy->getElementType()->getPrimitiveSizeInBits();
00626           SV = new InsertElementInst(Old, SV,
00627                                      ConstantUInt::get(Type::UIntTy, Elt),
00628                                      "tmp", SI);
00629         } else {
00630           // If SV is signed, convert it to unsigned, so that the next cast zero
00631           // extends the value.
00632           if (SV->getType()->isSigned())
00633             SV = new CastInst(SV, SV->getType()->getUnsignedVersion(),
00634                               SV->getName(), SI);
00635           SV = new CastInst(SV, Old->getType(), SV->getName(), SI);
00636           if (Offset && Offset < SV->getType()->getPrimitiveSizeInBits())
00637             SV = new ShiftInst(Instruction::Shl, SV,
00638                                ConstantUInt::get(Type::UByteTy, Offset),
00639                                SV->getName()+".adj", SI);
00640           // Mask out the bits we are about to insert from the old value.
00641           unsigned TotalBits = SV->getType()->getPrimitiveSizeInBits();
00642           unsigned InsertBits =
00643             SI->getOperand(0)->getType()->getPrimitiveSizeInBits();
00644           if (TotalBits != InsertBits) {
00645             assert(TotalBits > InsertBits);
00646             uint64_t Mask = ~(((1ULL << InsertBits)-1) << Offset);
00647             if (TotalBits != 64)
00648               Mask = Mask & ((1ULL << TotalBits)-1);
00649             Old = BinaryOperator::createAnd(Old,
00650                                         ConstantUInt::get(Old->getType(), Mask),
00651                                             Old->getName()+".mask", SI);
00652             SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI);
00653           }
00654         }
00655       }
00656       new StoreInst(SV, NewAI, SI);
00657       SI->eraseFromParent();
00658       
00659     } else if (CastInst *CI = dyn_cast<CastInst>(User)) {
00660       unsigned NewOff = Offset;
00661       const TargetData &TD = getAnalysis<TargetData>();
00662       if (TD.isBigEndian() && !isVectorInsert) {
00663         // Adjust the pointer.  For example, storing 16-bits into a 32-bit
00664         // alloca with just a cast makes it modify the top 16-bits.
00665         const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType();
00666         const Type *DstTy = cast<PointerType>(CI->getType())->getElementType();
00667         int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8;
00668         NewOff += PtrDiffBits;
00669       }
00670       ConvertUsesToScalar(CI, NewAI, NewOff);
00671       CI->eraseFromParent();
00672     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
00673       const PointerType *AggPtrTy = 
00674         cast<PointerType>(GEP->getOperand(0)->getType());
00675       const TargetData &TD = getAnalysis<TargetData>();
00676       unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8;
00677       
00678       // Check to see if this is stepping over an element: GEP Ptr, int C
00679       unsigned NewOffset = Offset;
00680       if (GEP->getNumOperands() == 2) {
00681         unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getRawValue();
00682         unsigned BitOffset = Idx*AggSizeInBits;
00683         
00684         if (TD.isLittleEndian() || isVectorInsert)
00685           NewOffset += BitOffset;
00686         else
00687           NewOffset -= BitOffset;
00688         
00689       } else if (GEP->getNumOperands() == 3) {
00690         // We know that operand #2 is zero.
00691         unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
00692         const Type *AggTy = AggPtrTy->getElementType();
00693         if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
00694           unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8;
00695 
00696           if (TD.isLittleEndian() || isVectorInsert)
00697             NewOffset += ElSizeBits*Idx;
00698           else
00699             NewOffset += AggSizeInBits-ElSizeBits*(Idx+1);
00700         } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
00701           unsigned EltBitOffset = TD.getStructLayout(STy)->MemberOffsets[Idx]*8;
00702           
00703           if (TD.isLittleEndian() || isVectorInsert)
00704             NewOffset += EltBitOffset;
00705           else {
00706             const PointerType *ElPtrTy = cast<PointerType>(GEP->getType());
00707             unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8;
00708             NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits);
00709           }
00710           
00711         } else {
00712           assert(0 && "Unsupported operation!");
00713           abort();
00714         }
00715       } else {
00716         assert(0 && "Unsupported operation!");
00717         abort();
00718       }
00719       ConvertUsesToScalar(GEP, NewAI, NewOffset);
00720       GEP->eraseFromParent();
00721     } else {
00722       assert(0 && "Unsupported operation!");
00723       abort();
00724     }
00725   }
00726 }