LLVM API Documentation

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