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