1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BuildLibCalls.h"
21 #include "llvm/IRBuilder.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/DataLayout.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
39 STATISTIC(NumSimplified, "Number of library calls simplified");
40 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
42 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46 //===----------------------------------------------------------------------===//
47 // Optimizer Base Class
48 //===----------------------------------------------------------------------===//
50 /// This class is the abstract base class for the set of optimizations that
51 /// corresponds to one library call.
53 class LibCallOptimization {
57 const TargetLibraryInfo *TLI;
60 LibCallOptimization() { }
61 virtual ~LibCallOptimization() {}
63 /// CallOptimizer - This pure virtual method is implemented by base classes to
64 /// do various optimizations. If this returns null then no transformation was
65 /// performed. If it returns CI, then it transformed the call and CI is to be
66 /// deleted. If it returns something else, replace CI with the new value and
68 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
71 Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
72 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
73 Caller = CI->getParent()->getParent();
76 if (CI->getCalledFunction())
77 Context = &CI->getCalledFunction()->getContext();
79 // We never change the calling convention.
80 if (CI->getCallingConv() != llvm::CallingConv::C)
83 return CallOptimizer(CI->getCalledFunction(), CI, B);
86 } // End anonymous namespace.
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 static bool CallHasFloatingPointArgument(const CallInst *CI) {
94 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
96 if ((*it)->getType()->isFloatingPointTy())
103 //===----------------------------------------------------------------------===//
104 // Math Library Optimizations
105 //===----------------------------------------------------------------------===//
107 //===---------------------------------------===//
108 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
110 struct UnaryDoubleFPOpt : public LibCallOptimization {
112 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
113 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
114 FunctionType *FT = Callee->getFunctionType();
115 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
116 !FT->getParamType(0)->isDoubleTy())
120 // Check if all the uses for function like 'sin' are converted to float.
121 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
123 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
124 if (Cast == 0 || !Cast->getType()->isFloatTy())
129 // If this is something like 'floor((double)floatval)', convert to floorf.
130 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
131 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
134 // floor((double)floatval) -> (double)floorf(floatval)
135 Value *V = Cast->getOperand(0);
136 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
137 return B.CreateFPExt(V, B.getDoubleTy());
141 //===---------------------------------------===//
142 // 'cos*' Optimizations
143 struct CosOpt : public LibCallOptimization {
144 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
146 if (UnsafeFPShrink && Callee->getName() == "cos" &&
147 TLI->has(LibFunc::cosf)) {
148 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
149 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
152 FunctionType *FT = Callee->getFunctionType();
153 // Just make sure this has 1 argument of FP type, which matches the
155 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
156 !FT->getParamType(0)->isFloatingPointTy())
160 Value *Op1 = CI->getArgOperand(0);
161 if (BinaryOperator::isFNeg(Op1)) {
162 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
163 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
169 //===---------------------------------------===//
170 // 'pow*' Optimizations
172 struct PowOpt : public LibCallOptimization {
173 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
175 if (UnsafeFPShrink && Callee->getName() == "pow" &&
176 TLI->has(LibFunc::powf)) {
177 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
178 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
181 FunctionType *FT = Callee->getFunctionType();
182 // Just make sure this has 2 arguments of the same FP type, which match the
184 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
185 FT->getParamType(0) != FT->getParamType(1) ||
186 !FT->getParamType(0)->isFloatingPointTy())
189 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
190 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
191 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
193 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
194 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
197 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
198 if (Op2C == 0) return Ret;
200 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
201 return ConstantFP::get(CI->getType(), 1.0);
203 if (Op2C->isExactlyValue(0.5)) {
204 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
205 // This is faster than calling pow, and still handles negative zero
206 // and negative infinity correctly.
207 // TODO: In fast-math mode, this could be just sqrt(x).
208 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
209 Value *Inf = ConstantFP::getInfinity(CI->getType());
210 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
211 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
212 Callee->getAttributes());
213 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
214 Callee->getAttributes());
215 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
216 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
220 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
222 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
223 return B.CreateFMul(Op1, Op1, "pow2");
224 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
225 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
231 //===---------------------------------------===//
232 // 'exp2' Optimizations
234 struct Exp2Opt : public LibCallOptimization {
235 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
237 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
238 TLI->has(LibFunc::exp2)) {
239 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
240 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
243 FunctionType *FT = Callee->getFunctionType();
244 // Just make sure this has 1 argument of FP type, which matches the
246 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
247 !FT->getParamType(0)->isFloatingPointTy())
250 Value *Op = CI->getArgOperand(0);
251 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
252 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
254 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
255 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
256 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
257 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
258 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
259 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
264 if (Op->getType()->isFloatTy())
266 else if (Op->getType()->isDoubleTy())
271 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
272 if (!Op->getType()->isFloatTy())
273 One = ConstantExpr::getFPExtend(One, Op->getType());
275 Module *M = Caller->getParent();
276 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
278 B.getInt32Ty(), NULL);
279 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
280 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
281 CI->setCallingConv(F->getCallingConv());
289 //===----------------------------------------------------------------------===//
290 // Integer Optimizations
291 //===----------------------------------------------------------------------===//
293 //===---------------------------------------===//
294 // 'ffs*' Optimizations
296 struct FFSOpt : public LibCallOptimization {
297 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
298 FunctionType *FT = Callee->getFunctionType();
299 // Just make sure this has 2 arguments of the same FP type, which match the
301 if (FT->getNumParams() != 1 ||
302 !FT->getReturnType()->isIntegerTy(32) ||
303 !FT->getParamType(0)->isIntegerTy())
306 Value *Op = CI->getArgOperand(0);
309 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
310 if (CI->isZero()) // ffs(0) -> 0.
311 return B.getInt32(0);
312 // ffs(c) -> cttz(c)+1
313 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
316 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
317 Type *ArgType = Op->getType();
318 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
319 Intrinsic::cttz, ArgType);
320 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
321 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
322 V = B.CreateIntCast(V, B.getInt32Ty(), false);
324 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
325 return B.CreateSelect(Cond, V, B.getInt32(0));
329 //===---------------------------------------===//
330 // 'isdigit' Optimizations
332 struct IsDigitOpt : public LibCallOptimization {
333 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
334 FunctionType *FT = Callee->getFunctionType();
335 // We require integer(i32)
336 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
337 !FT->getParamType(0)->isIntegerTy(32))
340 // isdigit(c) -> (c-'0') <u 10
341 Value *Op = CI->getArgOperand(0);
342 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
343 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
344 return B.CreateZExt(Op, CI->getType());
348 //===---------------------------------------===//
349 // 'isascii' Optimizations
351 struct IsAsciiOpt : public LibCallOptimization {
352 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
353 FunctionType *FT = Callee->getFunctionType();
354 // We require integer(i32)
355 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
356 !FT->getParamType(0)->isIntegerTy(32))
359 // isascii(c) -> c <u 128
360 Value *Op = CI->getArgOperand(0);
361 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
362 return B.CreateZExt(Op, CI->getType());
366 //===---------------------------------------===//
367 // 'abs', 'labs', 'llabs' Optimizations
369 struct AbsOpt : public LibCallOptimization {
370 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
371 FunctionType *FT = Callee->getFunctionType();
372 // We require integer(integer) where the types agree.
373 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
374 FT->getParamType(0) != FT->getReturnType())
377 // abs(x) -> x >s -1 ? x : -x
378 Value *Op = CI->getArgOperand(0);
379 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
381 Value *Neg = B.CreateNeg(Op, "neg");
382 return B.CreateSelect(Pos, Op, Neg);
387 //===---------------------------------------===//
388 // 'toascii' Optimizations
390 struct ToAsciiOpt : public LibCallOptimization {
391 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
392 FunctionType *FT = Callee->getFunctionType();
393 // We require i32(i32)
394 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
395 !FT->getParamType(0)->isIntegerTy(32))
398 // isascii(c) -> c & 0x7f
399 return B.CreateAnd(CI->getArgOperand(0),
400 ConstantInt::get(CI->getType(),0x7F));
404 //===----------------------------------------------------------------------===//
405 // Formatting and IO Optimizations
406 //===----------------------------------------------------------------------===//
408 //===---------------------------------------===//
409 // 'printf' Optimizations
411 struct PrintFOpt : public LibCallOptimization {
412 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
414 // Check for a fixed format string.
416 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
419 // Empty format string -> noop.
420 if (FormatStr.empty()) // Tolerate printf's declared void.
421 return CI->use_empty() ? (Value*)CI :
422 ConstantInt::get(CI->getType(), 0);
424 // Do not do any of the following transformations if the printf return value
425 // is used, in general the printf return value is not compatible with either
426 // putchar() or puts().
427 if (!CI->use_empty())
430 // printf("x") -> putchar('x'), even for '%'.
431 if (FormatStr.size() == 1) {
432 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
433 if (CI->use_empty() || !Res) return Res;
434 return B.CreateIntCast(Res, CI->getType(), true);
437 // printf("foo\n") --> puts("foo")
438 if (FormatStr[FormatStr.size()-1] == '\n' &&
439 FormatStr.find('%') == std::string::npos) { // no format characters.
440 // Create a string literal with no \n on it. We expect the constant merge
441 // pass to be run after this pass, to merge duplicate strings.
442 FormatStr = FormatStr.drop_back();
443 Value *GV = B.CreateGlobalString(FormatStr, "str");
444 Value *NewCI = EmitPutS(GV, B, TD, TLI);
445 return (CI->use_empty() || !NewCI) ?
447 ConstantInt::get(CI->getType(), FormatStr.size()+1);
450 // Optimize specific format strings.
451 // printf("%c", chr) --> putchar(chr)
452 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
453 CI->getArgOperand(1)->getType()->isIntegerTy()) {
454 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
456 if (CI->use_empty() || !Res) return Res;
457 return B.CreateIntCast(Res, CI->getType(), true);
460 // printf("%s\n", str) --> puts(str)
461 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
462 CI->getArgOperand(1)->getType()->isPointerTy()) {
463 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
468 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
469 // Require one fixed pointer argument and an integer/void result.
470 FunctionType *FT = Callee->getFunctionType();
471 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
472 !(FT->getReturnType()->isIntegerTy() ||
473 FT->getReturnType()->isVoidTy()))
476 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
480 // printf(format, ...) -> iprintf(format, ...) if no floating point
482 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
483 Module *M = B.GetInsertBlock()->getParent()->getParent();
484 Constant *IPrintFFn =
485 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
486 CallInst *New = cast<CallInst>(CI->clone());
487 New->setCalledFunction(IPrintFFn);
495 //===---------------------------------------===//
496 // 'sprintf' Optimizations
498 struct SPrintFOpt : public LibCallOptimization {
499 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
501 // Check for a fixed format string.
503 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
506 // If we just have a format string (nothing else crazy) transform it.
507 if (CI->getNumArgOperands() == 2) {
508 // Make sure there's no % in the constant array. We could try to handle
509 // %% -> % in the future if we cared.
510 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
511 if (FormatStr[i] == '%')
512 return 0; // we found a format specifier, bail out.
514 // These optimizations require DataLayout.
517 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
518 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
519 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
520 FormatStr.size() + 1), 1); // nul byte.
521 return ConstantInt::get(CI->getType(), FormatStr.size());
524 // The remaining optimizations require the format string to be "%s" or "%c"
525 // and have an extra operand.
526 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
527 CI->getNumArgOperands() < 3)
530 // Decode the second character of the format string.
531 if (FormatStr[1] == 'c') {
532 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
533 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
534 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
535 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
536 B.CreateStore(V, Ptr);
537 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
538 B.CreateStore(B.getInt8(0), Ptr);
540 return ConstantInt::get(CI->getType(), 1);
543 if (FormatStr[1] == 's') {
544 // These optimizations require DataLayout.
547 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
548 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
550 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
553 Value *IncLen = B.CreateAdd(Len,
554 ConstantInt::get(Len->getType(), 1),
556 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
558 // The sprintf result is the unincremented number of bytes in the string.
559 return B.CreateIntCast(Len, CI->getType(), false);
564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
565 // Require two fixed pointer arguments and an integer result.
566 FunctionType *FT = Callee->getFunctionType();
567 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
568 !FT->getParamType(1)->isPointerTy() ||
569 !FT->getReturnType()->isIntegerTy())
572 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
576 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
578 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
579 Module *M = B.GetInsertBlock()->getParent()->getParent();
580 Constant *SIPrintFFn =
581 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
582 CallInst *New = cast<CallInst>(CI->clone());
583 New->setCalledFunction(SIPrintFFn);
591 //===---------------------------------------===//
592 // 'fwrite' Optimizations
594 struct FWriteOpt : public LibCallOptimization {
595 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
596 // Require a pointer, an integer, an integer, a pointer, returning integer.
597 FunctionType *FT = Callee->getFunctionType();
598 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
599 !FT->getParamType(1)->isIntegerTy() ||
600 !FT->getParamType(2)->isIntegerTy() ||
601 !FT->getParamType(3)->isPointerTy() ||
602 !FT->getReturnType()->isIntegerTy())
605 // Get the element size and count.
606 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
607 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
608 if (!SizeC || !CountC) return 0;
609 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
611 // If this is writing zero records, remove the call (it's a noop).
613 return ConstantInt::get(CI->getType(), 0);
615 // If this is writing one byte, turn it into fputc.
616 // This optimisation is only valid, if the return value is unused.
617 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
618 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
619 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
620 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
627 //===---------------------------------------===//
628 // 'fputs' Optimizations
630 struct FPutsOpt : public LibCallOptimization {
631 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
632 // These optimizations require DataLayout.
635 // Require two pointers. Also, we can't optimize if return value is used.
636 FunctionType *FT = Callee->getFunctionType();
637 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
638 !FT->getParamType(1)->isPointerTy() ||
642 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
643 uint64_t Len = GetStringLength(CI->getArgOperand(0));
645 // Known to have no uses (see above).
646 return EmitFWrite(CI->getArgOperand(0),
647 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
648 CI->getArgOperand(1), B, TD, TLI);
652 //===---------------------------------------===//
653 // 'fprintf' Optimizations
655 struct FPrintFOpt : public LibCallOptimization {
656 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
658 // All the optimizations depend on the format string.
660 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
663 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
664 if (CI->getNumArgOperands() == 2) {
665 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
666 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
667 return 0; // We found a format specifier.
669 // These optimizations require DataLayout.
672 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
673 ConstantInt::get(TD->getIntPtrType(*Context),
675 CI->getArgOperand(0), B, TD, TLI);
676 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
679 // The remaining optimizations require the format string to be "%s" or "%c"
680 // and have an extra operand.
681 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
682 CI->getNumArgOperands() < 3)
685 // Decode the second character of the format string.
686 if (FormatStr[1] == 'c') {
687 // fprintf(F, "%c", chr) --> fputc(chr, F)
688 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
689 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
691 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
694 if (FormatStr[1] == 's') {
695 // fprintf(F, "%s", str) --> fputs(str, F)
696 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
698 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
703 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
704 // Require two fixed paramters as pointers and integer result.
705 FunctionType *FT = Callee->getFunctionType();
706 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
707 !FT->getParamType(1)->isPointerTy() ||
708 !FT->getReturnType()->isIntegerTy())
711 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
715 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
716 // floating point arguments.
717 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
718 Module *M = B.GetInsertBlock()->getParent()->getParent();
719 Constant *FIPrintFFn =
720 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
721 CallInst *New = cast<CallInst>(CI->clone());
722 New->setCalledFunction(FIPrintFFn);
730 //===---------------------------------------===//
731 // 'puts' Optimizations
733 struct PutsOpt : public LibCallOptimization {
734 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
735 // Require one fixed pointer argument and an integer/void result.
736 FunctionType *FT = Callee->getFunctionType();
737 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
738 !(FT->getReturnType()->isIntegerTy() ||
739 FT->getReturnType()->isVoidTy()))
742 // Check for a constant string.
744 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
747 if (Str.empty() && CI->use_empty()) {
748 // puts("") -> putchar('\n')
749 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
750 if (CI->use_empty() || !Res) return Res;
751 return B.CreateIntCast(Res, CI->getType(), true);
758 } // end anonymous namespace.
760 //===----------------------------------------------------------------------===//
761 // SimplifyLibCalls Pass Implementation
762 //===----------------------------------------------------------------------===//
765 /// This pass optimizes well known library functions from libc and libm.
767 class SimplifyLibCalls : public FunctionPass {
768 TargetLibraryInfo *TLI;
770 StringMap<LibCallOptimization*> Optimizations;
771 // Math Library Optimizations
772 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
773 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
774 // Integer Optimizations
775 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
777 // Formatting and IO Optimizations
778 SPrintFOpt SPrintF; PrintFOpt PrintF;
779 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
782 bool Modified; // This is only used by doInitialization.
784 static char ID; // Pass identification
785 SimplifyLibCalls() : FunctionPass(ID), UnaryDoubleFP(false),
786 UnsafeUnaryDoubleFP(true) {
787 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
789 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
790 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
792 void InitOptimizations();
793 bool runOnFunction(Function &F);
795 void setDoesNotAccessMemory(Function &F);
796 void setOnlyReadsMemory(Function &F);
797 void setDoesNotThrow(Function &F);
798 void setDoesNotCapture(Function &F, unsigned n);
799 void setDoesNotAlias(Function &F, unsigned n);
800 bool doInitialization(Module &M);
802 void inferPrototypeAttributes(Function &F);
803 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
804 AU.addRequired<TargetLibraryInfo>();
807 } // end anonymous namespace.
809 char SimplifyLibCalls::ID = 0;
811 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
812 "Simplify well-known library calls", false, false)
813 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
814 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
815 "Simplify well-known library calls", false, false)
817 // Public interface to the Simplify LibCalls pass.
818 FunctionPass *llvm::createSimplifyLibCallsPass() {
819 return new SimplifyLibCalls();
822 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
824 Optimizations[TLI->getName(F)] = Opt;
827 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
828 LibCallOptimization* Opt) {
829 if (TLI->has(F1) && TLI->has(F2))
830 Optimizations[TLI->getName(F1)] = Opt;
833 /// Optimizations - Populate the Optimizations map with all the optimizations
835 void SimplifyLibCalls::InitOptimizations() {
836 // Math Library Optimizations
837 Optimizations["cosf"] = &Cos;
838 Optimizations["cos"] = &Cos;
839 Optimizations["cosl"] = &Cos;
840 Optimizations["powf"] = &Pow;
841 Optimizations["pow"] = &Pow;
842 Optimizations["powl"] = &Pow;
843 Optimizations["llvm.pow.f32"] = &Pow;
844 Optimizations["llvm.pow.f64"] = &Pow;
845 Optimizations["llvm.pow.f80"] = &Pow;
846 Optimizations["llvm.pow.f128"] = &Pow;
847 Optimizations["llvm.pow.ppcf128"] = &Pow;
848 Optimizations["exp2l"] = &Exp2;
849 Optimizations["exp2"] = &Exp2;
850 Optimizations["exp2f"] = &Exp2;
851 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
852 Optimizations["llvm.exp2.f128"] = &Exp2;
853 Optimizations["llvm.exp2.f80"] = &Exp2;
854 Optimizations["llvm.exp2.f64"] = &Exp2;
855 Optimizations["llvm.exp2.f32"] = &Exp2;
857 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
858 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
859 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
860 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
861 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
862 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
863 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
866 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
867 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
868 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
869 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
870 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
871 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
872 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
873 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
874 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
875 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
876 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
877 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
878 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
879 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
880 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
881 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
882 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
883 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
884 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
885 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
886 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
889 // Integer Optimizations
890 Optimizations["ffs"] = &FFS;
891 Optimizations["ffsl"] = &FFS;
892 Optimizations["ffsll"] = &FFS;
893 Optimizations["abs"] = &Abs;
894 Optimizations["labs"] = &Abs;
895 Optimizations["llabs"] = &Abs;
896 Optimizations["isdigit"] = &IsDigit;
897 Optimizations["isascii"] = &IsAscii;
898 Optimizations["toascii"] = &ToAscii;
900 // Formatting and IO Optimizations
901 Optimizations["sprintf"] = &SPrintF;
902 Optimizations["printf"] = &PrintF;
903 AddOpt(LibFunc::fwrite, &FWrite);
904 AddOpt(LibFunc::fputs, &FPuts);
905 Optimizations["fprintf"] = &FPrintF;
906 Optimizations["puts"] = &Puts;
910 /// runOnFunction - Top level algorithm.
912 bool SimplifyLibCalls::runOnFunction(Function &F) {
913 TLI = &getAnalysis<TargetLibraryInfo>();
915 if (Optimizations.empty())
918 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
920 IRBuilder<> Builder(F.getContext());
922 bool Changed = false;
923 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
924 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
926 CallInst *CI = dyn_cast<CallInst>(I++);
929 // Ignore indirect calls and calls to non-external functions.
930 Function *Callee = CI->getCalledFunction();
931 if (Callee == 0 || !Callee->isDeclaration() ||
932 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
935 // Ignore unknown calls.
936 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
939 // Set the builder to the instruction after the call.
940 Builder.SetInsertPoint(BB, I);
942 // Use debug location of CI for all new instructions.
943 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
945 // Try to optimize this call.
946 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
947 if (Result == 0) continue;
949 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
950 dbgs() << " into: " << *Result << "\n");
952 // Something changed!
956 // Inspect the instruction after the call (which was potentially just
960 if (CI != Result && !CI->use_empty()) {
961 CI->replaceAllUsesWith(Result);
962 if (!Result->hasName())
963 Result->takeName(CI);
965 CI->eraseFromParent();
971 // Utility methods for doInitialization.
973 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
974 if (!F.doesNotAccessMemory()) {
975 F.setDoesNotAccessMemory();
980 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
981 if (!F.onlyReadsMemory()) {
982 F.setOnlyReadsMemory();
987 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
988 if (!F.doesNotThrow()) {
994 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
995 if (!F.doesNotCapture(n)) {
996 F.setDoesNotCapture(n);
1001 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1002 if (!F.doesNotAlias(n)) {
1003 F.setDoesNotAlias(n);
1010 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1011 FunctionType *FTy = F.getFunctionType();
1013 StringRef Name = F.getName();
1016 if (Name == "strlen") {
1017 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1019 setOnlyReadsMemory(F);
1021 setDoesNotCapture(F, 1);
1022 } else if (Name == "strchr" ||
1023 Name == "strrchr") {
1024 if (FTy->getNumParams() != 2 ||
1025 !FTy->getParamType(0)->isPointerTy() ||
1026 !FTy->getParamType(1)->isIntegerTy())
1028 setOnlyReadsMemory(F);
1030 } else if (Name == "strcpy" ||
1036 Name == "strtoul" ||
1037 Name == "strtoll" ||
1038 Name == "strtold" ||
1039 Name == "strncat" ||
1040 Name == "strncpy" ||
1041 Name == "stpncpy" ||
1042 Name == "strtoull") {
1043 if (FTy->getNumParams() < 2 ||
1044 !FTy->getParamType(1)->isPointerTy())
1047 setDoesNotCapture(F, 2);
1048 } else if (Name == "strxfrm") {
1049 if (FTy->getNumParams() != 3 ||
1050 !FTy->getParamType(0)->isPointerTy() ||
1051 !FTy->getParamType(1)->isPointerTy())
1054 setDoesNotCapture(F, 1);
1055 setDoesNotCapture(F, 2);
1056 } else if (Name == "strcmp" ||
1058 Name == "strncmp" ||
1059 Name == "strcspn" ||
1060 Name == "strcoll" ||
1061 Name == "strcasecmp" ||
1062 Name == "strncasecmp") {
1063 if (FTy->getNumParams() < 2 ||
1064 !FTy->getParamType(0)->isPointerTy() ||
1065 !FTy->getParamType(1)->isPointerTy())
1067 setOnlyReadsMemory(F);
1069 setDoesNotCapture(F, 1);
1070 setDoesNotCapture(F, 2);
1071 } else if (Name == "strstr" ||
1072 Name == "strpbrk") {
1073 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1075 setOnlyReadsMemory(F);
1077 setDoesNotCapture(F, 2);
1078 } else if (Name == "strtok" ||
1079 Name == "strtok_r") {
1080 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1083 setDoesNotCapture(F, 2);
1084 } else if (Name == "scanf" ||
1086 Name == "setvbuf") {
1087 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1090 setDoesNotCapture(F, 1);
1091 } else if (Name == "strdup" ||
1092 Name == "strndup") {
1093 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1094 !FTy->getParamType(0)->isPointerTy())
1097 setDoesNotAlias(F, 0);
1098 setDoesNotCapture(F, 1);
1099 } else if (Name == "stat" ||
1101 Name == "sprintf" ||
1102 Name == "statvfs") {
1103 if (FTy->getNumParams() < 2 ||
1104 !FTy->getParamType(0)->isPointerTy() ||
1105 !FTy->getParamType(1)->isPointerTy())
1108 setDoesNotCapture(F, 1);
1109 setDoesNotCapture(F, 2);
1110 } else if (Name == "snprintf") {
1111 if (FTy->getNumParams() != 3 ||
1112 !FTy->getParamType(0)->isPointerTy() ||
1113 !FTy->getParamType(2)->isPointerTy())
1116 setDoesNotCapture(F, 1);
1117 setDoesNotCapture(F, 3);
1118 } else if (Name == "setitimer") {
1119 if (FTy->getNumParams() != 3 ||
1120 !FTy->getParamType(1)->isPointerTy() ||
1121 !FTy->getParamType(2)->isPointerTy())
1124 setDoesNotCapture(F, 2);
1125 setDoesNotCapture(F, 3);
1126 } else if (Name == "system") {
1127 if (FTy->getNumParams() != 1 ||
1128 !FTy->getParamType(0)->isPointerTy())
1130 // May throw; "system" is a valid pthread cancellation point.
1131 setDoesNotCapture(F, 1);
1135 if (Name == "malloc") {
1136 if (FTy->getNumParams() != 1 ||
1137 !FTy->getReturnType()->isPointerTy())
1140 setDoesNotAlias(F, 0);
1141 } else if (Name == "memcmp") {
1142 if (FTy->getNumParams() != 3 ||
1143 !FTy->getParamType(0)->isPointerTy() ||
1144 !FTy->getParamType(1)->isPointerTy())
1146 setOnlyReadsMemory(F);
1148 setDoesNotCapture(F, 1);
1149 setDoesNotCapture(F, 2);
1150 } else if (Name == "memchr" ||
1151 Name == "memrchr") {
1152 if (FTy->getNumParams() != 3)
1154 setOnlyReadsMemory(F);
1156 } else if (Name == "modf" ||
1160 Name == "memccpy" ||
1161 Name == "memmove") {
1162 if (FTy->getNumParams() < 2 ||
1163 !FTy->getParamType(1)->isPointerTy())
1166 setDoesNotCapture(F, 2);
1167 } else if (Name == "memalign") {
1168 if (!FTy->getReturnType()->isPointerTy())
1170 setDoesNotAlias(F, 0);
1171 } else if (Name == "mkdir" ||
1173 if (FTy->getNumParams() == 0 ||
1174 !FTy->getParamType(0)->isPointerTy())
1177 setDoesNotCapture(F, 1);
1181 if (Name == "realloc") {
1182 if (FTy->getNumParams() != 2 ||
1183 !FTy->getParamType(0)->isPointerTy() ||
1184 !FTy->getReturnType()->isPointerTy())
1187 setDoesNotAlias(F, 0);
1188 setDoesNotCapture(F, 1);
1189 } else if (Name == "read") {
1190 if (FTy->getNumParams() != 3 ||
1191 !FTy->getParamType(1)->isPointerTy())
1193 // May throw; "read" is a valid pthread cancellation point.
1194 setDoesNotCapture(F, 2);
1195 } else if (Name == "rmdir" ||
1198 Name == "realpath") {
1199 if (FTy->getNumParams() < 1 ||
1200 !FTy->getParamType(0)->isPointerTy())
1203 setDoesNotCapture(F, 1);
1204 } else if (Name == "rename" ||
1205 Name == "readlink") {
1206 if (FTy->getNumParams() < 2 ||
1207 !FTy->getParamType(0)->isPointerTy() ||
1208 !FTy->getParamType(1)->isPointerTy())
1211 setDoesNotCapture(F, 1);
1212 setDoesNotCapture(F, 2);
1216 if (Name == "write") {
1217 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1219 // May throw; "write" is a valid pthread cancellation point.
1220 setDoesNotCapture(F, 2);
1224 if (Name == "bcopy") {
1225 if (FTy->getNumParams() != 3 ||
1226 !FTy->getParamType(0)->isPointerTy() ||
1227 !FTy->getParamType(1)->isPointerTy())
1230 setDoesNotCapture(F, 1);
1231 setDoesNotCapture(F, 2);
1232 } else if (Name == "bcmp") {
1233 if (FTy->getNumParams() != 3 ||
1234 !FTy->getParamType(0)->isPointerTy() ||
1235 !FTy->getParamType(1)->isPointerTy())
1238 setOnlyReadsMemory(F);
1239 setDoesNotCapture(F, 1);
1240 setDoesNotCapture(F, 2);
1241 } else if (Name == "bzero") {
1242 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1245 setDoesNotCapture(F, 1);
1249 if (Name == "calloc") {
1250 if (FTy->getNumParams() != 2 ||
1251 !FTy->getReturnType()->isPointerTy())
1254 setDoesNotAlias(F, 0);
1255 } else if (Name == "chmod" ||
1257 Name == "ctermid" ||
1258 Name == "clearerr" ||
1259 Name == "closedir") {
1260 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1263 setDoesNotCapture(F, 1);
1267 if (Name == "atoi" ||
1271 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1274 setOnlyReadsMemory(F);
1275 setDoesNotCapture(F, 1);
1276 } else if (Name == "access") {
1277 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1280 setDoesNotCapture(F, 1);
1284 if (Name == "fopen") {
1285 if (FTy->getNumParams() != 2 ||
1286 !FTy->getReturnType()->isPointerTy() ||
1287 !FTy->getParamType(0)->isPointerTy() ||
1288 !FTy->getParamType(1)->isPointerTy())
1291 setDoesNotAlias(F, 0);
1292 setDoesNotCapture(F, 1);
1293 setDoesNotCapture(F, 2);
1294 } else if (Name == "fdopen") {
1295 if (FTy->getNumParams() != 2 ||
1296 !FTy->getReturnType()->isPointerTy() ||
1297 !FTy->getParamType(1)->isPointerTy())
1300 setDoesNotAlias(F, 0);
1301 setDoesNotCapture(F, 2);
1302 } else if (Name == "feof" ||
1312 Name == "fsetpos" ||
1313 Name == "flockfile" ||
1314 Name == "funlockfile" ||
1315 Name == "ftrylockfile") {
1316 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1319 setDoesNotCapture(F, 1);
1320 } else if (Name == "ferror") {
1321 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1324 setDoesNotCapture(F, 1);
1325 setOnlyReadsMemory(F);
1326 } else if (Name == "fputc" ||
1331 Name == "fstatvfs") {
1332 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1335 setDoesNotCapture(F, 2);
1336 } else if (Name == "fgets") {
1337 if (FTy->getNumParams() != 3 ||
1338 !FTy->getParamType(0)->isPointerTy() ||
1339 !FTy->getParamType(2)->isPointerTy())
1342 setDoesNotCapture(F, 3);
1343 } else if (Name == "fread" ||
1345 if (FTy->getNumParams() != 4 ||
1346 !FTy->getParamType(0)->isPointerTy() ||
1347 !FTy->getParamType(3)->isPointerTy())
1350 setDoesNotCapture(F, 1);
1351 setDoesNotCapture(F, 4);
1352 } else if (Name == "fputs" ||
1354 Name == "fprintf" ||
1355 Name == "fgetpos") {
1356 if (FTy->getNumParams() < 2 ||
1357 !FTy->getParamType(0)->isPointerTy() ||
1358 !FTy->getParamType(1)->isPointerTy())
1361 setDoesNotCapture(F, 1);
1362 setDoesNotCapture(F, 2);
1366 if (Name == "getc" ||
1367 Name == "getlogin_r" ||
1368 Name == "getc_unlocked") {
1369 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1372 setDoesNotCapture(F, 1);
1373 } else if (Name == "getenv") {
1374 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1377 setOnlyReadsMemory(F);
1378 setDoesNotCapture(F, 1);
1379 } else if (Name == "gets" ||
1380 Name == "getchar") {
1382 } else if (Name == "getitimer") {
1383 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1386 setDoesNotCapture(F, 2);
1387 } else if (Name == "getpwnam") {
1388 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1391 setDoesNotCapture(F, 1);
1395 if (Name == "ungetc") {
1396 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1399 setDoesNotCapture(F, 2);
1400 } else if (Name == "uname" ||
1402 Name == "unsetenv") {
1403 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1406 setDoesNotCapture(F, 1);
1407 } else if (Name == "utime" ||
1409 if (FTy->getNumParams() != 2 ||
1410 !FTy->getParamType(0)->isPointerTy() ||
1411 !FTy->getParamType(1)->isPointerTy())
1414 setDoesNotCapture(F, 1);
1415 setDoesNotCapture(F, 2);
1419 if (Name == "putc") {
1420 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1423 setDoesNotCapture(F, 2);
1424 } else if (Name == "puts" ||
1427 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1430 setDoesNotCapture(F, 1);
1431 } else if (Name == "pread" ||
1433 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1435 // May throw; these are valid pthread cancellation points.
1436 setDoesNotCapture(F, 2);
1437 } else if (Name == "putchar") {
1439 } else if (Name == "popen") {
1440 if (FTy->getNumParams() != 2 ||
1441 !FTy->getReturnType()->isPointerTy() ||
1442 !FTy->getParamType(0)->isPointerTy() ||
1443 !FTy->getParamType(1)->isPointerTy())
1446 setDoesNotAlias(F, 0);
1447 setDoesNotCapture(F, 1);
1448 setDoesNotCapture(F, 2);
1449 } else if (Name == "pclose") {
1450 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1453 setDoesNotCapture(F, 1);
1457 if (Name == "vscanf") {
1458 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1461 setDoesNotCapture(F, 1);
1462 } else if (Name == "vsscanf" ||
1463 Name == "vfscanf") {
1464 if (FTy->getNumParams() != 3 ||
1465 !FTy->getParamType(1)->isPointerTy() ||
1466 !FTy->getParamType(2)->isPointerTy())
1469 setDoesNotCapture(F, 1);
1470 setDoesNotCapture(F, 2);
1471 } else if (Name == "valloc") {
1472 if (!FTy->getReturnType()->isPointerTy())
1475 setDoesNotAlias(F, 0);
1476 } else if (Name == "vprintf") {
1477 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1480 setDoesNotCapture(F, 1);
1481 } else if (Name == "vfprintf" ||
1482 Name == "vsprintf") {
1483 if (FTy->getNumParams() != 3 ||
1484 !FTy->getParamType(0)->isPointerTy() ||
1485 !FTy->getParamType(1)->isPointerTy())
1488 setDoesNotCapture(F, 1);
1489 setDoesNotCapture(F, 2);
1490 } else if (Name == "vsnprintf") {
1491 if (FTy->getNumParams() != 4 ||
1492 !FTy->getParamType(0)->isPointerTy() ||
1493 !FTy->getParamType(2)->isPointerTy())
1496 setDoesNotCapture(F, 1);
1497 setDoesNotCapture(F, 3);
1501 if (Name == "open") {
1502 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1504 // May throw; "open" is a valid pthread cancellation point.
1505 setDoesNotCapture(F, 1);
1506 } else if (Name == "opendir") {
1507 if (FTy->getNumParams() != 1 ||
1508 !FTy->getReturnType()->isPointerTy() ||
1509 !FTy->getParamType(0)->isPointerTy())
1512 setDoesNotAlias(F, 0);
1513 setDoesNotCapture(F, 1);
1517 if (Name == "tmpfile") {
1518 if (!FTy->getReturnType()->isPointerTy())
1521 setDoesNotAlias(F, 0);
1522 } else if (Name == "times") {
1523 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1526 setDoesNotCapture(F, 1);
1530 if (Name == "htonl" ||
1533 setDoesNotAccessMemory(F);
1537 if (Name == "ntohl" ||
1540 setDoesNotAccessMemory(F);
1544 if (Name == "lstat") {
1545 if (FTy->getNumParams() != 2 ||
1546 !FTy->getParamType(0)->isPointerTy() ||
1547 !FTy->getParamType(1)->isPointerTy())
1550 setDoesNotCapture(F, 1);
1551 setDoesNotCapture(F, 2);
1552 } else if (Name == "lchown") {
1553 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1556 setDoesNotCapture(F, 1);
1560 if (Name == "qsort") {
1561 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1563 // May throw; places call through function pointer.
1564 setDoesNotCapture(F, 4);
1568 if (Name == "__strdup" ||
1569 Name == "__strndup") {
1570 if (FTy->getNumParams() < 1 ||
1571 !FTy->getReturnType()->isPointerTy() ||
1572 !FTy->getParamType(0)->isPointerTy())
1575 setDoesNotAlias(F, 0);
1576 setDoesNotCapture(F, 1);
1577 } else if (Name == "__strtok_r") {
1578 if (FTy->getNumParams() != 3 ||
1579 !FTy->getParamType(1)->isPointerTy())
1582 setDoesNotCapture(F, 2);
1583 } else if (Name == "_IO_getc") {
1584 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1587 setDoesNotCapture(F, 1);
1588 } else if (Name == "_IO_putc") {
1589 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1592 setDoesNotCapture(F, 2);
1596 if (Name == "\1__isoc99_scanf") {
1597 if (FTy->getNumParams() < 1 ||
1598 !FTy->getParamType(0)->isPointerTy())
1601 setDoesNotCapture(F, 1);
1602 } else if (Name == "\1stat64" ||
1603 Name == "\1lstat64" ||
1604 Name == "\1statvfs64" ||
1605 Name == "\1__isoc99_sscanf") {
1606 if (FTy->getNumParams() < 1 ||
1607 !FTy->getParamType(0)->isPointerTy() ||
1608 !FTy->getParamType(1)->isPointerTy())
1611 setDoesNotCapture(F, 1);
1612 setDoesNotCapture(F, 2);
1613 } else if (Name == "\1fopen64") {
1614 if (FTy->getNumParams() != 2 ||
1615 !FTy->getReturnType()->isPointerTy() ||
1616 !FTy->getParamType(0)->isPointerTy() ||
1617 !FTy->getParamType(1)->isPointerTy())
1620 setDoesNotAlias(F, 0);
1621 setDoesNotCapture(F, 1);
1622 setDoesNotCapture(F, 2);
1623 } else if (Name == "\1fseeko64" ||
1624 Name == "\1ftello64") {
1625 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1628 setDoesNotCapture(F, 1);
1629 } else if (Name == "\1tmpfile64") {
1630 if (!FTy->getReturnType()->isPointerTy())
1633 setDoesNotAlias(F, 0);
1634 } else if (Name == "\1fstat64" ||
1635 Name == "\1fstatvfs64") {
1636 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1639 setDoesNotCapture(F, 2);
1640 } else if (Name == "\1open64") {
1641 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1643 // May throw; "open" is a valid pthread cancellation point.
1644 setDoesNotCapture(F, 1);
1650 /// doInitialization - Add attributes to well-known functions.
1652 bool SimplifyLibCalls::doInitialization(Module &M) {
1654 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1656 if (F.isDeclaration() && F.hasName())
1657 inferPrototypeAttributes(F);
1663 // Additional cases that we need to add to this file:
1666 // * cbrt(expN(X)) -> expN(x/3)
1667 // * cbrt(sqrt(x)) -> pow(x,1/6)
1668 // * cbrt(sqrt(x)) -> pow(x,1/9)
1671 // * exp(log(x)) -> x
1674 // * log(exp(x)) -> x
1675 // * log(x**y) -> y*log(x)
1676 // * log(exp(y)) -> y*log(e)
1677 // * log(exp2(y)) -> y*log(2)
1678 // * log(exp10(y)) -> y*log(10)
1679 // * log(sqrt(x)) -> 0.5*log(x)
1680 // * log(pow(x,y)) -> y*log(x)
1682 // lround, lroundf, lroundl:
1683 // * lround(cnst) -> cnst'
1686 // * pow(exp(x),y) -> exp(x*y)
1687 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1688 // * pow(pow(x,y),z)-> pow(x,y*z)
1690 // round, roundf, roundl:
1691 // * round(cnst) -> cnst'
1694 // * signbit(cnst) -> cnst'
1695 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1697 // sqrt, sqrtf, sqrtl:
1698 // * sqrt(expN(x)) -> expN(x*0.5)
1699 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1700 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1703 // * strchr(p, 0) -> strlen(p)
1705 // * tan(atan(x)) -> x
1707 // trunc, truncf, truncl:
1708 // * trunc(cnst) -> cnst'