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/PatternMatch.h"
00020 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00021 #include "llvm/Transforms/Utils/Local.h"
00022 using namespace llvm;
00023 using namespace PatternMatch;
00024 
00025 STATISTIC(NumSimplified, "Number of library calls simplified");
00026 
00027 /// getPromotedType - Return the specified type promoted as it would be to pass
00028 /// though a va_arg area.
00029 static Type *getPromotedType(Type *Ty) {
00030   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
00031     if (ITy->getBitWidth() < 32)
00032       return Type::getInt32Ty(Ty->getContext());
00033   }
00034   return Ty;
00035 }
00036 
00037 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
00038 /// single scalar element, like {{{type}}} or [1 x type], return type.
00039 static Type *reduceToSingleValueType(Type *T) {
00040   while (!T->isSingleValueType()) {
00041     if (StructType *STy = dyn_cast<StructType>(T)) {
00042       if (STy->getNumElements() == 1)
00043         T = STy->getElementType(0);
00044       else
00045         break;
00046     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
00047       if (ATy->getNumElements() == 1)
00048         T = ATy->getElementType();
00049       else
00050         break;
00051     } else
00052       break;
00053   }
00054 
00055   return T;
00056 }
00057 
00058 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
00059   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL);
00060   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL);
00061   unsigned MinAlign = std::min(DstAlign, SrcAlign);
00062   unsigned CopyAlign = MI->getAlignment();
00063 
00064   if (CopyAlign < MinAlign) {
00065     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00066                                              MinAlign, false));
00067     return MI;
00068   }
00069 
00070   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
00071   // load/store.
00072   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
00073   if (MemOpLength == 0) return 0;
00074 
00075   // Source and destination pointer types are always "i8*" for intrinsic.  See
00076   // if the size is something we can handle with a single primitive load/store.
00077   // A single load+store correctly handles overlapping memory in the memmove
00078   // case.
00079   uint64_t Size = MemOpLength->getLimitedValue();
00080   assert(Size && "0-sized memory transferring should be removed already.");
00081 
00082   if (Size > 8 || (Size&(Size-1)))
00083     return 0;  // If not 1/2/4/8 bytes, exit.
00084 
00085   // Use an integer load+store unless we can find something better.
00086   unsigned SrcAddrSp =
00087     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
00088   unsigned DstAddrSp =
00089     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
00090 
00091   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
00092   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
00093   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
00094 
00095   // Memcpy forces the use of i8* for the source and destination.  That means
00096   // that if you're using memcpy to move one double around, you'll get a cast
00097   // from double* to i8*.  We'd much rather use a double load+store rather than
00098   // an i64 load+store, here because this improves the odds that the source or
00099   // dest address will be promotable.  See if we can find a better type than the
00100   // integer datatype.
00101   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
00102   MDNode *CopyMD = 0;
00103   if (StrippedDest != MI->getArgOperand(0)) {
00104     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
00105                                     ->getElementType();
00106     if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
00107       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
00108       // down through these levels if so.
00109       SrcETy = reduceToSingleValueType(SrcETy);
00110 
00111       if (SrcETy->isSingleValueType()) {
00112         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
00113         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
00114 
00115         // If the memcpy has metadata describing the members, see if we can
00116         // get the TBAA tag describing our copy.
00117         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
00118           if (M->getNumOperands() == 3 &&
00119               M->getOperand(0) &&
00120               isa<ConstantInt>(M->getOperand(0)) &&
00121               cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
00122               M->getOperand(1) &&
00123               isa<ConstantInt>(M->getOperand(1)) &&
00124               cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
00125               M->getOperand(2) &&
00126               isa<MDNode>(M->getOperand(2)))
00127             CopyMD = cast<MDNode>(M->getOperand(2));
00128         }
00129       }
00130     }
00131   }
00132 
00133   // If the memcpy/memmove provides better alignment info than we can
00134   // infer, use it.
00135   SrcAlign = std::max(SrcAlign, CopyAlign);
00136   DstAlign = std::max(DstAlign, CopyAlign);
00137 
00138   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
00139   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
00140   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
00141   L->setAlignment(SrcAlign);
00142   if (CopyMD)
00143     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00144   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
00145   S->setAlignment(DstAlign);
00146   if (CopyMD)
00147     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
00148 
00149   // Set the size of the copy to 0, it will be deleted on the next iteration.
00150   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
00151   return MI;
00152 }
00153 
00154 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
00155   unsigned Alignment = getKnownAlignment(MI->getDest(), DL);
00156   if (MI->getAlignment() < Alignment) {
00157     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
00158                                              Alignment, false));
00159     return MI;
00160   }
00161 
00162   // Extract the length and alignment and fill if they are constant.
00163   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
00164   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
00165   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
00166     return 0;
00167   uint64_t Len = LenC->getLimitedValue();
00168   Alignment = MI->getAlignment();
00169   assert(Len && "0-sized memory setting should be removed already.");
00170 
00171   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
00172   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
00173     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
00174 
00175     Value *Dest = MI->getDest();
00176     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
00177     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
00178     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
00179 
00180     // Alignment 0 is identity for alignment 1 for memset, but not store.
00181     if (Alignment == 0) Alignment = 1;
00182 
00183     // Extract the fill value and store.
00184     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
00185     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
00186                                         MI->isVolatile());
00187     S->setAlignment(Alignment);
00188 
00189     // Set the size of the copy to 0, it will be deleted on the next iteration.
00190     MI->setLength(Constant::getNullValue(LenC->getType()));
00191     return MI;
00192   }
00193 
00194   return 0;
00195 }
00196 
00197 /// visitCallInst - CallInst simplification.  This mostly only handles folding
00198 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
00199 /// the heavy lifting.
00200 ///
00201 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
00202   if (isFreeCall(&CI, TLI))
00203     return visitFree(CI);
00204 
00205   // If the caller function is nounwind, mark the call as nounwind, even if the
00206   // callee isn't.
00207   if (CI.getParent()->getParent()->doesNotThrow() &&
00208       !CI.doesNotThrow()) {
00209     CI.setDoesNotThrow();
00210     return &CI;
00211   }
00212 
00213   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
00214   if (!II) return visitCallSite(&CI);
00215 
00216   // Intrinsics cannot occur in an invoke, so handle them here instead of in
00217   // visitCallSite.
00218   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
00219     bool Changed = false;
00220 
00221     // memmove/cpy/set of zero bytes is a noop.
00222     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
00223       if (NumBytes->isNullValue())
00224         return EraseInstFromFunction(CI);
00225 
00226       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
00227         if (CI->getZExtValue() == 1) {
00228           // Replace the instruction with just byte operations.  We would
00229           // transform other cases to loads/stores, but we don't know if
00230           // alignment is sufficient.
00231         }
00232     }
00233 
00234     // No other transformations apply to volatile transfers.
00235     if (MI->isVolatile())
00236       return 0;
00237 
00238     // If we have a memmove and the source operation is a constant global,
00239     // then the source and dest pointers can't alias, so we can change this
00240     // into a call to memcpy.
00241     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
00242       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
00243         if (GVSrc->isConstant()) {
00244           Module *M = CI.getParent()->getParent()->getParent();
00245           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
00246           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
00247                            CI.getArgOperand(1)->getType(),
00248                            CI.getArgOperand(2)->getType() };
00249           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
00250           Changed = true;
00251         }
00252     }
00253 
00254     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
00255       // memmove(x,x,size) -> noop.
00256       if (MTI->getSource() == MTI->getDest())
00257         return EraseInstFromFunction(CI);
00258     }
00259 
00260     // If we can determine a pointer alignment that is bigger than currently
00261     // set, update the alignment.
00262     if (isa<MemTransferInst>(MI)) {
00263       if (Instruction *I = SimplifyMemTransfer(MI))
00264         return I;
00265     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
00266       if (Instruction *I = SimplifyMemSet(MSI))
00267         return I;
00268     }
00269 
00270     if (Changed) return II;
00271   }
00272 
00273   switch (II->getIntrinsicID()) {
00274   default: break;
00275   case Intrinsic::objectsize: {
00276     uint64_t Size;
00277     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
00278       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
00279     return 0;
00280   }
00281   case Intrinsic::bswap: {
00282     Value *IIOperand = II->getArgOperand(0);
00283     Value *X = 0;
00284 
00285     // bswap(bswap(x)) -> x
00286     if (match(IIOperand, m_BSwap(m_Value(X))))
00287         return ReplaceInstUsesWith(CI, X);
00288 
00289     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
00290     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
00291       unsigned C = X->getType()->getPrimitiveSizeInBits() -
00292         IIOperand->getType()->getPrimitiveSizeInBits();
00293       Value *CV = ConstantInt::get(X->getType(), C);
00294       Value *V = Builder->CreateLShr(X, CV);
00295       return new TruncInst(V, IIOperand->getType());
00296     }
00297     break;
00298   }
00299 
00300   case Intrinsic::powi:
00301     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00302       // powi(x, 0) -> 1.0
00303       if (Power->isZero())
00304         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
00305       // powi(x, 1) -> x
00306       if (Power->isOne())
00307         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
00308       // powi(x, -1) -> 1/x
00309       if (Power->isAllOnesValue())
00310         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
00311                                           II->getArgOperand(0));
00312     }
00313     break;
00314   case Intrinsic::cttz: {
00315     // If all bits below the first known one are known zero,
00316     // this value is constant.
00317     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00318     // FIXME: Try to simplify vectors of integers.
00319     if (!IT) break;
00320     uint32_t BitWidth = IT->getBitWidth();
00321     APInt KnownZero(BitWidth, 0);
00322     APInt KnownOne(BitWidth, 0);
00323     ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
00324     unsigned TrailingZeros = KnownOne.countTrailingZeros();
00325     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
00326     if ((Mask & KnownZero) == Mask)
00327       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00328                                  APInt(BitWidth, TrailingZeros)));
00329 
00330     }
00331     break;
00332   case Intrinsic::ctlz: {
00333     // If all bits above the first known one are known zero,
00334     // this value is constant.
00335     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
00336     // FIXME: Try to simplify vectors of integers.
00337     if (!IT) break;
00338     uint32_t BitWidth = IT->getBitWidth();
00339     APInt KnownZero(BitWidth, 0);
00340     APInt KnownOne(BitWidth, 0);
00341     ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
00342     unsigned LeadingZeros = KnownOne.countLeadingZeros();
00343     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
00344     if ((Mask & KnownZero) == Mask)
00345       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
00346                                  APInt(BitWidth, LeadingZeros)));
00347 
00348     }
00349     break;
00350   case Intrinsic::uadd_with_overflow: {
00351     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00352     IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
00353     uint32_t BitWidth = IT->getBitWidth();
00354     APInt LHSKnownZero(BitWidth, 0);
00355     APInt LHSKnownOne(BitWidth, 0);
00356     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
00357     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
00358     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
00359 
00360     if (LHSKnownNegative || LHSKnownPositive) {
00361       APInt RHSKnownZero(BitWidth, 0);
00362       APInt RHSKnownOne(BitWidth, 0);
00363       ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
00364       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
00365       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
00366       if (LHSKnownNegative && RHSKnownNegative) {
00367         // The sign bit is set in both cases: this MUST overflow.
00368         // Create a simple add instruction, and insert it into the struct.
00369         Value *Add = Builder->CreateAdd(LHS, RHS);
00370         Add->takeName(&CI);
00371         Constant *V[] = {
00372           UndefValue::get(LHS->getType()),
00373           ConstantInt::getTrue(II->getContext())
00374         };
00375         StructType *ST = cast<StructType>(II->getType());
00376         Constant *Struct = ConstantStruct::get(ST, V);
00377         return InsertValueInst::Create(Struct, Add, 0);
00378       }
00379 
00380       if (LHSKnownPositive && RHSKnownPositive) {
00381         // The sign bit is clear in both cases: this CANNOT overflow.
00382         // Create a simple add instruction, and insert it into the struct.
00383         Value *Add = Builder->CreateNUWAdd(LHS, RHS);
00384         Add->takeName(&CI);
00385         Constant *V[] = {
00386           UndefValue::get(LHS->getType()),
00387           ConstantInt::getFalse(II->getContext())
00388         };
00389         StructType *ST = cast<StructType>(II->getType());
00390         Constant *Struct = ConstantStruct::get(ST, V);
00391         return InsertValueInst::Create(Struct, Add, 0);
00392       }
00393     }
00394   }
00395   // FALL THROUGH uadd into sadd
00396   case Intrinsic::sadd_with_overflow:
00397     // Canonicalize constants into the RHS.
00398     if (isa<Constant>(II->getArgOperand(0)) &&
00399         !isa<Constant>(II->getArgOperand(1))) {
00400       Value *LHS = II->getArgOperand(0);
00401       II->setArgOperand(0, II->getArgOperand(1));
00402       II->setArgOperand(1, LHS);
00403       return II;
00404     }
00405 
00406     // X + undef -> undef
00407     if (isa<UndefValue>(II->getArgOperand(1)))
00408       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00409 
00410     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00411       // X + 0 -> {X, false}
00412       if (RHS->isZero()) {
00413         Constant *V[] = {
00414           UndefValue::get(II->getArgOperand(0)->getType()),
00415           ConstantInt::getFalse(II->getContext())
00416         };
00417         Constant *Struct =
00418           ConstantStruct::get(cast<StructType>(II->getType()), V);
00419         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
00420       }
00421     }
00422     break;
00423   case Intrinsic::usub_with_overflow:
00424   case Intrinsic::ssub_with_overflow:
00425     // undef - X -> undef
00426     // X - undef -> undef
00427     if (isa<UndefValue>(II->getArgOperand(0)) ||
00428         isa<UndefValue>(II->getArgOperand(1)))
00429       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00430 
00431     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00432       // X - 0 -> {X, false}
00433       if (RHS->isZero()) {
00434         Constant *V[] = {
00435           UndefValue::get(II->getArgOperand(0)->getType()),
00436           ConstantInt::getFalse(II->getContext())
00437         };
00438         Constant *Struct =
00439           ConstantStruct::get(cast<StructType>(II->getType()), V);
00440         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
00441       }
00442     }
00443     break;
00444   case Intrinsic::umul_with_overflow: {
00445     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
00446     unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
00447 
00448     APInt LHSKnownZero(BitWidth, 0);
00449     APInt LHSKnownOne(BitWidth, 0);
00450     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
00451     APInt RHSKnownZero(BitWidth, 0);
00452     APInt RHSKnownOne(BitWidth, 0);
00453     ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
00454 
00455     // Get the largest possible values for each operand.
00456     APInt LHSMax = ~LHSKnownZero;
00457     APInt RHSMax = ~RHSKnownZero;
00458 
00459     // If multiplying the maximum values does not overflow then we can turn
00460     // this into a plain NUW mul.
00461     bool Overflow;
00462     LHSMax.umul_ov(RHSMax, Overflow);
00463     if (!Overflow) {
00464       Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
00465       Constant *V[] = {
00466         UndefValue::get(LHS->getType()),
00467         Builder->getFalse()
00468       };
00469       Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
00470       return InsertValueInst::Create(Struct, Mul, 0);
00471     }
00472   } // FALL THROUGH
00473   case Intrinsic::smul_with_overflow:
00474     // Canonicalize constants into the RHS.
00475     if (isa<Constant>(II->getArgOperand(0)) &&
00476         !isa<Constant>(II->getArgOperand(1))) {
00477       Value *LHS = II->getArgOperand(0);
00478       II->setArgOperand(0, II->getArgOperand(1));
00479       II->setArgOperand(1, LHS);
00480       return II;
00481     }
00482 
00483     // X * undef -> undef
00484     if (isa<UndefValue>(II->getArgOperand(1)))
00485       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
00486 
00487     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
00488       // X*0 -> {0, false}
00489       if (RHSI->isZero())
00490         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
00491 
00492       // X * 1 -> {X, false}
00493       if (RHSI->equalsInt(1)) {
00494         Constant *V[] = {
00495           UndefValue::get(II->getArgOperand(0)->getType()),
00496           ConstantInt::getFalse(II->getContext())
00497         };
00498         Constant *Struct =
00499           ConstantStruct::get(cast<StructType>(II->getType()), V);
00500         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
00501       }
00502     }
00503     break;
00504   case Intrinsic::ppc_altivec_lvx:
00505   case Intrinsic::ppc_altivec_lvxl:
00506     // Turn PPC lvx -> load if the pointer is known aligned.
00507     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
00508       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
00509                                          PointerType::getUnqual(II->getType()));
00510       return new LoadInst(Ptr);
00511     }
00512     break;
00513   case Intrinsic::ppc_altivec_stvx:
00514   case Intrinsic::ppc_altivec_stvxl:
00515     // Turn stvx -> store if the pointer is known aligned.
00516     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL) >= 16) {
00517       Type *OpPtrTy =
00518         PointerType::getUnqual(II->getArgOperand(0)->getType());
00519       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
00520       return new StoreInst(II->getArgOperand(0), Ptr);
00521     }
00522     break;
00523   case Intrinsic::x86_sse_storeu_ps:
00524   case Intrinsic::x86_sse2_storeu_pd:
00525   case Intrinsic::x86_sse2_storeu_dq:
00526     // Turn X86 storeu -> store if the pointer is known aligned.
00527     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
00528       Type *OpPtrTy =
00529         PointerType::getUnqual(II->getArgOperand(1)->getType());
00530       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
00531       return new StoreInst(II->getArgOperand(1), Ptr);
00532     }
00533     break;
00534 
00535   case Intrinsic::x86_sse_cvtss2si:
00536   case Intrinsic::x86_sse_cvtss2si64:
00537   case Intrinsic::x86_sse_cvttss2si:
00538   case Intrinsic::x86_sse_cvttss2si64:
00539   case Intrinsic::x86_sse2_cvtsd2si:
00540   case Intrinsic::x86_sse2_cvtsd2si64:
00541   case Intrinsic::x86_sse2_cvttsd2si:
00542   case Intrinsic::x86_sse2_cvttsd2si64: {
00543     // These intrinsics only demand the 0th element of their input vectors. If
00544     // we can simplify the input based on that, do so now.
00545     unsigned VWidth =
00546       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00547     APInt DemandedElts(VWidth, 1);
00548     APInt UndefElts(VWidth, 0);
00549     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
00550                                               DemandedElts, UndefElts)) {
00551       II->setArgOperand(0, V);
00552       return II;
00553     }
00554     break;
00555   }
00556 
00557 
00558   case Intrinsic::x86_sse41_pmovsxbw:
00559   case Intrinsic::x86_sse41_pmovsxwd:
00560   case Intrinsic::x86_sse41_pmovsxdq:
00561   case Intrinsic::x86_sse41_pmovzxbw:
00562   case Intrinsic::x86_sse41_pmovzxwd:
00563   case Intrinsic::x86_sse41_pmovzxdq: {
00564     // pmov{s|z}x ignores the upper half of their input vectors.
00565     unsigned VWidth =
00566       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
00567     unsigned LowHalfElts = VWidth / 2;
00568     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
00569     APInt UndefElts(VWidth, 0);
00570     if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
00571                                                  InputDemandedElts,
00572                                                  UndefElts)) {
00573       II->setArgOperand(0, TmpV);
00574       return II;
00575     }
00576     break;
00577   }
00578 
00579   case Intrinsic::ppc_altivec_vperm:
00580     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
00581     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
00582       assert(Mask->getType()->getVectorNumElements() == 16 &&
00583              "Bad type for intrinsic!");
00584 
00585       // Check that all of the elements are integer constants or undefs.
00586       bool AllEltsOk = true;
00587       for (unsigned i = 0; i != 16; ++i) {
00588         Constant *Elt = Mask->getAggregateElement(i);
00589         if (Elt == 0 ||
00590             !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
00591           AllEltsOk = false;
00592           break;
00593         }
00594       }
00595 
00596       if (AllEltsOk) {
00597         // Cast the input vectors to byte vectors.
00598         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
00599                                             Mask->getType());
00600         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
00601                                             Mask->getType());
00602         Value *Result = UndefValue::get(Op0->getType());
00603 
00604         // Only extract each element once.
00605         Value *ExtractedElts[32];
00606         memset(ExtractedElts, 0, sizeof(ExtractedElts));
00607 
00608         for (unsigned i = 0; i != 16; ++i) {
00609           if (isa<UndefValue>(Mask->getAggregateElement(i)))
00610             continue;
00611           unsigned Idx =
00612             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
00613           Idx &= 31;  // Match the hardware behavior.
00614 
00615           if (ExtractedElts[Idx] == 0) {
00616             ExtractedElts[Idx] =
00617               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
00618                                             Builder->getInt32(Idx&15));
00619           }
00620 
00621           // Insert this value into the result vector.
00622           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
00623                                                 Builder->getInt32(i));
00624         }
00625         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
00626       }
00627     }
00628     break;
00629 
00630   case Intrinsic::arm_neon_vld1:
00631   case Intrinsic::arm_neon_vld2:
00632   case Intrinsic::arm_neon_vld3:
00633   case Intrinsic::arm_neon_vld4:
00634   case Intrinsic::arm_neon_vld2lane:
00635   case Intrinsic::arm_neon_vld3lane:
00636   case Intrinsic::arm_neon_vld4lane:
00637   case Intrinsic::arm_neon_vst1:
00638   case Intrinsic::arm_neon_vst2:
00639   case Intrinsic::arm_neon_vst3:
00640   case Intrinsic::arm_neon_vst4:
00641   case Intrinsic::arm_neon_vst2lane:
00642   case Intrinsic::arm_neon_vst3lane:
00643   case Intrinsic::arm_neon_vst4lane: {
00644     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL);
00645     unsigned AlignArg = II->getNumArgOperands() - 1;
00646     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
00647     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
00648       II->setArgOperand(AlignArg,
00649                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
00650                                          MemAlign, false));
00651       return II;
00652     }
00653     break;
00654   }
00655 
00656   case Intrinsic::arm_neon_vmulls:
00657   case Intrinsic::arm_neon_vmullu:
00658   case Intrinsic::arm64_neon_smull:
00659   case Intrinsic::arm64_neon_umull: {
00660     Value *Arg0 = II->getArgOperand(0);
00661     Value *Arg1 = II->getArgOperand(1);
00662 
00663     // Handle mul by zero first:
00664     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
00665       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
00666     }
00667 
00668     // Check for constant LHS & RHS - in this case we just simplify.
00669     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
00670                  II->getIntrinsicID() == Intrinsic::arm64_neon_umull);
00671     VectorType *NewVT = cast<VectorType>(II->getType());
00672     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
00673       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
00674         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
00675         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
00676 
00677         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
00678       }
00679 
00680       // Couldn't simplify - canonicalize constant to the RHS.
00681       std::swap(Arg0, Arg1);
00682     }
00683 
00684     // Handle mul by one:
00685     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
00686       if (ConstantInt *Splat =
00687               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
00688         if (Splat->isOne())
00689           return CastInst::CreateIntegerCast(Arg0, II->getType(),
00690                                              /*isSigned=*/!Zext);
00691 
00692     break;
00693   }
00694 
00695   case Intrinsic::stackrestore: {
00696     // If the save is right next to the restore, remove the restore.  This can
00697     // happen when variable allocas are DCE'd.
00698     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
00699       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
00700         BasicBlock::iterator BI = SS;
00701         if (&*++BI == II)
00702           return EraseInstFromFunction(CI);
00703       }
00704     }
00705 
00706     // Scan down this block to see if there is another stack restore in the
00707     // same block without an intervening call/alloca.
00708     BasicBlock::iterator BI = II;
00709     TerminatorInst *TI = II->getParent()->getTerminator();
00710     bool CannotRemove = false;
00711     for (++BI; &*BI != TI; ++BI) {
00712       if (isa<AllocaInst>(BI)) {
00713         CannotRemove = true;
00714         break;
00715       }
00716       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
00717         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
00718           // If there is a stackrestore below this one, remove this one.
00719           if (II->getIntrinsicID() == Intrinsic::stackrestore)
00720             return EraseInstFromFunction(CI);
00721           // Otherwise, ignore the intrinsic.
00722         } else {
00723           // If we found a non-intrinsic call, we can't remove the stack
00724           // restore.
00725           CannotRemove = true;
00726           break;
00727         }
00728       }
00729     }
00730 
00731     // If the stack restore is in a return, resume, or unwind block and if there
00732     // are no allocas or calls between the restore and the return, nuke the
00733     // restore.
00734     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
00735       return EraseInstFromFunction(CI);
00736     break;
00737   }
00738   }
00739 
00740   return visitCallSite(II);
00741 }
00742 
00743 // InvokeInst simplification
00744 //
00745 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
00746   return visitCallSite(&II);
00747 }
00748 
00749 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
00750 /// passed through the varargs area, we can eliminate the use of the cast.
00751 static bool isSafeToEliminateVarargsCast(const CallSite CS,
00752                                          const CastInst * const CI,
00753                                          const DataLayout * const DL,
00754                                          const int ix) {
00755   if (!CI->isLosslessCast())
00756     return false;
00757 
00758   // The size of ByVal or InAlloca arguments is derived from the type, so we
00759   // can't change to a type with a different size.  If the size were
00760   // passed explicitly we could avoid this check.
00761   if (!CS.isByValOrInAllocaArgument(ix))
00762     return true;
00763 
00764   Type* SrcTy =
00765             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
00766   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
00767   if (!SrcTy->isSized() || !DstTy->isSized())
00768     return false;
00769   if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
00770     return false;
00771   return true;
00772 }
00773 
00774 // Try to fold some different type of calls here.
00775 // Currently we're only working with the checking functions, memcpy_chk,
00776 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
00777 // strcat_chk and strncat_chk.
00778 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
00779   if (CI->getCalledFunction() == 0) return 0;
00780 
00781   if (Value *With = Simplifier->optimizeCall(CI)) {
00782     ++NumSimplified;
00783     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
00784   }
00785 
00786   return 0;
00787 }
00788 
00789 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
00790   // Strip off at most one level of pointer casts, looking for an alloca.  This
00791   // is good enough in practice and simpler than handling any number of casts.
00792   Value *Underlying = TrampMem->stripPointerCasts();
00793   if (Underlying != TrampMem &&
00794       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
00795     return 0;
00796   if (!isa<AllocaInst>(Underlying))
00797     return 0;
00798 
00799   IntrinsicInst *InitTrampoline = 0;
00800   for (User *U : TrampMem->users()) {
00801     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
00802     if (!II)
00803       return 0;
00804     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
00805       if (InitTrampoline)
00806         // More than one init_trampoline writes to this value.  Give up.
00807         return 0;
00808       InitTrampoline = II;
00809       continue;
00810     }
00811     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
00812       // Allow any number of calls to adjust.trampoline.
00813       continue;
00814     return 0;
00815   }
00816 
00817   // No call to init.trampoline found.
00818   if (!InitTrampoline)
00819     return 0;
00820 
00821   // Check that the alloca is being used in the expected way.
00822   if (InitTrampoline->getOperand(0) != TrampMem)
00823     return 0;
00824 
00825   return InitTrampoline;
00826 }
00827 
00828 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
00829                                                Value *TrampMem) {
00830   // Visit all the previous instructions in the basic block, and try to find a
00831   // init.trampoline which has a direct path to the adjust.trampoline.
00832   for (BasicBlock::iterator I = AdjustTramp,
00833        E = AdjustTramp->getParent()->begin(); I != E; ) {
00834     Instruction *Inst = --I;
00835     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
00836       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
00837           II->getOperand(0) == TrampMem)
00838         return II;
00839     if (Inst->mayWriteToMemory())
00840       return 0;
00841   }
00842   return 0;
00843 }
00844 
00845 // Given a call to llvm.adjust.trampoline, find and return the corresponding
00846 // call to llvm.init.trampoline if the call to the trampoline can be optimized
00847 // to a direct call to a function.  Otherwise return NULL.
00848 //
00849 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
00850   Callee = Callee->stripPointerCasts();
00851   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
00852   if (!AdjustTramp ||
00853       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
00854     return 0;
00855 
00856   Value *TrampMem = AdjustTramp->getOperand(0);
00857 
00858   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
00859     return IT;
00860   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
00861     return IT;
00862   return 0;
00863 }
00864 
00865 // visitCallSite - Improvements for call and invoke instructions.
00866 //
00867 Instruction *InstCombiner::visitCallSite(CallSite CS) {
00868   if (isAllocLikeFn(CS.getInstruction(), TLI))
00869     return visitAllocSite(*CS.getInstruction());
00870 
00871   bool Changed = false;
00872 
00873   // If the callee is a pointer to a function, attempt to move any casts to the
00874   // arguments of the call/invoke.
00875   Value *Callee = CS.getCalledValue();
00876   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
00877     return 0;
00878 
00879   if (Function *CalleeF = dyn_cast<Function>(Callee))
00880     // If the call and callee calling conventions don't match, this call must
00881     // be unreachable, as the call is undefined.
00882     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
00883         // Only do this for calls to a function with a body.  A prototype may
00884         // not actually end up matching the implementation's calling conv for a
00885         // variety of reasons (e.g. it may be written in assembly).
00886         !CalleeF->isDeclaration()) {
00887       Instruction *OldCall = CS.getInstruction();
00888       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
00889                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
00890                                   OldCall);
00891       // If OldCall does not return void then replaceAllUsesWith undef.
00892       // This allows ValueHandlers and custom metadata to adjust itself.
00893       if (!OldCall->getType()->isVoidTy())
00894         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
00895       if (isa<CallInst>(OldCall))
00896         return EraseInstFromFunction(*OldCall);
00897 
00898       // We cannot remove an invoke, because it would change the CFG, just
00899       // change the callee to a null pointer.
00900       cast<InvokeInst>(OldCall)->setCalledFunction(
00901                                     Constant::getNullValue(CalleeF->getType()));
00902       return 0;
00903     }
00904 
00905   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
00906     // If CS does not return void then replaceAllUsesWith undef.
00907     // This allows ValueHandlers and custom metadata to adjust itself.
00908     if (!CS.getInstruction()->getType()->isVoidTy())
00909       ReplaceInstUsesWith(*CS.getInstruction(),
00910                           UndefValue::get(CS.getInstruction()->getType()));
00911 
00912     if (isa<InvokeInst>(CS.getInstruction())) {
00913       // Can't remove an invoke because we cannot change the CFG.
00914       return 0;
00915     }
00916 
00917     // This instruction is not reachable, just remove it.  We insert a store to
00918     // undef so that we know that this code is not reachable, despite the fact
00919     // that we can't modify the CFG here.
00920     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
00921                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
00922                   CS.getInstruction());
00923 
00924     return EraseInstFromFunction(*CS.getInstruction());
00925   }
00926 
00927   if (IntrinsicInst *II = FindInitTrampoline(Callee))
00928     return transformCallThroughTrampoline(CS, II);
00929 
00930   PointerType *PTy = cast<PointerType>(Callee->getType());
00931   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
00932   if (FTy->isVarArg()) {
00933     int ix = FTy->getNumParams();
00934     // See if we can optimize any arguments passed through the varargs area of
00935     // the call.
00936     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
00937            E = CS.arg_end(); I != E; ++I, ++ix) {
00938       CastInst *CI = dyn_cast<CastInst>(*I);
00939       if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
00940         *I = CI->getOperand(0);
00941         Changed = true;
00942       }
00943     }
00944   }
00945 
00946   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
00947     // Inline asm calls cannot throw - mark them 'nounwind'.
00948     CS.setDoesNotThrow();
00949     Changed = true;
00950   }
00951 
00952   // Try to optimize the call if possible, we require DataLayout for most of
00953   // this.  None of these calls are seen as possibly dead so go ahead and
00954   // delete the instruction now.
00955   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
00956     Instruction *I = tryOptimizeCall(CI, DL);
00957     // If we changed something return the result, etc. Otherwise let
00958     // the fallthrough check.
00959     if (I) return EraseInstFromFunction(*I);
00960   }
00961 
00962   return Changed ? CS.getInstruction() : 0;
00963 }
00964 
00965 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
00966 // attempt to move the cast to the arguments of the call/invoke.
00967 //
00968 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
00969   Function *Callee =
00970     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
00971   if (Callee == 0)
00972     return false;
00973   Instruction *Caller = CS.getInstruction();
00974   const AttributeSet &CallerPAL = CS.getAttributes();
00975 
00976   // Okay, this is a cast from a function to a different type.  Unless doing so
00977   // would cause a type conversion of one of our arguments, change this call to
00978   // be a direct call with arguments casted to the appropriate types.
00979   //
00980   FunctionType *FT = Callee->getFunctionType();
00981   Type *OldRetTy = Caller->getType();
00982   Type *NewRetTy = FT->getReturnType();
00983 
00984   // Check to see if we are changing the return type...
00985   if (OldRetTy != NewRetTy) {
00986 
00987     if (NewRetTy->isStructTy())
00988       return false; // TODO: Handle multiple return values.
00989 
00990     if (!CastInst::isBitCastable(NewRetTy, OldRetTy)) {
00991       if (Callee->isDeclaration())
00992         return false;   // Cannot transform this return value.
00993 
00994       if (!Caller->use_empty() &&
00995           // void -> non-void is handled specially
00996           !NewRetTy->isVoidTy())
00997       return false;   // Cannot transform this return value.
00998     }
00999 
01000     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
01001       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01002       if (RAttrs.
01003           hasAttributes(AttributeFuncs::
01004                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01005                         AttributeSet::ReturnIndex))
01006         return false;   // Attribute not compatible with transformed value.
01007     }
01008 
01009     // If the callsite is an invoke instruction, and the return value is used by
01010     // a PHI node in a successor, we cannot change the return type of the call
01011     // because there is no place to put the cast instruction (without breaking
01012     // the critical edge).  Bail out in this case.
01013     if (!Caller->use_empty())
01014       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
01015         for (User *U : II->users())
01016           if (PHINode *PN = dyn_cast<PHINode>(U))
01017             if (PN->getParent() == II->getNormalDest() ||
01018                 PN->getParent() == II->getUnwindDest())
01019               return false;
01020   }
01021 
01022   unsigned NumActualArgs = CS.arg_size();
01023   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
01024 
01025   CallSite::arg_iterator AI = CS.arg_begin();
01026   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
01027     Type *ParamTy = FT->getParamType(i);
01028     Type *ActTy = (*AI)->getType();
01029 
01030     if (!CastInst::isBitCastable(ActTy, ParamTy))
01031       return false;   // Cannot transform this parameter value.
01032 
01033     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
01034           hasAttributes(AttributeFuncs::
01035                         typeIncompatible(ParamTy, i + 1), i + 1))
01036       return false;   // Attribute not compatible with transformed value.
01037 
01038     if (CS.isInAllocaArgument(i))
01039       return false;   // Cannot transform to and from inalloca.
01040 
01041     // If the parameter is passed as a byval argument, then we have to have a
01042     // sized type and the sized type has to have the same size as the old type.
01043     if (ParamTy != ActTy &&
01044         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
01045                                                          Attribute::ByVal)) {
01046       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
01047       if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || DL == 0)
01048         return false;
01049 
01050       Type *CurElTy = ActTy->getPointerElementType();
01051       if (DL->getTypeAllocSize(CurElTy) !=
01052           DL->getTypeAllocSize(ParamPTy->getElementType()))
01053         return false;
01054     }
01055   }
01056 
01057   if (Callee->isDeclaration()) {
01058     // Do not delete arguments unless we have a function body.
01059     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
01060       return false;
01061 
01062     // If the callee is just a declaration, don't change the varargsness of the
01063     // call.  We don't want to introduce a varargs call where one doesn't
01064     // already exist.
01065     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
01066     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
01067       return false;
01068 
01069     // If both the callee and the cast type are varargs, we still have to make
01070     // sure the number of fixed parameters are the same or we have the same
01071     // ABI issues as if we introduce a varargs call.
01072     if (FT->isVarArg() &&
01073         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
01074         FT->getNumParams() !=
01075         cast<FunctionType>(APTy->getElementType())->getNumParams())
01076       return false;
01077   }
01078 
01079   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
01080       !CallerPAL.isEmpty())
01081     // In this case we have more arguments than the new function type, but we
01082     // won't be dropping them.  Check that these extra arguments have attributes
01083     // that are compatible with being a vararg call argument.
01084     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
01085       unsigned Index = CallerPAL.getSlotIndex(i - 1);
01086       if (Index <= FT->getNumParams())
01087         break;
01088 
01089       // Check if it has an attribute that's incompatible with varargs.
01090       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
01091       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
01092         return false;
01093     }
01094 
01095 
01096   // Okay, we decided that this is a safe thing to do: go ahead and start
01097   // inserting cast instructions as necessary.
01098   std::vector<Value*> Args;
01099   Args.reserve(NumActualArgs);
01100   SmallVector<AttributeSet, 8> attrVec;
01101   attrVec.reserve(NumCommonArgs);
01102 
01103   // Get any return attributes.
01104   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
01105 
01106   // If the return value is not being used, the type may not be compatible
01107   // with the existing attributes.  Wipe out any problematic attributes.
01108   RAttrs.
01109     removeAttributes(AttributeFuncs::
01110                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
01111                      AttributeSet::ReturnIndex);
01112 
01113   // Add the new return attributes.
01114   if (RAttrs.hasAttributes())
01115     attrVec.push_back(AttributeSet::get(Caller->getContext(),
01116                                         AttributeSet::ReturnIndex, RAttrs));
01117 
01118   AI = CS.arg_begin();
01119   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
01120     Type *ParamTy = FT->getParamType(i);
01121 
01122     if ((*AI)->getType() == ParamTy) {
01123       Args.push_back(*AI);
01124     } else {
01125       Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
01126     }
01127 
01128     // Add any parameter attributes.
01129     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01130     if (PAttrs.hasAttributes())
01131       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
01132                                           PAttrs));
01133   }
01134 
01135   // If the function takes more arguments than the call was taking, add them
01136   // now.
01137   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
01138     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
01139 
01140   // If we are removing arguments to the function, emit an obnoxious warning.
01141   if (FT->getNumParams() < NumActualArgs) {
01142     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
01143     if (FT->isVarArg()) {
01144       // Add all of the arguments in their promoted form to the arg list.
01145       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
01146         Type *PTy = getPromotedType((*AI)->getType());
01147         if (PTy != (*AI)->getType()) {
01148           // Must promote to pass through va_arg area!
01149           Instruction::CastOps opcode =
01150             CastInst::getCastOpcode(*AI, false, PTy, false);
01151           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
01152         } else {
01153           Args.push_back(*AI);
01154         }
01155 
01156         // Add any parameter attributes.
01157         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
01158         if (PAttrs.hasAttributes())
01159           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
01160                                               PAttrs));
01161       }
01162     }
01163   }
01164 
01165   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
01166   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
01167     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
01168 
01169   if (NewRetTy->isVoidTy())
01170     Caller->setName("");   // Void type should not have a name.
01171 
01172   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
01173                                                        attrVec);
01174 
01175   Instruction *NC;
01176   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01177     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
01178                                II->getUnwindDest(), Args);
01179     NC->takeName(II);
01180     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
01181     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
01182   } else {
01183     CallInst *CI = cast<CallInst>(Caller);
01184     NC = Builder->CreateCall(Callee, Args);
01185     NC->takeName(CI);
01186     if (CI->isTailCall())
01187       cast<CallInst>(NC)->setTailCall();
01188     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
01189     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
01190   }
01191 
01192   // Insert a cast of the return type as necessary.
01193   Value *NV = NC;
01194   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
01195     if (!NV->getType()->isVoidTy()) {
01196       NV = NC = CastInst::Create(CastInst::BitCast, NC, OldRetTy);
01197       NC->setDebugLoc(Caller->getDebugLoc());
01198 
01199       // If this is an invoke instruction, we should insert it after the first
01200       // non-phi, instruction in the normal successor block.
01201       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01202         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
01203         InsertNewInstBefore(NC, *I);
01204       } else {
01205         // Otherwise, it's a call, just insert cast right after the call.
01206         InsertNewInstBefore(NC, *Caller);
01207       }
01208       Worklist.AddUsersToWorkList(*Caller);
01209     } else {
01210       NV = UndefValue::get(Caller->getType());
01211     }
01212   }
01213 
01214   if (!Caller->use_empty())
01215     ReplaceInstUsesWith(*Caller, NV);
01216   else if (Caller->hasValueHandle())
01217     ValueHandleBase::ValueIsRAUWd(Caller, NV);
01218 
01219   EraseInstFromFunction(*Caller);
01220   return true;
01221 }
01222 
01223 // transformCallThroughTrampoline - Turn a call to a function created by
01224 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
01225 // underlying function.
01226 //
01227 Instruction *
01228 InstCombiner::transformCallThroughTrampoline(CallSite CS,
01229                                              IntrinsicInst *Tramp) {
01230   Value *Callee = CS.getCalledValue();
01231   PointerType *PTy = cast<PointerType>(Callee->getType());
01232   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01233   const AttributeSet &Attrs = CS.getAttributes();
01234 
01235   // If the call already has the 'nest' attribute somewhere then give up -
01236   // otherwise 'nest' would occur twice after splicing in the chain.
01237   if (Attrs.hasAttrSomewhere(Attribute::Nest))
01238     return 0;
01239 
01240   assert(Tramp &&
01241          "transformCallThroughTrampoline called with incorrect CallSite.");
01242 
01243   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
01244   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
01245   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
01246 
01247   const AttributeSet &NestAttrs = NestF->getAttributes();
01248   if (!NestAttrs.isEmpty()) {
01249     unsigned NestIdx = 1;
01250     Type *NestTy = 0;
01251     AttributeSet NestAttr;
01252 
01253     // Look for a parameter marked with the 'nest' attribute.
01254     for (FunctionType::param_iterator I = NestFTy->param_begin(),
01255          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
01256       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
01257         // Record the parameter type and any other attributes.
01258         NestTy = *I;
01259         NestAttr = NestAttrs.getParamAttributes(NestIdx);
01260         break;
01261       }
01262 
01263     if (NestTy) {
01264       Instruction *Caller = CS.getInstruction();
01265       std::vector<Value*> NewArgs;
01266       NewArgs.reserve(CS.arg_size() + 1);
01267 
01268       SmallVector<AttributeSet, 8> NewAttrs;
01269       NewAttrs.reserve(Attrs.getNumSlots() + 1);
01270 
01271       // Insert the nest argument into the call argument list, which may
01272       // mean appending it.  Likewise for attributes.
01273 
01274       // Add any result attributes.
01275       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01276         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01277                                              Attrs.getRetAttributes()));
01278 
01279       {
01280         unsigned Idx = 1;
01281         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
01282         do {
01283           if (Idx == NestIdx) {
01284             // Add the chain argument and attributes.
01285             Value *NestVal = Tramp->getArgOperand(2);
01286             if (NestVal->getType() != NestTy)
01287               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
01288             NewArgs.push_back(NestVal);
01289             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01290                                                  NestAttr));
01291           }
01292 
01293           if (I == E)
01294             break;
01295 
01296           // Add the original argument and attributes.
01297           NewArgs.push_back(*I);
01298           AttributeSet Attr = Attrs.getParamAttributes(Idx);
01299           if (Attr.hasAttributes(Idx)) {
01300             AttrBuilder B(Attr, Idx);
01301             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
01302                                                  Idx + (Idx >= NestIdx), B));
01303           }
01304 
01305           ++Idx, ++I;
01306         } while (1);
01307       }
01308 
01309       // Add any function attributes.
01310       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01311         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
01312                                              Attrs.getFnAttributes()));
01313 
01314       // The trampoline may have been bitcast to a bogus type (FTy).
01315       // Handle this by synthesizing a new function type, equal to FTy
01316       // with the chain parameter inserted.
01317 
01318       std::vector<Type*> NewTypes;
01319       NewTypes.reserve(FTy->getNumParams()+1);
01320 
01321       // Insert the chain's type into the list of parameter types, which may
01322       // mean appending it.
01323       {
01324         unsigned Idx = 1;
01325         FunctionType::param_iterator I = FTy->param_begin(),
01326           E = FTy->param_end();
01327 
01328         do {
01329           if (Idx == NestIdx)
01330             // Add the chain's type.
01331             NewTypes.push_back(NestTy);
01332 
01333           if (I == E)
01334             break;
01335 
01336           // Add the original type.
01337           NewTypes.push_back(*I);
01338 
01339           ++Idx, ++I;
01340         } while (1);
01341       }
01342 
01343       // Replace the trampoline call with a direct call.  Let the generic
01344       // code sort out any function type mismatches.
01345       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
01346                                                 FTy->isVarArg());
01347       Constant *NewCallee =
01348         NestF->getType() == PointerType::getUnqual(NewFTy) ?
01349         NestF : ConstantExpr::getBitCast(NestF,
01350                                          PointerType::getUnqual(NewFTy));
01351       const AttributeSet &NewPAL =
01352           AttributeSet::get(FTy->getContext(), NewAttrs);
01353 
01354       Instruction *NewCaller;
01355       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
01356         NewCaller = InvokeInst::Create(NewCallee,
01357                                        II->getNormalDest(), II->getUnwindDest(),
01358                                        NewArgs);
01359         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
01360         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
01361       } else {
01362         NewCaller = CallInst::Create(NewCallee, NewArgs);
01363         if (cast<CallInst>(Caller)->isTailCall())
01364           cast<CallInst>(NewCaller)->setTailCall();
01365         cast<CallInst>(NewCaller)->
01366           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
01367         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
01368       }
01369 
01370       return NewCaller;
01371     }
01372   }
01373 
01374   // Replace the trampoline call with a direct call.  Since there is no 'nest'
01375   // parameter, there is no need to adjust the argument list.  Let the generic
01376   // code sort out any function type mismatches.
01377   Constant *NewCallee =
01378     NestF->getType() == PTy ? NestF :
01379                               ConstantExpr::getBitCast(NestF, PTy);
01380   CS.setCalledFunction(NewCallee);
01381   return CS.getInstruction();
01382 }