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())
102 //===----------------------------------------------------------------------===//
103 // Memory LibCall Optimizations
104 //===----------------------------------------------------------------------===//
107 //===---------------------------------------===//
108 // 'memset' Optimizations
110 struct MemSetOpt : public LibCallOptimization {
111 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
112 // These optimizations require DataLayout.
115 FunctionType *FT = Callee->getFunctionType();
116 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
117 !FT->getParamType(0)->isPointerTy() ||
118 !FT->getParamType(1)->isIntegerTy() ||
119 FT->getParamType(2) != TD->getIntPtrType(*Context))
122 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
123 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
124 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
125 return CI->getArgOperand(0);
129 //===----------------------------------------------------------------------===//
130 // Math Library Optimizations
131 //===----------------------------------------------------------------------===//
133 //===---------------------------------------===//
134 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
136 struct UnaryDoubleFPOpt : public LibCallOptimization {
138 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
139 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
140 FunctionType *FT = Callee->getFunctionType();
141 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
142 !FT->getParamType(0)->isDoubleTy())
146 // Check if all the uses for function like 'sin' are converted to float.
147 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
149 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
150 if (Cast == 0 || !Cast->getType()->isFloatTy())
155 // If this is something like 'floor((double)floatval)', convert to floorf.
156 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
157 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
160 // floor((double)floatval) -> (double)floorf(floatval)
161 Value *V = Cast->getOperand(0);
162 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
163 return B.CreateFPExt(V, B.getDoubleTy());
167 //===---------------------------------------===//
168 // 'cos*' Optimizations
169 struct CosOpt : public LibCallOptimization {
170 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
172 if (UnsafeFPShrink && Callee->getName() == "cos" &&
173 TLI->has(LibFunc::cosf)) {
174 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
175 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
178 FunctionType *FT = Callee->getFunctionType();
179 // Just make sure this has 1 argument of FP type, which matches the
181 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
182 !FT->getParamType(0)->isFloatingPointTy())
186 Value *Op1 = CI->getArgOperand(0);
187 if (BinaryOperator::isFNeg(Op1)) {
188 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
189 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
195 //===---------------------------------------===//
196 // 'pow*' Optimizations
198 struct PowOpt : public LibCallOptimization {
199 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
201 if (UnsafeFPShrink && Callee->getName() == "pow" &&
202 TLI->has(LibFunc::powf)) {
203 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
204 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
207 FunctionType *FT = Callee->getFunctionType();
208 // Just make sure this has 2 arguments of the same FP type, which match the
210 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
211 FT->getParamType(0) != FT->getParamType(1) ||
212 !FT->getParamType(0)->isFloatingPointTy())
215 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
216 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
217 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
219 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
220 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
223 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
224 if (Op2C == 0) return Ret;
226 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
227 return ConstantFP::get(CI->getType(), 1.0);
229 if (Op2C->isExactlyValue(0.5)) {
230 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
231 // This is faster than calling pow, and still handles negative zero
232 // and negative infinity correctly.
233 // TODO: In fast-math mode, this could be just sqrt(x).
234 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
235 Value *Inf = ConstantFP::getInfinity(CI->getType());
236 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
237 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
238 Callee->getAttributes());
239 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
240 Callee->getAttributes());
241 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
242 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
246 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
248 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
249 return B.CreateFMul(Op1, Op1, "pow2");
250 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
251 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
257 //===---------------------------------------===//
258 // 'exp2' Optimizations
260 struct Exp2Opt : public LibCallOptimization {
261 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
263 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
264 TLI->has(LibFunc::exp2)) {
265 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
266 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
269 FunctionType *FT = Callee->getFunctionType();
270 // Just make sure this has 1 argument of FP type, which matches the
272 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
273 !FT->getParamType(0)->isFloatingPointTy())
276 Value *Op = CI->getArgOperand(0);
277 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
278 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
280 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
281 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
282 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
283 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
284 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
285 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
290 if (Op->getType()->isFloatTy())
292 else if (Op->getType()->isDoubleTy())
297 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
298 if (!Op->getType()->isFloatTy())
299 One = ConstantExpr::getFPExtend(One, Op->getType());
301 Module *M = Caller->getParent();
302 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
304 B.getInt32Ty(), NULL);
305 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
306 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
307 CI->setCallingConv(F->getCallingConv());
315 //===----------------------------------------------------------------------===//
316 // Integer Optimizations
317 //===----------------------------------------------------------------------===//
319 //===---------------------------------------===//
320 // 'ffs*' Optimizations
322 struct FFSOpt : public LibCallOptimization {
323 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
324 FunctionType *FT = Callee->getFunctionType();
325 // Just make sure this has 2 arguments of the same FP type, which match the
327 if (FT->getNumParams() != 1 ||
328 !FT->getReturnType()->isIntegerTy(32) ||
329 !FT->getParamType(0)->isIntegerTy())
332 Value *Op = CI->getArgOperand(0);
335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
336 if (CI->isZero()) // ffs(0) -> 0.
337 return B.getInt32(0);
338 // ffs(c) -> cttz(c)+1
339 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
342 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
343 Type *ArgType = Op->getType();
344 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
345 Intrinsic::cttz, ArgType);
346 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
347 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
348 V = B.CreateIntCast(V, B.getInt32Ty(), false);
350 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
351 return B.CreateSelect(Cond, V, B.getInt32(0));
355 //===---------------------------------------===//
356 // 'isdigit' Optimizations
358 struct IsDigitOpt : public LibCallOptimization {
359 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
360 FunctionType *FT = Callee->getFunctionType();
361 // We require integer(i32)
362 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
363 !FT->getParamType(0)->isIntegerTy(32))
366 // isdigit(c) -> (c-'0') <u 10
367 Value *Op = CI->getArgOperand(0);
368 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
369 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
370 return B.CreateZExt(Op, CI->getType());
374 //===---------------------------------------===//
375 // 'isascii' Optimizations
377 struct IsAsciiOpt : public LibCallOptimization {
378 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
379 FunctionType *FT = Callee->getFunctionType();
380 // We require integer(i32)
381 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
382 !FT->getParamType(0)->isIntegerTy(32))
385 // isascii(c) -> c <u 128
386 Value *Op = CI->getArgOperand(0);
387 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
388 return B.CreateZExt(Op, CI->getType());
392 //===---------------------------------------===//
393 // 'abs', 'labs', 'llabs' Optimizations
395 struct AbsOpt : public LibCallOptimization {
396 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
397 FunctionType *FT = Callee->getFunctionType();
398 // We require integer(integer) where the types agree.
399 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
400 FT->getParamType(0) != FT->getReturnType())
403 // abs(x) -> x >s -1 ? x : -x
404 Value *Op = CI->getArgOperand(0);
405 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
407 Value *Neg = B.CreateNeg(Op, "neg");
408 return B.CreateSelect(Pos, Op, Neg);
413 //===---------------------------------------===//
414 // 'toascii' Optimizations
416 struct ToAsciiOpt : public LibCallOptimization {
417 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
418 FunctionType *FT = Callee->getFunctionType();
419 // We require i32(i32)
420 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
421 !FT->getParamType(0)->isIntegerTy(32))
424 // isascii(c) -> c & 0x7f
425 return B.CreateAnd(CI->getArgOperand(0),
426 ConstantInt::get(CI->getType(),0x7F));
430 //===----------------------------------------------------------------------===//
431 // Formatting and IO Optimizations
432 //===----------------------------------------------------------------------===//
434 //===---------------------------------------===//
435 // 'printf' Optimizations
437 struct PrintFOpt : public LibCallOptimization {
438 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
440 // Check for a fixed format string.
442 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
445 // Empty format string -> noop.
446 if (FormatStr.empty()) // Tolerate printf's declared void.
447 return CI->use_empty() ? (Value*)CI :
448 ConstantInt::get(CI->getType(), 0);
450 // Do not do any of the following transformations if the printf return value
451 // is used, in general the printf return value is not compatible with either
452 // putchar() or puts().
453 if (!CI->use_empty())
456 // printf("x") -> putchar('x'), even for '%'.
457 if (FormatStr.size() == 1) {
458 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
459 if (CI->use_empty() || !Res) return Res;
460 return B.CreateIntCast(Res, CI->getType(), true);
463 // printf("foo\n") --> puts("foo")
464 if (FormatStr[FormatStr.size()-1] == '\n' &&
465 FormatStr.find('%') == std::string::npos) { // no format characters.
466 // Create a string literal with no \n on it. We expect the constant merge
467 // pass to be run after this pass, to merge duplicate strings.
468 FormatStr = FormatStr.drop_back();
469 Value *GV = B.CreateGlobalString(FormatStr, "str");
470 Value *NewCI = EmitPutS(GV, B, TD, TLI);
471 return (CI->use_empty() || !NewCI) ?
473 ConstantInt::get(CI->getType(), FormatStr.size()+1);
476 // Optimize specific format strings.
477 // printf("%c", chr) --> putchar(chr)
478 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
479 CI->getArgOperand(1)->getType()->isIntegerTy()) {
480 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
482 if (CI->use_empty() || !Res) return Res;
483 return B.CreateIntCast(Res, CI->getType(), true);
486 // printf("%s\n", str) --> puts(str)
487 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
488 CI->getArgOperand(1)->getType()->isPointerTy()) {
489 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
494 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
495 // Require one fixed pointer argument and an integer/void result.
496 FunctionType *FT = Callee->getFunctionType();
497 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
498 !(FT->getReturnType()->isIntegerTy() ||
499 FT->getReturnType()->isVoidTy()))
502 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
506 // printf(format, ...) -> iprintf(format, ...) if no floating point
508 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
509 Module *M = B.GetInsertBlock()->getParent()->getParent();
510 Constant *IPrintFFn =
511 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
512 CallInst *New = cast<CallInst>(CI->clone());
513 New->setCalledFunction(IPrintFFn);
521 //===---------------------------------------===//
522 // 'sprintf' Optimizations
524 struct SPrintFOpt : public LibCallOptimization {
525 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
527 // Check for a fixed format string.
529 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
532 // If we just have a format string (nothing else crazy) transform it.
533 if (CI->getNumArgOperands() == 2) {
534 // Make sure there's no % in the constant array. We could try to handle
535 // %% -> % in the future if we cared.
536 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
537 if (FormatStr[i] == '%')
538 return 0; // we found a format specifier, bail out.
540 // These optimizations require DataLayout.
543 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
544 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
545 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
546 FormatStr.size() + 1), 1); // nul byte.
547 return ConstantInt::get(CI->getType(), FormatStr.size());
550 // The remaining optimizations require the format string to be "%s" or "%c"
551 // and have an extra operand.
552 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
553 CI->getNumArgOperands() < 3)
556 // Decode the second character of the format string.
557 if (FormatStr[1] == 'c') {
558 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
559 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
560 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
561 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
562 B.CreateStore(V, Ptr);
563 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
564 B.CreateStore(B.getInt8(0), Ptr);
566 return ConstantInt::get(CI->getType(), 1);
569 if (FormatStr[1] == 's') {
570 // These optimizations require DataLayout.
573 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
574 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
576 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
579 Value *IncLen = B.CreateAdd(Len,
580 ConstantInt::get(Len->getType(), 1),
582 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
584 // The sprintf result is the unincremented number of bytes in the string.
585 return B.CreateIntCast(Len, CI->getType(), false);
590 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
591 // Require two fixed pointer arguments and an integer result.
592 FunctionType *FT = Callee->getFunctionType();
593 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
594 !FT->getParamType(1)->isPointerTy() ||
595 !FT->getReturnType()->isIntegerTy())
598 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
602 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
604 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
605 Module *M = B.GetInsertBlock()->getParent()->getParent();
606 Constant *SIPrintFFn =
607 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
608 CallInst *New = cast<CallInst>(CI->clone());
609 New->setCalledFunction(SIPrintFFn);
617 //===---------------------------------------===//
618 // 'fwrite' Optimizations
620 struct FWriteOpt : public LibCallOptimization {
621 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
622 // Require a pointer, an integer, an integer, a pointer, returning integer.
623 FunctionType *FT = Callee->getFunctionType();
624 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
625 !FT->getParamType(1)->isIntegerTy() ||
626 !FT->getParamType(2)->isIntegerTy() ||
627 !FT->getParamType(3)->isPointerTy() ||
628 !FT->getReturnType()->isIntegerTy())
631 // Get the element size and count.
632 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
633 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
634 if (!SizeC || !CountC) return 0;
635 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
637 // If this is writing zero records, remove the call (it's a noop).
639 return ConstantInt::get(CI->getType(), 0);
641 // If this is writing one byte, turn it into fputc.
642 // This optimisation is only valid, if the return value is unused.
643 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
644 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
645 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
646 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
653 //===---------------------------------------===//
654 // 'fputs' Optimizations
656 struct FPutsOpt : public LibCallOptimization {
657 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
658 // These optimizations require DataLayout.
661 // Require two pointers. Also, we can't optimize if return value is used.
662 FunctionType *FT = Callee->getFunctionType();
663 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
664 !FT->getParamType(1)->isPointerTy() ||
668 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
669 uint64_t Len = GetStringLength(CI->getArgOperand(0));
671 // Known to have no uses (see above).
672 return EmitFWrite(CI->getArgOperand(0),
673 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
674 CI->getArgOperand(1), B, TD, TLI);
678 //===---------------------------------------===//
679 // 'fprintf' Optimizations
681 struct FPrintFOpt : public LibCallOptimization {
682 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
684 // All the optimizations depend on the format string.
686 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
689 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
690 if (CI->getNumArgOperands() == 2) {
691 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
692 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
693 return 0; // We found a format specifier.
695 // These optimizations require DataLayout.
698 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
699 ConstantInt::get(TD->getIntPtrType(*Context),
701 CI->getArgOperand(0), B, TD, TLI);
702 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
705 // The remaining optimizations require the format string to be "%s" or "%c"
706 // and have an extra operand.
707 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
708 CI->getNumArgOperands() < 3)
711 // Decode the second character of the format string.
712 if (FormatStr[1] == 'c') {
713 // fprintf(F, "%c", chr) --> fputc(chr, F)
714 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
715 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
717 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
720 if (FormatStr[1] == 's') {
721 // fprintf(F, "%s", str) --> fputs(str, F)
722 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
724 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
729 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
730 // Require two fixed paramters as pointers and integer result.
731 FunctionType *FT = Callee->getFunctionType();
732 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
733 !FT->getParamType(1)->isPointerTy() ||
734 !FT->getReturnType()->isIntegerTy())
737 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
741 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
742 // floating point arguments.
743 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
744 Module *M = B.GetInsertBlock()->getParent()->getParent();
745 Constant *FIPrintFFn =
746 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
747 CallInst *New = cast<CallInst>(CI->clone());
748 New->setCalledFunction(FIPrintFFn);
756 //===---------------------------------------===//
757 // 'puts' Optimizations
759 struct PutsOpt : public LibCallOptimization {
760 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
761 // Require one fixed pointer argument and an integer/void result.
762 FunctionType *FT = Callee->getFunctionType();
763 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
764 !(FT->getReturnType()->isIntegerTy() ||
765 FT->getReturnType()->isVoidTy()))
768 // Check for a constant string.
770 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
773 if (Str.empty() && CI->use_empty()) {
774 // puts("") -> putchar('\n')
775 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
776 if (CI->use_empty() || !Res) return Res;
777 return B.CreateIntCast(Res, CI->getType(), true);
784 } // end anonymous namespace.
786 //===----------------------------------------------------------------------===//
787 // SimplifyLibCalls Pass Implementation
788 //===----------------------------------------------------------------------===//
791 /// This pass optimizes well known library functions from libc and libm.
793 class SimplifyLibCalls : public FunctionPass {
794 TargetLibraryInfo *TLI;
796 StringMap<LibCallOptimization*> Optimizations;
797 // Memory LibCall Optimizations
799 // Math Library Optimizations
800 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
801 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
802 // Integer Optimizations
803 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
805 // Formatting and IO Optimizations
806 SPrintFOpt SPrintF; PrintFOpt PrintF;
807 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
810 bool Modified; // This is only used by doInitialization.
812 static char ID; // Pass identification
813 SimplifyLibCalls() : FunctionPass(ID), UnaryDoubleFP(false),
814 UnsafeUnaryDoubleFP(true) {
815 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
817 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
818 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
820 void InitOptimizations();
821 bool runOnFunction(Function &F);
823 void setDoesNotAccessMemory(Function &F);
824 void setOnlyReadsMemory(Function &F);
825 void setDoesNotThrow(Function &F);
826 void setDoesNotCapture(Function &F, unsigned n);
827 void setDoesNotAlias(Function &F, unsigned n);
828 bool doInitialization(Module &M);
830 void inferPrototypeAttributes(Function &F);
831 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
832 AU.addRequired<TargetLibraryInfo>();
835 } // end anonymous namespace.
837 char SimplifyLibCalls::ID = 0;
839 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
840 "Simplify well-known library calls", false, false)
841 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
842 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
843 "Simplify well-known library calls", false, false)
845 // Public interface to the Simplify LibCalls pass.
846 FunctionPass *llvm::createSimplifyLibCallsPass() {
847 return new SimplifyLibCalls();
850 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
852 Optimizations[TLI->getName(F)] = Opt;
855 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
856 LibCallOptimization* Opt) {
857 if (TLI->has(F1) && TLI->has(F2))
858 Optimizations[TLI->getName(F1)] = Opt;
861 /// Optimizations - Populate the Optimizations map with all the optimizations
863 void SimplifyLibCalls::InitOptimizations() {
864 // Memory LibCall Optimizations
865 AddOpt(LibFunc::memset, &MemSet);
867 // Math Library Optimizations
868 Optimizations["cosf"] = &Cos;
869 Optimizations["cos"] = &Cos;
870 Optimizations["cosl"] = &Cos;
871 Optimizations["powf"] = &Pow;
872 Optimizations["pow"] = &Pow;
873 Optimizations["powl"] = &Pow;
874 Optimizations["llvm.pow.f32"] = &Pow;
875 Optimizations["llvm.pow.f64"] = &Pow;
876 Optimizations["llvm.pow.f80"] = &Pow;
877 Optimizations["llvm.pow.f128"] = &Pow;
878 Optimizations["llvm.pow.ppcf128"] = &Pow;
879 Optimizations["exp2l"] = &Exp2;
880 Optimizations["exp2"] = &Exp2;
881 Optimizations["exp2f"] = &Exp2;
882 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
883 Optimizations["llvm.exp2.f128"] = &Exp2;
884 Optimizations["llvm.exp2.f80"] = &Exp2;
885 Optimizations["llvm.exp2.f64"] = &Exp2;
886 Optimizations["llvm.exp2.f32"] = &Exp2;
888 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
889 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
890 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
891 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
892 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
893 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
894 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
897 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
898 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
899 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
900 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
901 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
902 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
903 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
904 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
905 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
906 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
907 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
908 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
909 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
910 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
911 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
912 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
913 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
914 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
915 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
916 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
917 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
920 // Integer Optimizations
921 Optimizations["ffs"] = &FFS;
922 Optimizations["ffsl"] = &FFS;
923 Optimizations["ffsll"] = &FFS;
924 Optimizations["abs"] = &Abs;
925 Optimizations["labs"] = &Abs;
926 Optimizations["llabs"] = &Abs;
927 Optimizations["isdigit"] = &IsDigit;
928 Optimizations["isascii"] = &IsAscii;
929 Optimizations["toascii"] = &ToAscii;
931 // Formatting and IO Optimizations
932 Optimizations["sprintf"] = &SPrintF;
933 Optimizations["printf"] = &PrintF;
934 AddOpt(LibFunc::fwrite, &FWrite);
935 AddOpt(LibFunc::fputs, &FPuts);
936 Optimizations["fprintf"] = &FPrintF;
937 Optimizations["puts"] = &Puts;
941 /// runOnFunction - Top level algorithm.
943 bool SimplifyLibCalls::runOnFunction(Function &F) {
944 TLI = &getAnalysis<TargetLibraryInfo>();
946 if (Optimizations.empty())
949 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
951 IRBuilder<> Builder(F.getContext());
953 bool Changed = false;
954 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
955 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
957 CallInst *CI = dyn_cast<CallInst>(I++);
960 // Ignore indirect calls and calls to non-external functions.
961 Function *Callee = CI->getCalledFunction();
962 if (Callee == 0 || !Callee->isDeclaration() ||
963 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
966 // Ignore unknown calls.
967 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
970 // Set the builder to the instruction after the call.
971 Builder.SetInsertPoint(BB, I);
973 // Use debug location of CI for all new instructions.
974 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
976 // Try to optimize this call.
977 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
978 if (Result == 0) continue;
980 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
981 dbgs() << " into: " << *Result << "\n");
983 // Something changed!
987 // Inspect the instruction after the call (which was potentially just
991 if (CI != Result && !CI->use_empty()) {
992 CI->replaceAllUsesWith(Result);
993 if (!Result->hasName())
994 Result->takeName(CI);
996 CI->eraseFromParent();
1002 // Utility methods for doInitialization.
1004 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1005 if (!F.doesNotAccessMemory()) {
1006 F.setDoesNotAccessMemory();
1011 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1012 if (!F.onlyReadsMemory()) {
1013 F.setOnlyReadsMemory();
1018 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1019 if (!F.doesNotThrow()) {
1020 F.setDoesNotThrow();
1025 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1026 if (!F.doesNotCapture(n)) {
1027 F.setDoesNotCapture(n);
1032 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1033 if (!F.doesNotAlias(n)) {
1034 F.setDoesNotAlias(n);
1041 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1042 FunctionType *FTy = F.getFunctionType();
1044 StringRef Name = F.getName();
1047 if (Name == "strlen") {
1048 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1050 setOnlyReadsMemory(F);
1052 setDoesNotCapture(F, 1);
1053 } else if (Name == "strchr" ||
1054 Name == "strrchr") {
1055 if (FTy->getNumParams() != 2 ||
1056 !FTy->getParamType(0)->isPointerTy() ||
1057 !FTy->getParamType(1)->isIntegerTy())
1059 setOnlyReadsMemory(F);
1061 } else if (Name == "strcpy" ||
1067 Name == "strtoul" ||
1068 Name == "strtoll" ||
1069 Name == "strtold" ||
1070 Name == "strncat" ||
1071 Name == "strncpy" ||
1072 Name == "stpncpy" ||
1073 Name == "strtoull") {
1074 if (FTy->getNumParams() < 2 ||
1075 !FTy->getParamType(1)->isPointerTy())
1078 setDoesNotCapture(F, 2);
1079 } else if (Name == "strxfrm") {
1080 if (FTy->getNumParams() != 3 ||
1081 !FTy->getParamType(0)->isPointerTy() ||
1082 !FTy->getParamType(1)->isPointerTy())
1085 setDoesNotCapture(F, 1);
1086 setDoesNotCapture(F, 2);
1087 } else if (Name == "strcmp" ||
1089 Name == "strncmp" ||
1090 Name == "strcspn" ||
1091 Name == "strcoll" ||
1092 Name == "strcasecmp" ||
1093 Name == "strncasecmp") {
1094 if (FTy->getNumParams() < 2 ||
1095 !FTy->getParamType(0)->isPointerTy() ||
1096 !FTy->getParamType(1)->isPointerTy())
1098 setOnlyReadsMemory(F);
1100 setDoesNotCapture(F, 1);
1101 setDoesNotCapture(F, 2);
1102 } else if (Name == "strstr" ||
1103 Name == "strpbrk") {
1104 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1106 setOnlyReadsMemory(F);
1108 setDoesNotCapture(F, 2);
1109 } else if (Name == "strtok" ||
1110 Name == "strtok_r") {
1111 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1114 setDoesNotCapture(F, 2);
1115 } else if (Name == "scanf" ||
1117 Name == "setvbuf") {
1118 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1121 setDoesNotCapture(F, 1);
1122 } else if (Name == "strdup" ||
1123 Name == "strndup") {
1124 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1125 !FTy->getParamType(0)->isPointerTy())
1128 setDoesNotAlias(F, 0);
1129 setDoesNotCapture(F, 1);
1130 } else if (Name == "stat" ||
1132 Name == "sprintf" ||
1133 Name == "statvfs") {
1134 if (FTy->getNumParams() < 2 ||
1135 !FTy->getParamType(0)->isPointerTy() ||
1136 !FTy->getParamType(1)->isPointerTy())
1139 setDoesNotCapture(F, 1);
1140 setDoesNotCapture(F, 2);
1141 } else if (Name == "snprintf") {
1142 if (FTy->getNumParams() != 3 ||
1143 !FTy->getParamType(0)->isPointerTy() ||
1144 !FTy->getParamType(2)->isPointerTy())
1147 setDoesNotCapture(F, 1);
1148 setDoesNotCapture(F, 3);
1149 } else if (Name == "setitimer") {
1150 if (FTy->getNumParams() != 3 ||
1151 !FTy->getParamType(1)->isPointerTy() ||
1152 !FTy->getParamType(2)->isPointerTy())
1155 setDoesNotCapture(F, 2);
1156 setDoesNotCapture(F, 3);
1157 } else if (Name == "system") {
1158 if (FTy->getNumParams() != 1 ||
1159 !FTy->getParamType(0)->isPointerTy())
1161 // May throw; "system" is a valid pthread cancellation point.
1162 setDoesNotCapture(F, 1);
1166 if (Name == "malloc") {
1167 if (FTy->getNumParams() != 1 ||
1168 !FTy->getReturnType()->isPointerTy())
1171 setDoesNotAlias(F, 0);
1172 } else if (Name == "memcmp") {
1173 if (FTy->getNumParams() != 3 ||
1174 !FTy->getParamType(0)->isPointerTy() ||
1175 !FTy->getParamType(1)->isPointerTy())
1177 setOnlyReadsMemory(F);
1179 setDoesNotCapture(F, 1);
1180 setDoesNotCapture(F, 2);
1181 } else if (Name == "memchr" ||
1182 Name == "memrchr") {
1183 if (FTy->getNumParams() != 3)
1185 setOnlyReadsMemory(F);
1187 } else if (Name == "modf" ||
1191 Name == "memccpy" ||
1192 Name == "memmove") {
1193 if (FTy->getNumParams() < 2 ||
1194 !FTy->getParamType(1)->isPointerTy())
1197 setDoesNotCapture(F, 2);
1198 } else if (Name == "memalign") {
1199 if (!FTy->getReturnType()->isPointerTy())
1201 setDoesNotAlias(F, 0);
1202 } else if (Name == "mkdir" ||
1204 if (FTy->getNumParams() == 0 ||
1205 !FTy->getParamType(0)->isPointerTy())
1208 setDoesNotCapture(F, 1);
1212 if (Name == "realloc") {
1213 if (FTy->getNumParams() != 2 ||
1214 !FTy->getParamType(0)->isPointerTy() ||
1215 !FTy->getReturnType()->isPointerTy())
1218 setDoesNotAlias(F, 0);
1219 setDoesNotCapture(F, 1);
1220 } else if (Name == "read") {
1221 if (FTy->getNumParams() != 3 ||
1222 !FTy->getParamType(1)->isPointerTy())
1224 // May throw; "read" is a valid pthread cancellation point.
1225 setDoesNotCapture(F, 2);
1226 } else if (Name == "rmdir" ||
1229 Name == "realpath") {
1230 if (FTy->getNumParams() < 1 ||
1231 !FTy->getParamType(0)->isPointerTy())
1234 setDoesNotCapture(F, 1);
1235 } else if (Name == "rename" ||
1236 Name == "readlink") {
1237 if (FTy->getNumParams() < 2 ||
1238 !FTy->getParamType(0)->isPointerTy() ||
1239 !FTy->getParamType(1)->isPointerTy())
1242 setDoesNotCapture(F, 1);
1243 setDoesNotCapture(F, 2);
1247 if (Name == "write") {
1248 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1250 // May throw; "write" is a valid pthread cancellation point.
1251 setDoesNotCapture(F, 2);
1255 if (Name == "bcopy") {
1256 if (FTy->getNumParams() != 3 ||
1257 !FTy->getParamType(0)->isPointerTy() ||
1258 !FTy->getParamType(1)->isPointerTy())
1261 setDoesNotCapture(F, 1);
1262 setDoesNotCapture(F, 2);
1263 } else if (Name == "bcmp") {
1264 if (FTy->getNumParams() != 3 ||
1265 !FTy->getParamType(0)->isPointerTy() ||
1266 !FTy->getParamType(1)->isPointerTy())
1269 setOnlyReadsMemory(F);
1270 setDoesNotCapture(F, 1);
1271 setDoesNotCapture(F, 2);
1272 } else if (Name == "bzero") {
1273 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1276 setDoesNotCapture(F, 1);
1280 if (Name == "calloc") {
1281 if (FTy->getNumParams() != 2 ||
1282 !FTy->getReturnType()->isPointerTy())
1285 setDoesNotAlias(F, 0);
1286 } else if (Name == "chmod" ||
1288 Name == "ctermid" ||
1289 Name == "clearerr" ||
1290 Name == "closedir") {
1291 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1294 setDoesNotCapture(F, 1);
1298 if (Name == "atoi" ||
1302 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1305 setOnlyReadsMemory(F);
1306 setDoesNotCapture(F, 1);
1307 } else if (Name == "access") {
1308 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1311 setDoesNotCapture(F, 1);
1315 if (Name == "fopen") {
1316 if (FTy->getNumParams() != 2 ||
1317 !FTy->getReturnType()->isPointerTy() ||
1318 !FTy->getParamType(0)->isPointerTy() ||
1319 !FTy->getParamType(1)->isPointerTy())
1322 setDoesNotAlias(F, 0);
1323 setDoesNotCapture(F, 1);
1324 setDoesNotCapture(F, 2);
1325 } else if (Name == "fdopen") {
1326 if (FTy->getNumParams() != 2 ||
1327 !FTy->getReturnType()->isPointerTy() ||
1328 !FTy->getParamType(1)->isPointerTy())
1331 setDoesNotAlias(F, 0);
1332 setDoesNotCapture(F, 2);
1333 } else if (Name == "feof" ||
1343 Name == "fsetpos" ||
1344 Name == "flockfile" ||
1345 Name == "funlockfile" ||
1346 Name == "ftrylockfile") {
1347 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1350 setDoesNotCapture(F, 1);
1351 } else if (Name == "ferror") {
1352 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1355 setDoesNotCapture(F, 1);
1356 setOnlyReadsMemory(F);
1357 } else if (Name == "fputc" ||
1362 Name == "fstatvfs") {
1363 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1366 setDoesNotCapture(F, 2);
1367 } else if (Name == "fgets") {
1368 if (FTy->getNumParams() != 3 ||
1369 !FTy->getParamType(0)->isPointerTy() ||
1370 !FTy->getParamType(2)->isPointerTy())
1373 setDoesNotCapture(F, 3);
1374 } else if (Name == "fread" ||
1376 if (FTy->getNumParams() != 4 ||
1377 !FTy->getParamType(0)->isPointerTy() ||
1378 !FTy->getParamType(3)->isPointerTy())
1381 setDoesNotCapture(F, 1);
1382 setDoesNotCapture(F, 4);
1383 } else if (Name == "fputs" ||
1385 Name == "fprintf" ||
1386 Name == "fgetpos") {
1387 if (FTy->getNumParams() < 2 ||
1388 !FTy->getParamType(0)->isPointerTy() ||
1389 !FTy->getParamType(1)->isPointerTy())
1392 setDoesNotCapture(F, 1);
1393 setDoesNotCapture(F, 2);
1397 if (Name == "getc" ||
1398 Name == "getlogin_r" ||
1399 Name == "getc_unlocked") {
1400 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1403 setDoesNotCapture(F, 1);
1404 } else if (Name == "getenv") {
1405 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1408 setOnlyReadsMemory(F);
1409 setDoesNotCapture(F, 1);
1410 } else if (Name == "gets" ||
1411 Name == "getchar") {
1413 } else if (Name == "getitimer") {
1414 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1417 setDoesNotCapture(F, 2);
1418 } else if (Name == "getpwnam") {
1419 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1422 setDoesNotCapture(F, 1);
1426 if (Name == "ungetc") {
1427 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1430 setDoesNotCapture(F, 2);
1431 } else if (Name == "uname" ||
1433 Name == "unsetenv") {
1434 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1437 setDoesNotCapture(F, 1);
1438 } else if (Name == "utime" ||
1440 if (FTy->getNumParams() != 2 ||
1441 !FTy->getParamType(0)->isPointerTy() ||
1442 !FTy->getParamType(1)->isPointerTy())
1445 setDoesNotCapture(F, 1);
1446 setDoesNotCapture(F, 2);
1450 if (Name == "putc") {
1451 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1454 setDoesNotCapture(F, 2);
1455 } else if (Name == "puts" ||
1458 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1461 setDoesNotCapture(F, 1);
1462 } else if (Name == "pread" ||
1464 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1466 // May throw; these are valid pthread cancellation points.
1467 setDoesNotCapture(F, 2);
1468 } else if (Name == "putchar") {
1470 } else if (Name == "popen") {
1471 if (FTy->getNumParams() != 2 ||
1472 !FTy->getReturnType()->isPointerTy() ||
1473 !FTy->getParamType(0)->isPointerTy() ||
1474 !FTy->getParamType(1)->isPointerTy())
1477 setDoesNotAlias(F, 0);
1478 setDoesNotCapture(F, 1);
1479 setDoesNotCapture(F, 2);
1480 } else if (Name == "pclose") {
1481 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1484 setDoesNotCapture(F, 1);
1488 if (Name == "vscanf") {
1489 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1492 setDoesNotCapture(F, 1);
1493 } else if (Name == "vsscanf" ||
1494 Name == "vfscanf") {
1495 if (FTy->getNumParams() != 3 ||
1496 !FTy->getParamType(1)->isPointerTy() ||
1497 !FTy->getParamType(2)->isPointerTy())
1500 setDoesNotCapture(F, 1);
1501 setDoesNotCapture(F, 2);
1502 } else if (Name == "valloc") {
1503 if (!FTy->getReturnType()->isPointerTy())
1506 setDoesNotAlias(F, 0);
1507 } else if (Name == "vprintf") {
1508 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1511 setDoesNotCapture(F, 1);
1512 } else if (Name == "vfprintf" ||
1513 Name == "vsprintf") {
1514 if (FTy->getNumParams() != 3 ||
1515 !FTy->getParamType(0)->isPointerTy() ||
1516 !FTy->getParamType(1)->isPointerTy())
1519 setDoesNotCapture(F, 1);
1520 setDoesNotCapture(F, 2);
1521 } else if (Name == "vsnprintf") {
1522 if (FTy->getNumParams() != 4 ||
1523 !FTy->getParamType(0)->isPointerTy() ||
1524 !FTy->getParamType(2)->isPointerTy())
1527 setDoesNotCapture(F, 1);
1528 setDoesNotCapture(F, 3);
1532 if (Name == "open") {
1533 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1535 // May throw; "open" is a valid pthread cancellation point.
1536 setDoesNotCapture(F, 1);
1537 } else if (Name == "opendir") {
1538 if (FTy->getNumParams() != 1 ||
1539 !FTy->getReturnType()->isPointerTy() ||
1540 !FTy->getParamType(0)->isPointerTy())
1543 setDoesNotAlias(F, 0);
1544 setDoesNotCapture(F, 1);
1548 if (Name == "tmpfile") {
1549 if (!FTy->getReturnType()->isPointerTy())
1552 setDoesNotAlias(F, 0);
1553 } else if (Name == "times") {
1554 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1557 setDoesNotCapture(F, 1);
1561 if (Name == "htonl" ||
1564 setDoesNotAccessMemory(F);
1568 if (Name == "ntohl" ||
1571 setDoesNotAccessMemory(F);
1575 if (Name == "lstat") {
1576 if (FTy->getNumParams() != 2 ||
1577 !FTy->getParamType(0)->isPointerTy() ||
1578 !FTy->getParamType(1)->isPointerTy())
1581 setDoesNotCapture(F, 1);
1582 setDoesNotCapture(F, 2);
1583 } else if (Name == "lchown") {
1584 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1587 setDoesNotCapture(F, 1);
1591 if (Name == "qsort") {
1592 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1594 // May throw; places call through function pointer.
1595 setDoesNotCapture(F, 4);
1599 if (Name == "__strdup" ||
1600 Name == "__strndup") {
1601 if (FTy->getNumParams() < 1 ||
1602 !FTy->getReturnType()->isPointerTy() ||
1603 !FTy->getParamType(0)->isPointerTy())
1606 setDoesNotAlias(F, 0);
1607 setDoesNotCapture(F, 1);
1608 } else if (Name == "__strtok_r") {
1609 if (FTy->getNumParams() != 3 ||
1610 !FTy->getParamType(1)->isPointerTy())
1613 setDoesNotCapture(F, 2);
1614 } else if (Name == "_IO_getc") {
1615 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1618 setDoesNotCapture(F, 1);
1619 } else if (Name == "_IO_putc") {
1620 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1623 setDoesNotCapture(F, 2);
1627 if (Name == "\1__isoc99_scanf") {
1628 if (FTy->getNumParams() < 1 ||
1629 !FTy->getParamType(0)->isPointerTy())
1632 setDoesNotCapture(F, 1);
1633 } else if (Name == "\1stat64" ||
1634 Name == "\1lstat64" ||
1635 Name == "\1statvfs64" ||
1636 Name == "\1__isoc99_sscanf") {
1637 if (FTy->getNumParams() < 1 ||
1638 !FTy->getParamType(0)->isPointerTy() ||
1639 !FTy->getParamType(1)->isPointerTy())
1642 setDoesNotCapture(F, 1);
1643 setDoesNotCapture(F, 2);
1644 } else if (Name == "\1fopen64") {
1645 if (FTy->getNumParams() != 2 ||
1646 !FTy->getReturnType()->isPointerTy() ||
1647 !FTy->getParamType(0)->isPointerTy() ||
1648 !FTy->getParamType(1)->isPointerTy())
1651 setDoesNotAlias(F, 0);
1652 setDoesNotCapture(F, 1);
1653 setDoesNotCapture(F, 2);
1654 } else if (Name == "\1fseeko64" ||
1655 Name == "\1ftello64") {
1656 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1659 setDoesNotCapture(F, 1);
1660 } else if (Name == "\1tmpfile64") {
1661 if (!FTy->getReturnType()->isPointerTy())
1664 setDoesNotAlias(F, 0);
1665 } else if (Name == "\1fstat64" ||
1666 Name == "\1fstatvfs64") {
1667 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1670 setDoesNotCapture(F, 2);
1671 } else if (Name == "\1open64") {
1672 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1674 // May throw; "open" is a valid pthread cancellation point.
1675 setDoesNotCapture(F, 1);
1681 /// doInitialization - Add attributes to well-known functions.
1683 bool SimplifyLibCalls::doInitialization(Module &M) {
1685 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1687 if (F.isDeclaration() && F.hasName())
1688 inferPrototypeAttributes(F);
1694 // Additional cases that we need to add to this file:
1697 // * cbrt(expN(X)) -> expN(x/3)
1698 // * cbrt(sqrt(x)) -> pow(x,1/6)
1699 // * cbrt(sqrt(x)) -> pow(x,1/9)
1702 // * exp(log(x)) -> x
1705 // * log(exp(x)) -> x
1706 // * log(x**y) -> y*log(x)
1707 // * log(exp(y)) -> y*log(e)
1708 // * log(exp2(y)) -> y*log(2)
1709 // * log(exp10(y)) -> y*log(10)
1710 // * log(sqrt(x)) -> 0.5*log(x)
1711 // * log(pow(x,y)) -> y*log(x)
1713 // lround, lroundf, lroundl:
1714 // * lround(cnst) -> cnst'
1717 // * pow(exp(x),y) -> exp(x*y)
1718 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1719 // * pow(pow(x,y),z)-> pow(x,y*z)
1721 // round, roundf, roundl:
1722 // * round(cnst) -> cnst'
1725 // * signbit(cnst) -> cnst'
1726 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1728 // sqrt, sqrtf, sqrtl:
1729 // * sqrt(expN(x)) -> expN(x*0.5)
1730 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1731 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1734 // * strchr(p, 0) -> strlen(p)
1736 // * tan(atan(x)) -> x
1738 // trunc, truncf, truncl:
1739 // * trunc(cnst) -> cnst'