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 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
94 /// value is equal or not-equal to zero.
95 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
96 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
98 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
100 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
101 if (C->isNullValue())
103 // Unknown instruction.
109 static bool CallHasFloatingPointArgument(const CallInst *CI) {
110 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
112 if ((*it)->getType()->isFloatingPointTy())
118 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
119 /// comparisons with With.
120 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
121 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
123 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
124 if (IC->isEquality() && IC->getOperand(1) == With)
126 // Unknown instruction.
132 //===----------------------------------------------------------------------===//
133 // String and Memory LibCall Optimizations
134 //===----------------------------------------------------------------------===//
137 //===---------------------------------------===//
138 // 'stpcpy' Optimizations
140 struct StpCpyOpt: public LibCallOptimization {
141 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
143 StpCpyOpt(bool c) : OptChkCall(c) {}
145 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
146 // Verify the "stpcpy" function prototype.
147 unsigned NumParams = OptChkCall ? 3 : 2;
148 FunctionType *FT = Callee->getFunctionType();
149 if (FT->getNumParams() != NumParams ||
150 FT->getReturnType() != FT->getParamType(0) ||
151 FT->getParamType(0) != FT->getParamType(1) ||
152 FT->getParamType(0) != B.getInt8PtrTy())
155 // These optimizations require DataLayout.
158 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
159 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
160 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
161 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
164 // See if we can get the length of the input string.
165 uint64_t Len = GetStringLength(Src);
166 if (Len == 0) return 0;
168 Type *PT = FT->getParamType(0);
169 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
170 Value *DstEnd = B.CreateGEP(Dst,
171 ConstantInt::get(TD->getIntPtrType(PT),
174 // We have enough information to now generate the memcpy call to do the
175 // copy for us. Make a memcpy to copy the nul byte with align = 1.
176 if (!OptChkCall || !EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B,
178 B.CreateMemCpy(Dst, Src, LenV, 1);
183 //===---------------------------------------===//
184 // 'strncpy' Optimizations
186 struct StrNCpyOpt : public LibCallOptimization {
187 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
188 FunctionType *FT = Callee->getFunctionType();
189 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
190 FT->getParamType(0) != FT->getParamType(1) ||
191 FT->getParamType(0) != B.getInt8PtrTy() ||
192 !FT->getParamType(2)->isIntegerTy())
195 Value *Dst = CI->getArgOperand(0);
196 Value *Src = CI->getArgOperand(1);
197 Value *LenOp = CI->getArgOperand(2);
199 // See if we can get the length of the input string.
200 uint64_t SrcLen = GetStringLength(Src);
201 if (SrcLen == 0) return 0;
205 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
206 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
211 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
212 Len = LengthArg->getZExtValue();
216 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
218 // These optimizations require DataLayout.
221 // Let strncpy handle the zero padding
222 if (Len > SrcLen+1) return 0;
224 Type *PT = FT->getParamType(0);
225 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
226 B.CreateMemCpy(Dst, Src,
227 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
233 //===---------------------------------------===//
234 // 'strlen' Optimizations
236 struct StrLenOpt : public LibCallOptimization {
237 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
238 FunctionType *FT = Callee->getFunctionType();
239 if (FT->getNumParams() != 1 ||
240 FT->getParamType(0) != B.getInt8PtrTy() ||
241 !FT->getReturnType()->isIntegerTy())
244 Value *Src = CI->getArgOperand(0);
246 // Constant folding: strlen("xyz") -> 3
247 if (uint64_t Len = GetStringLength(Src))
248 return ConstantInt::get(CI->getType(), Len-1);
250 // strlen(x) != 0 --> *x != 0
251 // strlen(x) == 0 --> *x == 0
252 if (IsOnlyUsedInZeroEqualityComparison(CI))
253 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
259 //===---------------------------------------===//
260 // 'strpbrk' Optimizations
262 struct StrPBrkOpt : public LibCallOptimization {
263 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
264 FunctionType *FT = Callee->getFunctionType();
265 if (FT->getNumParams() != 2 ||
266 FT->getParamType(0) != B.getInt8PtrTy() ||
267 FT->getParamType(1) != FT->getParamType(0) ||
268 FT->getReturnType() != FT->getParamType(0))
272 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
273 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
275 // strpbrk(s, "") -> NULL
276 // strpbrk("", s) -> NULL
277 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
278 return Constant::getNullValue(CI->getType());
281 if (HasS1 && HasS2) {
282 size_t I = S1.find_first_of(S2);
283 if (I == std::string::npos) // No match.
284 return Constant::getNullValue(CI->getType());
286 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
289 // strpbrk(s, "a") -> strchr(s, 'a')
290 if (TD && HasS2 && S2.size() == 1)
291 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
297 //===---------------------------------------===//
298 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
300 struct StrToOpt : public LibCallOptimization {
301 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
302 FunctionType *FT = Callee->getFunctionType();
303 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
304 !FT->getParamType(0)->isPointerTy() ||
305 !FT->getParamType(1)->isPointerTy())
308 Value *EndPtr = CI->getArgOperand(1);
309 if (isa<ConstantPointerNull>(EndPtr)) {
310 // With a null EndPtr, this function won't capture the main argument.
311 // It would be readonly too, except that it still may write to errno.
312 CI->addAttribute(1, Attributes::get(Callee->getContext(),
313 Attributes::NoCapture));
320 //===---------------------------------------===//
321 // 'strspn' Optimizations
323 struct StrSpnOpt : public LibCallOptimization {
324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
325 FunctionType *FT = Callee->getFunctionType();
326 if (FT->getNumParams() != 2 ||
327 FT->getParamType(0) != B.getInt8PtrTy() ||
328 FT->getParamType(1) != FT->getParamType(0) ||
329 !FT->getReturnType()->isIntegerTy())
333 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
334 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
336 // strspn(s, "") -> 0
337 // strspn("", s) -> 0
338 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
339 return Constant::getNullValue(CI->getType());
342 if (HasS1 && HasS2) {
343 size_t Pos = S1.find_first_not_of(S2);
344 if (Pos == StringRef::npos) Pos = S1.size();
345 return ConstantInt::get(CI->getType(), Pos);
352 //===---------------------------------------===//
353 // 'strcspn' Optimizations
355 struct StrCSpnOpt : public LibCallOptimization {
356 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
357 FunctionType *FT = Callee->getFunctionType();
358 if (FT->getNumParams() != 2 ||
359 FT->getParamType(0) != B.getInt8PtrTy() ||
360 FT->getParamType(1) != FT->getParamType(0) ||
361 !FT->getReturnType()->isIntegerTy())
365 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
366 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
368 // strcspn("", s) -> 0
369 if (HasS1 && S1.empty())
370 return Constant::getNullValue(CI->getType());
373 if (HasS1 && HasS2) {
374 size_t Pos = S1.find_first_of(S2);
375 if (Pos == StringRef::npos) Pos = S1.size();
376 return ConstantInt::get(CI->getType(), Pos);
379 // strcspn(s, "") -> strlen(s)
380 if (TD && HasS2 && S2.empty())
381 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
387 //===---------------------------------------===//
388 // 'strstr' Optimizations
390 struct StrStrOpt : public LibCallOptimization {
391 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
392 FunctionType *FT = Callee->getFunctionType();
393 if (FT->getNumParams() != 2 ||
394 !FT->getParamType(0)->isPointerTy() ||
395 !FT->getParamType(1)->isPointerTy() ||
396 !FT->getReturnType()->isPointerTy())
399 // fold strstr(x, x) -> x.
400 if (CI->getArgOperand(0) == CI->getArgOperand(1))
401 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
403 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
404 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
405 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
408 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
412 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
414 ICmpInst *Old = cast<ICmpInst>(*UI++);
415 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
416 ConstantInt::getNullValue(StrNCmp->getType()),
418 Old->replaceAllUsesWith(Cmp);
419 Old->eraseFromParent();
424 // See if either input string is a constant string.
425 StringRef SearchStr, ToFindStr;
426 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
427 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
429 // fold strstr(x, "") -> x.
430 if (HasStr2 && ToFindStr.empty())
431 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
433 // If both strings are known, constant fold it.
434 if (HasStr1 && HasStr2) {
435 std::string::size_type Offset = SearchStr.find(ToFindStr);
437 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
438 return Constant::getNullValue(CI->getType());
440 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
441 Value *Result = CastToCStr(CI->getArgOperand(0), B);
442 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
443 return B.CreateBitCast(Result, CI->getType());
446 // fold strstr(x, "y") -> strchr(x, 'y').
447 if (HasStr2 && ToFindStr.size() == 1) {
448 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
449 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
456 //===---------------------------------------===//
457 // 'memcmp' Optimizations
459 struct MemCmpOpt : public LibCallOptimization {
460 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
461 FunctionType *FT = Callee->getFunctionType();
462 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
463 !FT->getParamType(1)->isPointerTy() ||
464 !FT->getReturnType()->isIntegerTy(32))
467 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
469 if (LHS == RHS) // memcmp(s,s,x) -> 0
470 return Constant::getNullValue(CI->getType());
472 // Make sure we have a constant length.
473 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
475 uint64_t Len = LenC->getZExtValue();
477 if (Len == 0) // memcmp(s1,s2,0) -> 0
478 return Constant::getNullValue(CI->getType());
480 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
482 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
483 CI->getType(), "lhsv");
484 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
485 CI->getType(), "rhsv");
486 return B.CreateSub(LHSV, RHSV, "chardiff");
489 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
490 StringRef LHSStr, RHSStr;
491 if (getConstantStringInfo(LHS, LHSStr) &&
492 getConstantStringInfo(RHS, RHSStr)) {
493 // Make sure we're not reading out-of-bounds memory.
494 if (Len > LHSStr.size() || Len > RHSStr.size())
496 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
497 return ConstantInt::get(CI->getType(), Ret);
504 //===---------------------------------------===//
505 // 'memcpy' Optimizations
507 struct MemCpyOpt : public LibCallOptimization {
508 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
509 // These optimizations require DataLayout.
512 FunctionType *FT = Callee->getFunctionType();
513 Type *PT = FT->getParamType(0);
514 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
515 !FT->getParamType(0)->isPointerTy() ||
516 !FT->getParamType(1)->isPointerTy() ||
517 FT->getParamType(2) != TD->getIntPtrType(PT))
520 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
521 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
522 CI->getArgOperand(2), 1);
523 return CI->getArgOperand(0);
527 //===---------------------------------------===//
528 // 'memmove' Optimizations
530 struct MemMoveOpt : public LibCallOptimization {
531 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
532 // These optimizations require DataLayout.
535 FunctionType *FT = Callee->getFunctionType();
536 Type *PT = FT->getParamType(0);
537 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
538 !FT->getParamType(0)->isPointerTy() ||
539 !FT->getParamType(1)->isPointerTy() ||
540 FT->getParamType(2) != TD->getIntPtrType(PT))
543 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
544 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
545 CI->getArgOperand(2), 1);
546 return CI->getArgOperand(0);
550 //===---------------------------------------===//
551 // 'memset' Optimizations
553 struct MemSetOpt : public LibCallOptimization {
554 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
555 // These optimizations require DataLayout.
558 FunctionType *FT = Callee->getFunctionType();
559 Type *PT = FT->getParamType(0);
560 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
561 !FT->getParamType(0)->isPointerTy() ||
562 !FT->getParamType(1)->isIntegerTy() ||
563 FT->getParamType(2) != TD->getIntPtrType(PT))
566 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
567 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
568 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
569 return CI->getArgOperand(0);
573 //===----------------------------------------------------------------------===//
574 // Math Library Optimizations
575 //===----------------------------------------------------------------------===//
577 //===---------------------------------------===//
578 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
580 struct UnaryDoubleFPOpt : public LibCallOptimization {
582 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
583 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
584 FunctionType *FT = Callee->getFunctionType();
585 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
586 !FT->getParamType(0)->isDoubleTy())
590 // Check if all the uses for function like 'sin' are converted to float.
591 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
593 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
594 if (Cast == 0 || !Cast->getType()->isFloatTy())
599 // If this is something like 'floor((double)floatval)', convert to floorf.
600 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
601 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
604 // floor((double)floatval) -> (double)floorf(floatval)
605 Value *V = Cast->getOperand(0);
606 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
607 return B.CreateFPExt(V, B.getDoubleTy());
611 //===---------------------------------------===//
612 // 'cos*' Optimizations
613 struct CosOpt : public LibCallOptimization {
614 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
616 if (UnsafeFPShrink && Callee->getName() == "cos" &&
617 TLI->has(LibFunc::cosf)) {
618 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
619 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
622 FunctionType *FT = Callee->getFunctionType();
623 // Just make sure this has 1 argument of FP type, which matches the
625 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
626 !FT->getParamType(0)->isFloatingPointTy())
630 Value *Op1 = CI->getArgOperand(0);
631 if (BinaryOperator::isFNeg(Op1)) {
632 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
633 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
639 //===---------------------------------------===//
640 // 'pow*' Optimizations
642 struct PowOpt : public LibCallOptimization {
643 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
645 if (UnsafeFPShrink && Callee->getName() == "pow" &&
646 TLI->has(LibFunc::powf)) {
647 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
648 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
651 FunctionType *FT = Callee->getFunctionType();
652 // Just make sure this has 2 arguments of the same FP type, which match the
654 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
655 FT->getParamType(0) != FT->getParamType(1) ||
656 !FT->getParamType(0)->isFloatingPointTy())
659 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
660 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
661 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
663 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
664 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
667 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
668 if (Op2C == 0) return Ret;
670 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
671 return ConstantFP::get(CI->getType(), 1.0);
673 if (Op2C->isExactlyValue(0.5)) {
674 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
675 // This is faster than calling pow, and still handles negative zero
676 // and negative infinity correctly.
677 // TODO: In fast-math mode, this could be just sqrt(x).
678 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
679 Value *Inf = ConstantFP::getInfinity(CI->getType());
680 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
681 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
682 Callee->getAttributes());
683 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
684 Callee->getAttributes());
685 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
686 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
690 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
692 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
693 return B.CreateFMul(Op1, Op1, "pow2");
694 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
695 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
701 //===---------------------------------------===//
702 // 'exp2' Optimizations
704 struct Exp2Opt : public LibCallOptimization {
705 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
707 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
708 TLI->has(LibFunc::exp2)) {
709 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
710 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
713 FunctionType *FT = Callee->getFunctionType();
714 // Just make sure this has 1 argument of FP type, which matches the
716 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
717 !FT->getParamType(0)->isFloatingPointTy())
720 Value *Op = CI->getArgOperand(0);
721 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
722 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
724 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
725 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
726 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
727 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
728 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
729 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
734 if (Op->getType()->isFloatTy())
736 else if (Op->getType()->isDoubleTy())
741 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
742 if (!Op->getType()->isFloatTy())
743 One = ConstantExpr::getFPExtend(One, Op->getType());
745 Module *M = Caller->getParent();
746 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
748 B.getInt32Ty(), NULL);
749 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
750 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
751 CI->setCallingConv(F->getCallingConv());
759 //===----------------------------------------------------------------------===//
760 // Integer Optimizations
761 //===----------------------------------------------------------------------===//
763 //===---------------------------------------===//
764 // 'ffs*' Optimizations
766 struct FFSOpt : public LibCallOptimization {
767 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
768 FunctionType *FT = Callee->getFunctionType();
769 // Just make sure this has 2 arguments of the same FP type, which match the
771 if (FT->getNumParams() != 1 ||
772 !FT->getReturnType()->isIntegerTy(32) ||
773 !FT->getParamType(0)->isIntegerTy())
776 Value *Op = CI->getArgOperand(0);
779 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
780 if (CI->isZero()) // ffs(0) -> 0.
781 return B.getInt32(0);
782 // ffs(c) -> cttz(c)+1
783 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
786 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
787 Type *ArgType = Op->getType();
788 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
789 Intrinsic::cttz, ArgType);
790 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
791 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
792 V = B.CreateIntCast(V, B.getInt32Ty(), false);
794 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
795 return B.CreateSelect(Cond, V, B.getInt32(0));
799 //===---------------------------------------===//
800 // 'isdigit' Optimizations
802 struct IsDigitOpt : public LibCallOptimization {
803 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
804 FunctionType *FT = Callee->getFunctionType();
805 // We require integer(i32)
806 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
807 !FT->getParamType(0)->isIntegerTy(32))
810 // isdigit(c) -> (c-'0') <u 10
811 Value *Op = CI->getArgOperand(0);
812 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
813 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
814 return B.CreateZExt(Op, CI->getType());
818 //===---------------------------------------===//
819 // 'isascii' Optimizations
821 struct IsAsciiOpt : public LibCallOptimization {
822 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
823 FunctionType *FT = Callee->getFunctionType();
824 // We require integer(i32)
825 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
826 !FT->getParamType(0)->isIntegerTy(32))
829 // isascii(c) -> c <u 128
830 Value *Op = CI->getArgOperand(0);
831 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
832 return B.CreateZExt(Op, CI->getType());
836 //===---------------------------------------===//
837 // 'abs', 'labs', 'llabs' Optimizations
839 struct AbsOpt : public LibCallOptimization {
840 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
841 FunctionType *FT = Callee->getFunctionType();
842 // We require integer(integer) where the types agree.
843 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
844 FT->getParamType(0) != FT->getReturnType())
847 // abs(x) -> x >s -1 ? x : -x
848 Value *Op = CI->getArgOperand(0);
849 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
851 Value *Neg = B.CreateNeg(Op, "neg");
852 return B.CreateSelect(Pos, Op, Neg);
857 //===---------------------------------------===//
858 // 'toascii' Optimizations
860 struct ToAsciiOpt : public LibCallOptimization {
861 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
862 FunctionType *FT = Callee->getFunctionType();
863 // We require i32(i32)
864 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
865 !FT->getParamType(0)->isIntegerTy(32))
868 // isascii(c) -> c & 0x7f
869 return B.CreateAnd(CI->getArgOperand(0),
870 ConstantInt::get(CI->getType(),0x7F));
874 //===----------------------------------------------------------------------===//
875 // Formatting and IO Optimizations
876 //===----------------------------------------------------------------------===//
878 //===---------------------------------------===//
879 // 'printf' Optimizations
881 struct PrintFOpt : public LibCallOptimization {
882 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
884 // Check for a fixed format string.
886 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
889 // Empty format string -> noop.
890 if (FormatStr.empty()) // Tolerate printf's declared void.
891 return CI->use_empty() ? (Value*)CI :
892 ConstantInt::get(CI->getType(), 0);
894 // Do not do any of the following transformations if the printf return value
895 // is used, in general the printf return value is not compatible with either
896 // putchar() or puts().
897 if (!CI->use_empty())
900 // printf("x") -> putchar('x'), even for '%'.
901 if (FormatStr.size() == 1) {
902 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
903 if (CI->use_empty() || !Res) return Res;
904 return B.CreateIntCast(Res, CI->getType(), true);
907 // printf("foo\n") --> puts("foo")
908 if (FormatStr[FormatStr.size()-1] == '\n' &&
909 FormatStr.find('%') == std::string::npos) { // no format characters.
910 // Create a string literal with no \n on it. We expect the constant merge
911 // pass to be run after this pass, to merge duplicate strings.
912 FormatStr = FormatStr.drop_back();
913 Value *GV = B.CreateGlobalString(FormatStr, "str");
914 Value *NewCI = EmitPutS(GV, B, TD, TLI);
915 return (CI->use_empty() || !NewCI) ?
917 ConstantInt::get(CI->getType(), FormatStr.size()+1);
920 // Optimize specific format strings.
921 // printf("%c", chr) --> putchar(chr)
922 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
923 CI->getArgOperand(1)->getType()->isIntegerTy()) {
924 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
926 if (CI->use_empty() || !Res) return Res;
927 return B.CreateIntCast(Res, CI->getType(), true);
930 // printf("%s\n", str) --> puts(str)
931 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
932 CI->getArgOperand(1)->getType()->isPointerTy()) {
933 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
938 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
939 // Require one fixed pointer argument and an integer/void result.
940 FunctionType *FT = Callee->getFunctionType();
941 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
942 !(FT->getReturnType()->isIntegerTy() ||
943 FT->getReturnType()->isVoidTy()))
946 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
950 // printf(format, ...) -> iprintf(format, ...) if no floating point
952 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
953 Module *M = B.GetInsertBlock()->getParent()->getParent();
954 Constant *IPrintFFn =
955 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
956 CallInst *New = cast<CallInst>(CI->clone());
957 New->setCalledFunction(IPrintFFn);
965 //===---------------------------------------===//
966 // 'sprintf' Optimizations
968 struct SPrintFOpt : public LibCallOptimization {
969 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
971 // Check for a fixed format string.
973 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
976 // If we just have a format string (nothing else crazy) transform it.
977 if (CI->getNumArgOperands() == 2) {
978 // Make sure there's no % in the constant array. We could try to handle
979 // %% -> % in the future if we cared.
980 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
981 if (FormatStr[i] == '%')
982 return 0; // we found a format specifier, bail out.
984 // These optimizations require DataLayout.
987 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
988 Type *AT = CI->getArgOperand(0)->getType();
989 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
990 ConstantInt::get(TD->getIntPtrType(AT), // Copy the
991 FormatStr.size() + 1), 1); // nul byte.
992 return ConstantInt::get(CI->getType(), FormatStr.size());
995 // The remaining optimizations require the format string to be "%s" or "%c"
996 // and have an extra operand.
997 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
998 CI->getNumArgOperands() < 3)
1001 // Decode the second character of the format string.
1002 if (FormatStr[1] == 'c') {
1003 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1004 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1005 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1006 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1007 B.CreateStore(V, Ptr);
1008 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1009 B.CreateStore(B.getInt8(0), Ptr);
1011 return ConstantInt::get(CI->getType(), 1);
1014 if (FormatStr[1] == 's') {
1015 // These optimizations require DataLayout.
1018 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1019 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1021 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1024 Value *IncLen = B.CreateAdd(Len,
1025 ConstantInt::get(Len->getType(), 1),
1027 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1029 // The sprintf result is the unincremented number of bytes in the string.
1030 return B.CreateIntCast(Len, CI->getType(), false);
1035 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1036 // Require two fixed pointer arguments and an integer result.
1037 FunctionType *FT = Callee->getFunctionType();
1038 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1039 !FT->getParamType(1)->isPointerTy() ||
1040 !FT->getReturnType()->isIntegerTy())
1043 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1047 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1049 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1050 Module *M = B.GetInsertBlock()->getParent()->getParent();
1051 Constant *SIPrintFFn =
1052 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1053 CallInst *New = cast<CallInst>(CI->clone());
1054 New->setCalledFunction(SIPrintFFn);
1062 //===---------------------------------------===//
1063 // 'fwrite' Optimizations
1065 struct FWriteOpt : public LibCallOptimization {
1066 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1067 // Require a pointer, an integer, an integer, a pointer, returning integer.
1068 FunctionType *FT = Callee->getFunctionType();
1069 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1070 !FT->getParamType(1)->isIntegerTy() ||
1071 !FT->getParamType(2)->isIntegerTy() ||
1072 !FT->getParamType(3)->isPointerTy() ||
1073 !FT->getReturnType()->isIntegerTy())
1076 // Get the element size and count.
1077 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1078 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1079 if (!SizeC || !CountC) return 0;
1080 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1082 // If this is writing zero records, remove the call (it's a noop).
1084 return ConstantInt::get(CI->getType(), 0);
1086 // If this is writing one byte, turn it into fputc.
1087 // This optimisation is only valid, if the return value is unused.
1088 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1089 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1090 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1091 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1098 //===---------------------------------------===//
1099 // 'fputs' Optimizations
1101 struct FPutsOpt : public LibCallOptimization {
1102 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1103 // These optimizations require DataLayout.
1106 // Require two pointers. Also, we can't optimize if return value is used.
1107 FunctionType *FT = Callee->getFunctionType();
1108 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1109 !FT->getParamType(1)->isPointerTy() ||
1113 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1114 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1116 // Known to have no uses (see above).
1117 Type *PT = FT->getParamType(0);
1118 return EmitFWrite(CI->getArgOperand(0),
1119 ConstantInt::get(TD->getIntPtrType(PT), Len-1),
1120 CI->getArgOperand(1), B, TD, TLI);
1124 //===---------------------------------------===//
1125 // 'fprintf' Optimizations
1127 struct FPrintFOpt : public LibCallOptimization {
1128 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1130 // All the optimizations depend on the format string.
1131 StringRef FormatStr;
1132 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1135 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1136 if (CI->getNumArgOperands() == 2) {
1137 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1138 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1139 return 0; // We found a format specifier.
1141 // These optimizations require DataLayout.
1144 Type *AT = CI->getArgOperand(1)->getType();
1145 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1146 ConstantInt::get(TD->getIntPtrType(AT),
1148 CI->getArgOperand(0), B, TD, TLI);
1149 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
1152 // The remaining optimizations require the format string to be "%s" or "%c"
1153 // and have an extra operand.
1154 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1155 CI->getNumArgOperands() < 3)
1158 // Decode the second character of the format string.
1159 if (FormatStr[1] == 'c') {
1160 // fprintf(F, "%c", chr) --> fputc(chr, F)
1161 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1162 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1164 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1167 if (FormatStr[1] == 's') {
1168 // fprintf(F, "%s", str) --> fputs(str, F)
1169 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1171 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1176 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1177 // Require two fixed paramters as pointers and integer result.
1178 FunctionType *FT = Callee->getFunctionType();
1179 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1180 !FT->getParamType(1)->isPointerTy() ||
1181 !FT->getReturnType()->isIntegerTy())
1184 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1188 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1189 // floating point arguments.
1190 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1191 Module *M = B.GetInsertBlock()->getParent()->getParent();
1192 Constant *FIPrintFFn =
1193 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1194 CallInst *New = cast<CallInst>(CI->clone());
1195 New->setCalledFunction(FIPrintFFn);
1203 //===---------------------------------------===//
1204 // 'puts' Optimizations
1206 struct PutsOpt : public LibCallOptimization {
1207 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1208 // Require one fixed pointer argument and an integer/void result.
1209 FunctionType *FT = Callee->getFunctionType();
1210 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1211 !(FT->getReturnType()->isIntegerTy() ||
1212 FT->getReturnType()->isVoidTy()))
1215 // Check for a constant string.
1217 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1220 if (Str.empty() && CI->use_empty()) {
1221 // puts("") -> putchar('\n')
1222 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1223 if (CI->use_empty() || !Res) return Res;
1224 return B.CreateIntCast(Res, CI->getType(), true);
1231 } // end anonymous namespace.
1233 //===----------------------------------------------------------------------===//
1234 // SimplifyLibCalls Pass Implementation
1235 //===----------------------------------------------------------------------===//
1238 /// This pass optimizes well known library functions from libc and libm.
1240 class SimplifyLibCalls : public FunctionPass {
1241 TargetLibraryInfo *TLI;
1243 StringMap<LibCallOptimization*> Optimizations;
1244 // String and Memory LibCall Optimizations
1245 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1247 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1248 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1249 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1250 // Math Library Optimizations
1251 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1252 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
1253 // Integer Optimizations
1254 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1256 // Formatting and IO Optimizations
1257 SPrintFOpt SPrintF; PrintFOpt PrintF;
1258 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1261 bool Modified; // This is only used by doInitialization.
1263 static char ID; // Pass identification
1264 SimplifyLibCalls() : FunctionPass(ID), StpCpy(false), StpCpyChk(true),
1265 UnaryDoubleFP(false), UnsafeUnaryDoubleFP(true) {
1266 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1268 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1269 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1271 void InitOptimizations();
1272 bool runOnFunction(Function &F);
1274 void setDoesNotAccessMemory(Function &F);
1275 void setOnlyReadsMemory(Function &F);
1276 void setDoesNotThrow(Function &F);
1277 void setDoesNotCapture(Function &F, unsigned n);
1278 void setDoesNotAlias(Function &F, unsigned n);
1279 bool doInitialization(Module &M);
1281 void inferPrototypeAttributes(Function &F);
1282 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1283 AU.addRequired<TargetLibraryInfo>();
1286 } // end anonymous namespace.
1288 char SimplifyLibCalls::ID = 0;
1290 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1291 "Simplify well-known library calls", false, false)
1292 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1293 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1294 "Simplify well-known library calls", false, false)
1296 // Public interface to the Simplify LibCalls pass.
1297 FunctionPass *llvm::createSimplifyLibCallsPass() {
1298 return new SimplifyLibCalls();
1301 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1303 Optimizations[TLI->getName(F)] = Opt;
1306 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1307 LibCallOptimization* Opt) {
1308 if (TLI->has(F1) && TLI->has(F2))
1309 Optimizations[TLI->getName(F1)] = Opt;
1312 /// Optimizations - Populate the Optimizations map with all the optimizations
1314 void SimplifyLibCalls::InitOptimizations() {
1315 // String and Memory LibCall Optimizations
1316 Optimizations["strncpy"] = &StrNCpy;
1317 Optimizations["stpcpy"] = &StpCpy;
1318 Optimizations["strlen"] = &StrLen;
1319 Optimizations["strpbrk"] = &StrPBrk;
1320 Optimizations["strtol"] = &StrTo;
1321 Optimizations["strtod"] = &StrTo;
1322 Optimizations["strtof"] = &StrTo;
1323 Optimizations["strtoul"] = &StrTo;
1324 Optimizations["strtoll"] = &StrTo;
1325 Optimizations["strtold"] = &StrTo;
1326 Optimizations["strtoull"] = &StrTo;
1327 Optimizations["strspn"] = &StrSpn;
1328 Optimizations["strcspn"] = &StrCSpn;
1329 Optimizations["strstr"] = &StrStr;
1330 Optimizations["memcmp"] = &MemCmp;
1331 AddOpt(LibFunc::memcpy, &MemCpy);
1332 Optimizations["memmove"] = &MemMove;
1333 AddOpt(LibFunc::memset, &MemSet);
1335 // _chk variants of String and Memory LibCall Optimizations.
1336 Optimizations["__stpcpy_chk"] = &StpCpyChk;
1338 // Math Library Optimizations
1339 Optimizations["cosf"] = &Cos;
1340 Optimizations["cos"] = &Cos;
1341 Optimizations["cosl"] = &Cos;
1342 Optimizations["powf"] = &Pow;
1343 Optimizations["pow"] = &Pow;
1344 Optimizations["powl"] = &Pow;
1345 Optimizations["llvm.pow.f32"] = &Pow;
1346 Optimizations["llvm.pow.f64"] = &Pow;
1347 Optimizations["llvm.pow.f80"] = &Pow;
1348 Optimizations["llvm.pow.f128"] = &Pow;
1349 Optimizations["llvm.pow.ppcf128"] = &Pow;
1350 Optimizations["exp2l"] = &Exp2;
1351 Optimizations["exp2"] = &Exp2;
1352 Optimizations["exp2f"] = &Exp2;
1353 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1354 Optimizations["llvm.exp2.f128"] = &Exp2;
1355 Optimizations["llvm.exp2.f80"] = &Exp2;
1356 Optimizations["llvm.exp2.f64"] = &Exp2;
1357 Optimizations["llvm.exp2.f32"] = &Exp2;
1359 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1360 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
1361 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1362 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1363 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1364 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1365 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
1367 if(UnsafeFPShrink) {
1368 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1369 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1370 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1371 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1372 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1373 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1374 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1375 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1376 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1377 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1378 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1379 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1380 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1381 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1382 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1383 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1384 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1385 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1386 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1387 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1388 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1391 // Integer Optimizations
1392 Optimizations["ffs"] = &FFS;
1393 Optimizations["ffsl"] = &FFS;
1394 Optimizations["ffsll"] = &FFS;
1395 Optimizations["abs"] = &Abs;
1396 Optimizations["labs"] = &Abs;
1397 Optimizations["llabs"] = &Abs;
1398 Optimizations["isdigit"] = &IsDigit;
1399 Optimizations["isascii"] = &IsAscii;
1400 Optimizations["toascii"] = &ToAscii;
1402 // Formatting and IO Optimizations
1403 Optimizations["sprintf"] = &SPrintF;
1404 Optimizations["printf"] = &PrintF;
1405 AddOpt(LibFunc::fwrite, &FWrite);
1406 AddOpt(LibFunc::fputs, &FPuts);
1407 Optimizations["fprintf"] = &FPrintF;
1408 Optimizations["puts"] = &Puts;
1412 /// runOnFunction - Top level algorithm.
1414 bool SimplifyLibCalls::runOnFunction(Function &F) {
1415 TLI = &getAnalysis<TargetLibraryInfo>();
1417 if (Optimizations.empty())
1418 InitOptimizations();
1420 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
1422 IRBuilder<> Builder(F.getContext());
1424 bool Changed = false;
1425 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1426 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1427 // Ignore non-calls.
1428 CallInst *CI = dyn_cast<CallInst>(I++);
1431 // Ignore indirect calls and calls to non-external functions.
1432 Function *Callee = CI->getCalledFunction();
1433 if (Callee == 0 || !Callee->isDeclaration() ||
1434 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1437 // Ignore unknown calls.
1438 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1441 // Set the builder to the instruction after the call.
1442 Builder.SetInsertPoint(BB, I);
1444 // Use debug location of CI for all new instructions.
1445 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1447 // Try to optimize this call.
1448 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1449 if (Result == 0) continue;
1451 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1452 dbgs() << " into: " << *Result << "\n");
1454 // Something changed!
1458 // Inspect the instruction after the call (which was potentially just
1462 if (CI != Result && !CI->use_empty()) {
1463 CI->replaceAllUsesWith(Result);
1464 if (!Result->hasName())
1465 Result->takeName(CI);
1467 CI->eraseFromParent();
1473 // Utility methods for doInitialization.
1475 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1476 if (!F.doesNotAccessMemory()) {
1477 F.setDoesNotAccessMemory();
1482 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1483 if (!F.onlyReadsMemory()) {
1484 F.setOnlyReadsMemory();
1489 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1490 if (!F.doesNotThrow()) {
1491 F.setDoesNotThrow();
1496 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1497 if (!F.doesNotCapture(n)) {
1498 F.setDoesNotCapture(n);
1503 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1504 if (!F.doesNotAlias(n)) {
1505 F.setDoesNotAlias(n);
1512 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1513 FunctionType *FTy = F.getFunctionType();
1515 StringRef Name = F.getName();
1518 if (Name == "strlen") {
1519 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1521 setOnlyReadsMemory(F);
1523 setDoesNotCapture(F, 1);
1524 } else if (Name == "strchr" ||
1525 Name == "strrchr") {
1526 if (FTy->getNumParams() != 2 ||
1527 !FTy->getParamType(0)->isPointerTy() ||
1528 !FTy->getParamType(1)->isIntegerTy())
1530 setOnlyReadsMemory(F);
1532 } else if (Name == "strcpy" ||
1538 Name == "strtoul" ||
1539 Name == "strtoll" ||
1540 Name == "strtold" ||
1541 Name == "strncat" ||
1542 Name == "strncpy" ||
1543 Name == "stpncpy" ||
1544 Name == "strtoull") {
1545 if (FTy->getNumParams() < 2 ||
1546 !FTy->getParamType(1)->isPointerTy())
1549 setDoesNotCapture(F, 2);
1550 } else if (Name == "strxfrm") {
1551 if (FTy->getNumParams() != 3 ||
1552 !FTy->getParamType(0)->isPointerTy() ||
1553 !FTy->getParamType(1)->isPointerTy())
1556 setDoesNotCapture(F, 1);
1557 setDoesNotCapture(F, 2);
1558 } else if (Name == "strcmp" ||
1560 Name == "strncmp" ||
1561 Name == "strcspn" ||
1562 Name == "strcoll" ||
1563 Name == "strcasecmp" ||
1564 Name == "strncasecmp") {
1565 if (FTy->getNumParams() < 2 ||
1566 !FTy->getParamType(0)->isPointerTy() ||
1567 !FTy->getParamType(1)->isPointerTy())
1569 setOnlyReadsMemory(F);
1571 setDoesNotCapture(F, 1);
1572 setDoesNotCapture(F, 2);
1573 } else if (Name == "strstr" ||
1574 Name == "strpbrk") {
1575 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1577 setOnlyReadsMemory(F);
1579 setDoesNotCapture(F, 2);
1580 } else if (Name == "strtok" ||
1581 Name == "strtok_r") {
1582 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1585 setDoesNotCapture(F, 2);
1586 } else if (Name == "scanf" ||
1588 Name == "setvbuf") {
1589 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1592 setDoesNotCapture(F, 1);
1593 } else if (Name == "strdup" ||
1594 Name == "strndup") {
1595 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1596 !FTy->getParamType(0)->isPointerTy())
1599 setDoesNotAlias(F, 0);
1600 setDoesNotCapture(F, 1);
1601 } else if (Name == "stat" ||
1603 Name == "sprintf" ||
1604 Name == "statvfs") {
1605 if (FTy->getNumParams() < 2 ||
1606 !FTy->getParamType(0)->isPointerTy() ||
1607 !FTy->getParamType(1)->isPointerTy())
1610 setDoesNotCapture(F, 1);
1611 setDoesNotCapture(F, 2);
1612 } else if (Name == "snprintf") {
1613 if (FTy->getNumParams() != 3 ||
1614 !FTy->getParamType(0)->isPointerTy() ||
1615 !FTy->getParamType(2)->isPointerTy())
1618 setDoesNotCapture(F, 1);
1619 setDoesNotCapture(F, 3);
1620 } else if (Name == "setitimer") {
1621 if (FTy->getNumParams() != 3 ||
1622 !FTy->getParamType(1)->isPointerTy() ||
1623 !FTy->getParamType(2)->isPointerTy())
1626 setDoesNotCapture(F, 2);
1627 setDoesNotCapture(F, 3);
1628 } else if (Name == "system") {
1629 if (FTy->getNumParams() != 1 ||
1630 !FTy->getParamType(0)->isPointerTy())
1632 // May throw; "system" is a valid pthread cancellation point.
1633 setDoesNotCapture(F, 1);
1637 if (Name == "malloc") {
1638 if (FTy->getNumParams() != 1 ||
1639 !FTy->getReturnType()->isPointerTy())
1642 setDoesNotAlias(F, 0);
1643 } else if (Name == "memcmp") {
1644 if (FTy->getNumParams() != 3 ||
1645 !FTy->getParamType(0)->isPointerTy() ||
1646 !FTy->getParamType(1)->isPointerTy())
1648 setOnlyReadsMemory(F);
1650 setDoesNotCapture(F, 1);
1651 setDoesNotCapture(F, 2);
1652 } else if (Name == "memchr" ||
1653 Name == "memrchr") {
1654 if (FTy->getNumParams() != 3)
1656 setOnlyReadsMemory(F);
1658 } else if (Name == "modf" ||
1662 Name == "memccpy" ||
1663 Name == "memmove") {
1664 if (FTy->getNumParams() < 2 ||
1665 !FTy->getParamType(1)->isPointerTy())
1668 setDoesNotCapture(F, 2);
1669 } else if (Name == "memalign") {
1670 if (!FTy->getReturnType()->isPointerTy())
1672 setDoesNotAlias(F, 0);
1673 } else if (Name == "mkdir" ||
1675 if (FTy->getNumParams() == 0 ||
1676 !FTy->getParamType(0)->isPointerTy())
1679 setDoesNotCapture(F, 1);
1683 if (Name == "realloc") {
1684 if (FTy->getNumParams() != 2 ||
1685 !FTy->getParamType(0)->isPointerTy() ||
1686 !FTy->getReturnType()->isPointerTy())
1689 setDoesNotAlias(F, 0);
1690 setDoesNotCapture(F, 1);
1691 } else if (Name == "read") {
1692 if (FTy->getNumParams() != 3 ||
1693 !FTy->getParamType(1)->isPointerTy())
1695 // May throw; "read" is a valid pthread cancellation point.
1696 setDoesNotCapture(F, 2);
1697 } else if (Name == "rmdir" ||
1700 Name == "realpath") {
1701 if (FTy->getNumParams() < 1 ||
1702 !FTy->getParamType(0)->isPointerTy())
1705 setDoesNotCapture(F, 1);
1706 } else if (Name == "rename" ||
1707 Name == "readlink") {
1708 if (FTy->getNumParams() < 2 ||
1709 !FTy->getParamType(0)->isPointerTy() ||
1710 !FTy->getParamType(1)->isPointerTy())
1713 setDoesNotCapture(F, 1);
1714 setDoesNotCapture(F, 2);
1718 if (Name == "write") {
1719 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1721 // May throw; "write" is a valid pthread cancellation point.
1722 setDoesNotCapture(F, 2);
1726 if (Name == "bcopy") {
1727 if (FTy->getNumParams() != 3 ||
1728 !FTy->getParamType(0)->isPointerTy() ||
1729 !FTy->getParamType(1)->isPointerTy())
1732 setDoesNotCapture(F, 1);
1733 setDoesNotCapture(F, 2);
1734 } else if (Name == "bcmp") {
1735 if (FTy->getNumParams() != 3 ||
1736 !FTy->getParamType(0)->isPointerTy() ||
1737 !FTy->getParamType(1)->isPointerTy())
1740 setOnlyReadsMemory(F);
1741 setDoesNotCapture(F, 1);
1742 setDoesNotCapture(F, 2);
1743 } else if (Name == "bzero") {
1744 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1747 setDoesNotCapture(F, 1);
1751 if (Name == "calloc") {
1752 if (FTy->getNumParams() != 2 ||
1753 !FTy->getReturnType()->isPointerTy())
1756 setDoesNotAlias(F, 0);
1757 } else if (Name == "chmod" ||
1759 Name == "ctermid" ||
1760 Name == "clearerr" ||
1761 Name == "closedir") {
1762 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1765 setDoesNotCapture(F, 1);
1769 if (Name == "atoi" ||
1773 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1776 setOnlyReadsMemory(F);
1777 setDoesNotCapture(F, 1);
1778 } else if (Name == "access") {
1779 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1782 setDoesNotCapture(F, 1);
1786 if (Name == "fopen") {
1787 if (FTy->getNumParams() != 2 ||
1788 !FTy->getReturnType()->isPointerTy() ||
1789 !FTy->getParamType(0)->isPointerTy() ||
1790 !FTy->getParamType(1)->isPointerTy())
1793 setDoesNotAlias(F, 0);
1794 setDoesNotCapture(F, 1);
1795 setDoesNotCapture(F, 2);
1796 } else if (Name == "fdopen") {
1797 if (FTy->getNumParams() != 2 ||
1798 !FTy->getReturnType()->isPointerTy() ||
1799 !FTy->getParamType(1)->isPointerTy())
1802 setDoesNotAlias(F, 0);
1803 setDoesNotCapture(F, 2);
1804 } else if (Name == "feof" ||
1814 Name == "fsetpos" ||
1815 Name == "flockfile" ||
1816 Name == "funlockfile" ||
1817 Name == "ftrylockfile") {
1818 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1821 setDoesNotCapture(F, 1);
1822 } else if (Name == "ferror") {
1823 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1826 setDoesNotCapture(F, 1);
1827 setOnlyReadsMemory(F);
1828 } else if (Name == "fputc" ||
1833 Name == "fstatvfs") {
1834 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1837 setDoesNotCapture(F, 2);
1838 } else if (Name == "fgets") {
1839 if (FTy->getNumParams() != 3 ||
1840 !FTy->getParamType(0)->isPointerTy() ||
1841 !FTy->getParamType(2)->isPointerTy())
1844 setDoesNotCapture(F, 3);
1845 } else if (Name == "fread" ||
1847 if (FTy->getNumParams() != 4 ||
1848 !FTy->getParamType(0)->isPointerTy() ||
1849 !FTy->getParamType(3)->isPointerTy())
1852 setDoesNotCapture(F, 1);
1853 setDoesNotCapture(F, 4);
1854 } else if (Name == "fputs" ||
1856 Name == "fprintf" ||
1857 Name == "fgetpos") {
1858 if (FTy->getNumParams() < 2 ||
1859 !FTy->getParamType(0)->isPointerTy() ||
1860 !FTy->getParamType(1)->isPointerTy())
1863 setDoesNotCapture(F, 1);
1864 setDoesNotCapture(F, 2);
1868 if (Name == "getc" ||
1869 Name == "getlogin_r" ||
1870 Name == "getc_unlocked") {
1871 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1874 setDoesNotCapture(F, 1);
1875 } else if (Name == "getenv") {
1876 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1879 setOnlyReadsMemory(F);
1880 setDoesNotCapture(F, 1);
1881 } else if (Name == "gets" ||
1882 Name == "getchar") {
1884 } else if (Name == "getitimer") {
1885 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1888 setDoesNotCapture(F, 2);
1889 } else if (Name == "getpwnam") {
1890 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1893 setDoesNotCapture(F, 1);
1897 if (Name == "ungetc") {
1898 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1901 setDoesNotCapture(F, 2);
1902 } else if (Name == "uname" ||
1904 Name == "unsetenv") {
1905 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1908 setDoesNotCapture(F, 1);
1909 } else if (Name == "utime" ||
1911 if (FTy->getNumParams() != 2 ||
1912 !FTy->getParamType(0)->isPointerTy() ||
1913 !FTy->getParamType(1)->isPointerTy())
1916 setDoesNotCapture(F, 1);
1917 setDoesNotCapture(F, 2);
1921 if (Name == "putc") {
1922 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1925 setDoesNotCapture(F, 2);
1926 } else if (Name == "puts" ||
1929 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1932 setDoesNotCapture(F, 1);
1933 } else if (Name == "pread" ||
1935 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1937 // May throw; these are valid pthread cancellation points.
1938 setDoesNotCapture(F, 2);
1939 } else if (Name == "putchar") {
1941 } else if (Name == "popen") {
1942 if (FTy->getNumParams() != 2 ||
1943 !FTy->getReturnType()->isPointerTy() ||
1944 !FTy->getParamType(0)->isPointerTy() ||
1945 !FTy->getParamType(1)->isPointerTy())
1948 setDoesNotAlias(F, 0);
1949 setDoesNotCapture(F, 1);
1950 setDoesNotCapture(F, 2);
1951 } else if (Name == "pclose") {
1952 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1955 setDoesNotCapture(F, 1);
1959 if (Name == "vscanf") {
1960 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1963 setDoesNotCapture(F, 1);
1964 } else if (Name == "vsscanf" ||
1965 Name == "vfscanf") {
1966 if (FTy->getNumParams() != 3 ||
1967 !FTy->getParamType(1)->isPointerTy() ||
1968 !FTy->getParamType(2)->isPointerTy())
1971 setDoesNotCapture(F, 1);
1972 setDoesNotCapture(F, 2);
1973 } else if (Name == "valloc") {
1974 if (!FTy->getReturnType()->isPointerTy())
1977 setDoesNotAlias(F, 0);
1978 } else if (Name == "vprintf") {
1979 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1982 setDoesNotCapture(F, 1);
1983 } else if (Name == "vfprintf" ||
1984 Name == "vsprintf") {
1985 if (FTy->getNumParams() != 3 ||
1986 !FTy->getParamType(0)->isPointerTy() ||
1987 !FTy->getParamType(1)->isPointerTy())
1990 setDoesNotCapture(F, 1);
1991 setDoesNotCapture(F, 2);
1992 } else if (Name == "vsnprintf") {
1993 if (FTy->getNumParams() != 4 ||
1994 !FTy->getParamType(0)->isPointerTy() ||
1995 !FTy->getParamType(2)->isPointerTy())
1998 setDoesNotCapture(F, 1);
1999 setDoesNotCapture(F, 3);
2003 if (Name == "open") {
2004 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2006 // May throw; "open" is a valid pthread cancellation point.
2007 setDoesNotCapture(F, 1);
2008 } else if (Name == "opendir") {
2009 if (FTy->getNumParams() != 1 ||
2010 !FTy->getReturnType()->isPointerTy() ||
2011 !FTy->getParamType(0)->isPointerTy())
2014 setDoesNotAlias(F, 0);
2015 setDoesNotCapture(F, 1);
2019 if (Name == "tmpfile") {
2020 if (!FTy->getReturnType()->isPointerTy())
2023 setDoesNotAlias(F, 0);
2024 } else if (Name == "times") {
2025 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2028 setDoesNotCapture(F, 1);
2032 if (Name == "htonl" ||
2035 setDoesNotAccessMemory(F);
2039 if (Name == "ntohl" ||
2042 setDoesNotAccessMemory(F);
2046 if (Name == "lstat") {
2047 if (FTy->getNumParams() != 2 ||
2048 !FTy->getParamType(0)->isPointerTy() ||
2049 !FTy->getParamType(1)->isPointerTy())
2052 setDoesNotCapture(F, 1);
2053 setDoesNotCapture(F, 2);
2054 } else if (Name == "lchown") {
2055 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2058 setDoesNotCapture(F, 1);
2062 if (Name == "qsort") {
2063 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2065 // May throw; places call through function pointer.
2066 setDoesNotCapture(F, 4);
2070 if (Name == "__strdup" ||
2071 Name == "__strndup") {
2072 if (FTy->getNumParams() < 1 ||
2073 !FTy->getReturnType()->isPointerTy() ||
2074 !FTy->getParamType(0)->isPointerTy())
2077 setDoesNotAlias(F, 0);
2078 setDoesNotCapture(F, 1);
2079 } else if (Name == "__strtok_r") {
2080 if (FTy->getNumParams() != 3 ||
2081 !FTy->getParamType(1)->isPointerTy())
2084 setDoesNotCapture(F, 2);
2085 } else if (Name == "_IO_getc") {
2086 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2089 setDoesNotCapture(F, 1);
2090 } else if (Name == "_IO_putc") {
2091 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2094 setDoesNotCapture(F, 2);
2098 if (Name == "\1__isoc99_scanf") {
2099 if (FTy->getNumParams() < 1 ||
2100 !FTy->getParamType(0)->isPointerTy())
2103 setDoesNotCapture(F, 1);
2104 } else if (Name == "\1stat64" ||
2105 Name == "\1lstat64" ||
2106 Name == "\1statvfs64" ||
2107 Name == "\1__isoc99_sscanf") {
2108 if (FTy->getNumParams() < 1 ||
2109 !FTy->getParamType(0)->isPointerTy() ||
2110 !FTy->getParamType(1)->isPointerTy())
2113 setDoesNotCapture(F, 1);
2114 setDoesNotCapture(F, 2);
2115 } else if (Name == "\1fopen64") {
2116 if (FTy->getNumParams() != 2 ||
2117 !FTy->getReturnType()->isPointerTy() ||
2118 !FTy->getParamType(0)->isPointerTy() ||
2119 !FTy->getParamType(1)->isPointerTy())
2122 setDoesNotAlias(F, 0);
2123 setDoesNotCapture(F, 1);
2124 setDoesNotCapture(F, 2);
2125 } else if (Name == "\1fseeko64" ||
2126 Name == "\1ftello64") {
2127 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2130 setDoesNotCapture(F, 1);
2131 } else if (Name == "\1tmpfile64") {
2132 if (!FTy->getReturnType()->isPointerTy())
2135 setDoesNotAlias(F, 0);
2136 } else if (Name == "\1fstat64" ||
2137 Name == "\1fstatvfs64") {
2138 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2141 setDoesNotCapture(F, 2);
2142 } else if (Name == "\1open64") {
2143 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2145 // May throw; "open" is a valid pthread cancellation point.
2146 setDoesNotCapture(F, 1);
2152 /// doInitialization - Add attributes to well-known functions.
2154 bool SimplifyLibCalls::doInitialization(Module &M) {
2156 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2158 if (F.isDeclaration() && F.hasName())
2159 inferPrototypeAttributes(F);
2165 // Additional cases that we need to add to this file:
2168 // * cbrt(expN(X)) -> expN(x/3)
2169 // * cbrt(sqrt(x)) -> pow(x,1/6)
2170 // * cbrt(sqrt(x)) -> pow(x,1/9)
2173 // * exp(log(x)) -> x
2176 // * log(exp(x)) -> x
2177 // * log(x**y) -> y*log(x)
2178 // * log(exp(y)) -> y*log(e)
2179 // * log(exp2(y)) -> y*log(2)
2180 // * log(exp10(y)) -> y*log(10)
2181 // * log(sqrt(x)) -> 0.5*log(x)
2182 // * log(pow(x,y)) -> y*log(x)
2184 // lround, lroundf, lroundl:
2185 // * lround(cnst) -> cnst'
2188 // * pow(exp(x),y) -> exp(x*y)
2189 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2190 // * pow(pow(x,y),z)-> pow(x,y*z)
2192 // round, roundf, roundl:
2193 // * round(cnst) -> cnst'
2196 // * signbit(cnst) -> cnst'
2197 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2199 // sqrt, sqrtf, sqrtl:
2200 // * sqrt(expN(x)) -> expN(x*0.5)
2201 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2202 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2205 // * strchr(p, 0) -> strlen(p)
2207 // * tan(atan(x)) -> x
2209 // trunc, truncf, truncl:
2210 // * trunc(cnst) -> cnst'