LLVM API Documentation

InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
00001 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
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 file implements the visit functions for load, store and alloca.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/Analysis/Loads.h"
00017 #include "llvm/IR/DataLayout.h"
00018 #include "llvm/IR/IntrinsicInst.h"
00019 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00020 #include "llvm/Transforms/Utils/Local.h"
00021 using namespace llvm;
00022 
00023 #define DEBUG_TYPE "instcombine"
00024 
00025 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
00026 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
00027 
00028 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
00029 /// some part of a constant global variable.  This intentionally only accepts
00030 /// constant expressions because we can't rewrite arbitrary instructions.
00031 static bool pointsToConstantGlobal(Value *V) {
00032   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00033     return GV->isConstant();
00034   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00035     if (CE->getOpcode() == Instruction::BitCast ||
00036         CE->getOpcode() == Instruction::GetElementPtr)
00037       return pointsToConstantGlobal(CE->getOperand(0));
00038   return false;
00039 }
00040 
00041 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
00042 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
00043 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
00044 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
00045 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
00046 /// the alloca, and if the source pointer is a pointer to a constant global, we
00047 /// can optimize this.
00048 static bool
00049 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
00050                                SmallVectorImpl<Instruction *> &ToDelete,
00051                                bool IsOffset = false) {
00052   // We track lifetime intrinsics as we encounter them.  If we decide to go
00053   // ahead and replace the value with the global, this lets the caller quickly
00054   // eliminate the markers.
00055 
00056   for (Use &U : V->uses()) {
00057     Instruction *I = cast<Instruction>(U.getUser());
00058 
00059     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00060       // Ignore non-volatile loads, they are always ok.
00061       if (!LI->isSimple()) return false;
00062       continue;
00063     }
00064 
00065     if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
00066       // If uses of the bitcast are ok, we are ok.
00067       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
00068         return false;
00069       continue;
00070     }
00071     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00072       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
00073       // doesn't, it does.
00074       if (!isOnlyCopiedFromConstantGlobal(
00075               GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
00076         return false;
00077       continue;
00078     }
00079 
00080     if (CallSite CS = I) {
00081       // If this is the function being called then we treat it like a load and
00082       // ignore it.
00083       if (CS.isCallee(&U))
00084         continue;
00085 
00086       // Inalloca arguments are clobbered by the call.
00087       unsigned ArgNo = CS.getArgumentNo(&U);
00088       if (CS.isInAllocaArgument(ArgNo))
00089         return false;
00090 
00091       // If this is a readonly/readnone call site, then we know it is just a
00092       // load (but one that potentially returns the value itself), so we can
00093       // ignore it if we know that the value isn't captured.
00094       if (CS.onlyReadsMemory() &&
00095           (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
00096         continue;
00097 
00098       // If this is being passed as a byval argument, the caller is making a
00099       // copy, so it is only a read of the alloca.
00100       if (CS.isByValArgument(ArgNo))
00101         continue;
00102     }
00103 
00104     // Lifetime intrinsics can be handled by the caller.
00105     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00106       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00107           II->getIntrinsicID() == Intrinsic::lifetime_end) {
00108         assert(II->use_empty() && "Lifetime markers have no result to use!");
00109         ToDelete.push_back(II);
00110         continue;
00111       }
00112     }
00113 
00114     // If this is isn't our memcpy/memmove, reject it as something we can't
00115     // handle.
00116     MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
00117     if (MI == 0)
00118       return false;
00119 
00120     // If the transfer is using the alloca as a source of the transfer, then
00121     // ignore it since it is a load (unless the transfer is volatile).
00122     if (U.getOperandNo() == 1) {
00123       if (MI->isVolatile()) return false;
00124       continue;
00125     }
00126 
00127     // If we already have seen a copy, reject the second one.
00128     if (TheCopy) return false;
00129 
00130     // If the pointer has been offset from the start of the alloca, we can't
00131     // safely handle this.
00132     if (IsOffset) return false;
00133 
00134     // If the memintrinsic isn't using the alloca as the dest, reject it.
00135     if (U.getOperandNo() != 0) return false;
00136 
00137     // If the source of the memcpy/move is not a constant global, reject it.
00138     if (!pointsToConstantGlobal(MI->getSource()))
00139       return false;
00140 
00141     // Otherwise, the transform is safe.  Remember the copy instruction.
00142     TheCopy = MI;
00143   }
00144   return true;
00145 }
00146 
00147 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
00148 /// modified by a copy from a constant global.  If we can prove this, we can
00149 /// replace any uses of the alloca with uses of the global directly.
00150 static MemTransferInst *
00151 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
00152                                SmallVectorImpl<Instruction *> &ToDelete) {
00153   MemTransferInst *TheCopy = 0;
00154   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
00155     return TheCopy;
00156   return 0;
00157 }
00158 
00159 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
00160   // Ensure that the alloca array size argument has type intptr_t, so that
00161   // any casting is exposed early.
00162   if (DL) {
00163     Type *IntPtrTy = DL->getIntPtrType(AI.getType());
00164     if (AI.getArraySize()->getType() != IntPtrTy) {
00165       Value *V = Builder->CreateIntCast(AI.getArraySize(),
00166                                         IntPtrTy, false);
00167       AI.setOperand(0, V);
00168       return &AI;
00169     }
00170   }
00171 
00172   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
00173   if (AI.isArrayAllocation()) {  // Check C != 1
00174     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
00175       Type *NewTy =
00176         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
00177       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
00178       New->setAlignment(AI.getAlignment());
00179 
00180       // Scan to the end of the allocation instructions, to skip over a block of
00181       // allocas if possible...also skip interleaved debug info
00182       //
00183       BasicBlock::iterator It = New;
00184       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
00185 
00186       // Now that I is pointing to the first non-allocation-inst in the block,
00187       // insert our getelementptr instruction...
00188       //
00189       Type *IdxTy = DL
00190                   ? DL->getIntPtrType(AI.getType())
00191                   : Type::getInt64Ty(AI.getContext());
00192       Value *NullIdx = Constant::getNullValue(IdxTy);
00193       Value *Idx[2] = { NullIdx, NullIdx };
00194       Instruction *GEP =
00195         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
00196       InsertNewInstBefore(GEP, *It);
00197 
00198       // Now make everything use the getelementptr instead of the original
00199       // allocation.
00200       return ReplaceInstUsesWith(AI, GEP);
00201     } else if (isa<UndefValue>(AI.getArraySize())) {
00202       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
00203     }
00204   }
00205 
00206   if (DL && AI.getAllocatedType()->isSized()) {
00207     // If the alignment is 0 (unspecified), assign it the preferred alignment.
00208     if (AI.getAlignment() == 0)
00209       AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
00210 
00211     // Move all alloca's of zero byte objects to the entry block and merge them
00212     // together.  Note that we only do this for alloca's, because malloc should
00213     // allocate and return a unique pointer, even for a zero byte allocation.
00214     if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
00215       // For a zero sized alloca there is no point in doing an array allocation.
00216       // This is helpful if the array size is a complicated expression not used
00217       // elsewhere.
00218       if (AI.isArrayAllocation()) {
00219         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
00220         return &AI;
00221       }
00222 
00223       // Get the first instruction in the entry block.
00224       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
00225       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
00226       if (FirstInst != &AI) {
00227         // If the entry block doesn't start with a zero-size alloca then move
00228         // this one to the start of the entry block.  There is no problem with
00229         // dominance as the array size was forced to a constant earlier already.
00230         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
00231         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
00232             DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
00233           AI.moveBefore(FirstInst);
00234           return &AI;
00235         }
00236 
00237         // If the alignment of the entry block alloca is 0 (unspecified),
00238         // assign it the preferred alignment.
00239         if (EntryAI->getAlignment() == 0)
00240           EntryAI->setAlignment(
00241             DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
00242         // Replace this zero-sized alloca with the one at the start of the entry
00243         // block after ensuring that the address will be aligned enough for both
00244         // types.
00245         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
00246                                      AI.getAlignment());
00247         EntryAI->setAlignment(MaxAlign);
00248         if (AI.getType() != EntryAI->getType())
00249           return new BitCastInst(EntryAI, AI.getType());
00250         return ReplaceInstUsesWith(AI, EntryAI);
00251       }
00252     }
00253   }
00254 
00255   if (AI.getAlignment()) {
00256     // Check to see if this allocation is only modified by a memcpy/memmove from
00257     // a constant global whose alignment is equal to or exceeds that of the
00258     // allocation.  If this is the case, we can change all users to use
00259     // the constant global instead.  This is commonly produced by the CFE by
00260     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
00261     // is only subsequently read.
00262     SmallVector<Instruction *, 4> ToDelete;
00263     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
00264       unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
00265                                                         AI.getAlignment(), DL);
00266       if (AI.getAlignment() <= SourceAlign) {
00267         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
00268         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
00269         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
00270           EraseInstFromFunction(*ToDelete[i]);
00271         Constant *TheSrc = cast<Constant>(Copy->getSource());
00272         Constant *Cast
00273           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
00274         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
00275         EraseInstFromFunction(*Copy);
00276         ++NumGlobalCopies;
00277         return NewI;
00278       }
00279     }
00280   }
00281 
00282   // At last, use the generic allocation site handler to aggressively remove
00283   // unused allocas.
00284   return visitAllocSite(AI);
00285 }
00286 
00287 
00288 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
00289 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
00290                                         const DataLayout *DL) {
00291   User *CI = cast<User>(LI.getOperand(0));
00292   Value *CastOp = CI->getOperand(0);
00293 
00294   PointerType *DestTy = cast<PointerType>(CI->getType());
00295   Type *DestPTy = DestTy->getElementType();
00296   if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
00297 
00298     // If the address spaces don't match, don't eliminate the cast.
00299     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
00300       return 0;
00301 
00302     Type *SrcPTy = SrcTy->getElementType();
00303 
00304     if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
00305          DestPTy->isVectorTy()) {
00306       // If the source is an array, the code below will not succeed.  Check to
00307       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
00308       // constants.
00309       if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
00310         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
00311           if (ASrcTy->getNumElements() != 0) {
00312             Type *IdxTy = DL
00313                         ? DL->getIntPtrType(SrcTy)
00314                         : Type::getInt64Ty(SrcTy->getContext());
00315             Value *Idx = Constant::getNullValue(IdxTy);
00316             Value *Idxs[2] = { Idx, Idx };
00317             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
00318             SrcTy = cast<PointerType>(CastOp->getType());
00319             SrcPTy = SrcTy->getElementType();
00320           }
00321 
00322       if (IC.getDataLayout() &&
00323           (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
00324             SrcPTy->isVectorTy()) &&
00325           // Do not allow turning this into a load of an integer, which is then
00326           // casted to a pointer, this pessimizes pointer analysis a lot.
00327           (SrcPTy->isPtrOrPtrVectorTy() ==
00328            LI.getType()->isPtrOrPtrVectorTy()) &&
00329           IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
00330                IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
00331 
00332         // Okay, we are casting from one integer or pointer type to another of
00333         // the same size.  Instead of casting the pointer before the load, cast
00334         // the result of the loaded value.
00335         LoadInst *NewLoad =
00336           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
00337         NewLoad->setAlignment(LI.getAlignment());
00338         NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
00339         // Now cast the result of the load.
00340         PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
00341         PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
00342         if (OldTy && NewTy &&
00343             OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
00344           return new AddrSpaceCastInst(NewLoad, LI.getType());
00345         }
00346 
00347         return new BitCastInst(NewLoad, LI.getType());
00348       }
00349     }
00350   }
00351   return 0;
00352 }
00353 
00354 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
00355   Value *Op = LI.getOperand(0);
00356 
00357   // Attempt to improve the alignment.
00358   if (DL) {
00359     unsigned KnownAlign =
00360       getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
00361     unsigned LoadAlign = LI.getAlignment();
00362     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
00363       DL->getABITypeAlignment(LI.getType());
00364 
00365     if (KnownAlign > EffectiveLoadAlign)
00366       LI.setAlignment(KnownAlign);
00367     else if (LoadAlign == 0)
00368       LI.setAlignment(EffectiveLoadAlign);
00369   }
00370 
00371   // load (cast X) --> cast (load X) iff safe.
00372   if (isa<CastInst>(Op))
00373     if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
00374       return Res;
00375 
00376   // None of the following transforms are legal for volatile/atomic loads.
00377   // FIXME: Some of it is okay for atomic loads; needs refactoring.
00378   if (!LI.isSimple()) return 0;
00379 
00380   // Do really simple store-to-load forwarding and load CSE, to catch cases
00381   // where there are several consecutive memory accesses to the same location,
00382   // separated by a few arithmetic operations.
00383   BasicBlock::iterator BBI = &LI;
00384   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
00385     return ReplaceInstUsesWith(LI, AvailableVal);
00386 
00387   // load(gep null, ...) -> unreachable
00388   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
00389     const Value *GEPI0 = GEPI->getOperand(0);
00390     // TODO: Consider a target hook for valid address spaces for this xform.
00391     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
00392       // Insert a new store to null instruction before the load to indicate
00393       // that this code is not reachable.  We do this instead of inserting
00394       // an unreachable instruction directly because we cannot modify the
00395       // CFG.
00396       new StoreInst(UndefValue::get(LI.getType()),
00397                     Constant::getNullValue(Op->getType()), &LI);
00398       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00399     }
00400   }
00401 
00402   // load null/undef -> unreachable
00403   // TODO: Consider a target hook for valid address spaces for this xform.
00404   if (isa<UndefValue>(Op) ||
00405       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
00406     // Insert a new store to null instruction before the load to indicate that
00407     // this code is not reachable.  We do this instead of inserting an
00408     // unreachable instruction directly because we cannot modify the CFG.
00409     new StoreInst(UndefValue::get(LI.getType()),
00410                   Constant::getNullValue(Op->getType()), &LI);
00411     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00412   }
00413 
00414   // Instcombine load (constantexpr_cast global) -> cast (load global)
00415   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
00416     if (CE->isCast())
00417       if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
00418         return Res;
00419 
00420   if (Op->hasOneUse()) {
00421     // Change select and PHI nodes to select values instead of addresses: this
00422     // helps alias analysis out a lot, allows many others simplifications, and
00423     // exposes redundancy in the code.
00424     //
00425     // Note that we cannot do the transformation unless we know that the
00426     // introduced loads cannot trap!  Something like this is valid as long as
00427     // the condition is always false: load (select bool %C, int* null, int* %G),
00428     // but it would not be valid if we transformed it to load from null
00429     // unconditionally.
00430     //
00431     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
00432       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
00433       unsigned Align = LI.getAlignment();
00434       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
00435           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
00436         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
00437                                            SI->getOperand(1)->getName()+".val");
00438         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
00439                                            SI->getOperand(2)->getName()+".val");
00440         V1->setAlignment(Align);
00441         V2->setAlignment(Align);
00442         return SelectInst::Create(SI->getCondition(), V1, V2);
00443       }
00444 
00445       // load (select (cond, null, P)) -> load P
00446       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
00447         if (C->isNullValue()) {
00448           LI.setOperand(0, SI->getOperand(2));
00449           return &LI;
00450         }
00451 
00452       // load (select (cond, P, null)) -> load P
00453       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
00454         if (C->isNullValue()) {
00455           LI.setOperand(0, SI->getOperand(1));
00456           return &LI;
00457         }
00458     }
00459   }
00460   return 0;
00461 }
00462 
00463 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
00464 /// when possible.  This makes it generally easy to do alias analysis and/or
00465 /// SROA/mem2reg of the memory object.
00466 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
00467   User *CI = cast<User>(SI.getOperand(1));
00468   Value *CastOp = CI->getOperand(0);
00469 
00470   Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
00471   PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
00472   if (SrcTy == 0) return 0;
00473 
00474   Type *SrcPTy = SrcTy->getElementType();
00475 
00476   if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
00477     return 0;
00478 
00479   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
00480   /// to its first element.  This allows us to handle things like:
00481   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
00482   /// on 32-bit hosts.
00483   SmallVector<Value*, 4> NewGEPIndices;
00484 
00485   // If the source is an array, the code below will not succeed.  Check to
00486   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
00487   // constants.
00488   if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
00489     // Index through pointer.
00490     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
00491     NewGEPIndices.push_back(Zero);
00492 
00493     while (1) {
00494       if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
00495         if (!STy->getNumElements()) /* Struct can be empty {} */
00496           break;
00497         NewGEPIndices.push_back(Zero);
00498         SrcPTy = STy->getElementType(0);
00499       } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
00500         NewGEPIndices.push_back(Zero);
00501         SrcPTy = ATy->getElementType();
00502       } else {
00503         break;
00504       }
00505     }
00506 
00507     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
00508   }
00509 
00510   if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
00511     return 0;
00512 
00513   // If the pointers point into different address spaces don't do the
00514   // transformation.
00515   if (SrcTy->getAddressSpace() !=
00516       cast<PointerType>(CI->getType())->getAddressSpace())
00517     return 0;
00518 
00519   // If the pointers point to values of different sizes don't do the
00520   // transformation.
00521   if (!IC.getDataLayout() ||
00522       IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
00523       IC.getDataLayout()->getTypeSizeInBits(DestPTy))
00524     return 0;
00525 
00526   // If the pointers point to pointers to different address spaces don't do the
00527   // transformation. It is not safe to introduce an addrspacecast instruction in
00528   // this case since, depending on the target, addrspacecast may not be a no-op
00529   // cast.
00530   if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
00531       SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
00532     return 0;
00533 
00534   // Okay, we are casting from one integer or pointer type to another of
00535   // the same size.  Instead of casting the pointer before
00536   // the store, cast the value to be stored.
00537   Value *NewCast;
00538   Instruction::CastOps opcode = Instruction::BitCast;
00539   Type* CastSrcTy = DestPTy;
00540   Type* CastDstTy = SrcPTy;
00541   if (CastDstTy->isPointerTy()) {
00542     if (CastSrcTy->isIntegerTy())
00543       opcode = Instruction::IntToPtr;
00544   } else if (CastDstTy->isIntegerTy()) {
00545     if (CastSrcTy->isPointerTy())
00546       opcode = Instruction::PtrToInt;
00547   }
00548 
00549   // SIOp0 is a pointer to aggregate and this is a store to the first field,
00550   // emit a GEP to index into its first field.
00551   if (!NewGEPIndices.empty())
00552     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
00553 
00554   Value *SIOp0 = SI.getOperand(0);
00555   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
00556                                    SIOp0->getName()+".c");
00557   SI.setOperand(0, NewCast);
00558   SI.setOperand(1, CastOp);
00559   return &SI;
00560 }
00561 
00562 /// equivalentAddressValues - Test if A and B will obviously have the same
00563 /// value. This includes recognizing that %t0 and %t1 will have the same
00564 /// value in code like this:
00565 ///   %t0 = getelementptr \@a, 0, 3
00566 ///   store i32 0, i32* %t0
00567 ///   %t1 = getelementptr \@a, 0, 3
00568 ///   %t2 = load i32* %t1
00569 ///
00570 static bool equivalentAddressValues(Value *A, Value *B) {
00571   // Test if the values are trivially equivalent.
00572   if (A == B) return true;
00573 
00574   // Test if the values come form identical arithmetic instructions.
00575   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
00576   // its only used to compare two uses within the same basic block, which
00577   // means that they'll always either have the same value or one of them
00578   // will have an undefined value.
00579   if (isa<BinaryOperator>(A) ||
00580       isa<CastInst>(A) ||
00581       isa<PHINode>(A) ||
00582       isa<GetElementPtrInst>(A))
00583     if (Instruction *BI = dyn_cast<Instruction>(B))
00584       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
00585         return true;
00586 
00587   // Otherwise they may not be equivalent.
00588   return false;
00589 }
00590 
00591 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
00592   Value *Val = SI.getOperand(0);
00593   Value *Ptr = SI.getOperand(1);
00594 
00595   // Attempt to improve the alignment.
00596   if (DL) {
00597     unsigned KnownAlign =
00598       getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
00599                                  DL);
00600     unsigned StoreAlign = SI.getAlignment();
00601     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
00602       DL->getABITypeAlignment(Val->getType());
00603 
00604     if (KnownAlign > EffectiveStoreAlign)
00605       SI.setAlignment(KnownAlign);
00606     else if (StoreAlign == 0)
00607       SI.setAlignment(EffectiveStoreAlign);
00608   }
00609 
00610   // Don't hack volatile/atomic stores.
00611   // FIXME: Some bits are legal for atomic stores; needs refactoring.
00612   if (!SI.isSimple()) return 0;
00613 
00614   // If the RHS is an alloca with a single use, zapify the store, making the
00615   // alloca dead.
00616   if (Ptr->hasOneUse()) {
00617     if (isa<AllocaInst>(Ptr))
00618       return EraseInstFromFunction(SI);
00619     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
00620       if (isa<AllocaInst>(GEP->getOperand(0))) {
00621         if (GEP->getOperand(0)->hasOneUse())
00622           return EraseInstFromFunction(SI);
00623       }
00624     }
00625   }
00626 
00627   // Do really simple DSE, to catch cases where there are several consecutive
00628   // stores to the same location, separated by a few arithmetic operations. This
00629   // situation often occurs with bitfield accesses.
00630   BasicBlock::iterator BBI = &SI;
00631   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
00632        --ScanInsts) {
00633     --BBI;
00634     // Don't count debug info directives, lest they affect codegen,
00635     // and we skip pointer-to-pointer bitcasts, which are NOPs.
00636     if (isa<DbgInfoIntrinsic>(BBI) ||
00637         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
00638       ScanInsts++;
00639       continue;
00640     }
00641 
00642     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
00643       // Prev store isn't volatile, and stores to the same location?
00644       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
00645                                                         SI.getOperand(1))) {
00646         ++NumDeadStore;
00647         ++BBI;
00648         EraseInstFromFunction(*PrevSI);
00649         continue;
00650       }
00651       break;
00652     }
00653 
00654     // If this is a load, we have to stop.  However, if the loaded value is from
00655     // the pointer we're loading and is producing the pointer we're storing,
00656     // then *this* store is dead (X = load P; store X -> P).
00657     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
00658       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
00659           LI->isSimple())
00660         return EraseInstFromFunction(SI);
00661 
00662       // Otherwise, this is a load from some other location.  Stores before it
00663       // may not be dead.
00664       break;
00665     }
00666 
00667     // Don't skip over loads or things that can modify memory.
00668     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
00669       break;
00670   }
00671 
00672   // store X, null    -> turns into 'unreachable' in SimplifyCFG
00673   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
00674     if (!isa<UndefValue>(Val)) {
00675       SI.setOperand(0, UndefValue::get(Val->getType()));
00676       if (Instruction *U = dyn_cast<Instruction>(Val))
00677         Worklist.Add(U);  // Dropped a use.
00678     }
00679     return 0;  // Do not modify these!
00680   }
00681 
00682   // store undef, Ptr -> noop
00683   if (isa<UndefValue>(Val))
00684     return EraseInstFromFunction(SI);
00685 
00686   // If the pointer destination is a cast, see if we can fold the cast into the
00687   // source instead.
00688   if (isa<CastInst>(Ptr))
00689     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
00690       return Res;
00691   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
00692     if (CE->isCast())
00693       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
00694         return Res;
00695 
00696 
00697   // If this store is the last instruction in the basic block (possibly
00698   // excepting debug info instructions), and if the block ends with an
00699   // unconditional branch, try to move it to the successor block.
00700   BBI = &SI;
00701   do {
00702     ++BBI;
00703   } while (isa<DbgInfoIntrinsic>(BBI) ||
00704            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
00705   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
00706     if (BI->isUnconditional())
00707       if (SimplifyStoreAtEndOfBlock(SI))
00708         return 0;  // xform done!
00709 
00710   return 0;
00711 }
00712 
00713 /// SimplifyStoreAtEndOfBlock - Turn things like:
00714 ///   if () { *P = v1; } else { *P = v2 }
00715 /// into a phi node with a store in the successor.
00716 ///
00717 /// Simplify things like:
00718 ///   *P = v1; if () { *P = v2; }
00719 /// into a phi node with a store in the successor.
00720 ///
00721 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
00722   BasicBlock *StoreBB = SI.getParent();
00723 
00724   // Check to see if the successor block has exactly two incoming edges.  If
00725   // so, see if the other predecessor contains a store to the same location.
00726   // if so, insert a PHI node (if needed) and move the stores down.
00727   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
00728 
00729   // Determine whether Dest has exactly two predecessors and, if so, compute
00730   // the other predecessor.
00731   pred_iterator PI = pred_begin(DestBB);
00732   BasicBlock *P = *PI;
00733   BasicBlock *OtherBB = 0;
00734 
00735   if (P != StoreBB)
00736     OtherBB = P;
00737 
00738   if (++PI == pred_end(DestBB))
00739     return false;
00740 
00741   P = *PI;
00742   if (P != StoreBB) {
00743     if (OtherBB)
00744       return false;
00745     OtherBB = P;
00746   }
00747   if (++PI != pred_end(DestBB))
00748     return false;
00749 
00750   // Bail out if all the relevant blocks aren't distinct (this can happen,
00751   // for example, if SI is in an infinite loop)
00752   if (StoreBB == DestBB || OtherBB == DestBB)
00753     return false;
00754 
00755   // Verify that the other block ends in a branch and is not otherwise empty.
00756   BasicBlock::iterator BBI = OtherBB->getTerminator();
00757   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
00758   if (!OtherBr || BBI == OtherBB->begin())
00759     return false;
00760 
00761   // If the other block ends in an unconditional branch, check for the 'if then
00762   // else' case.  there is an instruction before the branch.
00763   StoreInst *OtherStore = 0;
00764   if (OtherBr->isUnconditional()) {
00765     --BBI;
00766     // Skip over debugging info.
00767     while (isa<DbgInfoIntrinsic>(BBI) ||
00768            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
00769       if (BBI==OtherBB->begin())
00770         return false;
00771       --BBI;
00772     }
00773     // If this isn't a store, isn't a store to the same location, or is not the
00774     // right kind of store, bail out.
00775     OtherStore = dyn_cast<StoreInst>(BBI);
00776     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
00777         !SI.isSameOperationAs(OtherStore))
00778       return false;
00779   } else {
00780     // Otherwise, the other block ended with a conditional branch. If one of the
00781     // destinations is StoreBB, then we have the if/then case.
00782     if (OtherBr->getSuccessor(0) != StoreBB &&
00783         OtherBr->getSuccessor(1) != StoreBB)
00784       return false;
00785 
00786     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
00787     // if/then triangle.  See if there is a store to the same ptr as SI that
00788     // lives in OtherBB.
00789     for (;; --BBI) {
00790       // Check to see if we find the matching store.
00791       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
00792         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
00793             !SI.isSameOperationAs(OtherStore))
00794           return false;
00795         break;
00796       }
00797       // If we find something that may be using or overwriting the stored
00798       // value, or if we run out of instructions, we can't do the xform.
00799       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
00800           BBI == OtherBB->begin())
00801         return false;
00802     }
00803 
00804     // In order to eliminate the store in OtherBr, we have to
00805     // make sure nothing reads or overwrites the stored value in
00806     // StoreBB.
00807     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
00808       // FIXME: This should really be AA driven.
00809       if (I->mayReadFromMemory() || I->mayWriteToMemory())
00810         return false;
00811     }
00812   }
00813 
00814   // Insert a PHI node now if we need it.
00815   Value *MergedVal = OtherStore->getOperand(0);
00816   if (MergedVal != SI.getOperand(0)) {
00817     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
00818     PN->addIncoming(SI.getOperand(0), SI.getParent());
00819     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
00820     MergedVal = InsertNewInstBefore(PN, DestBB->front());
00821   }
00822 
00823   // Advance to a place where it is safe to insert the new store and
00824   // insert it.
00825   BBI = DestBB->getFirstInsertionPt();
00826   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
00827                                    SI.isVolatile(),
00828                                    SI.getAlignment(),
00829                                    SI.getOrdering(),
00830                                    SI.getSynchScope());
00831   InsertNewInstBefore(NewSI, *BBI);
00832   NewSI->setDebugLoc(OtherStore->getDebugLoc());
00833 
00834   // If the two stores had the same TBAA tag, preserve it.
00835   if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
00836     if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
00837                                OtherStore->getMetadata(LLVMContext::MD_tbaa))))
00838       NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
00839 
00840 
00841   // Nuke the old stores.
00842   EraseInstFromFunction(SI);
00843   EraseInstFromFunction(*OtherStore);
00844   return true;
00845 }