LLVM API Documentation

InstCombineCalls.cpp
Go to the documentation of this file.
00001 //===- InstCombineCalls.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 visitCall and visitInvoke functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/Analysis/MemoryBuiltins.h"
00017 #include "llvm/IR/CallSite.h"
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/PatternMatch.h"
00020 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00021 #include "llvm/Transforms/Utils/Local.h"
00022 using namespace llvm;
00023 using namespace PatternMatch;
00024 
00025 #define DEBUG_TYPE "instcombine"
00026 
00027 STATISTIC(NumSimplified, "Number of library calls simplified");
00028 
00029 /// getPromotedType - Return the specified type promoted as it would be to pass
00030 /// though a va_arg area.
00031 static Type *getPromotedType(Type *Ty) {
00032   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
00033     if (ITy->getBitWidth() < 32)
00034       return Type::getInt32Ty(Ty->getContext());
00035   }
00036   return Ty;
00037 }
00038 
00039 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
00040 /// single scalar element, like {{{type}}} or [1 x type], return type.
00041 static Type *reduceToSingleValueType(Type *T) {
00042   while (!T->isSingleValueType()) {
00043     if (StructType *STy = dyn_cast<StructType>(T)) {
00044       if (STy->getNumElements() == 1)
00045         T = STy->getElementType(0);
00046       else
00047         break;
00048     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
00049       if (ATy->getNumElements() == 1)
00050         T = ATy->getElementType();
00051       else
00052         break;
00053     } else
00054       break;
00055   }
00056 
00057   return T;
00058 }
00059 
00060 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
00061   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL);
00062   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL);
00063   unsigned MinAlign = std::min(DstAlign, SrcAlign);
00064   unsigned CopyAlign = MI->getAlignment();
00065 
00066   if (CopyAlign < MinAlign) {
00067     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00068                                              MinAlign, false));
00069     return MI;
00070   }
00071 
00072   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
00073   // load/store.
00074   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
00075   if (MemOpLength == 0) return 0;
00076 
00077   // Source and destination pointer types are always "i8*" for intrinsic.  See
00078   // if the size is something we can handle with a single primitive load/store.
00079   // A single load+store correctly handles overlapping memory in the memmove
00080   // case.
00081   uint64_t Size = MemOpLength->getLimitedValue();
00082   assert(Size && "0-sized memory transferring should be removed already.");
00083 
00084   if (Size > 8 || (Size&(Size-1)))
00085     return 0;  // If not 1/2/4/8 bytes, exit.
00086 
00087   // Use an integer load+store unless we can find something better.
00088   unsigned SrcAddrSp =
00089     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
00090   unsigned DstAddrSp =
00091     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
00092 
00093   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
00094   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
00095   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
00096 
00097   // Memcpy forces the use of i8* for the source and destination.  That means
00098   // that if you're using memcpy to move one double around, you'll get a cast
00099   // from double* to i8*.  We'd much rather use a double load+store rather than
00100   // an i64 load+store, here because this improves the odds that the source or
00101   // dest address will be promotable.  See if we can find a better type than the
00102   // integer datatype.
00103   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
00104   MDNode *CopyMD = 0;
00105   if (StrippedDest != MI->getArgOperand(0)) {
00106     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
00107                                     ->getElementType();
00108     if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
00109       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
00110       // down through these levels if so.
00111       SrcETy = reduceToSingleValueType(SrcETy);
00112 
00113       if (SrcETy->isSingleValueType()) {
00114         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
00115         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
00116 
00117         // If the memcpy has metadata describing the members, see if we can
00118         // get the TBAA tag describing our copy.
00119         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
00120           if (M->getNumOperands() == 3 &&
00121               M->getOperand(0) &&
00122               isa<ConstantInt>(M->getOperand(0)) &&
00123               cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
00124               M->getOperand(1) &&
00125               isa<ConstantInt>(M->getOperand(1)) &&
00126               cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
00127               M->getOperand(2) &&
00128               isa<MDNode>(M->getOperand(2)))
00129             CopyMD = cast<MDNode>(M->getOperand(2));
00130         }
00131       }
00132     }
00133   }
00134 
00135   // If the memcpy/memmove provides better alignment info than we can
00136   // infer, use it.
00137   SrcAlign = std::max(SrcAlign, CopyAlign);
00138   DstAlign = std::max(DstAlign, CopyAlign);
00139 
00140   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
00141   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
00142   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
00143   L->setAlignment(SrcAlign);
00144   if (CopyMD)
00145     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00146   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
00147   S->setAlignment(DstAlign);
00148   if (CopyMD)
00149     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00150 
00151   // Set the size of the copy to 0, it will be deleted on the next iteration.
00152   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
00153   return MI;
00154 }
00155 
00156 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
00157   unsigned Alignment = getKnownAlignment(MI->getDest(), DL);
00158   if (MI->getAlignment() < Alignment) {
00159     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00160                                              Alignment, false));
00161     return MI;
00162   }
00163 
00164   // Extract the length and alignment and fill if they are constant.
00165   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
00166   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
00167   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
00168     return 0;
00169   uint64_t Len = LenC->getLimitedValue();
00170   Alignment = MI->getAlignment();
00171   assert(Len && "0-sized memory setting should be removed already.");
00172 
00173   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
00174   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
00175     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
00176 
00177     Value *Dest = MI->getDest();
00178     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
00179     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
00180     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
00181 
00182     // Alignment 0 is identity for alignment 1 for memset, but not store.
00183     if (Alignment == 0) Alignment = 1;
00184 
00185     // Extract the fill value and store.
00186     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
00187     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
00188                                         MI->isVolatile());
00189     S->setAlignment(Alignment);
00190 
00191     // Set the size of the copy to 0, it will be deleted on the next iteration.
00192     MI->setLength(Constant::getNullValue(LenC->getType()));
00193     return MI;
00194   }
00195 
00196   return 0;
00197 }
00198 
00199 /// visitCallInst - CallInst simplification.  This mostly only handles folding
00200 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
00201 /// the heavy lifting.
00202 ///
00203 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
00204   if (isFreeCall(&CI, TLI))
00205     return visitFree(CI);
00206 
00207   // If the caller function is nounwind, mark the call as nounwind, even if the
00208   // callee isn't.
00209   if (CI.getParent()->getParent()->doesNotThrow() &&
00210       !CI.doesNotThrow()) {
00211     CI.setDoesNotThrow();
00212     return &CI;
00213   }
00214 
00215   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
00216   if (!II) return visitCallSite(&CI);
00217 
00218   // Intrinsics cannot occur in an invoke, so handle them here instead of in
00219   // visitCallSite.
00220   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
00221     bool Changed = false;
00222 
00223     // memmove/cpy/set of zero bytes is a noop.
00224     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
00225       if (NumBytes->isNullValue())
00226         return EraseInstFromFunction(CI);
00227 
00228       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
00229         if (CI->getZExtValue() == 1) {
00230           // Replace the instruction with just byte operations.  We would
00231           // transform other cases to loads/stores, but we don't know if
00232           // alignment is sufficient.
00233         }
00234     }
00235 
00236     // No other transformations apply to volatile transfers.
00237     if (MI->isVolatile())
00238       return 0;
00239 
00240     // If we have a memmove and the source operation is a constant global,
00241     // then the source and dest pointers can't alias, so we can change this
00242     // into a call to memcpy.
00243     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
00244       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
00245         if (GVSrc->isConstant()) {
00246           Module *M = CI.getParent()->getParent()->getParent();
00247           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
00248           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
00249                            CI.getArgOperand(1)->getType(),
00250                            CI.getArgOperand(2)->getType() };
00251           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
00252           Changed = true;
00253         }
00254     }
00255 
00256     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
00257       // memmove(x,x,size) -> noop.
00258       if (MTI->getSource() == MTI->getDest())
00259         return EraseInstFromFunction(CI);
00260     }
00261 
00262     // If we can determine a pointer alignment that is bigger than currently
00263     // set, update the alignment.
00264     if (isa<MemTransferInst>(MI)) {
00265       if (Instruction *I = SimplifyMemTransfer(MI))
00266         return I;
00267     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
00268       if (Instruction *I = SimplifyMemSet(MSI))
00269         return I;
00270     }
00271 
00272     if (Changed) return II;
00273   }
00274 
00275   switch (II->getIntrinsicID()) {
00276   default: break;
00277   case Intrinsic::objectsize: {
00278     uint64_t Size;
00279     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
00280       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
00281     return 0;
00282   }
00283   case Intrinsic::bswap: {
00284     Value *IIOperand = II->getArgOperand(0);
00285     Value *X = 0;
00286 
00287     // bswap(bswap(x)) -> x
00288     if (match(IIOperand, m_BSwap(m_Value(X))))
00289         return ReplaceInstUsesWith(CI, X);
00290 
00291     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
00292     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
00293       unsigned C = X->getType()->getPrimitiveSizeInBits() -
00294         IIOperand->getType()->getPrimitiveSizeInBits();
00295       Value *CV = ConstantInt::get(X->getType(), C);
00296       Value *V = Builder->CreateLShr(X, CV);
00297       return new TruncInst(V, IIOperand->getType());
00298     }
00299     break;
00300   }
00301 
00302   case Intrinsic::powi:
00303     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00304       // powi(x, 0) -> 1.0
00305       if (Power->isZero())
00306         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
00307       // powi(x, 1) -> x
00308       if (Power->isOne())
00309         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
00310       // powi(x, -1) -> 1/x
00311       if (Power->isAllOnesValue())
00312         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
00313                                           II->getArgOperand(0));
00314     }
00315     break;
00316   case Intrinsic::cttz: {
00317     // If all bits below the first known one are known zero,
00318     // this value is constant.
00319     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00320     // FIXME: Try to simplify vectors of integers.
00321     if (!IT) break;
00322     uint32_t BitWidth = IT->getBitWidth();
00323     APInt KnownZero(BitWidth, 0);
00324     APInt KnownOne(BitWidth, 0);
00325     ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
00326     unsigned TrailingZeros = KnownOne.countTrailingZeros();
00327     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
00328     if ((Mask & KnownZero) == Mask)
00329       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00330                                  APInt(BitWidth, TrailingZeros)));
00331 
00332     }
00333     break;
00334   case Intrinsic::ctlz: {
00335     // If all bits above the first known one are known zero,
00336     // this value is constant.
00337     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00338     // FIXME: Try to simplify vectors of integers.
00339     if (!IT) break;
00340     uint32_t BitWidth = IT->getBitWidth();
00341     APInt KnownZero(BitWidth, 0);
00342     APInt KnownOne(BitWidth, 0);
00343     ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
00344     unsigned LeadingZeros = KnownOne.countLeadingZeros();
00345     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
00346     if ((Mask & KnownZero) == Mask)
00347       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00348                                  APInt(BitWidth, LeadingZeros)));
00349 
00350     }
00351     break;
00352   case Intrinsic::uadd_with_overflow: {
00353     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00354     IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
00355     uint32_t BitWidth = IT->getBitWidth();
00356     APInt LHSKnownZero(BitWidth, 0);
00357     APInt LHSKnownOne(BitWidth, 0);
00358     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
00359     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
00360     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
00361 
00362     if (LHSKnownNegative || LHSKnownPositive) {
00363       APInt RHSKnownZero(BitWidth, 0);
00364       APInt RHSKnownOne(BitWidth, 0);
00365       ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
00366       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
00367       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
00368       if (LHSKnownNegative && RHSKnownNegative) {
00369         // The sign bit is set in both cases: this MUST overflow.
00370         // Create a simple add instruction, and insert it into the struct.
00371         Value *Add = Builder->CreateAdd(LHS, RHS);
00372         Add->takeName(&CI);
00373         Constant *V[] = {
00374           UndefValue::get(LHS->getType()),
00375           ConstantInt::getTrue(II->getContext())
00376         };
00377         StructType *ST = cast<StructType>(II->getType());
00378         Constant *Struct = ConstantStruct::get(ST, V);
00379         return InsertValueInst::Create(Struct, Add, 0);
00380       }
00381 
00382       if (LHSKnownPositive && RHSKnownPositive) {
00383         // The sign bit is clear in both cases: this CANNOT overflow.
00384         // Create a simple add instruction, and insert it into the struct.
00385         Value *Add = Builder->CreateNUWAdd(LHS, RHS);
00386         Add->takeName(&CI);
00387         Constant *V[] = {
00388           UndefValue::get(LHS->getType()),
00389           ConstantInt::getFalse(II->getContext())
00390         };
00391         StructType *ST = cast<StructType>(II->getType());
00392         Constant *Struct = ConstantStruct::get(ST, V);
00393         return InsertValueInst::Create(Struct, Add, 0);
00394       }
00395     }
00396   }
00397   // FALL THROUGH uadd into sadd
00398   case Intrinsic::sadd_with_overflow:
00399     // Canonicalize constants into the RHS.
00400     if (isa<Constant>(II->getArgOperand(0)) &&
00401         !isa<Constant>(II->getArgOperand(1))) {
00402       Value *LHS = II->getArgOperand(0);
00403       II->setArgOperand(0, II->getArgOperand(1));
00404       II->setArgOperand(1, LHS);
00405       return II;
00406     }
00407 
00408     // X + undef -> undef
00409     if (isa<UndefValue>(II->getArgOperand(1)))
00410       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00411 
00412     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00413       // X + 0 -> {X, false}
00414       if (RHS->isZero()) {
00415         Constant *V[] = {
00416           UndefValue::get(II->getArgOperand(0)->getType()),
00417           ConstantInt::getFalse(II->getContext())
00418         };
00419         Constant *Struct =
00420           ConstantStruct::get(cast<StructType>(II->getType()), V);
00421         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
00422       }
00423     }
00424     break;
00425   case Intrinsic::usub_with_overflow:
00426   case Intrinsic::ssub_with_overflow:
00427     // undef - X -> undef
00428     // X - undef -> undef
00429     if (isa<UndefValue>(II->getArgOperand(0)) ||
00430         isa<UndefValue>(II->getArgOperand(1)))
00431       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00432 
00433     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00434       // X - 0 -> {X, false}
00435       if (RHS->isZero()) {
00436         Constant *V[] = {
00437           UndefValue::get(II->getArgOperand(0)->getType()),
00438           ConstantInt::getFalse(II->getContext())
00439         };
00440         Constant *Struct =
00441           ConstantStruct::get(cast<StructType>(II->getType()), V);
00442         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
00443       }
00444     }
00445     break;
00446   case Intrinsic::umul_with_overflow: {
00447     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00448     unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
00449 
00450     APInt LHSKnownZero(BitWidth, 0);
00451     APInt LHSKnownOne(BitWidth, 0);
00452     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
00453     APInt RHSKnownZero(BitWidth, 0);
00454     APInt RHSKnownOne(BitWidth, 0);
00455     ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
00456 
00457     // Get the largest possible values for each operand.
00458     APInt LHSMax = ~LHSKnownZero;
00459     APInt RHSMax = ~RHSKnownZero;
00460 
00461     // If multiplying the maximum values does not overflow then we can turn
00462     // this into a plain NUW mul.
00463     bool Overflow;
00464     LHSMax.umul_ov(RHSMax, Overflow);
00465     if (!Overflow) {
00466       Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
00467       Constant *V[] = {
00468         UndefValue::get(LHS->getType()),
00469         Builder->getFalse()
00470       };
00471       Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
00472       return InsertValueInst::Create(Struct, Mul, 0);
00473     }
00474   } // FALL THROUGH
00475   case Intrinsic::smul_with_overflow:
00476     // Canonicalize constants into the RHS.
00477     if (isa<Constant>(II->getArgOperand(0)) &&
00478         !isa<Constant>(II->getArgOperand(1))) {
00479       Value *LHS = II->getArgOperand(0);
00480       II->setArgOperand(0, II->getArgOperand(1));
00481       II->setArgOperand(1, LHS);
00482       return II;
00483     }
00484 
00485     // X * undef -> undef
00486     if (isa<UndefValue>(II->getArgOperand(1)))
00487       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00488 
00489     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00490       // X*0 -> {0, false}
00491       if (RHSI->isZero())
00492         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
00493 
00494       // X * 1 -> {X, false}
00495       if (RHSI->equalsInt(1)) {
00496         Constant *V[] = {
00497           UndefValue::get(II->getArgOperand(0)->getType()),
00498           ConstantInt::getFalse(II->getContext())
00499         };
00500         Constant *Struct =
00501           ConstantStruct::get(cast<StructType>(II->getType()), V);
00502         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
00503       }
00504     }
00505     break;
00506   case Intrinsic::ppc_altivec_lvx:
00507   case Intrinsic::ppc_altivec_lvxl:
00508     // Turn PPC lvx -> load if the pointer is known aligned.
00509     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
00510       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00511                                          PointerType::getUnqual(II->getType()));
00512       return new LoadInst(Ptr);
00513     }
00514     break;
00515   case Intrinsic::ppc_altivec_stvx:
00516   case Intrinsic::ppc_altivec_stvxl:
00517     // Turn stvx -> store if the pointer is known aligned.
00518     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL) >= 16) {
00519       Type *OpPtrTy =
00520         PointerType::getUnqual(II->getArgOperand(0)->getType());
00521       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00522       return new StoreInst(II->getArgOperand(0), Ptr);
00523     }
00524     break;
00525   case Intrinsic::x86_sse_storeu_ps:
00526   case Intrinsic::x86_sse2_storeu_pd:
00527   case Intrinsic::x86_sse2_storeu_dq:
00528     // Turn X86 storeu -> store if the pointer is known aligned.
00529     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
00530       Type *OpPtrTy =
00531         PointerType::getUnqual(II->getArgOperand(1)->getType());
00532       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
00533       return new StoreInst(II->getArgOperand(1), Ptr);
00534     }
00535     break;
00536 
00537   case Intrinsic::x86_sse_cvtss2si:
00538   case Intrinsic::x86_sse_cvtss2si64:
00539   case Intrinsic::x86_sse_cvttss2si:
00540   case Intrinsic::x86_sse_cvttss2si64:
00541   case Intrinsic::x86_sse2_cvtsd2si:
00542   case Intrinsic::x86_sse2_cvtsd2si64:
00543   case Intrinsic::x86_sse2_cvttsd2si:
00544   case Intrinsic::x86_sse2_cvttsd2si64: {
00545     // These intrinsics only demand the 0th element of their input vectors. If
00546     // we can simplify the input based on that, do so now.
00547     unsigned VWidth =
00548       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00549     APInt DemandedElts(VWidth, 1);
00550     APInt UndefElts(VWidth, 0);
00551     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
00552                                               DemandedElts, UndefElts)) {
00553       II->setArgOperand(0, V);
00554       return II;
00555     }
00556     break;
00557   }
00558 
00559   // Constant fold <A x Bi> << Ci.
00560   // FIXME: We don't handle _dq because it's a shift of an i128, but is
00561   // represented in the IR as <2 x i64>. A per element shift is wrong.
00562   case Intrinsic::x86_sse2_psll_d:
00563   case Intrinsic::x86_sse2_psll_q:
00564   case Intrinsic::x86_sse2_psll_w:
00565   case Intrinsic::x86_sse2_pslli_d:
00566   case Intrinsic::x86_sse2_pslli_q:
00567   case Intrinsic::x86_sse2_pslli_w:
00568   case Intrinsic::x86_avx2_psll_d:
00569   case Intrinsic::x86_avx2_psll_q:
00570   case Intrinsic::x86_avx2_psll_w:
00571   case Intrinsic::x86_avx2_pslli_d:
00572   case Intrinsic::x86_avx2_pslli_q:
00573   case Intrinsic::x86_avx2_pslli_w: {
00574     // Simplify if count is constant. To 0 if > BitWidth, otherwise to shl.
00575     auto CDV = dyn_cast<ConstantDataVector>(II->getArgOperand(1));
00576     auto CInt = dyn_cast<ConstantInt>(II->getArgOperand(1));
00577     if (!CDV && !CInt)
00578       break;
00579     ConstantInt *Count;
00580     if (CDV)
00581       Count = cast<ConstantInt>(CDV->getElementAsConstant(0));
00582     else
00583       Count = CInt;
00584 
00585     auto Vec = II->getArgOperand(0);
00586     auto VT = cast<VectorType>(Vec->getType());
00587     if (Count->getZExtValue() >
00588         VT->getElementType()->getPrimitiveSizeInBits() - 1)
00589       return ReplaceInstUsesWith(
00590           CI, ConstantAggregateZero::get(Vec->getType()));
00591     else {
00592       unsigned VWidth = VT->getNumElements();
00593       // Get a constant vector of the same type as the first operand.
00594       auto VTCI = ConstantInt::get(VT->getElementType(), Count->getZExtValue());
00595       return BinaryOperator::CreateShl(
00596           Vec, Builder->CreateVectorSplat(VWidth, VTCI));
00597     }
00598     break;
00599   }
00600 
00601   case Intrinsic::x86_sse41_pmovsxbw:
00602   case Intrinsic::x86_sse41_pmovsxwd:
00603   case Intrinsic::x86_sse41_pmovsxdq:
00604   case Intrinsic::x86_sse41_pmovzxbw:
00605   case Intrinsic::x86_sse41_pmovzxwd:
00606   case Intrinsic::x86_sse41_pmovzxdq: {
00607     // pmov{s|z}x ignores the upper half of their input vectors.
00608     unsigned VWidth =
00609       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00610     unsigned LowHalfElts = VWidth / 2;
00611     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
00612     APInt UndefElts(VWidth, 0);
00613     if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
00614                                                  InputDemandedElts,
00615                                                  UndefElts)) {
00616       II->setArgOperand(0, TmpV);
00617       return II;
00618     }
00619     break;
00620   }
00621 
00622   case Intrinsic::x86_sse4a_insertqi: {
00623     // insertqi x, y, 64, 0 can just copy y's lower bits and leave the top
00624     // ones undef
00625     // TODO: eventually we should lower this intrinsic to IR
00626     if (auto CIWidth = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
00627       if (auto CIStart = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
00628         if (CIWidth->equalsInt(64) && CIStart->isZero()) {
00629           Value *Vec = II->getArgOperand(1);
00630           Value *Undef = UndefValue::get(Vec->getType());
00631           const uint32_t Mask[] = { 0, 2 };
00632           return ReplaceInstUsesWith(
00633               CI,
00634               Builder->CreateShuffleVector(
00635                   Vec, Undef, ConstantDataVector::get(
00636                                   II->getContext(), ArrayRef<uint32_t>(Mask))));
00637 
00638         } else if (auto Source =
00639                        dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00640           if (Source->hasOneUse() &&
00641               Source->getArgOperand(1) == II->getArgOperand(1)) {
00642             // If the source of the insert has only one use and it's another
00643             // insert (and they're both inserting from the same vector), try to
00644             // bundle both together.
00645             auto CISourceWidth =
00646                 dyn_cast<ConstantInt>(Source->getArgOperand(2));
00647             auto CISourceStart =
00648                 dyn_cast<ConstantInt>(Source->getArgOperand(3));
00649             if (CISourceStart && CISourceWidth) {
00650               unsigned Start = CIStart->getZExtValue();
00651               unsigned Width = CIWidth->getZExtValue();
00652               unsigned End = Start + Width;
00653               unsigned SourceStart = CISourceStart->getZExtValue();
00654               unsigned SourceWidth = CISourceWidth->getZExtValue();
00655               unsigned SourceEnd = SourceStart + SourceWidth;
00656               unsigned NewStart, NewWidth;
00657               bool ShouldReplace = false;
00658               if (Start <= SourceStart && SourceStart <= End) {
00659                 NewStart = Start;
00660                 NewWidth = std::max(End, SourceEnd) - NewStart;
00661                 ShouldReplace = true;
00662               } else if (SourceStart <= Start && Start <= SourceEnd) {
00663                 NewStart = SourceStart;
00664                 NewWidth = std::max(SourceEnd, End) - NewStart;
00665                 ShouldReplace = true;
00666               }
00667 
00668               if (ShouldReplace) {
00669                 Constant *ConstantWidth = ConstantInt::get(
00670                     II->getArgOperand(2)->getType(), NewWidth, false);
00671                 Constant *ConstantStart = ConstantInt::get(
00672                     II->getArgOperand(3)->getType(), NewStart, false);
00673                 Value *Args[4] = { Source->getArgOperand(0),
00674                                    II->getArgOperand(1), ConstantWidth,
00675                                    ConstantStart };
00676                 Module *M = CI.getParent()->getParent()->getParent();
00677                 Value *F =
00678                     Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
00679                 return ReplaceInstUsesWith(CI, Builder->CreateCall(F, Args));
00680               }
00681             }
00682           }
00683         }
00684       }
00685     }
00686     break;
00687   }
00688 
00689   case Intrinsic::x86_avx_vpermilvar_ps:
00690   case Intrinsic::x86_avx_vpermilvar_ps_256:
00691   case Intrinsic::x86_avx_vpermilvar_pd:
00692   case Intrinsic::x86_avx_vpermilvar_pd_256: {
00693     // Convert vpermil* to shufflevector if the mask is constant.
00694     Value *V = II->getArgOperand(1);
00695     if (auto C = dyn_cast<ConstantDataVector>(V)) {
00696       auto V1 = II->getArgOperand(0);
00697       auto V2 = UndefValue::get(V1->getType());
00698       auto Shuffle = Builder->CreateShuffleVector(V1, V2, C);
00699       return ReplaceInstUsesWith(CI, Shuffle);
00700     }
00701     break;
00702   }
00703 
00704   case Intrinsic::ppc_altivec_vperm:
00705     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
00706     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
00707       assert(Mask->getType()->getVectorNumElements() == 16 &&
00708              "Bad type for intrinsic!");
00709 
00710       // Check that all of the elements are integer constants or undefs.
00711       bool AllEltsOk = true;
00712       for (unsigned i = 0; i != 16; ++i) {
00713         Constant *Elt = Mask->getAggregateElement(i);
00714         if (Elt == 0 ||
00715             !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
00716           AllEltsOk = false;
00717           break;
00718         }
00719       }
00720 
00721       if (AllEltsOk) {
00722         // Cast the input vectors to byte vectors.
00723         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
00724                                             Mask->getType());
00725         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
00726                                             Mask->getType());
00727         Value *Result = UndefValue::get(Op0->getType());
00728 
00729         // Only extract each element once.
00730         Value *ExtractedElts[32];
00731         memset(ExtractedElts, 0, sizeof(ExtractedElts));
00732 
00733         for (unsigned i = 0; i != 16; ++i) {
00734           if (isa<UndefValue>(Mask->getAggregateElement(i)))
00735             continue;
00736           unsigned Idx =
00737             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
00738           Idx &= 31;  // Match the hardware behavior.
00739 
00740           if (ExtractedElts[Idx] == 0) {
00741             ExtractedElts[Idx] =
00742               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
00743                                             Builder->getInt32(Idx&15));
00744           }
00745 
00746           // Insert this value into the result vector.
00747           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
00748                                                 Builder->getInt32(i));
00749         }
00750         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
00751       }
00752     }
00753     break;
00754 
00755   case Intrinsic::arm_neon_vld1:
00756   case Intrinsic::arm_neon_vld2:
00757   case Intrinsic::arm_neon_vld3:
00758   case Intrinsic::arm_neon_vld4:
00759   case Intrinsic::arm_neon_vld2lane:
00760   case Intrinsic::arm_neon_vld3lane:
00761   case Intrinsic::arm_neon_vld4lane:
00762   case Intrinsic::arm_neon_vst1:
00763   case Intrinsic::arm_neon_vst2:
00764   case Intrinsic::arm_neon_vst3:
00765   case Intrinsic::arm_neon_vst4:
00766   case Intrinsic::arm_neon_vst2lane:
00767   case Intrinsic::arm_neon_vst3lane:
00768   case Intrinsic::arm_neon_vst4lane: {
00769     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL);
00770     unsigned AlignArg = II->getNumArgOperands() - 1;
00771     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
00772     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
00773       II->setArgOperand(AlignArg,
00774                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
00775                                          MemAlign, false));
00776       return II;
00777     }
00778     break;
00779   }
00780 
00781   case Intrinsic::arm_neon_vmulls:
00782   case Intrinsic::arm_neon_vmullu:
00783   case Intrinsic::arm64_neon_smull:
00784   case Intrinsic::arm64_neon_umull: {
00785     Value *Arg0 = II->getArgOperand(0);
00786     Value *Arg1 = II->getArgOperand(1);
00787 
00788     // Handle mul by zero first:
00789     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
00790       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
00791     }
00792 
00793     // Check for constant LHS & RHS - in this case we just simplify.
00794     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
00795                  II->getIntrinsicID() == Intrinsic::arm64_neon_umull);
00796     VectorType *NewVT = cast<VectorType>(II->getType());
00797     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
00798       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
00799         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
00800         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
00801 
00802         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
00803       }
00804 
00805       // Couldn't simplify - canonicalize constant to the RHS.
00806       std::swap(Arg0, Arg1);
00807     }
00808 
00809     // Handle mul by one:
00810     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
00811       if (ConstantInt *Splat =
00812               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
00813         if (Splat->isOne())
00814           return CastInst::CreateIntegerCast(Arg0, II->getType(),
00815                                              /*isSigned=*/!Zext);
00816 
00817     break;
00818   }
00819 
00820   case Intrinsic::stackrestore: {
00821     // If the save is right next to the restore, remove the restore.  This can
00822     // happen when variable allocas are DCE'd.
00823     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00824       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
00825         BasicBlock::iterator BI = SS;
00826         if (&*++BI == II)
00827           return EraseInstFromFunction(CI);
00828       }
00829     }
00830 
00831     // Scan down this block to see if there is another stack restore in the
00832     // same block without an intervening call/alloca.
00833     BasicBlock::iterator BI = II;
00834     TerminatorInst *TI = II->getParent()->getTerminator();
00835     bool CannotRemove = false;
00836     for (++BI; &*BI != TI; ++BI) {
00837       if (isa<AllocaInst>(BI)) {
00838         CannotRemove = true;
00839         break;
00840       }
00841       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
00842         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
00843           // If there is a stackrestore below this one, remove this one.
00844           if (II->getIntrinsicID() == Intrinsic::stackrestore)
00845             return EraseInstFromFunction(CI);
00846           // Otherwise, ignore the intrinsic.
00847         } else {
00848           // If we found a non-intrinsic call, we can't remove the stack
00849           // restore.
00850           CannotRemove = true;
00851           break;
00852         }
00853       }
00854     }
00855 
00856     // If the stack restore is in a return, resume, or unwind block and if there
00857     // are no allocas or calls between the restore and the return, nuke the
00858     // restore.
00859     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
00860       return EraseInstFromFunction(CI);
00861     break;
00862   }
00863   }
00864 
00865   return visitCallSite(II);
00866 }
00867 
00868 // InvokeInst simplification
00869 //
00870 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
00871   return visitCallSite(&II);
00872 }
00873 
00874 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
00875 /// passed through the varargs area, we can eliminate the use of the cast.
00876 static bool isSafeToEliminateVarargsCast(const CallSite CS,
00877                                          const CastInst * const CI,
00878                                          const DataLayout * const DL,
00879                                          const int ix) {
00880   if (!CI->isLosslessCast())
00881     return false;
00882 
00883   // The size of ByVal or InAlloca arguments is derived from the type, so we
00884   // can't change to a type with a different size.  If the size were
00885   // passed explicitly we could avoid this check.
00886   if (!CS.isByValOrInAllocaArgument(ix))
00887     return true;
00888 
00889   Type* SrcTy =
00890             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
00891   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
00892   if (!SrcTy->isSized() || !DstTy->isSized())
00893     return false;
00894   if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
00895     return false;
00896   return true;
00897 }
00898 
00899 // Try to fold some different type of calls here.
00900 // Currently we're only working with the checking functions, memcpy_chk,
00901 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
00902 // strcat_chk and strncat_chk.
00903 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
00904   if (CI->getCalledFunction() == 0) return 0;
00905 
00906   if (Value *With = Simplifier->optimizeCall(CI)) {
00907     ++NumSimplified;
00908     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
00909   }
00910 
00911   return 0;
00912 }
00913 
00914 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
00915   // Strip off at most one level of pointer casts, looking for an alloca.  This
00916   // is good enough in practice and simpler than handling any number of casts.
00917   Value *Underlying = TrampMem->stripPointerCasts();
00918   if (Underlying != TrampMem &&
00919       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
00920     return 0;
00921   if (!isa<AllocaInst>(Underlying))
00922     return 0;
00923 
00924   IntrinsicInst *InitTrampoline = 0;
00925   for (User *U : TrampMem->users()) {
00926     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
00927     if (!II)
00928       return 0;
00929     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
00930       if (InitTrampoline)
00931         // More than one init_trampoline writes to this value.  Give up.
00932         return 0;
00933       InitTrampoline = II;
00934       continue;
00935     }
00936     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
00937       // Allow any number of calls to adjust.trampoline.
00938       continue;
00939     return 0;
00940   }
00941 
00942   // No call to init.trampoline found.
00943   if (!InitTrampoline)
00944     return 0;
00945 
00946   // Check that the alloca is being used in the expected way.
00947   if (InitTrampoline->getOperand(0) != TrampMem)
00948     return 0;
00949 
00950   return InitTrampoline;
00951 }
00952 
00953 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
00954                                                Value *TrampMem) {
00955   // Visit all the previous instructions in the basic block, and try to find a
00956   // init.trampoline which has a direct path to the adjust.trampoline.
00957   for (BasicBlock::iterator I = AdjustTramp,
00958        E = AdjustTramp->getParent()->begin(); I != E; ) {
00959     Instruction *Inst = --I;
00960     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
00961       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
00962           II->getOperand(0) == TrampMem)
00963         return II;
00964     if (Inst->mayWriteToMemory())
00965       return 0;
00966   }
00967   return 0;
00968 }
00969 
00970 // Given a call to llvm.adjust.trampoline, find and return the corresponding
00971 // call to llvm.init.trampoline if the call to the trampoline can be optimized
00972 // to a direct call to a function.  Otherwise return NULL.
00973 //
00974 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
00975   Callee = Callee->stripPointerCasts();
00976   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
00977   if (!AdjustTramp ||
00978       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
00979     return 0;
00980 
00981   Value *TrampMem = AdjustTramp->getOperand(0);
00982 
00983   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
00984     return IT;
00985   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
00986     return IT;
00987   return 0;
00988 }
00989 
00990 // visitCallSite - Improvements for call and invoke instructions.
00991 //
00992 Instruction *InstCombiner::visitCallSite(CallSite CS) {
00993   if (isAllocLikeFn(CS.getInstruction(), TLI))
00994     return visitAllocSite(*CS.getInstruction());
00995 
00996   bool Changed = false;
00997 
00998   // If the callee is a pointer to a function, attempt to move any casts to the
00999   // arguments of the call/invoke.
01000   Value *Callee = CS.getCalledValue();
01001   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
01002     return 0;
01003 
01004   if (Function *CalleeF = dyn_cast<Function>(Callee))
01005     // If the call and callee calling conventions don't match, this call must
01006     // be unreachable, as the call is undefined.
01007     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
01008         // Only do this for calls to a function with a body.  A prototype may
01009         // not actually end up matching the implementation's calling conv for a
01010         // variety of reasons (e.g. it may be written in assembly).
01011         !CalleeF->isDeclaration()) {
01012       Instruction *OldCall = CS.getInstruction();
01013       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01014                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01015                                   OldCall);
01016       // If OldCall does not return void then replaceAllUsesWith undef.
01017       // This allows ValueHandlers and custom metadata to adjust itself.
01018       if (!OldCall->getType()->isVoidTy())
01019         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
01020       if (isa<CallInst>(OldCall))
01021         return EraseInstFromFunction(*OldCall);
01022 
01023       // We cannot remove an invoke, because it would change the CFG, just
01024       // change the callee to a null pointer.
01025       cast<InvokeInst>(OldCall)->setCalledFunction(
01026                                     Constant::getNullValue(CalleeF->getType()));
01027       return 0;
01028     }
01029 
01030   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01031     // If CS does not return void then replaceAllUsesWith undef.
01032     // This allows ValueHandlers and custom metadata to adjust itself.
01033     if (!CS.getInstruction()->getType()->isVoidTy())
01034       ReplaceInstUsesWith(*CS.getInstruction(),
01035                           UndefValue::get(CS.getInstruction()->getType()));
01036 
01037     if (isa<InvokeInst>(CS.getInstruction())) {
01038       // Can't remove an invoke because we cannot change the CFG.
01039       return 0;
01040     }
01041 
01042     // This instruction is not reachable, just remove it.  We insert a store to
01043     // undef so that we know that this code is not reachable, despite the fact
01044     // that we can't modify the CFG here.
01045     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01046                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01047                   CS.getInstruction());
01048 
01049     return EraseInstFromFunction(*CS.getInstruction());
01050   }
01051 
01052   if (IntrinsicInst *II = FindInitTrampoline(Callee))
01053     return transformCallThroughTrampoline(CS, II);
01054 
01055   PointerType *PTy = cast<PointerType>(Callee->getType());
01056   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01057   if (FTy->isVarArg()) {
01058     int ix = FTy->getNumParams();
01059     // See if we can optimize any arguments passed through the varargs area of
01060     // the call.
01061     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
01062            E = CS.arg_end(); I != E; ++I, ++ix) {
01063       CastInst *CI = dyn_cast<CastInst>(*I);
01064       if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
01065         *I = CI->getOperand(0);
01066         Changed = true;
01067       }
01068     }
01069   }
01070 
01071   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
01072     // Inline asm calls cannot throw - mark them 'nounwind'.
01073     CS.setDoesNotThrow();
01074     Changed = true;
01075   }
01076 
01077   // Try to optimize the call if possible, we require DataLayout for most of
01078   // this.  None of these calls are seen as possibly dead so go ahead and
01079   // delete the instruction now.
01080   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
01081     Instruction *I = tryOptimizeCall(CI, DL);
01082     // If we changed something return the result, etc. Otherwise let
01083     // the fallthrough check.
01084     if (I) return EraseInstFromFunction(*I);
01085   }
01086 
01087   return Changed ? CS.getInstruction() : 0;
01088 }
01089 
01090 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
01091 // attempt to move the cast to the arguments of the call/invoke.
01092 //
01093 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
01094   Function *Callee =
01095     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
01096   if (Callee == 0)
01097     return false;
01098   Instruction *Caller = CS.getInstruction();
01099   const AttributeSet &CallerPAL = CS.getAttributes();
01100 
01101   // Okay, this is a cast from a function to a different type.  Unless doing so
01102   // would cause a type conversion of one of our arguments, change this call to
01103   // be a direct call with arguments casted to the appropriate types.
01104   //
01105   FunctionType *FT = Callee->getFunctionType();
01106   Type *OldRetTy = Caller->getType();
01107   Type *NewRetTy = FT->getReturnType();
01108 
01109   // Check to see if we are changing the return type...
01110   if (OldRetTy != NewRetTy) {
01111 
01112     if (NewRetTy->isStructTy())
01113       return false; // TODO: Handle multiple return values.
01114 
01115     if (!CastInst::isBitCastable(NewRetTy, OldRetTy)) {
01116       if (Callee->isDeclaration())
01117         return false;   // Cannot transform this return value.
01118 
01119       if (!Caller->use_empty() &&
01120           // void -> non-void is handled specially
01121           !NewRetTy->isVoidTy())
01122       return false;   // Cannot transform this return value.
01123     }
01124 
01125     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
01126       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01127       if (RAttrs.
01128           hasAttributes(AttributeFuncs::
01129                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01130                         AttributeSet::ReturnIndex))
01131         return false;   // Attribute not compatible with transformed value.
01132     }
01133 
01134     // If the callsite is an invoke instruction, and the return value is used by
01135     // a PHI node in a successor, we cannot change the return type of the call
01136     // because there is no place to put the cast instruction (without breaking
01137     // the critical edge).  Bail out in this case.
01138     if (!Caller->use_empty())
01139       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
01140         for (User *U : II->users())
01141           if (PHINode *PN = dyn_cast<PHINode>(U))
01142             if (PN->getParent() == II->getNormalDest() ||
01143                 PN->getParent() == II->getUnwindDest())
01144               return false;
01145   }
01146 
01147   unsigned NumActualArgs = CS.arg_size();
01148   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
01149 
01150   CallSite::arg_iterator AI = CS.arg_begin();
01151   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
01152     Type *ParamTy = FT->getParamType(i);
01153     Type *ActTy = (*AI)->getType();
01154 
01155     if (!CastInst::isBitCastable(ActTy, ParamTy))
01156       return false;   // Cannot transform this parameter value.
01157 
01158     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
01159           hasAttributes(AttributeFuncs::
01160                         typeIncompatible(ParamTy, i + 1), i + 1))
01161       return false;   // Attribute not compatible with transformed value.
01162 
01163     if (CS.isInAllocaArgument(i))
01164       return false;   // Cannot transform to and from inalloca.
01165 
01166     // If the parameter is passed as a byval argument, then we have to have a
01167     // sized type and the sized type has to have the same size as the old type.
01168     if (ParamTy != ActTy &&
01169         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
01170                                                          Attribute::ByVal)) {
01171       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
01172       if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || DL == 0)
01173         return false;
01174 
01175       Type *CurElTy = ActTy->getPointerElementType();
01176       if (DL->getTypeAllocSize(CurElTy) !=
01177           DL->getTypeAllocSize(ParamPTy->getElementType()))
01178         return false;
01179     }
01180   }
01181 
01182   if (Callee->isDeclaration()) {
01183     // Do not delete arguments unless we have a function body.
01184     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
01185       return false;
01186 
01187     // If the callee is just a declaration, don't change the varargsness of the
01188     // call.  We don't want to introduce a varargs call where one doesn't
01189     // already exist.
01190     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
01191     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
01192       return false;
01193 
01194     // If both the callee and the cast type are varargs, we still have to make
01195     // sure the number of fixed parameters are the same or we have the same
01196     // ABI issues as if we introduce a varargs call.
01197     if (FT->isVarArg() &&
01198         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
01199         FT->getNumParams() !=
01200         cast<FunctionType>(APTy->getElementType())->getNumParams())
01201       return false;
01202   }
01203 
01204   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
01205       !CallerPAL.isEmpty())
01206     // In this case we have more arguments than the new function type, but we
01207     // won't be dropping them.  Check that these extra arguments have attributes
01208     // that are compatible with being a vararg call argument.
01209     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
01210       unsigned Index = CallerPAL.getSlotIndex(i - 1);
01211       if (Index <= FT->getNumParams())
01212         break;
01213 
01214       // Check if it has an attribute that's incompatible with varargs.
01215       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
01216       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
01217         return false;
01218     }
01219 
01220 
01221   // Okay, we decided that this is a safe thing to do: go ahead and start
01222   // inserting cast instructions as necessary.
01223   std::vector<Value*> Args;
01224   Args.reserve(NumActualArgs);
01225   SmallVector<AttributeSet, 8> attrVec;
01226   attrVec.reserve(NumCommonArgs);
01227 
01228   // Get any return attributes.
01229   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01230 
01231   // If the return value is not being used, the type may not be compatible
01232   // with the existing attributes.  Wipe out any problematic attributes.
01233   RAttrs.
01234     removeAttributes(AttributeFuncs::
01235                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01236                      AttributeSet::ReturnIndex);
01237 
01238   // Add the new return attributes.
01239   if (RAttrs.hasAttributes())
01240     attrVec.push_back(AttributeSet::get(Caller->getContext(),
01241                                         AttributeSet::ReturnIndex, RAttrs));
01242 
01243   AI = CS.arg_begin();
01244   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
01245     Type *ParamTy = FT->getParamType(i);
01246 
01247     if ((*AI)->getType() == ParamTy) {
01248       Args.push_back(*AI);
01249     } else {
01250       Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
01251     }
01252 
01253     // Add any parameter attributes.
01254     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01255     if (PAttrs.hasAttributes())
01256       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
01257                                           PAttrs));
01258   }
01259 
01260   // If the function takes more arguments than the call was taking, add them
01261   // now.
01262   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
01263     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
01264 
01265   // If we are removing arguments to the function, emit an obnoxious warning.
01266   if (FT->getNumParams() < NumActualArgs) {
01267     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
01268     if (FT->isVarArg()) {
01269       // Add all of the arguments in their promoted form to the arg list.
01270       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
01271         Type *PTy = getPromotedType((*AI)->getType());
01272         if (PTy != (*AI)->getType()) {
01273           // Must promote to pass through va_arg area!
01274           Instruction::CastOps opcode =
01275             CastInst::getCastOpcode(*AI, false, PTy, false);
01276           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
01277         } else {
01278           Args.push_back(*AI);
01279         }
01280 
01281         // Add any parameter attributes.
01282         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01283         if (PAttrs.hasAttributes())
01284           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
01285                                               PAttrs));
01286       }
01287     }
01288   }
01289 
01290   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
01291   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
01292     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
01293 
01294   if (NewRetTy->isVoidTy())
01295     Caller->setName("");   // Void type should not have a name.
01296 
01297   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
01298                                                        attrVec);
01299 
01300   Instruction *NC;
01301   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01302     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
01303                                II->getUnwindDest(), Args);
01304     NC->takeName(II);
01305     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
01306     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
01307   } else {
01308     CallInst *CI = cast<CallInst>(Caller);
01309     NC = Builder->CreateCall(Callee, Args);
01310     NC->takeName(CI);
01311     if (CI->isTailCall())
01312       cast<CallInst>(NC)->setTailCall();
01313     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
01314     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
01315   }
01316 
01317   // Insert a cast of the return type as necessary.
01318   Value *NV = NC;
01319   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
01320     if (!NV->getType()->isVoidTy()) {
01321       NV = NC = CastInst::Create(CastInst::BitCast, NC, OldRetTy);
01322       NC->setDebugLoc(Caller->getDebugLoc());
01323 
01324       // If this is an invoke instruction, we should insert it after the first
01325       // non-phi, instruction in the normal successor block.
01326       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01327         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
01328         InsertNewInstBefore(NC, *I);
01329       } else {
01330         // Otherwise, it's a call, just insert cast right after the call.
01331         InsertNewInstBefore(NC, *Caller);
01332       }
01333       Worklist.AddUsersToWorkList(*Caller);
01334     } else {
01335       NV = UndefValue::get(Caller->getType());
01336     }
01337   }
01338 
01339   if (!Caller->use_empty())
01340     ReplaceInstUsesWith(*Caller, NV);
01341   else if (Caller->hasValueHandle())
01342     ValueHandleBase::ValueIsRAUWd(Caller, NV);
01343 
01344   EraseInstFromFunction(*Caller);
01345   return true;
01346 }
01347 
01348 // transformCallThroughTrampoline - Turn a call to a function created by
01349 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
01350 // underlying function.
01351 //
01352 Instruction *
01353 InstCombiner::transformCallThroughTrampoline(CallSite CS,
01354                                              IntrinsicInst *Tramp) {
01355   Value *Callee = CS.getCalledValue();
01356   PointerType *PTy = cast<PointerType>(Callee->getType());
01357   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01358   const AttributeSet &Attrs = CS.getAttributes();
01359 
01360   // If the call already has the 'nest' attribute somewhere then give up -
01361   // otherwise 'nest' would occur twice after splicing in the chain.
01362   if (Attrs.hasAttrSomewhere(Attribute::Nest))
01363     return 0;
01364 
01365   assert(Tramp &&
01366          "transformCallThroughTrampoline called with incorrect CallSite.");
01367 
01368   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
01369   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
01370   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
01371 
01372   const AttributeSet &NestAttrs = NestF->getAttributes();
01373   if (!NestAttrs.isEmpty()) {
01374     unsigned NestIdx = 1;
01375     Type *NestTy = 0;
01376     AttributeSet NestAttr;
01377 
01378     // Look for a parameter marked with the 'nest' attribute.
01379     for (FunctionType::param_iterator I = NestFTy->param_begin(),
01380          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
01381       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
01382         // Record the parameter type and any other attributes.
01383         NestTy = *I;
01384         NestAttr = NestAttrs.getParamAttributes(NestIdx);
01385         break;
01386       }
01387 
01388     if (NestTy) {
01389       Instruction *Caller = CS.getInstruction();
01390       std::vector<Value*> NewArgs;
01391       NewArgs.reserve(CS.arg_size() + 1);
01392 
01393       SmallVector<AttributeSet, 8> NewAttrs;
01394       NewAttrs.reserve(Attrs.getNumSlots() + 1);
01395 
01396       // Insert the nest argument into the call argument list, which may
01397       // mean appending it.  Likewise for attributes.
01398 
01399       // Add any result attributes.
01400       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01401         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01402                                              Attrs.getRetAttributes()));
01403 
01404       {
01405         unsigned Idx = 1;
01406         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
01407         do {
01408           if (Idx == NestIdx) {
01409             // Add the chain argument and attributes.
01410             Value *NestVal = Tramp->getArgOperand(2);
01411             if (NestVal->getType() != NestTy)
01412               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
01413             NewArgs.push_back(NestVal);
01414             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01415                                                  NestAttr));
01416           }
01417 
01418           if (I == E)
01419             break;
01420 
01421           // Add the original argument and attributes.
01422           NewArgs.push_back(*I);
01423           AttributeSet Attr = Attrs.getParamAttributes(Idx);
01424           if (Attr.hasAttributes(Idx)) {
01425             AttrBuilder B(Attr, Idx);
01426             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01427                                                  Idx + (Idx >= NestIdx), B));
01428           }
01429 
01430           ++Idx, ++I;
01431         } while (1);
01432       }
01433 
01434       // Add any function attributes.
01435       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01436         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
01437                                              Attrs.getFnAttributes()));
01438 
01439       // The trampoline may have been bitcast to a bogus type (FTy).
01440       // Handle this by synthesizing a new function type, equal to FTy
01441       // with the chain parameter inserted.
01442 
01443       std::vector<Type*> NewTypes;
01444       NewTypes.reserve(FTy->getNumParams()+1);
01445 
01446       // Insert the chain's type into the list of parameter types, which may
01447       // mean appending it.
01448       {
01449         unsigned Idx = 1;
01450         FunctionType::param_iterator I = FTy->param_begin(),
01451           E = FTy->param_end();
01452 
01453         do {
01454           if (Idx == NestIdx)
01455             // Add the chain's type.
01456             NewTypes.push_back(NestTy);
01457 
01458           if (I == E)
01459             break;
01460 
01461           // Add the original type.
01462           NewTypes.push_back(*I);
01463 
01464           ++Idx, ++I;
01465         } while (1);
01466       }
01467 
01468       // Replace the trampoline call with a direct call.  Let the generic
01469       // code sort out any function type mismatches.
01470       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
01471                                                 FTy->isVarArg());
01472       Constant *NewCallee =
01473         NestF->getType() == PointerType::getUnqual(NewFTy) ?
01474         NestF : ConstantExpr::getBitCast(NestF,
01475                                          PointerType::getUnqual(NewFTy));
01476       const AttributeSet &NewPAL =
01477           AttributeSet::get(FTy->getContext(), NewAttrs);
01478 
01479       Instruction *NewCaller;
01480       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01481         NewCaller = InvokeInst::Create(NewCallee,
01482                                        II->getNormalDest(), II->getUnwindDest(),
01483                                        NewArgs);
01484         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
01485         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
01486       } else {
01487         NewCaller = CallInst::Create(NewCallee, NewArgs);
01488         if (cast<CallInst>(Caller)->isTailCall())
01489           cast<CallInst>(NewCaller)->setTailCall();
01490         cast<CallInst>(NewCaller)->
01491           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
01492         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
01493       }
01494 
01495       return NewCaller;
01496     }
01497   }
01498 
01499   // Replace the trampoline call with a direct call.  Since there is no 'nest'
01500   // parameter, there is no need to adjust the argument list.  Let the generic
01501   // code sort out any function type mismatches.
01502   Constant *NewCallee =
01503     NestF->getType() == PTy ? NestF :
01504                               ConstantExpr::getBitCast(NestF, PTy);
01505   CS.setCalledFunction(NewCallee);
01506   return CS.getInstruction();
01507 }