LLVM API Documentation

Utils/SimplifyLibCalls.cpp
Go to the documentation of this file.
00001 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
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 is a utility pass used for testing the InstructionSimplify analysis.
00011 // The analysis is applied to every instruction, and if it simplifies then the
00012 // instruction is replaced by the simplification.  If you are looking for a pass
00013 // that performs serious instruction folding, use the instcombine pass instead.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/ADT/StringMap.h"
00020 #include "llvm/Analysis/ValueTracking.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/Function.h"
00023 #include "llvm/IR/IRBuilder.h"
00024 #include "llvm/IR/IntrinsicInst.h"
00025 #include "llvm/IR/Intrinsics.h"
00026 #include "llvm/IR/LLVMContext.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/Support/Allocator.h"
00029 #include "llvm/Target/TargetLibraryInfo.h"
00030 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00031 
00032 using namespace llvm;
00033 
00034 /// This class is the abstract base class for the set of optimizations that
00035 /// corresponds to one library call.
00036 namespace {
00037 class LibCallOptimization {
00038 protected:
00039   Function *Caller;
00040   const DataLayout *TD;
00041   const TargetLibraryInfo *TLI;
00042   const LibCallSimplifier *LCS;
00043   LLVMContext* Context;
00044 public:
00045   LibCallOptimization() { }
00046   virtual ~LibCallOptimization() {}
00047 
00048   /// callOptimizer - This pure virtual method is implemented by base classes to
00049   /// do various optimizations.  If this returns null then no transformation was
00050   /// performed.  If it returns CI, then it transformed the call and CI is to be
00051   /// deleted.  If it returns something else, replace CI with the new value and
00052   /// delete CI.
00053   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
00054     =0;
00055 
00056   /// ignoreCallingConv - Returns false if this transformation could possibly
00057   /// change the calling convention.
00058   virtual bool ignoreCallingConv() { return false; }
00059 
00060   Value *optimizeCall(CallInst *CI, const DataLayout *TD,
00061                       const TargetLibraryInfo *TLI,
00062                       const LibCallSimplifier *LCS, IRBuilder<> &B) {
00063     Caller = CI->getParent()->getParent();
00064     this->TD = TD;
00065     this->TLI = TLI;
00066     this->LCS = LCS;
00067     if (CI->getCalledFunction())
00068       Context = &CI->getCalledFunction()->getContext();
00069 
00070     // We never change the calling convention.
00071     if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
00072       return NULL;
00073 
00074     return callOptimizer(CI->getCalledFunction(), CI, B);
00075   }
00076 };
00077 
00078 //===----------------------------------------------------------------------===//
00079 // Helper Functions
00080 //===----------------------------------------------------------------------===//
00081 
00082 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
00083 /// value is equal or not-equal to zero.
00084 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
00085   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
00086        UI != E; ++UI) {
00087     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
00088       if (IC->isEquality())
00089         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
00090           if (C->isNullValue())
00091             continue;
00092     // Unknown instruction.
00093     return false;
00094   }
00095   return true;
00096 }
00097 
00098 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
00099 /// comparisons with With.
00100 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
00101   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
00102        UI != E; ++UI) {
00103     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
00104       if (IC->isEquality() && IC->getOperand(1) == With)
00105         continue;
00106     // Unknown instruction.
00107     return false;
00108   }
00109   return true;
00110 }
00111 
00112 static bool callHasFloatingPointArgument(const CallInst *CI) {
00113   for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
00114        it != e; ++it) {
00115     if ((*it)->getType()->isFloatingPointTy())
00116       return true;
00117   }
00118   return false;
00119 }
00120 
00121 //===----------------------------------------------------------------------===//
00122 // Fortified Library Call Optimizations
00123 //===----------------------------------------------------------------------===//
00124 
00125 struct FortifiedLibCallOptimization : public LibCallOptimization {
00126 protected:
00127   virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
00128         bool isString) const = 0;
00129 };
00130 
00131 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
00132   CallInst *CI;
00133 
00134   bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
00135     if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
00136       return true;
00137     if (ConstantInt *SizeCI =
00138                            dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
00139       if (SizeCI->isAllOnesValue())
00140         return true;
00141       if (isString) {
00142         uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
00143         // If the length is 0 we don't know how long it is and so we can't
00144         // remove the check.
00145         if (Len == 0) return false;
00146         return SizeCI->getZExtValue() >= Len;
00147       }
00148       if (ConstantInt *Arg = dyn_cast<ConstantInt>(
00149                                                   CI->getArgOperand(SizeArgOp)))
00150         return SizeCI->getZExtValue() >= Arg->getZExtValue();
00151     }
00152     return false;
00153   }
00154 };
00155 
00156 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
00157   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00158     this->CI = CI;
00159     FunctionType *FT = Callee->getFunctionType();
00160     LLVMContext &Context = CI->getParent()->getContext();
00161 
00162     // Check if this has the right signature.
00163     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
00164         !FT->getParamType(0)->isPointerTy() ||
00165         !FT->getParamType(1)->isPointerTy() ||
00166         FT->getParamType(2) != TD->getIntPtrType(Context) ||
00167         FT->getParamType(3) != TD->getIntPtrType(Context))
00168       return 0;
00169 
00170     if (isFoldable(3, 2, false)) {
00171       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
00172                      CI->getArgOperand(2), 1);
00173       return CI->getArgOperand(0);
00174     }
00175     return 0;
00176   }
00177 };
00178 
00179 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
00180   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00181     this->CI = CI;
00182     FunctionType *FT = Callee->getFunctionType();
00183     LLVMContext &Context = CI->getParent()->getContext();
00184 
00185     // Check if this has the right signature.
00186     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
00187         !FT->getParamType(0)->isPointerTy() ||
00188         !FT->getParamType(1)->isPointerTy() ||
00189         FT->getParamType(2) != TD->getIntPtrType(Context) ||
00190         FT->getParamType(3) != TD->getIntPtrType(Context))
00191       return 0;
00192 
00193     if (isFoldable(3, 2, false)) {
00194       B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
00195                       CI->getArgOperand(2), 1);
00196       return CI->getArgOperand(0);
00197     }
00198     return 0;
00199   }
00200 };
00201 
00202 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
00203   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00204     this->CI = CI;
00205     FunctionType *FT = Callee->getFunctionType();
00206     LLVMContext &Context = CI->getParent()->getContext();
00207 
00208     // Check if this has the right signature.
00209     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
00210         !FT->getParamType(0)->isPointerTy() ||
00211         !FT->getParamType(1)->isIntegerTy() ||
00212         FT->getParamType(2) != TD->getIntPtrType(Context) ||
00213         FT->getParamType(3) != TD->getIntPtrType(Context))
00214       return 0;
00215 
00216     if (isFoldable(3, 2, false)) {
00217       Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
00218                                    false);
00219       B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
00220       return CI->getArgOperand(0);
00221     }
00222     return 0;
00223   }
00224 };
00225 
00226 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
00227   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00228     this->CI = CI;
00229     StringRef Name = Callee->getName();
00230     FunctionType *FT = Callee->getFunctionType();
00231     LLVMContext &Context = CI->getParent()->getContext();
00232 
00233     // Check if this has the right signature.
00234     if (FT->getNumParams() != 3 ||
00235         FT->getReturnType() != FT->getParamType(0) ||
00236         FT->getParamType(0) != FT->getParamType(1) ||
00237         FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
00238         FT->getParamType(2) != TD->getIntPtrType(Context))
00239       return 0;
00240 
00241     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
00242     if (Dst == Src)      // __strcpy_chk(x,x)  -> x
00243       return Src;
00244 
00245     // If a) we don't have any length information, or b) we know this will
00246     // fit then just lower to a plain strcpy. Otherwise we'll keep our
00247     // strcpy_chk call which may fail at runtime if the size is too long.
00248     // TODO: It might be nice to get a maximum length out of the possible
00249     // string lengths for varying.
00250     if (isFoldable(2, 1, true)) {
00251       Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
00252       return Ret;
00253     } else {
00254       // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
00255       uint64_t Len = GetStringLength(Src);
00256       if (Len == 0) return 0;
00257 
00258       // This optimization require DataLayout.
00259       if (!TD) return 0;
00260 
00261       Value *Ret =
00262   EmitMemCpyChk(Dst, Src,
00263                       ConstantInt::get(TD->getIntPtrType(Context), Len),
00264                       CI->getArgOperand(2), B, TD, TLI);
00265       return Ret;
00266     }
00267     return 0;
00268   }
00269 };
00270 
00271 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
00272   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00273     this->CI = CI;
00274     StringRef Name = Callee->getName();
00275     FunctionType *FT = Callee->getFunctionType();
00276     LLVMContext &Context = CI->getParent()->getContext();
00277 
00278     // Check if this has the right signature.
00279     if (FT->getNumParams() != 3 ||
00280         FT->getReturnType() != FT->getParamType(0) ||
00281         FT->getParamType(0) != FT->getParamType(1) ||
00282         FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
00283         FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
00284       return 0;
00285 
00286     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
00287     if (Dst == Src) {  // stpcpy(x,x)  -> x+strlen(x)
00288       Value *StrLen = EmitStrLen(Src, B, TD, TLI);
00289       return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
00290     }
00291 
00292     // If a) we don't have any length information, or b) we know this will
00293     // fit then just lower to a plain stpcpy. Otherwise we'll keep our
00294     // stpcpy_chk call which may fail at runtime if the size is too long.
00295     // TODO: It might be nice to get a maximum length out of the possible
00296     // string lengths for varying.
00297     if (isFoldable(2, 1, true)) {
00298       Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
00299       return Ret;
00300     } else {
00301       // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
00302       uint64_t Len = GetStringLength(Src);
00303       if (Len == 0) return 0;
00304 
00305       // This optimization require DataLayout.
00306       if (!TD) return 0;
00307 
00308       Type *PT = FT->getParamType(0);
00309       Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
00310       Value *DstEnd = B.CreateGEP(Dst,
00311                                   ConstantInt::get(TD->getIntPtrType(PT),
00312                                                    Len - 1));
00313       if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI))
00314         return 0;
00315       return DstEnd;
00316     }
00317     return 0;
00318   }
00319 };
00320 
00321 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
00322   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00323     this->CI = CI;
00324     StringRef Name = Callee->getName();
00325     FunctionType *FT = Callee->getFunctionType();
00326     LLVMContext &Context = CI->getParent()->getContext();
00327 
00328     // Check if this has the right signature.
00329     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
00330         FT->getParamType(0) != FT->getParamType(1) ||
00331         FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
00332         !FT->getParamType(2)->isIntegerTy() ||
00333         FT->getParamType(3) != TD->getIntPtrType(Context))
00334       return 0;
00335 
00336     if (isFoldable(3, 2, false)) {
00337       Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
00338                                CI->getArgOperand(2), B, TD, TLI,
00339                                Name.substr(2, 7));
00340       return Ret;
00341     }
00342     return 0;
00343   }
00344 };
00345 
00346 //===----------------------------------------------------------------------===//
00347 // String and Memory Library Call Optimizations
00348 //===----------------------------------------------------------------------===//
00349 
00350 struct StrCatOpt : public LibCallOptimization {
00351   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00352     // Verify the "strcat" function prototype.
00353     FunctionType *FT = Callee->getFunctionType();
00354     if (FT->getNumParams() != 2 ||
00355         FT->getReturnType() != B.getInt8PtrTy() ||
00356         FT->getParamType(0) != FT->getReturnType() ||
00357         FT->getParamType(1) != FT->getReturnType())
00358       return 0;
00359 
00360     // Extract some information from the instruction
00361     Value *Dst = CI->getArgOperand(0);
00362     Value *Src = CI->getArgOperand(1);
00363 
00364     // See if we can get the length of the input string.
00365     uint64_t Len = GetStringLength(Src);
00366     if (Len == 0) return 0;
00367     --Len;  // Unbias length.
00368 
00369     // Handle the simple, do-nothing case: strcat(x, "") -> x
00370     if (Len == 0)
00371       return Dst;
00372 
00373     // These optimizations require DataLayout.
00374     if (!TD) return 0;
00375 
00376     return emitStrLenMemCpy(Src, Dst, Len, B);
00377   }
00378 
00379   Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
00380                           IRBuilder<> &B) {
00381     // We need to find the end of the destination string.  That's where the
00382     // memory is to be moved to. We just generate a call to strlen.
00383     Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
00384     if (!DstLen)
00385       return 0;
00386 
00387     // Now that we have the destination's length, we must index into the
00388     // destination's pointer to get the actual memcpy destination (end of
00389     // the string .. we're concatenating).
00390     Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
00391 
00392     // We have enough information to now generate the memcpy call to do the
00393     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
00394     B.CreateMemCpy(CpyDst, Src,
00395                    ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
00396     return Dst;
00397   }
00398 };
00399 
00400 struct StrNCatOpt : public StrCatOpt {
00401   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00402     // Verify the "strncat" function prototype.
00403     FunctionType *FT = Callee->getFunctionType();
00404     if (FT->getNumParams() != 3 ||
00405         FT->getReturnType() != B.getInt8PtrTy() ||
00406         FT->getParamType(0) != FT->getReturnType() ||
00407         FT->getParamType(1) != FT->getReturnType() ||
00408         !FT->getParamType(2)->isIntegerTy())
00409       return 0;
00410 
00411     // Extract some information from the instruction
00412     Value *Dst = CI->getArgOperand(0);
00413     Value *Src = CI->getArgOperand(1);
00414     uint64_t Len;
00415 
00416     // We don't do anything if length is not constant
00417     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
00418       Len = LengthArg->getZExtValue();
00419     else
00420       return 0;
00421 
00422     // See if we can get the length of the input string.
00423     uint64_t SrcLen = GetStringLength(Src);
00424     if (SrcLen == 0) return 0;
00425     --SrcLen;  // Unbias length.
00426 
00427     // Handle the simple, do-nothing cases:
00428     // strncat(x, "", c) -> x
00429     // strncat(x,  c, 0) -> x
00430     if (SrcLen == 0 || Len == 0) return Dst;
00431 
00432     // These optimizations require DataLayout.
00433     if (!TD) return 0;
00434 
00435     // We don't optimize this case
00436     if (Len < SrcLen) return 0;
00437 
00438     // strncat(x, s, c) -> strcat(x, s)
00439     // s is constant so the strcat can be optimized further
00440     return emitStrLenMemCpy(Src, Dst, SrcLen, B);
00441   }
00442 };
00443 
00444 struct StrChrOpt : public LibCallOptimization {
00445   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00446     // Verify the "strchr" function prototype.
00447     FunctionType *FT = Callee->getFunctionType();
00448     if (FT->getNumParams() != 2 ||
00449         FT->getReturnType() != B.getInt8PtrTy() ||
00450         FT->getParamType(0) != FT->getReturnType() ||
00451         !FT->getParamType(1)->isIntegerTy(32))
00452       return 0;
00453 
00454     Value *SrcStr = CI->getArgOperand(0);
00455 
00456     // If the second operand is non-constant, see if we can compute the length
00457     // of the input string and turn this into memchr.
00458     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
00459     if (CharC == 0) {
00460       // These optimizations require DataLayout.
00461       if (!TD) return 0;
00462 
00463       uint64_t Len = GetStringLength(SrcStr);
00464       if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
00465         return 0;
00466 
00467       return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
00468                         ConstantInt::get(TD->getIntPtrType(*Context), Len),
00469                         B, TD, TLI);
00470     }
00471 
00472     // Otherwise, the character is a constant, see if the first argument is
00473     // a string literal.  If so, we can constant fold.
00474     StringRef Str;
00475     if (!getConstantStringInfo(SrcStr, Str))
00476       return 0;
00477 
00478     // Compute the offset, make sure to handle the case when we're searching for
00479     // zero (a weird way to spell strlen).
00480     size_t I = CharC->getSExtValue() == 0 ?
00481         Str.size() : Str.find(CharC->getSExtValue());
00482     if (I == StringRef::npos) // Didn't find the char.  strchr returns null.
00483       return Constant::getNullValue(CI->getType());
00484 
00485     // strchr(s+n,c)  -> gep(s+n+i,c)
00486     return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
00487   }
00488 };
00489 
00490 struct StrRChrOpt : public LibCallOptimization {
00491   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00492     // Verify the "strrchr" function prototype.
00493     FunctionType *FT = Callee->getFunctionType();
00494     if (FT->getNumParams() != 2 ||
00495         FT->getReturnType() != B.getInt8PtrTy() ||
00496         FT->getParamType(0) != FT->getReturnType() ||
00497         !FT->getParamType(1)->isIntegerTy(32))
00498       return 0;
00499 
00500     Value *SrcStr = CI->getArgOperand(0);
00501     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
00502 
00503     // Cannot fold anything if we're not looking for a constant.
00504     if (!CharC)
00505       return 0;
00506 
00507     StringRef Str;
00508     if (!getConstantStringInfo(SrcStr, Str)) {
00509       // strrchr(s, 0) -> strchr(s, 0)
00510       if (TD && CharC->isZero())
00511         return EmitStrChr(SrcStr, '\0', B, TD, TLI);
00512       return 0;
00513     }
00514 
00515     // Compute the offset.
00516     size_t I = CharC->getSExtValue() == 0 ?
00517         Str.size() : Str.rfind(CharC->getSExtValue());
00518     if (I == StringRef::npos) // Didn't find the char. Return null.
00519       return Constant::getNullValue(CI->getType());
00520 
00521     // strrchr(s+n,c) -> gep(s+n+i,c)
00522     return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
00523   }
00524 };
00525 
00526 struct StrCmpOpt : public LibCallOptimization {
00527   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00528     // Verify the "strcmp" function prototype.
00529     FunctionType *FT = Callee->getFunctionType();
00530     if (FT->getNumParams() != 2 ||
00531         !FT->getReturnType()->isIntegerTy(32) ||
00532         FT->getParamType(0) != FT->getParamType(1) ||
00533         FT->getParamType(0) != B.getInt8PtrTy())
00534       return 0;
00535 
00536     Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
00537     if (Str1P == Str2P)      // strcmp(x,x)  -> 0
00538       return ConstantInt::get(CI->getType(), 0);
00539 
00540     StringRef Str1, Str2;
00541     bool HasStr1 = getConstantStringInfo(Str1P, Str1);
00542     bool HasStr2 = getConstantStringInfo(Str2P, Str2);
00543 
00544     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
00545     if (HasStr1 && HasStr2)
00546       return ConstantInt::get(CI->getType(), Str1.compare(Str2));
00547 
00548     if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
00549       return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
00550                                       CI->getType()));
00551 
00552     if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
00553       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
00554 
00555     // strcmp(P, "x") -> memcmp(P, "x", 2)
00556     uint64_t Len1 = GetStringLength(Str1P);
00557     uint64_t Len2 = GetStringLength(Str2P);
00558     if (Len1 && Len2) {
00559       // These optimizations require DataLayout.
00560       if (!TD) return 0;
00561 
00562       return EmitMemCmp(Str1P, Str2P,
00563                         ConstantInt::get(TD->getIntPtrType(*Context),
00564                         std::min(Len1, Len2)), B, TD, TLI);
00565     }
00566 
00567     return 0;
00568   }
00569 };
00570 
00571 struct StrNCmpOpt : public LibCallOptimization {
00572   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00573     // Verify the "strncmp" function prototype.
00574     FunctionType *FT = Callee->getFunctionType();
00575     if (FT->getNumParams() != 3 ||
00576         !FT->getReturnType()->isIntegerTy(32) ||
00577         FT->getParamType(0) != FT->getParamType(1) ||
00578         FT->getParamType(0) != B.getInt8PtrTy() ||
00579         !FT->getParamType(2)->isIntegerTy())
00580       return 0;
00581 
00582     Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
00583     if (Str1P == Str2P)      // strncmp(x,x,n)  -> 0
00584       return ConstantInt::get(CI->getType(), 0);
00585 
00586     // Get the length argument if it is constant.
00587     uint64_t Length;
00588     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
00589       Length = LengthArg->getZExtValue();
00590     else
00591       return 0;
00592 
00593     if (Length == 0) // strncmp(x,y,0)   -> 0
00594       return ConstantInt::get(CI->getType(), 0);
00595 
00596     if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
00597       return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
00598 
00599     StringRef Str1, Str2;
00600     bool HasStr1 = getConstantStringInfo(Str1P, Str1);
00601     bool HasStr2 = getConstantStringInfo(Str2P, Str2);
00602 
00603     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
00604     if (HasStr1 && HasStr2) {
00605       StringRef SubStr1 = Str1.substr(0, Length);
00606       StringRef SubStr2 = Str2.substr(0, Length);
00607       return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
00608     }
00609 
00610     if (HasStr1 && Str1.empty())  // strncmp("", x, n) -> -*x
00611       return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
00612                                       CI->getType()));
00613 
00614     if (HasStr2 && Str2.empty())  // strncmp(x, "", n) -> *x
00615       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
00616 
00617     return 0;
00618   }
00619 };
00620 
00621 struct StrCpyOpt : public LibCallOptimization {
00622   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00623     // Verify the "strcpy" function prototype.
00624     FunctionType *FT = Callee->getFunctionType();
00625     if (FT->getNumParams() != 2 ||
00626         FT->getReturnType() != FT->getParamType(0) ||
00627         FT->getParamType(0) != FT->getParamType(1) ||
00628         FT->getParamType(0) != B.getInt8PtrTy())
00629       return 0;
00630 
00631     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
00632     if (Dst == Src)      // strcpy(x,x)  -> x
00633       return Src;
00634 
00635     // These optimizations require DataLayout.
00636     if (!TD) return 0;
00637 
00638     // See if we can get the length of the input string.
00639     uint64_t Len = GetStringLength(Src);
00640     if (Len == 0) return 0;
00641 
00642     // We have enough information to now generate the memcpy call to do the
00643     // copy for us.  Make a memcpy to copy the nul byte with align = 1.
00644     B.CreateMemCpy(Dst, Src,
00645        ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
00646     return Dst;
00647   }
00648 };
00649 
00650 struct StpCpyOpt: public LibCallOptimization {
00651   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00652     // Verify the "stpcpy" function prototype.
00653     FunctionType *FT = Callee->getFunctionType();
00654     if (FT->getNumParams() != 2 ||
00655         FT->getReturnType() != FT->getParamType(0) ||
00656         FT->getParamType(0) != FT->getParamType(1) ||
00657         FT->getParamType(0) != B.getInt8PtrTy())
00658       return 0;
00659 
00660     // These optimizations require DataLayout.
00661     if (!TD) return 0;
00662 
00663     Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
00664     if (Dst == Src) {  // stpcpy(x,x)  -> x+strlen(x)
00665       Value *StrLen = EmitStrLen(Src, B, TD, TLI);
00666       return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
00667     }
00668 
00669     // See if we can get the length of the input string.
00670     uint64_t Len = GetStringLength(Src);
00671     if (Len == 0) return 0;
00672 
00673     Type *PT = FT->getParamType(0);
00674     Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
00675     Value *DstEnd = B.CreateGEP(Dst,
00676                                 ConstantInt::get(TD->getIntPtrType(PT),
00677                                                  Len - 1));
00678 
00679     // We have enough information to now generate the memcpy call to do the
00680     // copy for us.  Make a memcpy to copy the nul byte with align = 1.
00681     B.CreateMemCpy(Dst, Src, LenV, 1);
00682     return DstEnd;
00683   }
00684 };
00685 
00686 struct StrNCpyOpt : public LibCallOptimization {
00687   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00688     FunctionType *FT = Callee->getFunctionType();
00689     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
00690         FT->getParamType(0) != FT->getParamType(1) ||
00691         FT->getParamType(0) != B.getInt8PtrTy() ||
00692         !FT->getParamType(2)->isIntegerTy())
00693       return 0;
00694 
00695     Value *Dst = CI->getArgOperand(0);
00696     Value *Src = CI->getArgOperand(1);
00697     Value *LenOp = CI->getArgOperand(2);
00698 
00699     // See if we can get the length of the input string.
00700     uint64_t SrcLen = GetStringLength(Src);
00701     if (SrcLen == 0) return 0;
00702     --SrcLen;
00703 
00704     if (SrcLen == 0) {
00705       // strncpy(x, "", y) -> memset(x, '\0', y, 1)
00706       B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
00707       return Dst;
00708     }
00709 
00710     uint64_t Len;
00711     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
00712       Len = LengthArg->getZExtValue();
00713     else
00714       return 0;
00715 
00716     if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
00717 
00718     // These optimizations require DataLayout.
00719     if (!TD) return 0;
00720 
00721     // Let strncpy handle the zero padding
00722     if (Len > SrcLen+1) return 0;
00723 
00724     Type *PT = FT->getParamType(0);
00725     // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
00726     B.CreateMemCpy(Dst, Src,
00727                    ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
00728 
00729     return Dst;
00730   }
00731 };
00732 
00733 struct StrLenOpt : public LibCallOptimization {
00734   virtual bool ignoreCallingConv() { return true; }
00735   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00736     FunctionType *FT = Callee->getFunctionType();
00737     if (FT->getNumParams() != 1 ||
00738         FT->getParamType(0) != B.getInt8PtrTy() ||
00739         !FT->getReturnType()->isIntegerTy())
00740       return 0;
00741 
00742     Value *Src = CI->getArgOperand(0);
00743 
00744     // Constant folding: strlen("xyz") -> 3
00745     if (uint64_t Len = GetStringLength(Src))
00746       return ConstantInt::get(CI->getType(), Len-1);
00747 
00748     // strlen(x) != 0 --> *x != 0
00749     // strlen(x) == 0 --> *x == 0
00750     if (isOnlyUsedInZeroEqualityComparison(CI))
00751       return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
00752     return 0;
00753   }
00754 };
00755 
00756 struct StrPBrkOpt : public LibCallOptimization {
00757   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00758     FunctionType *FT = Callee->getFunctionType();
00759     if (FT->getNumParams() != 2 ||
00760         FT->getParamType(0) != B.getInt8PtrTy() ||
00761         FT->getParamType(1) != FT->getParamType(0) ||
00762         FT->getReturnType() != FT->getParamType(0))
00763       return 0;
00764 
00765     StringRef S1, S2;
00766     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
00767     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
00768 
00769     // strpbrk(s, "") -> NULL
00770     // strpbrk("", s) -> NULL
00771     if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
00772       return Constant::getNullValue(CI->getType());
00773 
00774     // Constant folding.
00775     if (HasS1 && HasS2) {
00776       size_t I = S1.find_first_of(S2);
00777       if (I == std::string::npos) // No match.
00778         return Constant::getNullValue(CI->getType());
00779 
00780       return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
00781     }
00782 
00783     // strpbrk(s, "a") -> strchr(s, 'a')
00784     if (TD && HasS2 && S2.size() == 1)
00785       return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
00786 
00787     return 0;
00788   }
00789 };
00790 
00791 struct StrToOpt : public LibCallOptimization {
00792   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00793     FunctionType *FT = Callee->getFunctionType();
00794     if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
00795         !FT->getParamType(0)->isPointerTy() ||
00796         !FT->getParamType(1)->isPointerTy())
00797       return 0;
00798 
00799     Value *EndPtr = CI->getArgOperand(1);
00800     if (isa<ConstantPointerNull>(EndPtr)) {
00801       // With a null EndPtr, this function won't capture the main argument.
00802       // It would be readonly too, except that it still may write to errno.
00803       CI->addAttribute(1, Attribute::NoCapture);
00804     }
00805 
00806     return 0;
00807   }
00808 };
00809 
00810 struct StrSpnOpt : public LibCallOptimization {
00811   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00812     FunctionType *FT = Callee->getFunctionType();
00813     if (FT->getNumParams() != 2 ||
00814         FT->getParamType(0) != B.getInt8PtrTy() ||
00815         FT->getParamType(1) != FT->getParamType(0) ||
00816         !FT->getReturnType()->isIntegerTy())
00817       return 0;
00818 
00819     StringRef S1, S2;
00820     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
00821     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
00822 
00823     // strspn(s, "") -> 0
00824     // strspn("", s) -> 0
00825     if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
00826       return Constant::getNullValue(CI->getType());
00827 
00828     // Constant folding.
00829     if (HasS1 && HasS2) {
00830       size_t Pos = S1.find_first_not_of(S2);
00831       if (Pos == StringRef::npos) Pos = S1.size();
00832       return ConstantInt::get(CI->getType(), Pos);
00833     }
00834 
00835     return 0;
00836   }
00837 };
00838 
00839 struct StrCSpnOpt : public LibCallOptimization {
00840   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00841     FunctionType *FT = Callee->getFunctionType();
00842     if (FT->getNumParams() != 2 ||
00843         FT->getParamType(0) != B.getInt8PtrTy() ||
00844         FT->getParamType(1) != FT->getParamType(0) ||
00845         !FT->getReturnType()->isIntegerTy())
00846       return 0;
00847 
00848     StringRef S1, S2;
00849     bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
00850     bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
00851 
00852     // strcspn("", s) -> 0
00853     if (HasS1 && S1.empty())
00854       return Constant::getNullValue(CI->getType());
00855 
00856     // Constant folding.
00857     if (HasS1 && HasS2) {
00858       size_t Pos = S1.find_first_of(S2);
00859       if (Pos == StringRef::npos) Pos = S1.size();
00860       return ConstantInt::get(CI->getType(), Pos);
00861     }
00862 
00863     // strcspn(s, "") -> strlen(s)
00864     if (TD && HasS2 && S2.empty())
00865       return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
00866 
00867     return 0;
00868   }
00869 };
00870 
00871 struct StrStrOpt : public LibCallOptimization {
00872   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00873     FunctionType *FT = Callee->getFunctionType();
00874     if (FT->getNumParams() != 2 ||
00875         !FT->getParamType(0)->isPointerTy() ||
00876         !FT->getParamType(1)->isPointerTy() ||
00877         !FT->getReturnType()->isPointerTy())
00878       return 0;
00879 
00880     // fold strstr(x, x) -> x.
00881     if (CI->getArgOperand(0) == CI->getArgOperand(1))
00882       return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
00883 
00884     // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
00885     if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
00886       Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
00887       if (!StrLen)
00888         return 0;
00889       Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
00890                                    StrLen, B, TD, TLI);
00891       if (!StrNCmp)
00892         return 0;
00893       for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
00894            UI != UE; ) {
00895         ICmpInst *Old = cast<ICmpInst>(*UI++);
00896         Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
00897                                   ConstantInt::getNullValue(StrNCmp->getType()),
00898                                   "cmp");
00899         LCS->replaceAllUsesWith(Old, Cmp);
00900       }
00901       return CI;
00902     }
00903 
00904     // See if either input string is a constant string.
00905     StringRef SearchStr, ToFindStr;
00906     bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
00907     bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
00908 
00909     // fold strstr(x, "") -> x.
00910     if (HasStr2 && ToFindStr.empty())
00911       return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
00912 
00913     // If both strings are known, constant fold it.
00914     if (HasStr1 && HasStr2) {
00915       std::string::size_type Offset = SearchStr.find(ToFindStr);
00916 
00917       if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
00918         return Constant::getNullValue(CI->getType());
00919 
00920       // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
00921       Value *Result = CastToCStr(CI->getArgOperand(0), B);
00922       Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
00923       return B.CreateBitCast(Result, CI->getType());
00924     }
00925 
00926     // fold strstr(x, "y") -> strchr(x, 'y').
00927     if (HasStr2 && ToFindStr.size() == 1) {
00928       Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
00929       return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
00930     }
00931     return 0;
00932   }
00933 };
00934 
00935 struct MemCmpOpt : public LibCallOptimization {
00936   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00937     FunctionType *FT = Callee->getFunctionType();
00938     if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
00939         !FT->getParamType(1)->isPointerTy() ||
00940         !FT->getReturnType()->isIntegerTy(32))
00941       return 0;
00942 
00943     Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
00944 
00945     if (LHS == RHS)  // memcmp(s,s,x) -> 0
00946       return Constant::getNullValue(CI->getType());
00947 
00948     // Make sure we have a constant length.
00949     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
00950     if (!LenC) return 0;
00951     uint64_t Len = LenC->getZExtValue();
00952 
00953     if (Len == 0) // memcmp(s1,s2,0) -> 0
00954       return Constant::getNullValue(CI->getType());
00955 
00956     // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
00957     if (Len == 1) {
00958       Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
00959                                  CI->getType(), "lhsv");
00960       Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
00961                                  CI->getType(), "rhsv");
00962       return B.CreateSub(LHSV, RHSV, "chardiff");
00963     }
00964 
00965     // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
00966     StringRef LHSStr, RHSStr;
00967     if (getConstantStringInfo(LHS, LHSStr) &&
00968         getConstantStringInfo(RHS, RHSStr)) {
00969       // Make sure we're not reading out-of-bounds memory.
00970       if (Len > LHSStr.size() || Len > RHSStr.size())
00971         return 0;
00972       // Fold the memcmp and normalize the result.  This way we get consistent
00973       // results across multiple platforms.
00974       uint64_t Ret = 0;
00975       int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
00976       if (Cmp < 0)
00977         Ret = -1;
00978       else if (Cmp > 0)
00979         Ret = 1;
00980       return ConstantInt::get(CI->getType(), Ret);
00981     }
00982 
00983     return 0;
00984   }
00985 };
00986 
00987 struct MemCpyOpt : public LibCallOptimization {
00988   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
00989     // These optimizations require DataLayout.
00990     if (!TD) return 0;
00991 
00992     FunctionType *FT = Callee->getFunctionType();
00993     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
00994         !FT->getParamType(0)->isPointerTy() ||
00995         !FT->getParamType(1)->isPointerTy() ||
00996         FT->getParamType(2) != TD->getIntPtrType(*Context))
00997       return 0;
00998 
00999     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
01000     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
01001                    CI->getArgOperand(2), 1);
01002     return CI->getArgOperand(0);
01003   }
01004 };
01005 
01006 struct MemMoveOpt : public LibCallOptimization {
01007   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01008     // These optimizations require DataLayout.
01009     if (!TD) return 0;
01010 
01011     FunctionType *FT = Callee->getFunctionType();
01012     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
01013         !FT->getParamType(0)->isPointerTy() ||
01014         !FT->getParamType(1)->isPointerTy() ||
01015         FT->getParamType(2) != TD->getIntPtrType(*Context))
01016       return 0;
01017 
01018     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
01019     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
01020                     CI->getArgOperand(2), 1);
01021     return CI->getArgOperand(0);
01022   }
01023 };
01024 
01025 struct MemSetOpt : public LibCallOptimization {
01026   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01027     // These optimizations require DataLayout.
01028     if (!TD) return 0;
01029 
01030     FunctionType *FT = Callee->getFunctionType();
01031     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
01032         !FT->getParamType(0)->isPointerTy() ||
01033         !FT->getParamType(1)->isIntegerTy() ||
01034         FT->getParamType(2) != TD->getIntPtrType(*Context))
01035       return 0;
01036 
01037     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
01038     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
01039     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
01040     return CI->getArgOperand(0);
01041   }
01042 };
01043 
01044 //===----------------------------------------------------------------------===//
01045 // Math Library Optimizations
01046 //===----------------------------------------------------------------------===//
01047 
01048 //===----------------------------------------------------------------------===//
01049 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
01050 
01051 struct UnaryDoubleFPOpt : public LibCallOptimization {
01052   bool CheckRetType;
01053   UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
01054   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01055     FunctionType *FT = Callee->getFunctionType();
01056     if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
01057         !FT->getParamType(0)->isDoubleTy())
01058       return 0;
01059 
01060     if (CheckRetType) {
01061       // Check if all the uses for function like 'sin' are converted to float.
01062       for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
01063           ++UseI) {
01064         FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
01065         if (Cast == 0 || !Cast->getType()->isFloatTy())
01066           return 0;
01067       }
01068     }
01069 
01070     // If this is something like 'floor((double)floatval)', convert to floorf.
01071     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
01072     if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
01073       return 0;
01074 
01075     // floor((double)floatval) -> (double)floorf(floatval)
01076     Value *V = Cast->getOperand(0);
01077     V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
01078     return B.CreateFPExt(V, B.getDoubleTy());
01079   }
01080 };
01081 
01082 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
01083   bool UnsafeFPShrink;
01084   UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
01085     this->UnsafeFPShrink = UnsafeFPShrink;
01086   }
01087 };
01088 
01089 struct CosOpt : public UnsafeFPLibCallOptimization {
01090   CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
01091   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01092     Value *Ret = NULL;
01093     if (UnsafeFPShrink && Callee->getName() == "cos" &&
01094         TLI->has(LibFunc::cosf)) {
01095       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
01096       Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
01097     }
01098 
01099     FunctionType *FT = Callee->getFunctionType();
01100     // Just make sure this has 1 argument of FP type, which matches the
01101     // result type.
01102     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
01103         !FT->getParamType(0)->isFloatingPointTy())
01104       return Ret;
01105 
01106     // cos(-x) -> cos(x)
01107     Value *Op1 = CI->getArgOperand(0);
01108     if (BinaryOperator::isFNeg(Op1)) {
01109       BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
01110       return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
01111     }
01112     return Ret;
01113   }
01114 };
01115 
01116 struct PowOpt : public UnsafeFPLibCallOptimization {
01117   PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
01118   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01119     Value *Ret = NULL;
01120     if (UnsafeFPShrink && Callee->getName() == "pow" &&
01121         TLI->has(LibFunc::powf)) {
01122       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
01123       Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
01124     }
01125 
01126     FunctionType *FT = Callee->getFunctionType();
01127     // Just make sure this has 2 arguments of the same FP type, which match the
01128     // result type.
01129     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
01130         FT->getParamType(0) != FT->getParamType(1) ||
01131         !FT->getParamType(0)->isFloatingPointTy())
01132       return Ret;
01133 
01134     Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
01135     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
01136       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
01137         return Op1C;
01138       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
01139         return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
01140     }
01141 
01142     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
01143     if (Op2C == 0) return Ret;
01144 
01145     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
01146       return ConstantFP::get(CI->getType(), 1.0);
01147 
01148     if (Op2C->isExactlyValue(0.5)) {
01149       // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
01150       // This is faster than calling pow, and still handles negative zero
01151       // and negative infinity correctly.
01152       // TODO: In fast-math mode, this could be just sqrt(x).
01153       // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
01154       Value *Inf = ConstantFP::getInfinity(CI->getType());
01155       Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
01156       Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
01157                                          Callee->getAttributes());
01158       Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
01159                                          Callee->getAttributes());
01160       Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
01161       Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
01162       return Sel;
01163     }
01164 
01165     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
01166       return Op1;
01167     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
01168       return B.CreateFMul(Op1, Op1, "pow2");
01169     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
01170       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
01171                           Op1, "powrecip");
01172     return 0;
01173   }
01174 };
01175 
01176 struct Exp2Opt : public UnsafeFPLibCallOptimization {
01177   Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
01178   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01179     Value *Ret = NULL;
01180     if (UnsafeFPShrink && Callee->getName() == "exp2" &&
01181         TLI->has(LibFunc::exp2)) {
01182       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
01183       Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
01184     }
01185 
01186     FunctionType *FT = Callee->getFunctionType();
01187     // Just make sure this has 1 argument of FP type, which matches the
01188     // result type.
01189     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
01190         !FT->getParamType(0)->isFloatingPointTy())
01191       return Ret;
01192 
01193     Value *Op = CI->getArgOperand(0);
01194     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
01195     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
01196     Value *LdExpArg = 0;
01197     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
01198       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
01199         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
01200     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
01201       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
01202         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
01203     }
01204 
01205     if (LdExpArg) {
01206       const char *Name;
01207       if (Op->getType()->isFloatTy())
01208         Name = "ldexpf";
01209       else if (Op->getType()->isDoubleTy())
01210         Name = "ldexp";
01211       else
01212         Name = "ldexpl";
01213 
01214       Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
01215       if (!Op->getType()->isFloatTy())
01216         One = ConstantExpr::getFPExtend(One, Op->getType());
01217 
01218       Module *M = Caller->getParent();
01219       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
01220                                              Op->getType(),
01221                                              B.getInt32Ty(), NULL);
01222       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
01223       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
01224         CI->setCallingConv(F->getCallingConv());
01225 
01226       return CI;
01227     }
01228     return Ret;
01229   }
01230 };
01231 
01232 //===----------------------------------------------------------------------===//
01233 // Integer Library Call Optimizations
01234 //===----------------------------------------------------------------------===//
01235 
01236 struct FFSOpt : public LibCallOptimization {
01237   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01238     FunctionType *FT = Callee->getFunctionType();
01239     // Just make sure this has 2 arguments of the same FP type, which match the
01240     // result type.
01241     if (FT->getNumParams() != 1 ||
01242         !FT->getReturnType()->isIntegerTy(32) ||
01243         !FT->getParamType(0)->isIntegerTy())
01244       return 0;
01245 
01246     Value *Op = CI->getArgOperand(0);
01247 
01248     // Constant fold.
01249     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
01250       if (CI->isZero()) // ffs(0) -> 0.
01251         return B.getInt32(0);
01252       // ffs(c) -> cttz(c)+1
01253       return B.getInt32(CI->getValue().countTrailingZeros() + 1);
01254     }
01255 
01256     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
01257     Type *ArgType = Op->getType();
01258     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
01259                                          Intrinsic::cttz, ArgType);
01260     Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
01261     V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
01262     V = B.CreateIntCast(V, B.getInt32Ty(), false);
01263 
01264     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
01265     return B.CreateSelect(Cond, V, B.getInt32(0));
01266   }
01267 };
01268 
01269 struct AbsOpt : public LibCallOptimization {
01270   virtual bool ignoreCallingConv() { return true; }
01271   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01272     FunctionType *FT = Callee->getFunctionType();
01273     // We require integer(integer) where the types agree.
01274     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
01275         FT->getParamType(0) != FT->getReturnType())
01276       return 0;
01277 
01278     // abs(x) -> x >s -1 ? x : -x
01279     Value *Op = CI->getArgOperand(0);
01280     Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
01281                                  "ispos");
01282     Value *Neg = B.CreateNeg(Op, "neg");
01283     return B.CreateSelect(Pos, Op, Neg);
01284   }
01285 };
01286 
01287 struct IsDigitOpt : public LibCallOptimization {
01288   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01289     FunctionType *FT = Callee->getFunctionType();
01290     // We require integer(i32)
01291     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
01292         !FT->getParamType(0)->isIntegerTy(32))
01293       return 0;
01294 
01295     // isdigit(c) -> (c-'0') <u 10
01296     Value *Op = CI->getArgOperand(0);
01297     Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
01298     Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
01299     return B.CreateZExt(Op, CI->getType());
01300   }
01301 };
01302 
01303 struct IsAsciiOpt : public LibCallOptimization {
01304   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01305     FunctionType *FT = Callee->getFunctionType();
01306     // We require integer(i32)
01307     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
01308         !FT->getParamType(0)->isIntegerTy(32))
01309       return 0;
01310 
01311     // isascii(c) -> c <u 128
01312     Value *Op = CI->getArgOperand(0);
01313     Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
01314     return B.CreateZExt(Op, CI->getType());
01315   }
01316 };
01317 
01318 struct ToAsciiOpt : public LibCallOptimization {
01319   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01320     FunctionType *FT = Callee->getFunctionType();
01321     // We require i32(i32)
01322     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
01323         !FT->getParamType(0)->isIntegerTy(32))
01324       return 0;
01325 
01326     // toascii(c) -> c & 0x7f
01327     return B.CreateAnd(CI->getArgOperand(0),
01328                        ConstantInt::get(CI->getType(),0x7F));
01329   }
01330 };
01331 
01332 //===----------------------------------------------------------------------===//
01333 // Formatting and IO Library Call Optimizations
01334 //===----------------------------------------------------------------------===//
01335 
01336 struct PrintFOpt : public LibCallOptimization {
01337   Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
01338                                    IRBuilder<> &B) {
01339     // Check for a fixed format string.
01340     StringRef FormatStr;
01341     if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
01342       return 0;
01343 
01344     // Empty format string -> noop.
01345     if (FormatStr.empty())  // Tolerate printf's declared void.
01346       return CI->use_empty() ? (Value*)CI :
01347                                ConstantInt::get(CI->getType(), 0);
01348 
01349     // Do not do any of the following transformations if the printf return value
01350     // is used, in general the printf return value is not compatible with either
01351     // putchar() or puts().
01352     if (!CI->use_empty())
01353       return 0;
01354 
01355     // printf("x") -> putchar('x'), even for '%'.
01356     if (FormatStr.size() == 1) {
01357       Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
01358       if (CI->use_empty() || !Res) return Res;
01359       return B.CreateIntCast(Res, CI->getType(), true);
01360     }
01361 
01362     // printf("foo\n") --> puts("foo")
01363     if (FormatStr[FormatStr.size()-1] == '\n' &&
01364         FormatStr.find('%') == std::string::npos) {  // no format characters.
01365       // Create a string literal with no \n on it.  We expect the constant merge
01366       // pass to be run after this pass, to merge duplicate strings.
01367       FormatStr = FormatStr.drop_back();
01368       Value *GV = B.CreateGlobalString(FormatStr, "str");
01369       Value *NewCI = EmitPutS(GV, B, TD, TLI);
01370       return (CI->use_empty() || !NewCI) ?
01371               NewCI :
01372               ConstantInt::get(CI->getType(), FormatStr.size()+1);
01373     }
01374 
01375     // Optimize specific format strings.
01376     // printf("%c", chr) --> putchar(chr)
01377     if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
01378         CI->getArgOperand(1)->getType()->isIntegerTy()) {
01379       Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
01380 
01381       if (CI->use_empty() || !Res) return Res;
01382       return B.CreateIntCast(Res, CI->getType(), true);
01383     }
01384 
01385     // printf("%s\n", str) --> puts(str)
01386     if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
01387         CI->getArgOperand(1)->getType()->isPointerTy()) {
01388       return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
01389     }
01390     return 0;
01391   }
01392 
01393   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01394     // Require one fixed pointer argument and an integer/void result.
01395     FunctionType *FT = Callee->getFunctionType();
01396     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
01397         !(FT->getReturnType()->isIntegerTy() ||
01398           FT->getReturnType()->isVoidTy()))
01399       return 0;
01400 
01401     if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
01402       return V;
01403     }
01404 
01405     // printf(format, ...) -> iprintf(format, ...) if no floating point
01406     // arguments.
01407     if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
01408       Module *M = B.GetInsertBlock()->getParent()->getParent();
01409       Constant *IPrintFFn =
01410         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
01411       CallInst *New = cast<CallInst>(CI->clone());
01412       New->setCalledFunction(IPrintFFn);
01413       B.Insert(New);
01414       return New;
01415     }
01416     return 0;
01417   }
01418 };
01419 
01420 struct SPrintFOpt : public LibCallOptimization {
01421   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
01422                                    IRBuilder<> &B) {
01423     // Check for a fixed format string.
01424     StringRef FormatStr;
01425     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
01426       return 0;
01427 
01428     // If we just have a format string (nothing else crazy) transform it.
01429     if (CI->getNumArgOperands() == 2) {
01430       // Make sure there's no % in the constant array.  We could try to handle
01431       // %% -> % in the future if we cared.
01432       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
01433         if (FormatStr[i] == '%')
01434           return 0; // we found a format specifier, bail out.
01435 
01436       // These optimizations require DataLayout.
01437       if (!TD) return 0;
01438 
01439       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
01440       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
01441                      ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
01442                                       FormatStr.size() + 1), 1);   // nul byte.
01443       return ConstantInt::get(CI->getType(), FormatStr.size());
01444     }
01445 
01446     // The remaining optimizations require the format string to be "%s" or "%c"
01447     // and have an extra operand.
01448     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
01449         CI->getNumArgOperands() < 3)
01450       return 0;
01451 
01452     // Decode the second character of the format string.
01453     if (FormatStr[1] == 'c') {
01454       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
01455       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
01456       Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
01457       Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
01458       B.CreateStore(V, Ptr);
01459       Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
01460       B.CreateStore(B.getInt8(0), Ptr);
01461 
01462       return ConstantInt::get(CI->getType(), 1);
01463     }
01464 
01465     if (FormatStr[1] == 's') {
01466       // These optimizations require DataLayout.
01467       if (!TD) return 0;
01468 
01469       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
01470       if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
01471 
01472       Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
01473       if (!Len)
01474         return 0;
01475       Value *IncLen = B.CreateAdd(Len,
01476                                   ConstantInt::get(Len->getType(), 1),
01477                                   "leninc");
01478       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
01479 
01480       // The sprintf result is the unincremented number of bytes in the string.
01481       return B.CreateIntCast(Len, CI->getType(), false);
01482     }
01483     return 0;
01484   }
01485 
01486   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01487     // Require two fixed pointer arguments and an integer result.
01488     FunctionType *FT = Callee->getFunctionType();
01489     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
01490         !FT->getParamType(1)->isPointerTy() ||
01491         !FT->getReturnType()->isIntegerTy())
01492       return 0;
01493 
01494     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
01495       return V;
01496     }
01497 
01498     // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
01499     // point arguments.
01500     if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
01501       Module *M = B.GetInsertBlock()->getParent()->getParent();
01502       Constant *SIPrintFFn =
01503         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
01504       CallInst *New = cast<CallInst>(CI->clone());
01505       New->setCalledFunction(SIPrintFFn);
01506       B.Insert(New);
01507       return New;
01508     }
01509     return 0;
01510   }
01511 };
01512 
01513 struct FPrintFOpt : public LibCallOptimization {
01514   Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
01515                                    IRBuilder<> &B) {
01516     // All the optimizations depend on the format string.
01517     StringRef FormatStr;
01518     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
01519       return 0;
01520 
01521     // Do not do any of the following transformations if the fprintf return
01522     // value is used, in general the fprintf return value is not compatible
01523     // with fwrite(), fputc() or fputs().
01524     if (!CI->use_empty())
01525       return 0;
01526 
01527     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
01528     if (CI->getNumArgOperands() == 2) {
01529       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
01530         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
01531           return 0; // We found a format specifier.
01532 
01533       // These optimizations require DataLayout.
01534       if (!TD) return 0;
01535 
01536       return EmitFWrite(CI->getArgOperand(1),
01537                         ConstantInt::get(TD->getIntPtrType(*Context),
01538                                          FormatStr.size()),
01539                         CI->getArgOperand(0), B, TD, TLI);
01540     }
01541 
01542     // The remaining optimizations require the format string to be "%s" or "%c"
01543     // and have an extra operand.
01544     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
01545         CI->getNumArgOperands() < 3)
01546       return 0;
01547 
01548     // Decode the second character of the format string.
01549     if (FormatStr[1] == 'c') {
01550       // fprintf(F, "%c", chr) --> fputc(chr, F)
01551       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
01552       return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
01553     }
01554 
01555     if (FormatStr[1] == 's') {
01556       // fprintf(F, "%s", str) --> fputs(str, F)
01557       if (!CI->getArgOperand(2)->getType()->isPointerTy())
01558         return 0;
01559       return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
01560     }
01561     return 0;
01562   }
01563 
01564   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01565     // Require two fixed paramters as pointers and integer result.
01566     FunctionType *FT = Callee->getFunctionType();
01567     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
01568         !FT->getParamType(1)->isPointerTy() ||
01569         !FT->getReturnType()->isIntegerTy())
01570       return 0;
01571 
01572     if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
01573       return V;
01574     }
01575 
01576     // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
01577     // floating point arguments.
01578     if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
01579       Module *M = B.GetInsertBlock()->getParent()->getParent();
01580       Constant *FIPrintFFn =
01581         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
01582       CallInst *New = cast<CallInst>(CI->clone());
01583       New->setCalledFunction(FIPrintFFn);
01584       B.Insert(New);
01585       return New;
01586     }
01587     return 0;
01588   }
01589 };
01590 
01591 struct FWriteOpt : public LibCallOptimization {
01592   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01593     // Require a pointer, an integer, an integer, a pointer, returning integer.
01594     FunctionType *FT = Callee->getFunctionType();
01595     if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
01596         !FT->getParamType(1)->isIntegerTy() ||
01597         !FT->getParamType(2)->isIntegerTy() ||
01598         !FT->getParamType(3)->isPointerTy() ||
01599         !FT->getReturnType()->isIntegerTy())
01600       return 0;
01601 
01602     // Get the element size and count.
01603     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
01604     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
01605     if (!SizeC || !CountC) return 0;
01606     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
01607 
01608     // If this is writing zero records, remove the call (it's a noop).
01609     if (Bytes == 0)
01610       return ConstantInt::get(CI->getType(), 0);
01611 
01612     // If this is writing one byte, turn it into fputc.
01613     // This optimisation is only valid, if the return value is unused.
01614     if (Bytes == 1 && CI->use_empty()) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
01615       Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
01616       Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
01617       return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
01618     }
01619 
01620     return 0;
01621   }
01622 };
01623 
01624 struct FPutsOpt : public LibCallOptimization {
01625   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01626     // These optimizations require DataLayout.
01627     if (!TD) return 0;
01628 
01629     // Require two pointers.  Also, we can't optimize if return value is used.
01630     FunctionType *FT = Callee->getFunctionType();
01631     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
01632         !FT->getParamType(1)->isPointerTy() ||
01633         !CI->use_empty())
01634       return 0;
01635 
01636     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
01637     uint64_t Len = GetStringLength(CI->getArgOperand(0));
01638     if (!Len) return 0;
01639     // Known to have no uses (see above).
01640     return EmitFWrite(CI->getArgOperand(0),
01641                       ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
01642                       CI->getArgOperand(1), B, TD, TLI);
01643   }
01644 };
01645 
01646 struct PutsOpt : public LibCallOptimization {
01647   virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
01648     // Require one fixed pointer argument and an integer/void result.
01649     FunctionType *FT = Callee->getFunctionType();
01650     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
01651         !(FT->getReturnType()->isIntegerTy() ||
01652           FT->getReturnType()->isVoidTy()))
01653       return 0;
01654 
01655     // Check for a constant string.
01656     StringRef Str;
01657     if (!getConstantStringInfo(CI->getArgOperand(0), Str))
01658       return 0;
01659 
01660     if (Str.empty() && CI->use_empty()) {
01661       // puts("") -> putchar('\n')
01662       Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
01663       if (CI->use_empty() || !Res) return Res;
01664       return B.CreateIntCast(Res, CI->getType(), true);
01665     }
01666 
01667     return 0;
01668   }
01669 };
01670 
01671 } // End anonymous namespace.
01672 
01673 namespace llvm {
01674 
01675 class LibCallSimplifierImpl {
01676   const DataLayout *TD;
01677   const TargetLibraryInfo *TLI;
01678   const LibCallSimplifier *LCS;
01679   bool UnsafeFPShrink;
01680 
01681   // Math library call optimizations.
01682   CosOpt Cos;
01683   PowOpt Pow;
01684   Exp2Opt Exp2;
01685 public:
01686   LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
01687                         const LibCallSimplifier *LCS,
01688                         bool UnsafeFPShrink = false)
01689     : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
01690     this->TD = TD;
01691     this->TLI = TLI;
01692     this->LCS = LCS;
01693     this->UnsafeFPShrink = UnsafeFPShrink;
01694   }
01695 
01696   Value *optimizeCall(CallInst *CI);
01697   LibCallOptimization *lookupOptimization(CallInst *CI);
01698   bool hasFloatVersion(StringRef FuncName);
01699 };
01700 
01701 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
01702   LibFunc::Func Func;
01703   SmallString<20> FloatFuncName = FuncName;
01704   FloatFuncName += 'f';
01705   if (TLI->getLibFunc(FloatFuncName, Func))
01706     return TLI->has(Func);
01707   return false;
01708 }
01709 
01710 // Fortified library call optimizations.
01711 static MemCpyChkOpt MemCpyChk;
01712 static MemMoveChkOpt MemMoveChk;
01713 static MemSetChkOpt MemSetChk;
01714 static StrCpyChkOpt StrCpyChk;
01715 static StpCpyChkOpt StpCpyChk;
01716 static StrNCpyChkOpt StrNCpyChk;
01717 
01718 // String library call optimizations.
01719 static StrCatOpt StrCat;
01720 static StrNCatOpt StrNCat;
01721 static StrChrOpt StrChr;
01722 static StrRChrOpt StrRChr;
01723 static StrCmpOpt StrCmp;
01724 static StrNCmpOpt StrNCmp;
01725 static StrCpyOpt StrCpy;
01726 static StpCpyOpt StpCpy;
01727 static StrNCpyOpt StrNCpy;
01728 static StrLenOpt StrLen;
01729 static StrPBrkOpt StrPBrk;
01730 static StrToOpt StrTo;
01731 static StrSpnOpt StrSpn;
01732 static StrCSpnOpt StrCSpn;
01733 static StrStrOpt StrStr;
01734 
01735 // Memory library call optimizations.
01736 static MemCmpOpt MemCmp;
01737 static MemCpyOpt MemCpy;
01738 static MemMoveOpt MemMove;
01739 static MemSetOpt MemSet;
01740 
01741 // Math library call optimizations.
01742 static UnaryDoubleFPOpt UnaryDoubleFP(false);
01743 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
01744 
01745   // Integer library call optimizations.
01746 static FFSOpt FFS;
01747 static AbsOpt Abs;
01748 static IsDigitOpt IsDigit;
01749 static IsAsciiOpt IsAscii;
01750 static ToAsciiOpt ToAscii;
01751 
01752 // Formatting and IO library call optimizations.
01753 static PrintFOpt PrintF;
01754 static SPrintFOpt SPrintF;
01755 static FPrintFOpt FPrintF;
01756 static FWriteOpt FWrite;
01757 static FPutsOpt FPuts;
01758 static PutsOpt Puts;
01759 
01760 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
01761   LibFunc::Func Func;
01762   Function *Callee = CI->getCalledFunction();
01763   StringRef FuncName = Callee->getName();
01764 
01765   // Next check for intrinsics.
01766   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
01767     switch (II->getIntrinsicID()) {
01768     case Intrinsic::pow:
01769        return &Pow;
01770     case Intrinsic::exp2:
01771        return &Exp2;
01772     default:
01773        return 0;
01774     }
01775   }
01776 
01777   // Then check for known library functions.
01778   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
01779     switch (Func) {
01780       case LibFunc::strcat:
01781         return &StrCat;
01782       case LibFunc::strncat:
01783         return &StrNCat;
01784       case LibFunc::strchr:
01785         return &StrChr;
01786       case LibFunc::strrchr:
01787         return &StrRChr;
01788       case LibFunc::strcmp:
01789         return &StrCmp;
01790       case LibFunc::strncmp:
01791         return &StrNCmp;
01792       case LibFunc::strcpy:
01793         return &StrCpy;
01794       case LibFunc::stpcpy:
01795         return &StpCpy;
01796       case LibFunc::strncpy:
01797         return &StrNCpy;
01798       case LibFunc::strlen:
01799         return &StrLen;
01800       case LibFunc::strpbrk:
01801         return &StrPBrk;
01802       case LibFunc::strtol:
01803       case LibFunc::strtod:
01804       case LibFunc::strtof:
01805       case LibFunc::strtoul:
01806       case LibFunc::strtoll:
01807       case LibFunc::strtold:
01808       case LibFunc::strtoull:
01809         return &StrTo;
01810       case LibFunc::strspn:
01811         return &StrSpn;
01812       case LibFunc::strcspn:
01813         return &StrCSpn;
01814       case LibFunc::strstr:
01815         return &StrStr;
01816       case LibFunc::memcmp:
01817         return &MemCmp;
01818       case LibFunc::memcpy:
01819         return &MemCpy;
01820       case LibFunc::memmove:
01821         return &MemMove;
01822       case LibFunc::memset:
01823         return &MemSet;
01824       case LibFunc::cosf:
01825       case LibFunc::cos:
01826       case LibFunc::cosl:
01827         return &Cos;
01828       case LibFunc::powf:
01829       case LibFunc::pow:
01830       case LibFunc::powl:
01831         return &Pow;
01832       case LibFunc::exp2l:
01833       case LibFunc::exp2:
01834       case LibFunc::exp2f:
01835         return &Exp2;
01836       case LibFunc::ffs:
01837       case LibFunc::ffsl:
01838       case LibFunc::ffsll:
01839         return &FFS;
01840       case LibFunc::abs:
01841       case LibFunc::labs:
01842       case LibFunc::llabs:
01843         return &Abs;
01844       case LibFunc::isdigit:
01845         return &IsDigit;
01846       case LibFunc::isascii:
01847         return &IsAscii;
01848       case LibFunc::toascii:
01849         return &ToAscii;
01850       case LibFunc::printf:
01851         return &PrintF;
01852       case LibFunc::sprintf:
01853         return &SPrintF;
01854       case LibFunc::fprintf:
01855         return &FPrintF;
01856       case LibFunc::fwrite:
01857         return &FWrite;
01858       case LibFunc::fputs:
01859         return &FPuts;
01860       case LibFunc::puts:
01861         return &Puts;
01862       case LibFunc::ceil:
01863       case LibFunc::fabs:
01864       case LibFunc::floor:
01865       case LibFunc::rint:
01866       case LibFunc::round:
01867       case LibFunc::nearbyint:
01868       case LibFunc::trunc:
01869         if (hasFloatVersion(FuncName))
01870           return &UnaryDoubleFP;
01871         return 0;
01872       case LibFunc::acos:
01873       case LibFunc::acosh:
01874       case LibFunc::asin:
01875       case LibFunc::asinh:
01876       case LibFunc::atan:
01877       case LibFunc::atanh:
01878       case LibFunc::cbrt:
01879       case LibFunc::cosh:
01880       case LibFunc::exp:
01881       case LibFunc::exp10:
01882       case LibFunc::expm1:
01883       case LibFunc::log:
01884       case LibFunc::log10:
01885       case LibFunc::log1p:
01886       case LibFunc::log2:
01887       case LibFunc::logb:
01888       case LibFunc::sin:
01889       case LibFunc::sinh:
01890       case LibFunc::sqrt:
01891       case LibFunc::tan:
01892       case LibFunc::tanh:
01893         if (UnsafeFPShrink && hasFloatVersion(FuncName))
01894          return &UnsafeUnaryDoubleFP;
01895         return 0;
01896       case LibFunc::memcpy_chk:
01897         return &MemCpyChk;
01898       default:
01899         return 0;
01900       }
01901   }
01902 
01903   // Finally check for fortified library calls.
01904   if (FuncName.endswith("_chk")) {
01905     if (FuncName == "__memmove_chk")
01906       return &MemMoveChk;
01907     else if (FuncName == "__memset_chk")
01908       return &MemSetChk;
01909     else if (FuncName == "__strcpy_chk")
01910       return &StrCpyChk;
01911     else if (FuncName == "__stpcpy_chk")
01912       return &StpCpyChk;
01913     else if (FuncName == "__strncpy_chk")
01914       return &StrNCpyChk;
01915     else if (FuncName == "__stpncpy_chk")
01916       return &StrNCpyChk;
01917   }
01918 
01919   return 0;
01920 
01921 }
01922 
01923 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
01924   LibCallOptimization *LCO = lookupOptimization(CI);
01925   if (LCO) {
01926     IRBuilder<> Builder(CI);
01927     return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
01928   }
01929   return 0;
01930 }
01931 
01932 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
01933                                      const TargetLibraryInfo *TLI,
01934                                      bool UnsafeFPShrink) {
01935   Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink);
01936 }
01937 
01938 LibCallSimplifier::~LibCallSimplifier() {
01939   delete Impl;
01940 }
01941 
01942 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
01943   if (CI->hasFnAttr(Attribute::NoBuiltin)) return 0;
01944   return Impl->optimizeCall(CI);
01945 }
01946 
01947 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
01948   I->replaceAllUsesWith(With);
01949   I->eraseFromParent();
01950 }
01951 
01952 }