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::ppc_altivec_lvx:
00523   case Intrinsic::ppc_altivec_lvxl:
00524     // Turn PPC lvx -> load if the pointer is known aligned.
00525     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16,
00526                                    DL, AT, II, DT) >= 16) {
00527       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00528                                          PointerType::getUnqual(II->getType()));
00529       return new LoadInst(Ptr);
00530     }
00531     break;
00532   case Intrinsic::ppc_altivec_stvx:
00533   case Intrinsic::ppc_altivec_stvxl:
00534     // Turn stvx -> store if the pointer is known aligned.
00535     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16,
00536                                    DL, AT, II, DT) >= 16) {
00537       Type *OpPtrTy =
00538         PointerType::getUnqual(II->getArgOperand(0)->getType());
00539       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00540       return new StoreInst(II->getArgOperand(0), Ptr);
00541     }
00542     break;
00543   case Intrinsic::x86_sse_storeu_ps:
00544   case Intrinsic::x86_sse2_storeu_pd:
00545   case Intrinsic::x86_sse2_storeu_dq:
00546     // Turn X86 storeu -> store if the pointer is known aligned.
00547     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16,
00548                                    DL, AT, II, DT) >= 16) {
00549       Type *OpPtrTy =
00550         PointerType::getUnqual(II->getArgOperand(1)->getType());
00551       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
00552       return new StoreInst(II->getArgOperand(1), Ptr);
00553     }
00554     break;
00555 
00556   case Intrinsic::x86_sse_cvtss2si:
00557   case Intrinsic::x86_sse_cvtss2si64:
00558   case Intrinsic::x86_sse_cvttss2si:
00559   case Intrinsic::x86_sse_cvttss2si64:
00560   case Intrinsic::x86_sse2_cvtsd2si:
00561   case Intrinsic::x86_sse2_cvtsd2si64:
00562   case Intrinsic::x86_sse2_cvttsd2si:
00563   case Intrinsic::x86_sse2_cvttsd2si64: {
00564     // These intrinsics only demand the 0th element of their input vectors. If
00565     // we can simplify the input based on that, do so now.
00566     unsigned VWidth =
00567       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00568     APInt DemandedElts(VWidth, 1);
00569     APInt UndefElts(VWidth, 0);
00570     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
00571                                               DemandedElts, UndefElts)) {
00572       II->setArgOperand(0, V);
00573       return II;
00574     }
00575     break;
00576   }
00577 
00578   // Constant fold <A x Bi> << Ci.
00579   // FIXME: We don't handle _dq because it's a shift of an i128, but is
00580   // represented in the IR as <2 x i64>. A per element shift is wrong.
00581   case Intrinsic::x86_sse2_psll_d:
00582   case Intrinsic::x86_sse2_psll_q:
00583   case Intrinsic::x86_sse2_psll_w:
00584   case Intrinsic::x86_sse2_pslli_d:
00585   case Intrinsic::x86_sse2_pslli_q:
00586   case Intrinsic::x86_sse2_pslli_w:
00587   case Intrinsic::x86_avx2_psll_d:
00588   case Intrinsic::x86_avx2_psll_q:
00589   case Intrinsic::x86_avx2_psll_w:
00590   case Intrinsic::x86_avx2_pslli_d:
00591   case Intrinsic::x86_avx2_pslli_q:
00592   case Intrinsic::x86_avx2_pslli_w:
00593   case Intrinsic::x86_sse2_psrl_d:
00594   case Intrinsic::x86_sse2_psrl_q:
00595   case Intrinsic::x86_sse2_psrl_w:
00596   case Intrinsic::x86_sse2_psrli_d:
00597   case Intrinsic::x86_sse2_psrli_q:
00598   case Intrinsic::x86_sse2_psrli_w:
00599   case Intrinsic::x86_avx2_psrl_d:
00600   case Intrinsic::x86_avx2_psrl_q:
00601   case Intrinsic::x86_avx2_psrl_w:
00602   case Intrinsic::x86_avx2_psrli_d:
00603   case Intrinsic::x86_avx2_psrli_q:
00604   case Intrinsic::x86_avx2_psrli_w: {
00605     // Simplify if count is constant. To 0 if >= BitWidth,
00606     // otherwise to shl/lshr.
00607     auto CDV = dyn_cast<ConstantDataVector>(II->getArgOperand(1));
00608     auto CInt = dyn_cast<ConstantInt>(II->getArgOperand(1));
00609     if (!CDV && !CInt)
00610       break;
00611     ConstantInt *Count;
00612     if (CDV)
00613       Count = cast<ConstantInt>(CDV->getElementAsConstant(0));
00614     else
00615       Count = CInt;
00616 
00617     auto Vec = II->getArgOperand(0);
00618     auto VT = cast<VectorType>(Vec->getType());
00619     if (Count->getZExtValue() >
00620         VT->getElementType()->getPrimitiveSizeInBits() - 1)
00621       return ReplaceInstUsesWith(
00622           CI, ConstantAggregateZero::get(Vec->getType()));
00623 
00624     bool isPackedShiftLeft = true;
00625     switch (II->getIntrinsicID()) {
00626     default : break;
00627     case Intrinsic::x86_sse2_psrl_d:
00628     case Intrinsic::x86_sse2_psrl_q:
00629     case Intrinsic::x86_sse2_psrl_w:
00630     case Intrinsic::x86_sse2_psrli_d:
00631     case Intrinsic::x86_sse2_psrli_q:
00632     case Intrinsic::x86_sse2_psrli_w:
00633     case Intrinsic::x86_avx2_psrl_d:
00634     case Intrinsic::x86_avx2_psrl_q:
00635     case Intrinsic::x86_avx2_psrl_w:
00636     case Intrinsic::x86_avx2_psrli_d:
00637     case Intrinsic::x86_avx2_psrli_q:
00638     case Intrinsic::x86_avx2_psrli_w: isPackedShiftLeft = false; break;
00639     }
00640 
00641     unsigned VWidth = VT->getNumElements();
00642     // Get a constant vector of the same type as the first operand.
00643     auto VTCI = ConstantInt::get(VT->getElementType(), Count->getZExtValue());
00644     if (isPackedShiftLeft)
00645       return BinaryOperator::CreateShl(Vec,
00646           Builder->CreateVectorSplat(VWidth, VTCI));
00647 
00648     return BinaryOperator::CreateLShr(Vec,
00649         Builder->CreateVectorSplat(VWidth, VTCI));
00650   }
00651 
00652   case Intrinsic::x86_sse41_pmovsxbw:
00653   case Intrinsic::x86_sse41_pmovsxwd:
00654   case Intrinsic::x86_sse41_pmovsxdq:
00655   case Intrinsic::x86_sse41_pmovzxbw:
00656   case Intrinsic::x86_sse41_pmovzxwd:
00657   case Intrinsic::x86_sse41_pmovzxdq: {
00658     // pmov{s|z}x ignores the upper half of their input vectors.
00659     unsigned VWidth =
00660       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00661     unsigned LowHalfElts = VWidth / 2;
00662     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
00663     APInt UndefElts(VWidth, 0);
00664     if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
00665                                                  InputDemandedElts,
00666                                                  UndefElts)) {
00667       II->setArgOperand(0, TmpV);
00668       return II;
00669     }
00670     break;
00671   }
00672 
00673   case Intrinsic::x86_sse4a_insertqi: {
00674     // insertqi x, y, 64, 0 can just copy y's lower bits and leave the top
00675     // ones undef
00676     // TODO: eventually we should lower this intrinsic to IR
00677     if (auto CIWidth = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
00678       if (auto CIStart = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
00679         if (CIWidth->equalsInt(64) && CIStart->isZero()) {
00680           Value *Vec = II->getArgOperand(1);
00681           Value *Undef = UndefValue::get(Vec->getType());
00682           const uint32_t Mask[] = { 0, 2 };
00683           return ReplaceInstUsesWith(
00684               CI,
00685               Builder->CreateShuffleVector(
00686                   Vec, Undef, ConstantDataVector::get(
00687                                   II->getContext(), makeArrayRef(Mask))));
00688 
00689         } else if (auto Source =
00690                        dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00691           if (Source->hasOneUse() &&
00692               Source->getArgOperand(1) == II->getArgOperand(1)) {
00693             // If the source of the insert has only one use and it's another
00694             // insert (and they're both inserting from the same vector), try to
00695             // bundle both together.
00696             auto CISourceWidth =
00697                 dyn_cast<ConstantInt>(Source->getArgOperand(2));
00698             auto CISourceStart =
00699                 dyn_cast<ConstantInt>(Source->getArgOperand(3));
00700             if (CISourceStart && CISourceWidth) {
00701               unsigned Start = CIStart->getZExtValue();
00702               unsigned Width = CIWidth->getZExtValue();
00703               unsigned End = Start + Width;
00704               unsigned SourceStart = CISourceStart->getZExtValue();
00705               unsigned SourceWidth = CISourceWidth->getZExtValue();
00706               unsigned SourceEnd = SourceStart + SourceWidth;
00707               unsigned NewStart, NewWidth;
00708               bool ShouldReplace = false;
00709               if (Start <= SourceStart && SourceStart <= End) {
00710                 NewStart = Start;
00711                 NewWidth = std::max(End, SourceEnd) - NewStart;
00712                 ShouldReplace = true;
00713               } else if (SourceStart <= Start && Start <= SourceEnd) {
00714                 NewStart = SourceStart;
00715                 NewWidth = std::max(SourceEnd, End) - NewStart;
00716                 ShouldReplace = true;
00717               }
00718 
00719               if (ShouldReplace) {
00720                 Constant *ConstantWidth = ConstantInt::get(
00721                     II->getArgOperand(2)->getType(), NewWidth, false);
00722                 Constant *ConstantStart = ConstantInt::get(
00723                     II->getArgOperand(3)->getType(), NewStart, false);
00724                 Value *Args[4] = { Source->getArgOperand(0),
00725                                    II->getArgOperand(1), ConstantWidth,
00726                                    ConstantStart };
00727                 Module *M = CI.getParent()->getParent()->getParent();
00728                 Value *F =
00729                     Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
00730                 return ReplaceInstUsesWith(CI, Builder->CreateCall(F, Args));
00731               }
00732             }
00733           }
00734         }
00735       }
00736     }
00737     break;
00738   }
00739 
00740   case Intrinsic::x86_sse41_pblendvb:
00741   case Intrinsic::x86_sse41_blendvps:
00742   case Intrinsic::x86_sse41_blendvpd:
00743   case Intrinsic::x86_avx_blendv_ps_256:
00744   case Intrinsic::x86_avx_blendv_pd_256:
00745   case Intrinsic::x86_avx2_pblendvb: {
00746     // Convert blendv* to vector selects if the mask is constant.
00747     // This optimization is convoluted because the intrinsic is defined as
00748     // getting a vector of floats or doubles for the ps and pd versions.
00749     // FIXME: That should be changed.
00750     Value *Mask = II->getArgOperand(2);
00751     if (auto C = dyn_cast<ConstantDataVector>(Mask)) {
00752       auto Tyi1 = Builder->getInt1Ty();
00753       auto SelectorType = cast<VectorType>(Mask->getType());
00754       auto EltTy = SelectorType->getElementType();
00755       unsigned Size = SelectorType->getNumElements();
00756       unsigned BitWidth =
00757           EltTy->isFloatTy()
00758               ? 32
00759               : (EltTy->isDoubleTy() ? 64 : EltTy->getIntegerBitWidth());
00760       assert((BitWidth == 64 || BitWidth == 32 || BitWidth == 8) &&
00761              "Wrong arguments for variable blend intrinsic");
00762       SmallVector<Constant *, 32> Selectors;
00763       for (unsigned I = 0; I < Size; ++I) {
00764         // The intrinsics only read the top bit
00765         uint64_t Selector;
00766         if (BitWidth == 8)
00767           Selector = C->getElementAsInteger(I);
00768         else
00769           Selector = C->getElementAsAPFloat(I).bitcastToAPInt().getZExtValue();
00770         Selectors.push_back(ConstantInt::get(Tyi1, Selector >> (BitWidth - 1)));
00771       }
00772       auto NewSelector = ConstantVector::get(Selectors);
00773       return SelectInst::Create(NewSelector, II->getArgOperand(1),
00774                                 II->getArgOperand(0), "blendv");
00775     } else {
00776       break;
00777     }
00778   }
00779 
00780   case Intrinsic::x86_avx_vpermilvar_ps:
00781   case Intrinsic::x86_avx_vpermilvar_ps_256:
00782   case Intrinsic::x86_avx_vpermilvar_pd:
00783   case Intrinsic::x86_avx_vpermilvar_pd_256: {
00784     // Convert vpermil* to shufflevector if the mask is constant.
00785     Value *V = II->getArgOperand(1);
00786     unsigned Size = cast<VectorType>(V->getType())->getNumElements();
00787     assert(Size == 8 || Size == 4 || Size == 2);
00788     uint32_t Indexes[8];
00789     if (auto C = dyn_cast<ConstantDataVector>(V)) {
00790       // The intrinsics only read one or two bits, clear the rest.
00791       for (unsigned I = 0; I < Size; ++I) {
00792         uint32_t Index = C->getElementAsInteger(I) & 0x3;
00793         if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
00794             II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
00795           Index >>= 1;
00796         Indexes[I] = Index;
00797       }
00798     } else if (isa<ConstantAggregateZero>(V)) {
00799       for (unsigned I = 0; I < Size; ++I)
00800         Indexes[I] = 0;
00801     } else {
00802       break;
00803     }
00804     // The _256 variants are a bit trickier since the mask bits always index
00805     // into the corresponding 128 half. In order to convert to a generic
00806     // shuffle, we have to make that explicit.
00807     if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
00808         II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) {
00809       for (unsigned I = Size / 2; I < Size; ++I)
00810         Indexes[I] += Size / 2;
00811     }
00812     auto NewC =
00813         ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size));
00814     auto V1 = II->getArgOperand(0);
00815     auto V2 = UndefValue::get(V1->getType());
00816     auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
00817     return ReplaceInstUsesWith(CI, Shuffle);
00818   }
00819 
00820   case Intrinsic::ppc_altivec_vperm:
00821     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
00822     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
00823     // a vectorshuffle for little endian, we must undo the transformation
00824     // performed on vec_perm in altivec.h.  That is, we must complement
00825     // the permutation mask with respect to 31 and reverse the order of
00826     // V1 and V2.
00827     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
00828       assert(Mask->getType()->getVectorNumElements() == 16 &&
00829              "Bad type for intrinsic!");
00830 
00831       // Check that all of the elements are integer constants or undefs.
00832       bool AllEltsOk = true;
00833       for (unsigned i = 0; i != 16; ++i) {
00834         Constant *Elt = Mask->getAggregateElement(i);
00835         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
00836           AllEltsOk = false;
00837           break;
00838         }
00839       }
00840 
00841       if (AllEltsOk) {
00842         // Cast the input vectors to byte vectors.
00843         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
00844                                             Mask->getType());
00845         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
00846                                             Mask->getType());
00847         Value *Result = UndefValue::get(Op0->getType());
00848 
00849         // Only extract each element once.
00850         Value *ExtractedElts[32];
00851         memset(ExtractedElts, 0, sizeof(ExtractedElts));
00852 
00853         for (unsigned i = 0; i != 16; ++i) {
00854           if (isa<UndefValue>(Mask->getAggregateElement(i)))
00855             continue;
00856           unsigned Idx =
00857             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
00858           Idx &= 31;  // Match the hardware behavior.
00859           if (DL && DL->isLittleEndian())
00860             Idx = 31 - Idx;
00861 
00862           if (!ExtractedElts[Idx]) {
00863             Value *Op0ToUse = (DL && DL->isLittleEndian()) ? Op1 : Op0;
00864             Value *Op1ToUse = (DL && DL->isLittleEndian()) ? Op0 : Op1;
00865             ExtractedElts[Idx] =
00866               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
00867                                             Builder->getInt32(Idx&15));
00868           }
00869 
00870           // Insert this value into the result vector.
00871           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
00872                                                 Builder->getInt32(i));
00873         }
00874         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
00875       }
00876     }
00877     break;
00878 
00879   case Intrinsic::arm_neon_vld1:
00880   case Intrinsic::arm_neon_vld2:
00881   case Intrinsic::arm_neon_vld3:
00882   case Intrinsic::arm_neon_vld4:
00883   case Intrinsic::arm_neon_vld2lane:
00884   case Intrinsic::arm_neon_vld3lane:
00885   case Intrinsic::arm_neon_vld4lane:
00886   case Intrinsic::arm_neon_vst1:
00887   case Intrinsic::arm_neon_vst2:
00888   case Intrinsic::arm_neon_vst3:
00889   case Intrinsic::arm_neon_vst4:
00890   case Intrinsic::arm_neon_vst2lane:
00891   case Intrinsic::arm_neon_vst3lane:
00892   case Intrinsic::arm_neon_vst4lane: {
00893     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, AT, II, DT);
00894     unsigned AlignArg = II->getNumArgOperands() - 1;
00895     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
00896     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
00897       II->setArgOperand(AlignArg,
00898                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
00899                                          MemAlign, false));
00900       return II;
00901     }
00902     break;
00903   }
00904 
00905   case Intrinsic::arm_neon_vmulls:
00906   case Intrinsic::arm_neon_vmullu:
00907   case Intrinsic::aarch64_neon_smull:
00908   case Intrinsic::aarch64_neon_umull: {
00909     Value *Arg0 = II->getArgOperand(0);
00910     Value *Arg1 = II->getArgOperand(1);
00911 
00912     // Handle mul by zero first:
00913     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
00914       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
00915     }
00916 
00917     // Check for constant LHS & RHS - in this case we just simplify.
00918     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
00919                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
00920     VectorType *NewVT = cast<VectorType>(II->getType());
00921     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
00922       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
00923         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
00924         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
00925 
00926         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
00927       }
00928 
00929       // Couldn't simplify - canonicalize constant to the RHS.
00930       std::swap(Arg0, Arg1);
00931     }
00932 
00933     // Handle mul by one:
00934     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
00935       if (ConstantInt *Splat =
00936               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
00937         if (Splat->isOne())
00938           return CastInst::CreateIntegerCast(Arg0, II->getType(),
00939                                              /*isSigned=*/!Zext);
00940 
00941     break;
00942   }
00943 
00944   case Intrinsic::AMDGPU_rcp: {
00945     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
00946       const APFloat &ArgVal = C->getValueAPF();
00947       APFloat Val(ArgVal.getSemantics(), 1.0);
00948       APFloat::opStatus Status = Val.divide(ArgVal,
00949                                             APFloat::rmNearestTiesToEven);
00950       // Only do this if it was exact and therefore not dependent on the
00951       // rounding mode.
00952       if (Status == APFloat::opOK)
00953         return ReplaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
00954     }
00955 
00956     break;
00957   }
00958   case Intrinsic::stackrestore: {
00959     // If the save is right next to the restore, remove the restore.  This can
00960     // happen when variable allocas are DCE'd.
00961     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00962       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
00963         BasicBlock::iterator BI = SS;
00964         if (&*++BI == II)
00965           return EraseInstFromFunction(CI);
00966       }
00967     }
00968 
00969     // Scan down this block to see if there is another stack restore in the
00970     // same block without an intervening call/alloca.
00971     BasicBlock::iterator BI = II;
00972     TerminatorInst *TI = II->getParent()->getTerminator();
00973     bool CannotRemove = false;
00974     for (++BI; &*BI != TI; ++BI) {
00975       if (isa<AllocaInst>(BI)) {
00976         CannotRemove = true;
00977         break;
00978       }
00979       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
00980         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
00981           // If there is a stackrestore below this one, remove this one.
00982           if (II->getIntrinsicID() == Intrinsic::stackrestore)
00983             return EraseInstFromFunction(CI);
00984           // Otherwise, ignore the intrinsic.
00985         } else {
00986           // If we found a non-intrinsic call, we can't remove the stack
00987           // restore.
00988           CannotRemove = true;
00989           break;
00990         }
00991       }
00992     }
00993 
00994     // If the stack restore is in a return, resume, or unwind block and if there
00995     // are no allocas or calls between the restore and the return, nuke the
00996     // restore.
00997     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
00998       return EraseInstFromFunction(CI);
00999     break;
01000   }
01001   case Intrinsic::assume: {
01002     // Canonicalize assume(a && b) -> assume(a); assume(b);
01003     // Note: New assumption intrinsics created here are registered by
01004     // the InstCombineIRInserter object.
01005     Value *IIOperand = II->getArgOperand(0), *A, *B,
01006           *AssumeIntrinsic = II->getCalledValue();
01007     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
01008       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
01009       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
01010       return EraseInstFromFunction(*II);
01011     }
01012     // assume(!(a || b)) -> assume(!a); assume(!b);
01013     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
01014       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
01015                           II->getName());
01016       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
01017                           II->getName());
01018       return EraseInstFromFunction(*II);
01019     }
01020 
01021     // If there is a dominating assume with the same condition as this one,
01022     // then this one is redundant, and should be removed.
01023     APInt KnownZero(1, 0), KnownOne(1, 0);
01024     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
01025     if (KnownOne.isAllOnesValue())
01026       return EraseInstFromFunction(*II);
01027 
01028     break;
01029   }
01030   }
01031 
01032   return visitCallSite(II);
01033 }
01034 
01035 // InvokeInst simplification
01036 //
01037 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
01038   return visitCallSite(&II);
01039 }
01040 
01041 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
01042 /// passed through the varargs area, we can eliminate the use of the cast.
01043 static bool isSafeToEliminateVarargsCast(const CallSite CS,
01044                                          const CastInst * const CI,
01045                                          const DataLayout * const DL,
01046                                          const int ix) {
01047   if (!CI->isLosslessCast())
01048     return false;
01049 
01050   // The size of ByVal or InAlloca arguments is derived from the type, so we
01051   // can't change to a type with a different size.  If the size were
01052   // passed explicitly we could avoid this check.
01053   if (!CS.isByValOrInAllocaArgument(ix))
01054     return true;
01055 
01056   Type* SrcTy =
01057             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
01058   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
01059   if (!SrcTy->isSized() || !DstTy->isSized())
01060     return false;
01061   if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
01062     return false;
01063   return true;
01064 }
01065 
01066 // Try to fold some different type of calls here.
01067 // Currently we're only working with the checking functions, memcpy_chk,
01068 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
01069 // strcat_chk and strncat_chk.
01070 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
01071   if (!CI->getCalledFunction()) return nullptr;
01072 
01073   if (Value *With = Simplifier->optimizeCall(CI)) {
01074     ++NumSimplified;
01075     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
01076   }
01077 
01078   return nullptr;
01079 }
01080 
01081 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
01082   // Strip off at most one level of pointer casts, looking for an alloca.  This
01083   // is good enough in practice and simpler than handling any number of casts.
01084   Value *Underlying = TrampMem->stripPointerCasts();
01085   if (Underlying != TrampMem &&
01086       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
01087     return nullptr;
01088   if (!isa<AllocaInst>(Underlying))
01089     return nullptr;
01090 
01091   IntrinsicInst *InitTrampoline = nullptr;
01092   for (User *U : TrampMem->users()) {
01093     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
01094     if (!II)
01095       return nullptr;
01096     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
01097       if (InitTrampoline)
01098         // More than one init_trampoline writes to this value.  Give up.
01099         return nullptr;
01100       InitTrampoline = II;
01101       continue;
01102     }
01103     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
01104       // Allow any number of calls to adjust.trampoline.
01105       continue;
01106     return nullptr;
01107   }
01108 
01109   // No call to init.trampoline found.
01110   if (!InitTrampoline)
01111     return nullptr;
01112 
01113   // Check that the alloca is being used in the expected way.
01114   if (InitTrampoline->getOperand(0) != TrampMem)
01115     return nullptr;
01116 
01117   return InitTrampoline;
01118 }
01119 
01120 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
01121                                                Value *TrampMem) {
01122   // Visit all the previous instructions in the basic block, and try to find a
01123   // init.trampoline which has a direct path to the adjust.trampoline.
01124   for (BasicBlock::iterator I = AdjustTramp,
01125        E = AdjustTramp->getParent()->begin(); I != E; ) {
01126     Instruction *Inst = --I;
01127     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
01128       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
01129           II->getOperand(0) == TrampMem)
01130         return II;
01131     if (Inst->mayWriteToMemory())
01132       return nullptr;
01133   }
01134   return nullptr;
01135 }
01136 
01137 // Given a call to llvm.adjust.trampoline, find and return the corresponding
01138 // call to llvm.init.trampoline if the call to the trampoline can be optimized
01139 // to a direct call to a function.  Otherwise return NULL.
01140 //
01141 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
01142   Callee = Callee->stripPointerCasts();
01143   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
01144   if (!AdjustTramp ||
01145       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
01146     return nullptr;
01147 
01148   Value *TrampMem = AdjustTramp->getOperand(0);
01149 
01150   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
01151     return IT;
01152   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
01153     return IT;
01154   return nullptr;
01155 }
01156 
01157 // visitCallSite - Improvements for call and invoke instructions.
01158 //
01159 Instruction *InstCombiner::visitCallSite(CallSite CS) {
01160   if (isAllocLikeFn(CS.getInstruction(), TLI))
01161     return visitAllocSite(*CS.getInstruction());
01162 
01163   bool Changed = false;
01164 
01165   // If the callee is a pointer to a function, attempt to move any casts to the
01166   // arguments of the call/invoke.
01167   Value *Callee = CS.getCalledValue();
01168   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
01169     return nullptr;
01170 
01171   if (Function *CalleeF = dyn_cast<Function>(Callee))
01172     // If the call and callee calling conventions don't match, this call must
01173     // be unreachable, as the call is undefined.
01174     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
01175         // Only do this for calls to a function with a body.  A prototype may
01176         // not actually end up matching the implementation's calling conv for a
01177         // variety of reasons (e.g. it may be written in assembly).
01178         !CalleeF->isDeclaration()) {
01179       Instruction *OldCall = CS.getInstruction();
01180       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01181                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01182                                   OldCall);
01183       // If OldCall does not return void then replaceAllUsesWith undef.
01184       // This allows ValueHandlers and custom metadata to adjust itself.
01185       if (!OldCall->getType()->isVoidTy())
01186         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
01187       if (isa<CallInst>(OldCall))
01188         return EraseInstFromFunction(*OldCall);
01189 
01190       // We cannot remove an invoke, because it would change the CFG, just
01191       // change the callee to a null pointer.
01192       cast<InvokeInst>(OldCall)->setCalledFunction(
01193                                     Constant::getNullValue(CalleeF->getType()));
01194       return nullptr;
01195     }
01196 
01197   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01198     // If CS does not return void then replaceAllUsesWith undef.
01199     // This allows ValueHandlers and custom metadata to adjust itself.
01200     if (!CS.getInstruction()->getType()->isVoidTy())
01201       ReplaceInstUsesWith(*CS.getInstruction(),
01202                           UndefValue::get(CS.getInstruction()->getType()));
01203 
01204     if (isa<InvokeInst>(CS.getInstruction())) {
01205       // Can't remove an invoke because we cannot change the CFG.
01206       return nullptr;
01207     }
01208 
01209     // This instruction is not reachable, just remove it.  We insert a store to
01210     // undef so that we know that this code is not reachable, despite the fact
01211     // that we can't modify the CFG here.
01212     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
01213                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
01214                   CS.getInstruction());
01215 
01216     return EraseInstFromFunction(*CS.getInstruction());
01217   }
01218 
01219   if (IntrinsicInst *II = FindInitTrampoline(Callee))
01220     return transformCallThroughTrampoline(CS, II);
01221 
01222   PointerType *PTy = cast<PointerType>(Callee->getType());
01223   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01224   if (FTy->isVarArg()) {
01225     int ix = FTy->getNumParams();
01226     // See if we can optimize any arguments passed through the varargs area of
01227     // the call.
01228     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
01229            E = CS.arg_end(); I != E; ++I, ++ix) {
01230       CastInst *CI = dyn_cast<CastInst>(*I);
01231       if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
01232         *I = CI->getOperand(0);
01233         Changed = true;
01234       }
01235     }
01236   }
01237 
01238   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
01239     // Inline asm calls cannot throw - mark them 'nounwind'.
01240     CS.setDoesNotThrow();
01241     Changed = true;
01242   }
01243 
01244   // Try to optimize the call if possible, we require DataLayout for most of
01245   // this.  None of these calls are seen as possibly dead so go ahead and
01246   // delete the instruction now.
01247   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
01248     Instruction *I = tryOptimizeCall(CI, DL);
01249     // If we changed something return the result, etc. Otherwise let
01250     // the fallthrough check.
01251     if (I) return EraseInstFromFunction(*I);
01252   }
01253 
01254   return Changed ? CS.getInstruction() : nullptr;
01255 }
01256 
01257 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
01258 // attempt to move the cast to the arguments of the call/invoke.
01259 //
01260 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
01261   Function *Callee =
01262     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
01263   if (!Callee)
01264     return false;
01265   Instruction *Caller = CS.getInstruction();
01266   const AttributeSet &CallerPAL = CS.getAttributes();
01267 
01268   // Okay, this is a cast from a function to a different type.  Unless doing so
01269   // would cause a type conversion of one of our arguments, change this call to
01270   // be a direct call with arguments casted to the appropriate types.
01271   //
01272   FunctionType *FT = Callee->getFunctionType();
01273   Type *OldRetTy = Caller->getType();
01274   Type *NewRetTy = FT->getReturnType();
01275 
01276   // Check to see if we are changing the return type...
01277   if (OldRetTy != NewRetTy) {
01278 
01279     if (NewRetTy->isStructTy())
01280       return false; // TODO: Handle multiple return values.
01281 
01282     if (!CastInst::isBitCastable(NewRetTy, OldRetTy)) {
01283       if (Callee->isDeclaration())
01284         return false;   // Cannot transform this return value.
01285 
01286       if (!Caller->use_empty() &&
01287           // void -> non-void is handled specially
01288           !NewRetTy->isVoidTy())
01289       return false;   // Cannot transform this return value.
01290     }
01291 
01292     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
01293       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01294       if (RAttrs.
01295           hasAttributes(AttributeFuncs::
01296                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01297                         AttributeSet::ReturnIndex))
01298         return false;   // Attribute not compatible with transformed value.
01299     }
01300 
01301     // If the callsite is an invoke instruction, and the return value is used by
01302     // a PHI node in a successor, we cannot change the return type of the call
01303     // because there is no place to put the cast instruction (without breaking
01304     // the critical edge).  Bail out in this case.
01305     if (!Caller->use_empty())
01306       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
01307         for (User *U : II->users())
01308           if (PHINode *PN = dyn_cast<PHINode>(U))
01309             if (PN->getParent() == II->getNormalDest() ||
01310                 PN->getParent() == II->getUnwindDest())
01311               return false;
01312   }
01313 
01314   unsigned NumActualArgs = CS.arg_size();
01315   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
01316 
01317   CallSite::arg_iterator AI = CS.arg_begin();
01318   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
01319     Type *ParamTy = FT->getParamType(i);
01320     Type *ActTy = (*AI)->getType();
01321 
01322     if (!CastInst::isBitCastable(ActTy, ParamTy))
01323       return false;   // Cannot transform this parameter value.
01324 
01325     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
01326           hasAttributes(AttributeFuncs::
01327                         typeIncompatible(ParamTy, i + 1), i + 1))
01328       return false;   // Attribute not compatible with transformed value.
01329 
01330     if (CS.isInAllocaArgument(i))
01331       return false;   // Cannot transform to and from inalloca.
01332 
01333     // If the parameter is passed as a byval argument, then we have to have a
01334     // sized type and the sized type has to have the same size as the old type.
01335     if (ParamTy != ActTy &&
01336         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
01337                                                          Attribute::ByVal)) {
01338       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
01339       if (!ParamPTy || !ParamPTy->getElementType()->isSized() || !DL)
01340         return false;
01341 
01342       Type *CurElTy = ActTy->getPointerElementType();
01343       if (DL->getTypeAllocSize(CurElTy) !=
01344           DL->getTypeAllocSize(ParamPTy->getElementType()))
01345         return false;
01346     }
01347   }
01348 
01349   if (Callee->isDeclaration()) {
01350     // Do not delete arguments unless we have a function body.
01351     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
01352       return false;
01353 
01354     // If the callee is just a declaration, don't change the varargsness of the
01355     // call.  We don't want to introduce a varargs call where one doesn't
01356     // already exist.
01357     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
01358     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
01359       return false;
01360 
01361     // If both the callee and the cast type are varargs, we still have to make
01362     // sure the number of fixed parameters are the same or we have the same
01363     // ABI issues as if we introduce a varargs call.
01364     if (FT->isVarArg() &&
01365         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
01366         FT->getNumParams() !=
01367         cast<FunctionType>(APTy->getElementType())->getNumParams())
01368       return false;
01369   }
01370 
01371   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
01372       !CallerPAL.isEmpty())
01373     // In this case we have more arguments than the new function type, but we
01374     // won't be dropping them.  Check that these extra arguments have attributes
01375     // that are compatible with being a vararg call argument.
01376     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
01377       unsigned Index = CallerPAL.getSlotIndex(i - 1);
01378       if (Index <= FT->getNumParams())
01379         break;
01380 
01381       // Check if it has an attribute that's incompatible with varargs.
01382       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
01383       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
01384         return false;
01385     }
01386 
01387 
01388   // Okay, we decided that this is a safe thing to do: go ahead and start
01389   // inserting cast instructions as necessary.
01390   std::vector<Value*> Args;
01391   Args.reserve(NumActualArgs);
01392   SmallVector<AttributeSet, 8> attrVec;
01393   attrVec.reserve(NumCommonArgs);
01394 
01395   // Get any return attributes.
01396   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01397 
01398   // If the return value is not being used, the type may not be compatible
01399   // with the existing attributes.  Wipe out any problematic attributes.
01400   RAttrs.
01401     removeAttributes(AttributeFuncs::
01402                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01403                      AttributeSet::ReturnIndex);
01404 
01405   // Add the new return attributes.
01406   if (RAttrs.hasAttributes())
01407     attrVec.push_back(AttributeSet::get(Caller->getContext(),
01408                                         AttributeSet::ReturnIndex, RAttrs));
01409 
01410   AI = CS.arg_begin();
01411   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
01412     Type *ParamTy = FT->getParamType(i);
01413 
01414     if ((*AI)->getType() == ParamTy) {
01415       Args.push_back(*AI);
01416     } else {
01417       Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
01418     }
01419 
01420     // Add any parameter attributes.
01421     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01422     if (PAttrs.hasAttributes())
01423       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
01424                                           PAttrs));
01425   }
01426 
01427   // If the function takes more arguments than the call was taking, add them
01428   // now.
01429   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
01430     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
01431 
01432   // If we are removing arguments to the function, emit an obnoxious warning.
01433   if (FT->getNumParams() < NumActualArgs) {
01434     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
01435     if (FT->isVarArg()) {
01436       // Add all of the arguments in their promoted form to the arg list.
01437       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
01438         Type *PTy = getPromotedType((*AI)->getType());
01439         if (PTy != (*AI)->getType()) {
01440           // Must promote to pass through va_arg area!
01441           Instruction::CastOps opcode =
01442             CastInst::getCastOpcode(*AI, false, PTy, false);
01443           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
01444         } else {
01445           Args.push_back(*AI);
01446         }
01447 
01448         // Add any parameter attributes.
01449         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01450         if (PAttrs.hasAttributes())
01451           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
01452                                               PAttrs));
01453       }
01454     }
01455   }
01456 
01457   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
01458   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
01459     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
01460 
01461   if (NewRetTy->isVoidTy())
01462     Caller->setName("");   // Void type should not have a name.
01463 
01464   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
01465                                                        attrVec);
01466 
01467   Instruction *NC;
01468   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01469     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
01470                                II->getUnwindDest(), Args);
01471     NC->takeName(II);
01472     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
01473     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
01474   } else {
01475     CallInst *CI = cast<CallInst>(Caller);
01476     NC = Builder->CreateCall(Callee, Args);
01477     NC->takeName(CI);
01478     if (CI->isTailCall())
01479       cast<CallInst>(NC)->setTailCall();
01480     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
01481     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
01482   }
01483 
01484   // Insert a cast of the return type as necessary.
01485   Value *NV = NC;
01486   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
01487     if (!NV->getType()->isVoidTy()) {
01488       NV = NC = CastInst::Create(CastInst::BitCast, NC, OldRetTy);
01489       NC->setDebugLoc(Caller->getDebugLoc());
01490 
01491       // If this is an invoke instruction, we should insert it after the first
01492       // non-phi, instruction in the normal successor block.
01493       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01494         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
01495         InsertNewInstBefore(NC, *I);
01496       } else {
01497         // Otherwise, it's a call, just insert cast right after the call.
01498         InsertNewInstBefore(NC, *Caller);
01499       }
01500       Worklist.AddUsersToWorkList(*Caller);
01501     } else {
01502       NV = UndefValue::get(Caller->getType());
01503     }
01504   }
01505 
01506   if (!Caller->use_empty())
01507     ReplaceInstUsesWith(*Caller, NV);
01508   else if (Caller->hasValueHandle())
01509     ValueHandleBase::ValueIsRAUWd(Caller, NV);
01510 
01511   EraseInstFromFunction(*Caller);
01512   return true;
01513 }
01514 
01515 // transformCallThroughTrampoline - Turn a call to a function created by
01516 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
01517 // underlying function.
01518 //
01519 Instruction *
01520 InstCombiner::transformCallThroughTrampoline(CallSite CS,
01521                                              IntrinsicInst *Tramp) {
01522   Value *Callee = CS.getCalledValue();
01523   PointerType *PTy = cast<PointerType>(Callee->getType());
01524   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01525   const AttributeSet &Attrs = CS.getAttributes();
01526 
01527   // If the call already has the 'nest' attribute somewhere then give up -
01528   // otherwise 'nest' would occur twice after splicing in the chain.
01529   if (Attrs.hasAttrSomewhere(Attribute::Nest))
01530     return nullptr;
01531 
01532   assert(Tramp &&
01533          "transformCallThroughTrampoline called with incorrect CallSite.");
01534 
01535   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
01536   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
01537   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
01538 
01539   const AttributeSet &NestAttrs = NestF->getAttributes();
01540   if (!NestAttrs.isEmpty()) {
01541     unsigned NestIdx = 1;
01542     Type *NestTy = nullptr;
01543     AttributeSet NestAttr;
01544 
01545     // Look for a parameter marked with the 'nest' attribute.
01546     for (FunctionType::param_iterator I = NestFTy->param_begin(),
01547          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
01548       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
01549         // Record the parameter type and any other attributes.
01550         NestTy = *I;
01551         NestAttr = NestAttrs.getParamAttributes(NestIdx);
01552         break;
01553       }
01554 
01555     if (NestTy) {
01556       Instruction *Caller = CS.getInstruction();
01557       std::vector<Value*> NewArgs;
01558       NewArgs.reserve(CS.arg_size() + 1);
01559 
01560       SmallVector<AttributeSet, 8> NewAttrs;
01561       NewAttrs.reserve(Attrs.getNumSlots() + 1);
01562 
01563       // Insert the nest argument into the call argument list, which may
01564       // mean appending it.  Likewise for attributes.
01565 
01566       // Add any result attributes.
01567       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01568         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01569                                              Attrs.getRetAttributes()));
01570 
01571       {
01572         unsigned Idx = 1;
01573         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
01574         do {
01575           if (Idx == NestIdx) {
01576             // Add the chain argument and attributes.
01577             Value *NestVal = Tramp->getArgOperand(2);
01578             if (NestVal->getType() != NestTy)
01579               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
01580             NewArgs.push_back(NestVal);
01581             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01582                                                  NestAttr));
01583           }
01584 
01585           if (I == E)
01586             break;
01587 
01588           // Add the original argument and attributes.
01589           NewArgs.push_back(*I);
01590           AttributeSet Attr = Attrs.getParamAttributes(Idx);
01591           if (Attr.hasAttributes(Idx)) {
01592             AttrBuilder B(Attr, Idx);
01593             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01594                                                  Idx + (Idx >= NestIdx), B));
01595           }
01596 
01597           ++Idx, ++I;
01598         } while (1);
01599       }
01600 
01601       // Add any function attributes.
01602       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01603         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
01604                                              Attrs.getFnAttributes()));
01605 
01606       // The trampoline may have been bitcast to a bogus type (FTy).
01607       // Handle this by synthesizing a new function type, equal to FTy
01608       // with the chain parameter inserted.
01609 
01610       std::vector<Type*> NewTypes;
01611       NewTypes.reserve(FTy->getNumParams()+1);
01612 
01613       // Insert the chain's type into the list of parameter types, which may
01614       // mean appending it.
01615       {
01616         unsigned Idx = 1;
01617         FunctionType::param_iterator I = FTy->param_begin(),
01618           E = FTy->param_end();
01619 
01620         do {
01621           if (Idx == NestIdx)
01622             // Add the chain's type.
01623             NewTypes.push_back(NestTy);
01624 
01625           if (I == E)
01626             break;
01627 
01628           // Add the original type.
01629           NewTypes.push_back(*I);
01630 
01631           ++Idx, ++I;
01632         } while (1);
01633       }
01634 
01635       // Replace the trampoline call with a direct call.  Let the generic
01636       // code sort out any function type mismatches.
01637       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
01638                                                 FTy->isVarArg());
01639       Constant *NewCallee =
01640         NestF->getType() == PointerType::getUnqual(NewFTy) ?
01641         NestF : ConstantExpr::getBitCast(NestF,
01642                                          PointerType::getUnqual(NewFTy));
01643       const AttributeSet &NewPAL =
01644           AttributeSet::get(FTy->getContext(), NewAttrs);
01645 
01646       Instruction *NewCaller;
01647       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01648         NewCaller = InvokeInst::Create(NewCallee,
01649                                        II->getNormalDest(), II->getUnwindDest(),
01650                                        NewArgs);
01651         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
01652         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
01653       } else {
01654         NewCaller = CallInst::Create(NewCallee, NewArgs);
01655         if (cast<CallInst>(Caller)->isTailCall())
01656           cast<CallInst>(NewCaller)->setTailCall();
01657         cast<CallInst>(NewCaller)->
01658           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
01659         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
01660       }
01661 
01662       return NewCaller;
01663     }
01664   }
01665 
01666   // Replace the trampoline call with a direct call.  Since there is no 'nest'
01667   // parameter, there is no need to adjust the argument list.  Let the generic
01668   // code sort out any function type mismatches.
01669   Constant *NewCallee =
01670     NestF->getType() == PTy ? NestF :
01671                               ConstantExpr::getBitCast(NestF, PTy);
01672   CS.setCalledFunction(NewCallee);
01673   return CS.getInstruction();
01674 }