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