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