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 "InstCombineInternal.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/Dominators.h"
00020 #include "llvm/IR/PatternMatch.h"
00021 #include "llvm/IR/Statepoint.h"
00022 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00023 #include "llvm/Transforms/Utils/Local.h"
00024 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
00025 using namespace llvm;
00026 using namespace PatternMatch;
00027 
00028 #define DEBUG_TYPE "instcombine"
00029 
00030 STATISTIC(NumSimplified, "Number of library calls simplified");
00031 
00032 /// getPromotedType - Return the specified type promoted as it would be to pass
00033 /// though a va_arg area.
00034 static Type *getPromotedType(Type *Ty) {
00035   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
00036     if (ITy->getBitWidth() < 32)
00037       return Type::getInt32Ty(Ty->getContext());
00038   }
00039   return Ty;
00040 }
00041 
00042 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
00043 /// single scalar element, like {{{type}}} or [1 x type], return type.
00044 static Type *reduceToSingleValueType(Type *T) {
00045   while (!T->isSingleValueType()) {
00046     if (StructType *STy = dyn_cast<StructType>(T)) {
00047       if (STy->getNumElements() == 1)
00048         T = STy->getElementType(0);
00049       else
00050         break;
00051     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
00052       if (ATy->getNumElements() == 1)
00053         T = ATy->getElementType();
00054       else
00055         break;
00056     } else
00057       break;
00058   }
00059 
00060   return T;
00061 }
00062 
00063 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
00064   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, AC, MI, DT);
00065   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, AC, MI, DT);
00066   unsigned MinAlign = std::min(DstAlign, SrcAlign);
00067   unsigned CopyAlign = MI->getAlignment();
00068 
00069   if (CopyAlign < MinAlign) {
00070     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00071                                              MinAlign, false));
00072     return MI;
00073   }
00074 
00075   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
00076   // load/store.
00077   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
00078   if (!MemOpLength) return nullptr;
00079 
00080   // Source and destination pointer types are always "i8*" for intrinsic.  See
00081   // if the size is something we can handle with a single primitive load/store.
00082   // A single load+store correctly handles overlapping memory in the memmove
00083   // case.
00084   uint64_t Size = MemOpLength->getLimitedValue();
00085   assert(Size && "0-sized memory transferring should be removed already.");
00086 
00087   if (Size > 8 || (Size&(Size-1)))
00088     return nullptr;  // If not 1/2/4/8 bytes, exit.
00089 
00090   // Use an integer load+store unless we can find something better.
00091   unsigned SrcAddrSp =
00092     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
00093   unsigned DstAddrSp =
00094     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
00095 
00096   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
00097   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
00098   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
00099 
00100   // Memcpy forces the use of i8* for the source and destination.  That means
00101   // that if you're using memcpy to move one double around, you'll get a cast
00102   // from double* to i8*.  We'd much rather use a double load+store rather than
00103   // an i64 load+store, here because this improves the odds that the source or
00104   // dest address will be promotable.  See if we can find a better type than the
00105   // integer datatype.
00106   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
00107   MDNode *CopyMD = nullptr;
00108   if (StrippedDest != MI->getArgOperand(0)) {
00109     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
00110                                     ->getElementType();
00111     if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
00112       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
00113       // down through these levels if so.
00114       SrcETy = reduceToSingleValueType(SrcETy);
00115 
00116       if (SrcETy->isSingleValueType()) {
00117         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
00118         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
00119 
00120         // If the memcpy has metadata describing the members, see if we can
00121         // get the TBAA tag describing our copy.
00122         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
00123           if (M->getNumOperands() == 3 && M->getOperand(0) &&
00124               mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
00125               mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
00126               M->getOperand(1) &&
00127               mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
00128               mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
00129                   Size &&
00130               M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
00131             CopyMD = cast<MDNode>(M->getOperand(2));
00132         }
00133       }
00134     }
00135   }
00136 
00137   // If the memcpy/memmove provides better alignment info than we can
00138   // infer, use it.
00139   SrcAlign = std::max(SrcAlign, CopyAlign);
00140   DstAlign = std::max(DstAlign, CopyAlign);
00141 
00142   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
00143   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
00144   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
00145   L->setAlignment(SrcAlign);
00146   if (CopyMD)
00147     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00148   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
00149   S->setAlignment(DstAlign);
00150   if (CopyMD)
00151     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00152 
00153   // Set the size of the copy to 0, it will be deleted on the next iteration.
00154   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
00155   return MI;
00156 }
00157 
00158 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
00159   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, AC, MI, DT);
00160   if (MI->getAlignment() < Alignment) {
00161     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00162                                              Alignment, false));
00163     return MI;
00164   }
00165 
00166   // Extract the length and alignment and fill if they are constant.
00167   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
00168   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
00169   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
00170     return nullptr;
00171   uint64_t Len = LenC->getLimitedValue();
00172   Alignment = MI->getAlignment();
00173   assert(Len && "0-sized memory setting should be removed already.");
00174 
00175   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
00176   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
00177     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
00178 
00179     Value *Dest = MI->getDest();
00180     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
00181     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
00182     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
00183 
00184     // Alignment 0 is identity for alignment 1 for memset, but not store.
00185     if (Alignment == 0) Alignment = 1;
00186 
00187     // Extract the fill value and store.
00188     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
00189     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
00190                                         MI->isVolatile());
00191     S->setAlignment(Alignment);
00192 
00193     // Set the size of the copy to 0, it will be deleted on the next iteration.
00194     MI->setLength(Constant::getNullValue(LenC->getType()));
00195     return MI;
00196   }
00197 
00198   return nullptr;
00199 }
00200 
00201 /// visitCallInst - CallInst simplification.  This mostly only handles folding
00202 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
00203 /// the heavy lifting.
00204 ///
00205 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
00206   if (isFreeCall(&CI, TLI))
00207     return visitFree(CI);
00208 
00209   // If the caller function is nounwind, mark the call as nounwind, even if the
00210   // callee isn't.
00211   if (CI.getParent()->getParent()->doesNotThrow() &&
00212       !CI.doesNotThrow()) {
00213     CI.setDoesNotThrow();
00214     return &CI;
00215   }
00216 
00217   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
00218   if (!II) return visitCallSite(&CI);
00219 
00220   // Intrinsics cannot occur in an invoke, so handle them here instead of in
00221   // visitCallSite.
00222   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
00223     bool Changed = false;
00224 
00225     // memmove/cpy/set of zero bytes is a noop.
00226     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
00227       if (NumBytes->isNullValue())
00228         return EraseInstFromFunction(CI);
00229 
00230       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
00231         if (CI->getZExtValue() == 1) {
00232           // Replace the instruction with just byte operations.  We would
00233           // transform other cases to loads/stores, but we don't know if
00234           // alignment is sufficient.
00235         }
00236     }
00237 
00238     // No other transformations apply to volatile transfers.
00239     if (MI->isVolatile())
00240       return nullptr;
00241 
00242     // If we have a memmove and the source operation is a constant global,
00243     // then the source and dest pointers can't alias, so we can change this
00244     // into a call to memcpy.
00245     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
00246       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
00247         if (GVSrc->isConstant()) {
00248           Module *M = CI.getParent()->getParent()->getParent();
00249           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
00250           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
00251                            CI.getArgOperand(1)->getType(),
00252                            CI.getArgOperand(2)->getType() };
00253           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
00254           Changed = true;
00255         }
00256     }
00257 
00258     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
00259       // memmove(x,x,size) -> noop.
00260       if (MTI->getSource() == MTI->getDest())
00261         return EraseInstFromFunction(CI);
00262     }
00263 
00264     // If we can determine a pointer alignment that is bigger than currently
00265     // set, update the alignment.
00266     if (isa<MemTransferInst>(MI)) {
00267       if (Instruction *I = SimplifyMemTransfer(MI))
00268         return I;
00269     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
00270       if (Instruction *I = SimplifyMemSet(MSI))
00271         return I;
00272     }
00273 
00274     if (Changed) return II;
00275   }
00276 
00277   switch (II->getIntrinsicID()) {
00278   default: break;
00279   case Intrinsic::objectsize: {
00280     uint64_t Size;
00281     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
00282       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
00283     return nullptr;
00284   }
00285   case Intrinsic::bswap: {
00286     Value *IIOperand = II->getArgOperand(0);
00287     Value *X = nullptr;
00288 
00289     // bswap(bswap(x)) -> x
00290     if (match(IIOperand, m_BSwap(m_Value(X))))
00291         return ReplaceInstUsesWith(CI, X);
00292 
00293     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
00294     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
00295       unsigned C = X->getType()->getPrimitiveSizeInBits() -
00296         IIOperand->getType()->getPrimitiveSizeInBits();
00297       Value *CV = ConstantInt::get(X->getType(), C);
00298       Value *V = Builder->CreateLShr(X, CV);
00299       return new TruncInst(V, IIOperand->getType());
00300     }
00301     break;
00302   }
00303 
00304   case Intrinsic::powi:
00305     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00306       // powi(x, 0) -> 1.0
00307       if (Power->isZero())
00308         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
00309       // powi(x, 1) -> x
00310       if (Power->isOne())
00311         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
00312       // powi(x, -1) -> 1/x
00313       if (Power->isAllOnesValue())
00314         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
00315                                           II->getArgOperand(0));
00316     }
00317     break;
00318   case Intrinsic::cttz: {
00319     // If all bits below the first known one are known zero,
00320     // this value is constant.
00321     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00322     // FIXME: Try to simplify vectors of integers.
00323     if (!IT) break;
00324     uint32_t BitWidth = IT->getBitWidth();
00325     APInt KnownZero(BitWidth, 0);
00326     APInt KnownOne(BitWidth, 0);
00327     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
00328     unsigned TrailingZeros = KnownOne.countTrailingZeros();
00329     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
00330     if ((Mask & KnownZero) == Mask)
00331       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00332                                  APInt(BitWidth, TrailingZeros)));
00333 
00334     }
00335     break;
00336   case Intrinsic::ctlz: {
00337     // If all bits above the first known one are known zero,
00338     // this value is constant.
00339     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00340     // FIXME: Try to simplify vectors of integers.
00341     if (!IT) break;
00342     uint32_t BitWidth = IT->getBitWidth();
00343     APInt KnownZero(BitWidth, 0);
00344     APInt KnownOne(BitWidth, 0);
00345     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
00346     unsigned LeadingZeros = KnownOne.countLeadingZeros();
00347     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
00348     if ((Mask & KnownZero) == Mask)
00349       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00350                                  APInt(BitWidth, LeadingZeros)));
00351 
00352     }
00353     break;
00354   case Intrinsic::uadd_with_overflow: {
00355     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00356     OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, II);
00357     if (OR == OverflowResult::NeverOverflows)
00358       return CreateOverflowTuple(II, Builder->CreateNUWAdd(LHS, RHS), false);
00359     if (OR == OverflowResult::AlwaysOverflows)
00360       return CreateOverflowTuple(II, Builder->CreateAdd(LHS, RHS), true);
00361   }
00362   // FALL THROUGH uadd into sadd
00363   case Intrinsic::sadd_with_overflow:
00364     // Canonicalize constants into the RHS.
00365     if (isa<Constant>(II->getArgOperand(0)) &&
00366         !isa<Constant>(II->getArgOperand(1))) {
00367       Value *LHS = II->getArgOperand(0);
00368       II->setArgOperand(0, II->getArgOperand(1));
00369       II->setArgOperand(1, LHS);
00370       return II;
00371     }
00372 
00373     // X + undef -> undef
00374     if (isa<UndefValue>(II->getArgOperand(1)))
00375       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00376 
00377     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00378       // X + 0 -> {X, false}
00379       if (RHS->isZero()) {
00380         return CreateOverflowTuple(II, II->getArgOperand(0), false,
00381                                     /*ReUseName*/false);
00382       }
00383     }
00384 
00385     // We can strength reduce reduce this signed add into a regular add if we
00386     // can prove that it will never overflow.
00387     if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow) {
00388       Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00389       if (WillNotOverflowSignedAdd(LHS, RHS, II)) {
00390         return CreateOverflowTuple(II, Builder->CreateNSWAdd(LHS, RHS), false);
00391       }
00392     }
00393 
00394     break;
00395   case Intrinsic::usub_with_overflow:
00396   case Intrinsic::ssub_with_overflow: {
00397     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00398     // undef - X -> undef
00399     // X - undef -> undef
00400     if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
00401       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00402 
00403     if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
00404       // X - 0 -> {X, false}
00405       if (ConstRHS->isZero()) {
00406         return CreateOverflowTuple(II, LHS, false, /*ReUseName*/false);
00407       }
00408     }
00409     if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
00410       if (WillNotOverflowSignedSub(LHS, RHS, II)) {
00411         return CreateOverflowTuple(II, Builder->CreateNSWSub(LHS, RHS), false);
00412       }
00413     } else {
00414       if (WillNotOverflowUnsignedSub(LHS, RHS, II)) {
00415         return CreateOverflowTuple(II, Builder->CreateNUWSub(LHS, RHS), false);
00416       }
00417     }
00418     break;
00419   }
00420   case Intrinsic::umul_with_overflow: {
00421     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00422     OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, II);
00423     if (OR == OverflowResult::NeverOverflows)
00424       return CreateOverflowTuple(II, Builder->CreateNUWMul(LHS, RHS), false);
00425     if (OR == OverflowResult::AlwaysOverflows)
00426       return CreateOverflowTuple(II, Builder->CreateMul(LHS, RHS), true);
00427   } // FALL THROUGH
00428   case Intrinsic::smul_with_overflow:
00429     // Canonicalize constants into the RHS.
00430     if (isa<Constant>(II->getArgOperand(0)) &&
00431         !isa<Constant>(II->getArgOperand(1))) {
00432       Value *LHS = II->getArgOperand(0);
00433       II->setArgOperand(0, II->getArgOperand(1));
00434       II->setArgOperand(1, LHS);
00435       return II;
00436     }
00437 
00438     // X * undef -> undef
00439     if (isa<UndefValue>(II->getArgOperand(1)))
00440       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00441 
00442     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00443       // X*0 -> {0, false}
00444       if (RHSI->isZero())
00445         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
00446 
00447       // X * 1 -> {X, false}
00448       if (RHSI->equalsInt(1)) {
00449         return CreateOverflowTuple(II, II->getArgOperand(0), false,
00450                                     /*ReUseName*/false);
00451       }
00452     }
00453     if (II->getIntrinsicID() == Intrinsic::smul_with_overflow) {
00454       Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00455       if (WillNotOverflowSignedMul(LHS, RHS, II)) {
00456         return CreateOverflowTuple(II, Builder->CreateNSWMul(LHS, RHS), false);
00457       }
00458     }
00459     break;
00460   case Intrinsic::minnum:
00461   case Intrinsic::maxnum: {
00462     Value *Arg0 = II->getArgOperand(0);
00463     Value *Arg1 = II->getArgOperand(1);
00464 
00465     // fmin(x, x) -> x
00466     if (Arg0 == Arg1)
00467       return ReplaceInstUsesWith(CI, Arg0);
00468 
00469     const ConstantFP *C0 = dyn_cast<ConstantFP>(Arg0);
00470     const ConstantFP *C1 = dyn_cast<ConstantFP>(Arg1);
00471 
00472     // Canonicalize constants into the RHS.
00473     if (C0 && !C1) {
00474       II->setArgOperand(0, Arg1);
00475       II->setArgOperand(1, Arg0);
00476       return II;
00477     }
00478 
00479     // fmin(x, nan) -> x
00480     if (C1 && C1->isNaN())
00481       return ReplaceInstUsesWith(CI, Arg0);
00482 
00483     // This is the value because if undef were NaN, we would return the other
00484     // value and cannot return a NaN unless both operands are.
00485     //
00486     // fmin(undef, x) -> x
00487     if (isa<UndefValue>(Arg0))
00488       return ReplaceInstUsesWith(CI, Arg1);
00489 
00490     // fmin(x, undef) -> x
00491     if (isa<UndefValue>(Arg1))
00492       return ReplaceInstUsesWith(CI, Arg0);
00493 
00494     Value *X = nullptr;
00495     Value *Y = nullptr;
00496     if (II->getIntrinsicID() == Intrinsic::minnum) {
00497       // fmin(x, fmin(x, y)) -> fmin(x, y)
00498       // fmin(y, fmin(x, y)) -> fmin(x, y)
00499       if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
00500         if (Arg0 == X || Arg0 == Y)
00501           return ReplaceInstUsesWith(CI, Arg1);
00502       }
00503 
00504       // fmin(fmin(x, y), x) -> fmin(x, y)
00505       // fmin(fmin(x, y), y) -> fmin(x, y)
00506       if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
00507         if (Arg1 == X || Arg1 == Y)
00508           return ReplaceInstUsesWith(CI, Arg0);
00509       }
00510 
00511       // TODO: fmin(nnan x, inf) -> x
00512       // TODO: fmin(nnan ninf x, flt_max) -> x
00513       if (C1 && C1->isInfinity()) {
00514         // fmin(x, -inf) -> -inf
00515         if (C1->isNegative())
00516           return ReplaceInstUsesWith(CI, Arg1);
00517       }
00518     } else {
00519       assert(II->getIntrinsicID() == Intrinsic::maxnum);
00520       // fmax(x, fmax(x, y)) -> fmax(x, y)
00521       // fmax(y, fmax(x, y)) -> fmax(x, y)
00522       if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
00523         if (Arg0 == X || Arg0 == Y)
00524           return ReplaceInstUsesWith(CI, Arg1);
00525       }
00526 
00527       // fmax(fmax(x, y), x) -> fmax(x, y)
00528       // fmax(fmax(x, y), y) -> fmax(x, y)
00529       if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
00530         if (Arg1 == X || Arg1 == Y)
00531           return ReplaceInstUsesWith(CI, Arg0);
00532       }
00533 
00534       // TODO: fmax(nnan x, -inf) -> x
00535       // TODO: fmax(nnan ninf x, -flt_max) -> x
00536       if (C1 && C1->isInfinity()) {
00537         // fmax(x, inf) -> inf
00538         if (!C1->isNegative())
00539           return ReplaceInstUsesWith(CI, Arg1);
00540       }
00541     }
00542     break;
00543   }
00544   case Intrinsic::ppc_altivec_lvx:
00545   case Intrinsic::ppc_altivec_lvxl:
00546     // Turn PPC lvx -> load if the pointer is known aligned.
00547     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, AC, II, DT) >=
00548         16) {
00549       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00550                                          PointerType::getUnqual(II->getType()));
00551       return new LoadInst(Ptr);
00552     }
00553     break;
00554   case Intrinsic::ppc_vsx_lxvw4x:
00555   case Intrinsic::ppc_vsx_lxvd2x: {
00556     // Turn PPC VSX loads into normal loads.
00557     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00558                                         PointerType::getUnqual(II->getType()));
00559     return new LoadInst(Ptr, Twine(""), false, 1);
00560   }
00561   case Intrinsic::ppc_altivec_stvx:
00562   case Intrinsic::ppc_altivec_stvxl:
00563     // Turn stvx -> store if the pointer is known aligned.
00564     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, AC, II, DT) >=
00565         16) {
00566       Type *OpPtrTy =
00567         PointerType::getUnqual(II->getArgOperand(0)->getType());
00568       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00569       return new StoreInst(II->getArgOperand(0), Ptr);
00570     }
00571     break;
00572   case Intrinsic::ppc_vsx_stxvw4x:
00573   case Intrinsic::ppc_vsx_stxvd2x: {
00574     // Turn PPC VSX stores into normal stores.
00575     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
00576     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00577     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
00578   }
00579   case Intrinsic::ppc_qpx_qvlfs:
00580     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
00581     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, AC, II, DT) >=
00582         16) {
00583       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00584                                          PointerType::getUnqual(II->getType()));
00585       return new LoadInst(Ptr);
00586     }
00587     break;
00588   case Intrinsic::ppc_qpx_qvlfd:
00589     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
00590     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, AC, II, DT) >=
00591         32) {
00592       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00593                                          PointerType::getUnqual(II->getType()));
00594       return new LoadInst(Ptr);
00595     }
00596     break;
00597   case Intrinsic::ppc_qpx_qvstfs:
00598     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
00599     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, AC, II, DT) >=
00600         16) {
00601       Type *OpPtrTy =
00602         PointerType::getUnqual(II->getArgOperand(0)->getType());
00603       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00604       return new StoreInst(II->getArgOperand(0), Ptr);
00605     }
00606     break;
00607   case Intrinsic::ppc_qpx_qvstfd:
00608     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
00609     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, AC, II, DT) >=
00610         32) {
00611       Type *OpPtrTy =
00612         PointerType::getUnqual(II->getArgOperand(0)->getType());
00613       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00614       return new StoreInst(II->getArgOperand(0), Ptr);
00615     }
00616     break;
00617   case Intrinsic::x86_sse_storeu_ps:
00618   case Intrinsic::x86_sse2_storeu_pd:
00619   case Intrinsic::x86_sse2_storeu_dq:
00620     // Turn X86 storeu -> store if the pointer is known aligned.
00621     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, AC, II, DT) >=
00622         16) {
00623       Type *OpPtrTy =
00624         PointerType::getUnqual(II->getArgOperand(1)->getType());
00625       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
00626       return new StoreInst(II->getArgOperand(1), Ptr);
00627     }
00628     break;
00629 
00630   case Intrinsic::x86_sse_cvtss2si:
00631   case Intrinsic::x86_sse_cvtss2si64:
00632   case Intrinsic::x86_sse_cvttss2si:
00633   case Intrinsic::x86_sse_cvttss2si64:
00634   case Intrinsic::x86_sse2_cvtsd2si:
00635   case Intrinsic::x86_sse2_cvtsd2si64:
00636   case Intrinsic::x86_sse2_cvttsd2si:
00637   case Intrinsic::x86_sse2_cvttsd2si64: {
00638     // These intrinsics only demand the 0th element of their input vectors. If
00639     // we can simplify the input based on that, do so now.
00640     unsigned VWidth =
00641       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00642     APInt DemandedElts(VWidth, 1);
00643     APInt UndefElts(VWidth, 0);
00644     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
00645                                               DemandedElts, UndefElts)) {
00646       II->setArgOperand(0, V);
00647       return II;
00648     }
00649     break;
00650   }
00651 
00652   // Constant fold <A x Bi> << Ci.
00653   // FIXME: We don't handle _dq because it's a shift of an i128, but is
00654   // represented in the IR as <2 x i64>. A per element shift is wrong.
00655   case Intrinsic::x86_sse2_psll_d:
00656   case Intrinsic::x86_sse2_psll_q:
00657   case Intrinsic::x86_sse2_psll_w:
00658   case Intrinsic::x86_sse2_pslli_d:
00659   case Intrinsic::x86_sse2_pslli_q:
00660   case Intrinsic::x86_sse2_pslli_w:
00661   case Intrinsic::x86_avx2_psll_d:
00662   case Intrinsic::x86_avx2_psll_q:
00663   case Intrinsic::x86_avx2_psll_w:
00664   case Intrinsic::x86_avx2_pslli_d:
00665   case Intrinsic::x86_avx2_pslli_q:
00666   case Intrinsic::x86_avx2_pslli_w:
00667   case Intrinsic::x86_sse2_psrl_d:
00668   case Intrinsic::x86_sse2_psrl_q:
00669   case Intrinsic::x86_sse2_psrl_w:
00670   case Intrinsic::x86_sse2_psrli_d:
00671   case Intrinsic::x86_sse2_psrli_q:
00672   case Intrinsic::x86_sse2_psrli_w:
00673   case Intrinsic::x86_avx2_psrl_d:
00674   case Intrinsic::x86_avx2_psrl_q:
00675   case Intrinsic::x86_avx2_psrl_w:
00676   case Intrinsic::x86_avx2_psrli_d:
00677   case Intrinsic::x86_avx2_psrli_q:
00678   case Intrinsic::x86_avx2_psrli_w: {
00679     // Simplify if count is constant. To 0 if >= BitWidth,
00680     // otherwise to shl/lshr.
00681     auto CDV = dyn_cast<ConstantDataVector>(II->getArgOperand(1));
00682     auto CInt = dyn_cast<ConstantInt>(II->getArgOperand(1));
00683     if (!CDV && !CInt)
00684       break;
00685     ConstantInt *Count;
00686     if (CDV)
00687       Count = cast<ConstantInt>(CDV->getElementAsConstant(0));
00688     else
00689       Count = CInt;
00690 
00691     auto Vec = II->getArgOperand(0);
00692     auto VT = cast<VectorType>(Vec->getType());
00693     if (Count->getZExtValue() >
00694         VT->getElementType()->getPrimitiveSizeInBits() - 1)
00695       return ReplaceInstUsesWith(
00696           CI, ConstantAggregateZero::get(Vec->getType()));
00697 
00698     bool isPackedShiftLeft = true;
00699     switch (II->getIntrinsicID()) {
00700     default : break;
00701     case Intrinsic::x86_sse2_psrl_d:
00702     case Intrinsic::x86_sse2_psrl_q:
00703     case Intrinsic::x86_sse2_psrl_w:
00704     case Intrinsic::x86_sse2_psrli_d:
00705     case Intrinsic::x86_sse2_psrli_q:
00706     case Intrinsic::x86_sse2_psrli_w:
00707     case Intrinsic::x86_avx2_psrl_d:
00708     case Intrinsic::x86_avx2_psrl_q:
00709     case Intrinsic::x86_avx2_psrl_w:
00710     case Intrinsic::x86_avx2_psrli_d:
00711     case Intrinsic::x86_avx2_psrli_q:
00712     case Intrinsic::x86_avx2_psrli_w: isPackedShiftLeft = false; break;
00713     }
00714 
00715     unsigned VWidth = VT->getNumElements();
00716     // Get a constant vector of the same type as the first operand.
00717     auto VTCI = ConstantInt::get(VT->getElementType(), Count->getZExtValue());
00718     if (isPackedShiftLeft)
00719       return BinaryOperator::CreateShl(Vec,
00720           Builder->CreateVectorSplat(VWidth, VTCI));
00721 
00722     return BinaryOperator::CreateLShr(Vec,
00723         Builder->CreateVectorSplat(VWidth, VTCI));
00724   }
00725 
00726   case Intrinsic::x86_sse41_pmovsxbw:
00727   case Intrinsic::x86_sse41_pmovsxwd:
00728   case Intrinsic::x86_sse41_pmovsxdq:
00729   case Intrinsic::x86_sse41_pmovzxbw:
00730   case Intrinsic::x86_sse41_pmovzxwd:
00731   case Intrinsic::x86_sse41_pmovzxdq: {
00732     // pmov{s|z}x ignores the upper half of their input vectors.
00733     unsigned VWidth =
00734       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00735     unsigned LowHalfElts = VWidth / 2;
00736     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
00737     APInt UndefElts(VWidth, 0);
00738     if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
00739                                                  InputDemandedElts,
00740                                                  UndefElts)) {
00741       II->setArgOperand(0, TmpV);
00742       return II;
00743     }
00744     break;
00745   }
00746 
00747   case Intrinsic::x86_sse4a_insertqi: {
00748     // insertqi x, y, 64, 0 can just copy y's lower bits and leave the top
00749     // ones undef
00750     // TODO: eventually we should lower this intrinsic to IR
00751     if (auto CIWidth = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
00752       if (auto CIStart = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
00753         unsigned Index = CIStart->getZExtValue();
00754         // From AMD documentation: "a value of zero in the field length is
00755         // defined as length of 64".
00756         unsigned Length = CIWidth->equalsInt(0) ? 64 : CIWidth->getZExtValue();
00757 
00758         // From AMD documentation: "If the sum of the bit index + length field
00759         // is greater than 64, the results are undefined".
00760 
00761         // Note that both field index and field length are 8-bit quantities.
00762         // Since variables 'Index' and 'Length' are unsigned values
00763         // obtained from zero-extending field index and field length
00764         // respectively, their sum should never wrap around.
00765         if ((Index + Length) > 64)
00766           return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00767 
00768         if (Length == 64 && Index == 0) {
00769           Value *Vec = II->getArgOperand(1);
00770           Value *Undef = UndefValue::get(Vec->getType());
00771           const uint32_t Mask[] = { 0, 2 };
00772           return ReplaceInstUsesWith(
00773               CI,
00774               Builder->CreateShuffleVector(
00775                   Vec, Undef, ConstantDataVector::get(
00776                                   II->getContext(), makeArrayRef(Mask))));
00777 
00778         } else if (auto Source =
00779                        dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00780           if (Source->hasOneUse() &&
00781               Source->getArgOperand(1) == II->getArgOperand(1)) {
00782             // If the source of the insert has only one use and it's another
00783             // insert (and they're both inserting from the same vector), try to
00784             // bundle both together.
00785             auto CISourceWidth =
00786                 dyn_cast<ConstantInt>(Source->getArgOperand(2));
00787             auto CISourceStart =
00788                 dyn_cast<ConstantInt>(Source->getArgOperand(3));
00789             if (CISourceStart && CISourceWidth) {
00790               unsigned Start = CIStart->getZExtValue();
00791               unsigned Width = CIWidth->getZExtValue();
00792               unsigned End = Start + Width;
00793               unsigned SourceStart = CISourceStart->getZExtValue();
00794               unsigned SourceWidth = CISourceWidth->getZExtValue();
00795               unsigned SourceEnd = SourceStart + SourceWidth;
00796               unsigned NewStart, NewWidth;
00797               bool ShouldReplace = false;
00798               if (Start <= SourceStart && SourceStart <= End) {
00799                 NewStart = Start;
00800                 NewWidth = std::max(End, SourceEnd) - NewStart;
00801                 ShouldReplace = true;
00802               } else if (SourceStart <= Start && Start <= SourceEnd) {
00803                 NewStart = SourceStart;
00804                 NewWidth = std::max(SourceEnd, End) - NewStart;
00805                 ShouldReplace = true;
00806               }
00807 
00808               if (ShouldReplace) {
00809                 Constant *ConstantWidth = ConstantInt::get(
00810                     II->getArgOperand(2)->getType(), NewWidth, false);
00811                 Constant *ConstantStart = ConstantInt::get(
00812                     II->getArgOperand(3)->getType(), NewStart, false);
00813                 Value *Args[4] = { Source->getArgOperand(0),
00814                                    II->getArgOperand(1), ConstantWidth,
00815                                    ConstantStart };
00816                 Module *M = CI.getParent()->getParent()->getParent();
00817                 Value *F =
00818                     Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
00819                 return ReplaceInstUsesWith(CI, Builder->CreateCall(F, Args));
00820               }
00821             }
00822           }
00823         }
00824       }
00825     }
00826     break;
00827   }
00828 
00829   case Intrinsic::x86_sse41_pblendvb:
00830   case Intrinsic::x86_sse41_blendvps:
00831   case Intrinsic::x86_sse41_blendvpd:
00832   case Intrinsic::x86_avx_blendv_ps_256:
00833   case Intrinsic::x86_avx_blendv_pd_256:
00834   case Intrinsic::x86_avx2_pblendvb: {
00835     // Convert blendv* to vector selects if the mask is constant.
00836     // This optimization is convoluted because the intrinsic is defined as
00837     // getting a vector of floats or doubles for the ps and pd versions.
00838     // FIXME: That should be changed.
00839     Value *Mask = II->getArgOperand(2);
00840     if (auto C = dyn_cast<ConstantDataVector>(Mask)) {
00841       auto Tyi1 = Builder->getInt1Ty();
00842       auto SelectorType = cast<VectorType>(Mask->getType());
00843       auto EltTy = SelectorType->getElementType();
00844       unsigned Size = SelectorType->getNumElements();
00845       unsigned BitWidth =
00846           EltTy->isFloatTy()
00847               ? 32
00848               : (EltTy->isDoubleTy() ? 64 : EltTy->getIntegerBitWidth());
00849       assert((BitWidth == 64 || BitWidth == 32 || BitWidth == 8) &&
00850              "Wrong arguments for variable blend intrinsic");
00851       SmallVector<Constant *, 32> Selectors;
00852       for (unsigned I = 0; I < Size; ++I) {
00853         // The intrinsics only read the top bit
00854         uint64_t Selector;
00855         if (BitWidth == 8)
00856           Selector = C->getElementAsInteger(I);
00857         else
00858           Selector = C->getElementAsAPFloat(I).bitcastToAPInt().getZExtValue();
00859         Selectors.push_back(ConstantInt::get(Tyi1, Selector >> (BitWidth - 1)));
00860       }
00861       auto NewSelector = ConstantVector::get(Selectors);
00862       return SelectInst::Create(NewSelector, II->getArgOperand(1),
00863                                 II->getArgOperand(0), "blendv");
00864     } else {
00865       break;
00866     }
00867   }
00868 
00869   case Intrinsic::x86_avx_vpermilvar_ps:
00870   case Intrinsic::x86_avx_vpermilvar_ps_256:
00871   case Intrinsic::x86_avx_vpermilvar_pd:
00872   case Intrinsic::x86_avx_vpermilvar_pd_256: {
00873     // Convert vpermil* to shufflevector if the mask is constant.
00874     Value *V = II->getArgOperand(1);
00875     unsigned Size = cast<VectorType>(V->getType())->getNumElements();
00876     assert(Size == 8 || Size == 4 || Size == 2);
00877     uint32_t Indexes[8];
00878     if (auto C = dyn_cast<ConstantDataVector>(V)) {
00879       // The intrinsics only read one or two bits, clear the rest.
00880       for (unsigned I = 0; I < Size; ++I) {
00881         uint32_t Index = C->getElementAsInteger(I) & 0x3;
00882         if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
00883             II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
00884           Index >>= 1;
00885         Indexes[I] = Index;
00886       }
00887     } else if (isa<ConstantAggregateZero>(V)) {
00888       for (unsigned I = 0; I < Size; ++I)
00889         Indexes[I] = 0;
00890     } else {
00891       break;
00892     }
00893     // The _256 variants are a bit trickier since the mask bits always index
00894     // into the corresponding 128 half. In order to convert to a generic
00895     // shuffle, we have to make that explicit.
00896     if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
00897         II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) {
00898       for (unsigned I = Size / 2; I < Size; ++I)
00899         Indexes[I] += Size / 2;
00900     }
00901     auto NewC =
00902         ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size));
00903     auto V1 = II->getArgOperand(0);
00904     auto V2 = UndefValue::get(V1->getType());
00905     auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
00906     return ReplaceInstUsesWith(CI, Shuffle);
00907   }
00908 
00909   case Intrinsic::ppc_altivec_vperm:
00910     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
00911     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
00912     // a vectorshuffle for little endian, we must undo the transformation
00913     // performed on vec_perm in altivec.h.  That is, we must complement
00914     // the permutation mask with respect to 31 and reverse the order of
00915     // V1 and V2.
00916     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
00917       assert(Mask->getType()->getVectorNumElements() == 16 &&
00918              "Bad type for intrinsic!");
00919 
00920       // Check that all of the elements are integer constants or undefs.
00921       bool AllEltsOk = true;
00922       for (unsigned i = 0; i != 16; ++i) {
00923         Constant *Elt = Mask->getAggregateElement(i);
00924         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
00925           AllEltsOk = false;
00926           break;
00927         }
00928       }
00929 
00930       if (AllEltsOk) {
00931         // Cast the input vectors to byte vectors.
00932         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
00933                                             Mask->getType());
00934         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
00935                                             Mask->getType());
00936         Value *Result = UndefValue::get(Op0->getType());
00937 
00938         // Only extract each element once.
00939         Value *ExtractedElts[32];
00940         memset(ExtractedElts, 0, sizeof(ExtractedElts));
00941 
00942         for (unsigned i = 0; i != 16; ++i) {
00943           if (isa<UndefValue>(Mask->getAggregateElement(i)))
00944             continue;
00945           unsigned Idx =
00946             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
00947           Idx &= 31;  // Match the hardware behavior.
00948           if (DL && DL->isLittleEndian())
00949             Idx = 31 - Idx;
00950 
00951           if (!ExtractedElts[Idx]) {
00952             Value *Op0ToUse = (DL && DL->isLittleEndian()) ? Op1 : Op0;
00953             Value *Op1ToUse = (DL && DL->isLittleEndian()) ? Op0 : Op1;
00954             ExtractedElts[Idx] =
00955               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
00956                                             Builder->getInt32(Idx&15));
00957           }
00958 
00959           // Insert this value into the result vector.
00960           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
00961                                                 Builder->getInt32(i));
00962         }
00963         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
00964       }
00965     }
00966     break;
00967 
00968   case Intrinsic::arm_neon_vld1:
00969   case Intrinsic::arm_neon_vld2:
00970   case Intrinsic::arm_neon_vld3:
00971   case Intrinsic::arm_neon_vld4:
00972   case Intrinsic::arm_neon_vld2lane:
00973   case Intrinsic::arm_neon_vld3lane:
00974   case Intrinsic::arm_neon_vld4lane:
00975   case Intrinsic::arm_neon_vst1:
00976   case Intrinsic::arm_neon_vst2:
00977   case Intrinsic::arm_neon_vst3:
00978   case Intrinsic::arm_neon_vst4:
00979   case Intrinsic::arm_neon_vst2lane:
00980   case Intrinsic::arm_neon_vst3lane:
00981   case Intrinsic::arm_neon_vst4lane: {
00982     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, AC, II, DT);
00983     unsigned AlignArg = II->getNumArgOperands() - 1;
00984     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
00985     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
00986       II->setArgOperand(AlignArg,
00987                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
00988                                          MemAlign, false));
00989       return II;
00990     }
00991     break;
00992   }
00993 
00994   case Intrinsic::arm_neon_vmulls:
00995   case Intrinsic::arm_neon_vmullu:
00996   case Intrinsic::aarch64_neon_smull:
00997   case Intrinsic::aarch64_neon_umull: {
00998     Value *Arg0 = II->getArgOperand(0);
00999     Value *Arg1 = II->getArgOperand(1);
01000 
01001     // Handle mul by zero first:
01002     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
01003       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
01004     }
01005 
01006     // Check for constant LHS & RHS - in this case we just simplify.
01007     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
01008                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
01009     VectorType *NewVT = cast<VectorType>(II->getType());
01010     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
01011       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
01012         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
01013         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
01014 
01015         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
01016       }
01017 
01018       // Couldn't simplify - canonicalize constant to the RHS.
01019       std::swap(Arg0, Arg1);
01020     }
01021 
01022     // Handle mul by one:
01023     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
01024       if (ConstantInt *Splat =
01025               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
01026         if (Splat->isOne())
01027           return CastInst::CreateIntegerCast(Arg0, II->getType(),
01028                                              /*isSigned=*/!Zext);
01029 
01030     break;
01031   }
01032 
01033   case Intrinsic::AMDGPU_rcp: {
01034     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
01035       const APFloat &ArgVal = C->getValueAPF();
01036       APFloat Val(ArgVal.getSemantics(), 1.0);
01037       APFloat::opStatus Status = Val.divide(ArgVal,
01038                                             APFloat::rmNearestTiesToEven);
01039       // Only do this if it was exact and therefore not dependent on the
01040       // rounding mode.
01041       if (Status == APFloat::opOK)
01042         return ReplaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
01043     }
01044 
01045     break;
01046   }
01047   case Intrinsic::stackrestore: {
01048     // If the save is right next to the restore, remove the restore.  This can
01049     // happen when variable allocas are DCE'd.
01050     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
01051       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
01052         BasicBlock::iterator BI = SS;
01053         if (&*++BI == II)
01054           return EraseInstFromFunction(CI);
01055       }
01056     }
01057 
01058     // Scan down this block to see if there is another stack restore in the
01059     // same block without an intervening call/alloca.
01060     BasicBlock::iterator BI = II;
01061     TerminatorInst *TI = II->getParent()->getTerminator();
01062     bool CannotRemove = false;
01063     for (++BI; &*BI != TI; ++BI) {
01064       if (isa<AllocaInst>(BI)) {
01065         CannotRemove = true;
01066         break;
01067       }
01068       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
01069         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
01070           // If there is a stackrestore below this one, remove this one.
01071           if (II->getIntrinsicID() == Intrinsic::stackrestore)
01072             return EraseInstFromFunction(CI);
01073           // Otherwise, ignore the intrinsic.
01074         } else {
01075           // If we found a non-intrinsic call, we can't remove the stack
01076           // restore.
01077           CannotRemove = true;
01078           break;
01079         }
01080       }
01081     }
01082 
01083     // If the stack restore is in a return, resume, or unwind block and if there
01084     // are no allocas or calls between the restore and the return, nuke the
01085     // restore.
01086     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
01087       return EraseInstFromFunction(CI);
01088     break;
01089   }
01090   case Intrinsic::assume: {
01091     // Canonicalize assume(a && b) -> assume(a); assume(b);
01092     // Note: New assumption intrinsics created here are registered by
01093     // the InstCombineIRInserter object.
01094     Value *IIOperand = II->getArgOperand(0), *A, *B,
01095           *AssumeIntrinsic = II->getCalledValue();
01096     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
01097       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
01098       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
01099       return EraseInstFromFunction(*II);
01100     }
01101     // assume(!(a || b)) -> assume(!a); assume(!b);
01102     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
01103       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
01104                           II->getName());
01105       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
01106                           II->getName());
01107       return EraseInstFromFunction(*II);
01108     }
01109 
01110     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
01111     // (if assume is valid at the load)
01112     if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
01113       Value *LHS = ICmp->getOperand(0);
01114       Value *RHS = ICmp->getOperand(1);
01115       if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
01116           isa<LoadInst>(LHS) &&
01117           isa<Constant>(RHS) &&
01118           RHS->getType()->isPointerTy() &&
01119           cast<Constant>(RHS)->isNullValue()) {
01120         LoadInst* LI = cast<LoadInst>(LHS);
01121         if (isValidAssumeForContext(II, LI, DL, DT)) {
01122           MDNode *MD = MDNode::get(II->getContext(), None);
01123           LI->setMetadata(LLVMContext::MD_nonnull, MD);
01124           return EraseInstFromFunction(*II);
01125         }
01126       }
01127       // TODO: apply nonnull return attributes to calls and invokes
01128       // TODO: apply range metadata for range check patterns?
01129     }
01130     // If there is a dominating assume with the same condition as this one,
01131     // then this one is redundant, and should be removed.
01132     APInt KnownZero(1, 0), KnownOne(1, 0);
01133     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
01134     if (KnownOne.isAllOnesValue())
01135       return EraseInstFromFunction(*II);
01136 
01137     break;
01138   }
01139   case Intrinsic::experimental_gc_relocate: {
01140     // Translate facts known about a pointer before relocating into
01141     // facts about the relocate value, while being careful to
01142     // preserve relocation semantics.
01143     GCRelocateOperands Operands(II);
01144     Value *DerivedPtr = Operands.derivedPtr();
01145 
01146     // Remove the relocation if unused, note that this check is required
01147     // to prevent the cases below from looping forever.
01148     if (II->use_empty())
01149       return EraseInstFromFunction(*II);
01150 
01151     // Undef is undef, even after relocation.
01152     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
01153     // most practical collectors, but there was discussion in the review thread
01154     // about whether it was legal for all possible collectors.
01155     if (isa<UndefValue>(DerivedPtr))
01156       return ReplaceInstUsesWith(*II, DerivedPtr);
01157 
01158     // The relocation of null will be null for most any collector.
01159     // TODO: provide a hook for this in GCStrategy.  There might be some weird
01160     // collector this property does not hold for.
01161     if (isa<ConstantPointerNull>(DerivedPtr))
01162       return ReplaceInstUsesWith(*II, DerivedPtr);
01163 
01164     // isKnownNonNull -> nonnull attribute
01165     if (isKnownNonNull(DerivedPtr))
01166       II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
01167 
01168     // isDereferenceablePointer -> deref attribute
01169     if (DerivedPtr->isDereferenceablePointer(DL)) {
01170       if (Argument *A = dyn_cast<Argument>(DerivedPtr)) {
01171         uint64_t Bytes = A->getDereferenceableBytes();
01172         II->addDereferenceableAttr(AttributeSet::ReturnIndex, Bytes);
01173       }
01174     }
01175 
01176     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
01177     // Canonicalize on the type from the uses to the defs
01178 
01179     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
01180   }
01181   }
01182 
01183   return visitCallSite(II);
01184 }
01185 
01186 // InvokeInst simplification
01187 //
01188 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
01189   return visitCallSite(&II);
01190 }
01191 
01192 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
01193 /// passed through the varargs area, we can eliminate the use of the cast.
01194 static bool isSafeToEliminateVarargsCast(const CallSite CS,
01195                                          const CastInst * const CI,
01196                                          const DataLayout * const DL,
01197                                          const int ix) {
01198   if (!CI->isLosslessCast())
01199     return false;
01200 
01201   // If this is a GC intrinsic, avoid munging types.  We need types for
01202   // statepoint reconstruction in SelectionDAG.
01203   // TODO: This is probably something which should be expanded to all
01204   // intrinsics since the entire point of intrinsics is that
01205   // they are understandable by the optimizer.
01206   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
01207     return false;
01208 
01209   // The size of ByVal or InAlloca arguments is derived from the type, so we
01210   // can't change to a type with a different size.  If the size were
01211   // passed explicitly we could avoid this check.
01212   if (!CS.isByValOrInAllocaArgument(ix))
01213     return true;
01214 
01215   Type* SrcTy =
01216             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
01217   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
01218   if (!SrcTy->isSized() || !DstTy->isSized())
01219     return false;
01220   if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
01221     return false;
01222   return true;
01223 }
01224 
01225 // Try to fold some different type of calls here.
01226 // Currently we're only working with the checking functions, memcpy_chk,
01227 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
01228 // strcat_chk and strncat_chk.
01229 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
01230   if (!CI->getCalledFunction()) return nullptr;
01231 
01232   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
01233     ReplaceInstUsesWith(*From, With);
01234   };
01235   LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
01236   if (Value *With = Simplifier.optimizeCall(CI)) {
01237     ++NumSimplified;
01238     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
01239   }
01240 
01241   return nullptr;
01242 }
01243 
01244 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
01245   // Strip off at most one level of pointer casts, looking for an alloca.  This
01246   // is good enough in practice and simpler than handling any number of casts.
01247   Value *Underlying = TrampMem->stripPointerCasts();
01248   if (Underlying != TrampMem &&
01249       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
01250     return nullptr;
01251   if (!isa<AllocaInst>(Underlying))
01252     return nullptr;
01253 
01254   IntrinsicInst *InitTrampoline = nullptr;
01255   for (User *U : TrampMem->users()) {
01256     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
01257     if (!II)
01258       return nullptr;
01259     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
01260       if (InitTrampoline)
01261         // More than one init_trampoline writes to this value.  Give up.
01262         return nullptr;
01263       InitTrampoline = II;
01264       continue;
01265     }
01266     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
01267       // Allow any number of calls to adjust.trampoline.
01268       continue;
01269     return nullptr;
01270   }
01271 
01272   // No call to init.trampoline found.
01273   if (!InitTrampoline)
01274     return nullptr;
01275 
01276   // Check that the alloca is being used in the expected way.
01277   if (InitTrampoline->getOperand(0) != TrampMem)
01278     return nullptr;
01279 
01280   return InitTrampoline;
01281 }
01282 
01283 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
01284                                                Value *TrampMem) {
01285   // Visit all the previous instructions in the basic block, and try to find a
01286   // init.trampoline which has a direct path to the adjust.trampoline.
01287   for (BasicBlock::iterator I = AdjustTramp,
01288        E = AdjustTramp->getParent()->begin(); I != E; ) {
01289     Instruction *Inst = --I;
01290     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
01291       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
01292           II->getOperand(0) == TrampMem)
01293         return II;
01294     if (Inst->mayWriteToMemory())
01295       return nullptr;
01296   }
01297   return nullptr;
01298 }
01299 
01300 // Given a call to llvm.adjust.trampoline, find and return the corresponding
01301 // call to llvm.init.trampoline if the call to the trampoline can be optimized
01302 // to a direct call to a function.  Otherwise return NULL.
01303 //
01304 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
01305   Callee = Callee->stripPointerCasts();
01306   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
01307   if (!AdjustTramp ||
01308       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
01309     return nullptr;
01310 
01311   Value *TrampMem = AdjustTramp->getOperand(0);
01312 
01313   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
01314     return IT;
01315   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
01316     return IT;
01317   return nullptr;
01318 }
01319 
01320 // visitCallSite - Improvements for call and invoke instructions.
01321 //
01322 Instruction *InstCombiner::visitCallSite(CallSite CS) {
01323   if (isAllocLikeFn(CS.getInstruction(), TLI))
01324     return visitAllocSite(*CS.getInstruction());
01325 
01326   bool Changed = false;
01327 
01328   // If the callee is a pointer to a function, attempt to move any casts to the
01329   // arguments of the call/invoke.
01330   Value *Callee = CS.getCalledValue();
01331   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
01332     return nullptr;
01333 
01334   if (Function *CalleeF = dyn_cast<Function>(Callee))
01335     // If the call and callee calling conventions don't match, this call must
01336     // be unreachable, as the call is undefined.
01337     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
01338         // Only do this for calls to a function with a body.  A prototype may
01339         // not actually end up matching the implementation's calling conv for a
01340         // variety of reasons (e.g. it may be written in assembly).
01341         !CalleeF->isDeclaration()) {
01342       Instruction *OldCall = CS.getInstruction();
01343       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01344                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01345                                   OldCall);
01346       // If OldCall does not return void then replaceAllUsesWith undef.
01347       // This allows ValueHandlers and custom metadata to adjust itself.
01348       if (!OldCall->getType()->isVoidTy())
01349         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
01350       if (isa<CallInst>(OldCall))
01351         return EraseInstFromFunction(*OldCall);
01352 
01353       // We cannot remove an invoke, because it would change the CFG, just
01354       // change the callee to a null pointer.
01355       cast<InvokeInst>(OldCall)->setCalledFunction(
01356                                     Constant::getNullValue(CalleeF->getType()));
01357       return nullptr;
01358     }
01359 
01360   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01361     // If CS does not return void then replaceAllUsesWith undef.
01362     // This allows ValueHandlers and custom metadata to adjust itself.
01363     if (!CS.getInstruction()->getType()->isVoidTy())
01364       ReplaceInstUsesWith(*CS.getInstruction(),
01365                           UndefValue::get(CS.getInstruction()->getType()));
01366 
01367     if (isa<InvokeInst>(CS.getInstruction())) {
01368       // Can't remove an invoke because we cannot change the CFG.
01369       return nullptr;
01370     }
01371 
01372     // This instruction is not reachable, just remove it.  We insert a store to
01373     // undef so that we know that this code is not reachable, despite the fact
01374     // that we can't modify the CFG here.
01375     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01376                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01377                   CS.getInstruction());
01378 
01379     return EraseInstFromFunction(*CS.getInstruction());
01380   }
01381 
01382   if (IntrinsicInst *II = FindInitTrampoline(Callee))
01383     return transformCallThroughTrampoline(CS, II);
01384 
01385   PointerType *PTy = cast<PointerType>(Callee->getType());
01386   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01387   if (FTy->isVarArg()) {
01388     int ix = FTy->getNumParams();
01389     // See if we can optimize any arguments passed through the varargs area of
01390     // the call.
01391     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
01392            E = CS.arg_end(); I != E; ++I, ++ix) {
01393       CastInst *CI = dyn_cast<CastInst>(*I);
01394       if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
01395         *I = CI->getOperand(0);
01396         Changed = true;
01397       }
01398     }
01399   }
01400 
01401   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
01402     // Inline asm calls cannot throw - mark them 'nounwind'.
01403     CS.setDoesNotThrow();
01404     Changed = true;
01405   }
01406 
01407   // Try to optimize the call if possible, we require DataLayout for most of
01408   // this.  None of these calls are seen as possibly dead so go ahead and
01409   // delete the instruction now.
01410   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
01411     Instruction *I = tryOptimizeCall(CI, DL);
01412     // If we changed something return the result, etc. Otherwise let
01413     // the fallthrough check.
01414     if (I) return EraseInstFromFunction(*I);
01415   }
01416 
01417   return Changed ? CS.getInstruction() : nullptr;
01418 }
01419 
01420 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
01421 // attempt to move the cast to the arguments of the call/invoke.
01422 //
01423 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
01424   Function *Callee =
01425     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
01426   if (!Callee)
01427     return false;
01428   // The prototype of thunks are a lie, don't try to directly call such
01429   // functions.
01430   if (Callee->hasFnAttribute("thunk"))
01431     return false;
01432   Instruction *Caller = CS.getInstruction();
01433   const AttributeSet &CallerPAL = CS.getAttributes();
01434 
01435   // Okay, this is a cast from a function to a different type.  Unless doing so
01436   // would cause a type conversion of one of our arguments, change this call to
01437   // be a direct call with arguments casted to the appropriate types.
01438   //
01439   FunctionType *FT = Callee->getFunctionType();
01440   Type *OldRetTy = Caller->getType();
01441   Type *NewRetTy = FT->getReturnType();
01442 
01443   // Check to see if we are changing the return type...
01444   if (OldRetTy != NewRetTy) {
01445 
01446     if (NewRetTy->isStructTy())
01447       return false; // TODO: Handle multiple return values.
01448 
01449     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
01450       if (Callee->isDeclaration())
01451         return false;   // Cannot transform this return value.
01452 
01453       if (!Caller->use_empty() &&
01454           // void -> non-void is handled specially
01455           !NewRetTy->isVoidTy())
01456         return false;   // Cannot transform this return value.
01457     }
01458 
01459     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
01460       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01461       if (RAttrs.
01462           hasAttributes(AttributeFuncs::
01463                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01464                         AttributeSet::ReturnIndex))
01465         return false;   // Attribute not compatible with transformed value.
01466     }
01467 
01468     // If the callsite is an invoke instruction, and the return value is used by
01469     // a PHI node in a successor, we cannot change the return type of the call
01470     // because there is no place to put the cast instruction (without breaking
01471     // the critical edge).  Bail out in this case.
01472     if (!Caller->use_empty())
01473       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
01474         for (User *U : II->users())
01475           if (PHINode *PN = dyn_cast<PHINode>(U))
01476             if (PN->getParent() == II->getNormalDest() ||
01477                 PN->getParent() == II->getUnwindDest())
01478               return false;
01479   }
01480 
01481   unsigned NumActualArgs = CS.arg_size();
01482   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
01483 
01484   // Prevent us turning:
01485   // declare void @takes_i32_inalloca(i32* inalloca)
01486   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
01487   //
01488   // into:
01489   //  call void @takes_i32_inalloca(i32* null)
01490   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca))
01491     return false;
01492 
01493   CallSite::arg_iterator AI = CS.arg_begin();
01494   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
01495     Type *ParamTy = FT->getParamType(i);
01496     Type *ActTy = (*AI)->getType();
01497 
01498     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
01499       return false;   // Cannot transform this parameter value.
01500 
01501     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
01502           hasAttributes(AttributeFuncs::
01503                         typeIncompatible(ParamTy, i + 1), i + 1))
01504       return false;   // Attribute not compatible with transformed value.
01505 
01506     if (CS.isInAllocaArgument(i))
01507       return false;   // Cannot transform to and from inalloca.
01508 
01509     // If the parameter is passed as a byval argument, then we have to have a
01510     // sized type and the sized type has to have the same size as the old type.
01511     if (ParamTy != ActTy &&
01512         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
01513                                                          Attribute::ByVal)) {
01514       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
01515       if (!ParamPTy || !ParamPTy->getElementType()->isSized() || !DL)
01516         return false;
01517 
01518       Type *CurElTy = ActTy->getPointerElementType();
01519       if (DL->getTypeAllocSize(CurElTy) !=
01520           DL->getTypeAllocSize(ParamPTy->getElementType()))
01521         return false;
01522     }
01523   }
01524 
01525   if (Callee->isDeclaration()) {
01526     // Do not delete arguments unless we have a function body.
01527     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
01528       return false;
01529 
01530     // If the callee is just a declaration, don't change the varargsness of the
01531     // call.  We don't want to introduce a varargs call where one doesn't
01532     // already exist.
01533     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
01534     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
01535       return false;
01536 
01537     // If both the callee and the cast type are varargs, we still have to make
01538     // sure the number of fixed parameters are the same or we have the same
01539     // ABI issues as if we introduce a varargs call.
01540     if (FT->isVarArg() &&
01541         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
01542         FT->getNumParams() !=
01543         cast<FunctionType>(APTy->getElementType())->getNumParams())
01544       return false;
01545   }
01546 
01547   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
01548       !CallerPAL.isEmpty())
01549     // In this case we have more arguments than the new function type, but we
01550     // won't be dropping them.  Check that these extra arguments have attributes
01551     // that are compatible with being a vararg call argument.
01552     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
01553       unsigned Index = CallerPAL.getSlotIndex(i - 1);
01554       if (Index <= FT->getNumParams())
01555         break;
01556 
01557       // Check if it has an attribute that's incompatible with varargs.
01558       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
01559       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
01560         return false;
01561     }
01562 
01563 
01564   // Okay, we decided that this is a safe thing to do: go ahead and start
01565   // inserting cast instructions as necessary.
01566   std::vector<Value*> Args;
01567   Args.reserve(NumActualArgs);
01568   SmallVector<AttributeSet, 8> attrVec;
01569   attrVec.reserve(NumCommonArgs);
01570 
01571   // Get any return attributes.
01572   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01573 
01574   // If the return value is not being used, the type may not be compatible
01575   // with the existing attributes.  Wipe out any problematic attributes.
01576   RAttrs.
01577     removeAttributes(AttributeFuncs::
01578                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01579                      AttributeSet::ReturnIndex);
01580 
01581   // Add the new return attributes.
01582   if (RAttrs.hasAttributes())
01583     attrVec.push_back(AttributeSet::get(Caller->getContext(),
01584                                         AttributeSet::ReturnIndex, RAttrs));
01585 
01586   AI = CS.arg_begin();
01587   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
01588     Type *ParamTy = FT->getParamType(i);
01589 
01590     if ((*AI)->getType() == ParamTy) {
01591       Args.push_back(*AI);
01592     } else {
01593       Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
01594     }
01595 
01596     // Add any parameter attributes.
01597     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01598     if (PAttrs.hasAttributes())
01599       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
01600                                           PAttrs));
01601   }
01602 
01603   // If the function takes more arguments than the call was taking, add them
01604   // now.
01605   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
01606     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
01607 
01608   // If we are removing arguments to the function, emit an obnoxious warning.
01609   if (FT->getNumParams() < NumActualArgs) {
01610     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
01611     if (FT->isVarArg()) {
01612       // Add all of the arguments in their promoted form to the arg list.
01613       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
01614         Type *PTy = getPromotedType((*AI)->getType());
01615         if (PTy != (*AI)->getType()) {
01616           // Must promote to pass through va_arg area!
01617           Instruction::CastOps opcode =
01618             CastInst::getCastOpcode(*AI, false, PTy, false);
01619           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
01620         } else {
01621           Args.push_back(*AI);
01622         }
01623 
01624         // Add any parameter attributes.
01625         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01626         if (PAttrs.hasAttributes())
01627           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
01628                                               PAttrs));
01629       }
01630     }
01631   }
01632 
01633   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
01634   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
01635     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
01636 
01637   if (NewRetTy->isVoidTy())
01638     Caller->setName("");   // Void type should not have a name.
01639 
01640   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
01641                                                        attrVec);
01642 
01643   Instruction *NC;
01644   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01645     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
01646                                II->getUnwindDest(), Args);
01647     NC->takeName(II);
01648     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
01649     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
01650   } else {
01651     CallInst *CI = cast<CallInst>(Caller);
01652     NC = Builder->CreateCall(Callee, Args);
01653     NC->takeName(CI);
01654     if (CI->isTailCall())
01655       cast<CallInst>(NC)->setTailCall();
01656     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
01657     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
01658   }
01659 
01660   // Insert a cast of the return type as necessary.
01661   Value *NV = NC;
01662   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
01663     if (!NV->getType()->isVoidTy()) {
01664       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
01665       NC->setDebugLoc(Caller->getDebugLoc());
01666 
01667       // If this is an invoke instruction, we should insert it after the first
01668       // non-phi, instruction in the normal successor block.
01669       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01670         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
01671         InsertNewInstBefore(NC, *I);
01672       } else {
01673         // Otherwise, it's a call, just insert cast right after the call.
01674         InsertNewInstBefore(NC, *Caller);
01675       }
01676       Worklist.AddUsersToWorkList(*Caller);
01677     } else {
01678       NV = UndefValue::get(Caller->getType());
01679     }
01680   }
01681 
01682   if (!Caller->use_empty())
01683     ReplaceInstUsesWith(*Caller, NV);
01684   else if (Caller->hasValueHandle()) {
01685     if (OldRetTy == NV->getType())
01686       ValueHandleBase::ValueIsRAUWd(Caller, NV);
01687     else
01688       // We cannot call ValueIsRAUWd with a different type, and the
01689       // actual tracked value will disappear.
01690       ValueHandleBase::ValueIsDeleted(Caller);
01691   }
01692 
01693   EraseInstFromFunction(*Caller);
01694   return true;
01695 }
01696 
01697 // transformCallThroughTrampoline - Turn a call to a function created by
01698 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
01699 // underlying function.
01700 //
01701 Instruction *
01702 InstCombiner::transformCallThroughTrampoline(CallSite CS,
01703                                              IntrinsicInst *Tramp) {
01704   Value *Callee = CS.getCalledValue();
01705   PointerType *PTy = cast<PointerType>(Callee->getType());
01706   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01707   const AttributeSet &Attrs = CS.getAttributes();
01708 
01709   // If the call already has the 'nest' attribute somewhere then give up -
01710   // otherwise 'nest' would occur twice after splicing in the chain.
01711   if (Attrs.hasAttrSomewhere(Attribute::Nest))
01712     return nullptr;
01713 
01714   assert(Tramp &&
01715          "transformCallThroughTrampoline called with incorrect CallSite.");
01716 
01717   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
01718   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
01719   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
01720 
01721   const AttributeSet &NestAttrs = NestF->getAttributes();
01722   if (!NestAttrs.isEmpty()) {
01723     unsigned NestIdx = 1;
01724     Type *NestTy = nullptr;
01725     AttributeSet NestAttr;
01726 
01727     // Look for a parameter marked with the 'nest' attribute.
01728     for (FunctionType::param_iterator I = NestFTy->param_begin(),
01729          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
01730       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
01731         // Record the parameter type and any other attributes.
01732         NestTy = *I;
01733         NestAttr = NestAttrs.getParamAttributes(NestIdx);
01734         break;
01735       }
01736 
01737     if (NestTy) {
01738       Instruction *Caller = CS.getInstruction();
01739       std::vector<Value*> NewArgs;
01740       NewArgs.reserve(CS.arg_size() + 1);
01741 
01742       SmallVector<AttributeSet, 8> NewAttrs;
01743       NewAttrs.reserve(Attrs.getNumSlots() + 1);
01744 
01745       // Insert the nest argument into the call argument list, which may
01746       // mean appending it.  Likewise for attributes.
01747 
01748       // Add any result attributes.
01749       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01750         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01751                                              Attrs.getRetAttributes()));
01752 
01753       {
01754         unsigned Idx = 1;
01755         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
01756         do {
01757           if (Idx == NestIdx) {
01758             // Add the chain argument and attributes.
01759             Value *NestVal = Tramp->getArgOperand(2);
01760             if (NestVal->getType() != NestTy)
01761               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
01762             NewArgs.push_back(NestVal);
01763             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01764                                                  NestAttr));
01765           }
01766 
01767           if (I == E)
01768             break;
01769 
01770           // Add the original argument and attributes.
01771           NewArgs.push_back(*I);
01772           AttributeSet Attr = Attrs.getParamAttributes(Idx);
01773           if (Attr.hasAttributes(Idx)) {
01774             AttrBuilder B(Attr, Idx);
01775             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01776                                                  Idx + (Idx >= NestIdx), B));
01777           }
01778 
01779           ++Idx, ++I;
01780         } while (1);
01781       }
01782 
01783       // Add any function attributes.
01784       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01785         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
01786                                              Attrs.getFnAttributes()));
01787 
01788       // The trampoline may have been bitcast to a bogus type (FTy).
01789       // Handle this by synthesizing a new function type, equal to FTy
01790       // with the chain parameter inserted.
01791 
01792       std::vector<Type*> NewTypes;
01793       NewTypes.reserve(FTy->getNumParams()+1);
01794 
01795       // Insert the chain's type into the list of parameter types, which may
01796       // mean appending it.
01797       {
01798         unsigned Idx = 1;
01799         FunctionType::param_iterator I = FTy->param_begin(),
01800           E = FTy->param_end();
01801 
01802         do {
01803           if (Idx == NestIdx)
01804             // Add the chain's type.
01805             NewTypes.push_back(NestTy);
01806 
01807           if (I == E)
01808             break;
01809 
01810           // Add the original type.
01811           NewTypes.push_back(*I);
01812 
01813           ++Idx, ++I;
01814         } while (1);
01815       }
01816 
01817       // Replace the trampoline call with a direct call.  Let the generic
01818       // code sort out any function type mismatches.
01819       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
01820                                                 FTy->isVarArg());
01821       Constant *NewCallee =
01822         NestF->getType() == PointerType::getUnqual(NewFTy) ?
01823         NestF : ConstantExpr::getBitCast(NestF,
01824                                          PointerType::getUnqual(NewFTy));
01825       const AttributeSet &NewPAL =
01826           AttributeSet::get(FTy->getContext(), NewAttrs);
01827 
01828       Instruction *NewCaller;
01829       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01830         NewCaller = InvokeInst::Create(NewCallee,
01831                                        II->getNormalDest(), II->getUnwindDest(),
01832                                        NewArgs);
01833         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
01834         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
01835       } else {
01836         NewCaller = CallInst::Create(NewCallee, NewArgs);
01837         if (cast<CallInst>(Caller)->isTailCall())
01838           cast<CallInst>(NewCaller)->setTailCall();
01839         cast<CallInst>(NewCaller)->
01840           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
01841         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
01842       }
01843 
01844       return NewCaller;
01845     }
01846   }
01847 
01848   // Replace the trampoline call with a direct call.  Since there is no 'nest'
01849   // parameter, there is no need to adjust the argument list.  Let the generic
01850   // code sort out any function type mismatches.
01851   Constant *NewCallee =
01852     NestF->getType() == PTy ? NestF :
01853                               ConstantExpr::getBitCast(NestF, PTy);
01854   CS.setCalledFunction(NewCallee);
01855   return CS.getInstruction();
01856 }