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