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 //===----------------------------------------------------------------------===//
136 //===---------------------------------------===//
137 // 'strcat' Optimizations
139 struct StrCatOpt : public LibCallOptimization {
140 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
141 // Verify the "strcat" function prototype.
142 FunctionType *FT = Callee->getFunctionType();
143 if (FT->getNumParams() != 2 ||
144 FT->getReturnType() != B.getInt8PtrTy() ||
145 FT->getParamType(0) != FT->getReturnType() ||
146 FT->getParamType(1) != FT->getReturnType())
149 // Extract some information from the instruction
150 Value *Dst = CI->getArgOperand(0);
151 Value *Src = CI->getArgOperand(1);
153 // See if we can get the length of the input string.
154 uint64_t Len = GetStringLength(Src);
155 if (Len == 0) return 0;
156 --Len; // Unbias length.
158 // Handle the simple, do-nothing case: strcat(x, "") -> x
162 // These optimizations require DataLayout.
165 return EmitStrLenMemCpy(Src, Dst, Len, B);
168 Value *EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
169 // We need to find the end of the destination string. That's where the
170 // memory is to be moved to. We just generate a call to strlen.
171 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
175 // Now that we have the destination's length, we must index into the
176 // destination's pointer to get the actual memcpy destination (end of
177 // the string .. we're concatenating).
178 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
180 // We have enough information to now generate the memcpy call to do the
181 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
182 B.CreateMemCpy(CpyDst, Src,
183 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
188 //===---------------------------------------===//
189 // 'strncat' Optimizations
191 struct StrNCatOpt : public StrCatOpt {
192 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
193 // Verify the "strncat" function prototype.
194 FunctionType *FT = Callee->getFunctionType();
195 if (FT->getNumParams() != 3 ||
196 FT->getReturnType() != B.getInt8PtrTy() ||
197 FT->getParamType(0) != FT->getReturnType() ||
198 FT->getParamType(1) != FT->getReturnType() ||
199 !FT->getParamType(2)->isIntegerTy())
202 // Extract some information from the instruction
203 Value *Dst = CI->getArgOperand(0);
204 Value *Src = CI->getArgOperand(1);
207 // We don't do anything if length is not constant
208 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
209 Len = LengthArg->getZExtValue();
213 // See if we can get the length of the input string.
214 uint64_t SrcLen = GetStringLength(Src);
215 if (SrcLen == 0) return 0;
216 --SrcLen; // Unbias length.
218 // Handle the simple, do-nothing cases:
219 // strncat(x, "", c) -> x
220 // strncat(x, c, 0) -> x
221 if (SrcLen == 0 || Len == 0) return Dst;
223 // These optimizations require DataLayout.
226 // We don't optimize this case
227 if (Len < SrcLen) return 0;
229 // strncat(x, s, c) -> strcat(x, s)
230 // s is constant so the strcat can be optimized further
231 return EmitStrLenMemCpy(Src, Dst, SrcLen, B);
235 //===---------------------------------------===//
236 // 'strchr' Optimizations
238 struct StrChrOpt : public LibCallOptimization {
239 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
240 // Verify the "strchr" function prototype.
241 FunctionType *FT = Callee->getFunctionType();
242 if (FT->getNumParams() != 2 ||
243 FT->getReturnType() != B.getInt8PtrTy() ||
244 FT->getParamType(0) != FT->getReturnType() ||
245 !FT->getParamType(1)->isIntegerTy(32))
248 Value *SrcStr = CI->getArgOperand(0);
250 // If the second operand is non-constant, see if we can compute the length
251 // of the input string and turn this into memchr.
252 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
254 // These optimizations require DataLayout.
257 uint64_t Len = GetStringLength(SrcStr);
258 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
261 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
262 ConstantInt::get(TD->getIntPtrType(*Context), Len),
266 // Otherwise, the character is a constant, see if the first argument is
267 // a string literal. If so, we can constant fold.
269 if (!getConstantStringInfo(SrcStr, Str))
272 // Compute the offset, make sure to handle the case when we're searching for
273 // zero (a weird way to spell strlen).
274 size_t I = CharC->getSExtValue() == 0 ?
275 Str.size() : Str.find(CharC->getSExtValue());
276 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
277 return Constant::getNullValue(CI->getType());
279 // strchr(s+n,c) -> gep(s+n+i,c)
280 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
284 //===---------------------------------------===//
285 // 'strrchr' Optimizations
287 struct StrRChrOpt : public LibCallOptimization {
288 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
289 // Verify the "strrchr" function prototype.
290 FunctionType *FT = Callee->getFunctionType();
291 if (FT->getNumParams() != 2 ||
292 FT->getReturnType() != B.getInt8PtrTy() ||
293 FT->getParamType(0) != FT->getReturnType() ||
294 !FT->getParamType(1)->isIntegerTy(32))
297 Value *SrcStr = CI->getArgOperand(0);
298 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
300 // Cannot fold anything if we're not looking for a constant.
305 if (!getConstantStringInfo(SrcStr, Str)) {
306 // strrchr(s, 0) -> strchr(s, 0)
307 if (TD && CharC->isZero())
308 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
312 // Compute the offset.
313 size_t I = CharC->getSExtValue() == 0 ?
314 Str.size() : Str.rfind(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. Return null.
316 return Constant::getNullValue(CI->getType());
318 // strrchr(s+n,c) -> gep(s+n+i,c)
319 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
323 //===---------------------------------------===//
324 // 'strcmp' Optimizations
326 struct StrCmpOpt : public LibCallOptimization {
327 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
328 // Verify the "strcmp" function prototype.
329 FunctionType *FT = Callee->getFunctionType();
330 if (FT->getNumParams() != 2 ||
331 !FT->getReturnType()->isIntegerTy(32) ||
332 FT->getParamType(0) != FT->getParamType(1) ||
333 FT->getParamType(0) != B.getInt8PtrTy())
336 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
337 if (Str1P == Str2P) // strcmp(x,x) -> 0
338 return ConstantInt::get(CI->getType(), 0);
340 StringRef Str1, Str2;
341 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
342 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
344 // strcmp(x, y) -> cnst (if both x and y are constant strings)
345 if (HasStr1 && HasStr2)
346 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
348 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
349 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
352 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
353 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
355 // strcmp(P, "x") -> memcmp(P, "x", 2)
356 uint64_t Len1 = GetStringLength(Str1P);
357 uint64_t Len2 = GetStringLength(Str2P);
359 // These optimizations require DataLayout.
362 return EmitMemCmp(Str1P, Str2P,
363 ConstantInt::get(TD->getIntPtrType(*Context),
364 std::min(Len1, Len2)), B, TD, TLI);
371 //===---------------------------------------===//
372 // 'strncmp' Optimizations
374 struct StrNCmpOpt : public LibCallOptimization {
375 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
376 // Verify the "strncmp" function prototype.
377 FunctionType *FT = Callee->getFunctionType();
378 if (FT->getNumParams() != 3 ||
379 !FT->getReturnType()->isIntegerTy(32) ||
380 FT->getParamType(0) != FT->getParamType(1) ||
381 FT->getParamType(0) != B.getInt8PtrTy() ||
382 !FT->getParamType(2)->isIntegerTy())
385 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
386 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
387 return ConstantInt::get(CI->getType(), 0);
389 // Get the length argument if it is constant.
391 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
392 Length = LengthArg->getZExtValue();
396 if (Length == 0) // strncmp(x,y,0) -> 0
397 return ConstantInt::get(CI->getType(), 0);
399 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
400 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
402 StringRef Str1, Str2;
403 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
404 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
406 // strncmp(x, y) -> cnst (if both x and y are constant strings)
407 if (HasStr1 && HasStr2) {
408 StringRef SubStr1 = Str1.substr(0, Length);
409 StringRef SubStr2 = Str2.substr(0, Length);
410 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
413 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
414 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
417 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
418 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
425 //===---------------------------------------===//
426 // 'strcpy' Optimizations
428 struct StrCpyOpt : public LibCallOptimization {
429 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
431 StrCpyOpt(bool c) : OptChkCall(c) {}
433 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
434 // Verify the "strcpy" function prototype.
435 unsigned NumParams = OptChkCall ? 3 : 2;
436 FunctionType *FT = Callee->getFunctionType();
437 if (FT->getNumParams() != NumParams ||
438 FT->getReturnType() != FT->getParamType(0) ||
439 FT->getParamType(0) != FT->getParamType(1) ||
440 FT->getParamType(0) != B.getInt8PtrTy())
443 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
444 if (Dst == Src) // strcpy(x,x) -> x
447 // These optimizations require DataLayout.
450 // See if we can get the length of the input string.
451 uint64_t Len = GetStringLength(Src);
452 if (Len == 0) return 0;
454 // We have enough information to now generate the memcpy call to do the
455 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
457 !EmitMemCpyChk(Dst, Src,
458 ConstantInt::get(TD->getIntPtrType(*Context), Len),
459 CI->getArgOperand(2), B, TD, TLI))
460 B.CreateMemCpy(Dst, Src,
461 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
466 //===---------------------------------------===//
467 // 'stpcpy' Optimizations
469 struct StpCpyOpt: public LibCallOptimization {
470 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
472 StpCpyOpt(bool c) : OptChkCall(c) {}
474 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
475 // Verify the "stpcpy" function prototype.
476 unsigned NumParams = OptChkCall ? 3 : 2;
477 FunctionType *FT = Callee->getFunctionType();
478 if (FT->getNumParams() != NumParams ||
479 FT->getReturnType() != FT->getParamType(0) ||
480 FT->getParamType(0) != FT->getParamType(1) ||
481 FT->getParamType(0) != B.getInt8PtrTy())
484 // These optimizations require DataLayout.
487 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
488 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
489 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
490 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
493 // See if we can get the length of the input string.
494 uint64_t Len = GetStringLength(Src);
495 if (Len == 0) return 0;
497 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
498 Value *DstEnd = B.CreateGEP(Dst,
499 ConstantInt::get(TD->getIntPtrType(*Context),
502 // We have enough information to now generate the memcpy call to do the
503 // copy for us. Make a memcpy to copy the nul byte with align = 1.
504 if (!OptChkCall || !EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B,
506 B.CreateMemCpy(Dst, Src, LenV, 1);
511 //===---------------------------------------===//
512 // 'strncpy' Optimizations
514 struct StrNCpyOpt : public LibCallOptimization {
515 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
516 FunctionType *FT = Callee->getFunctionType();
517 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
518 FT->getParamType(0) != FT->getParamType(1) ||
519 FT->getParamType(0) != B.getInt8PtrTy() ||
520 !FT->getParamType(2)->isIntegerTy())
523 Value *Dst = CI->getArgOperand(0);
524 Value *Src = CI->getArgOperand(1);
525 Value *LenOp = CI->getArgOperand(2);
527 // See if we can get the length of the input string.
528 uint64_t SrcLen = GetStringLength(Src);
529 if (SrcLen == 0) return 0;
533 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
534 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
539 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
540 Len = LengthArg->getZExtValue();
544 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
546 // These optimizations require DataLayout.
549 // Let strncpy handle the zero padding
550 if (Len > SrcLen+1) return 0;
552 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
553 B.CreateMemCpy(Dst, Src,
554 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
560 //===---------------------------------------===//
561 // 'strlen' Optimizations
563 struct StrLenOpt : public LibCallOptimization {
564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
565 FunctionType *FT = Callee->getFunctionType();
566 if (FT->getNumParams() != 1 ||
567 FT->getParamType(0) != B.getInt8PtrTy() ||
568 !FT->getReturnType()->isIntegerTy())
571 Value *Src = CI->getArgOperand(0);
573 // Constant folding: strlen("xyz") -> 3
574 if (uint64_t Len = GetStringLength(Src))
575 return ConstantInt::get(CI->getType(), Len-1);
577 // strlen(x) != 0 --> *x != 0
578 // strlen(x) == 0 --> *x == 0
579 if (IsOnlyUsedInZeroEqualityComparison(CI))
580 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
586 //===---------------------------------------===//
587 // 'strpbrk' Optimizations
589 struct StrPBrkOpt : public LibCallOptimization {
590 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
591 FunctionType *FT = Callee->getFunctionType();
592 if (FT->getNumParams() != 2 ||
593 FT->getParamType(0) != B.getInt8PtrTy() ||
594 FT->getParamType(1) != FT->getParamType(0) ||
595 FT->getReturnType() != FT->getParamType(0))
599 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
600 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
602 // strpbrk(s, "") -> NULL
603 // strpbrk("", s) -> NULL
604 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
605 return Constant::getNullValue(CI->getType());
608 if (HasS1 && HasS2) {
609 size_t I = S1.find_first_of(S2);
610 if (I == std::string::npos) // No match.
611 return Constant::getNullValue(CI->getType());
613 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
616 // strpbrk(s, "a") -> strchr(s, 'a')
617 if (TD && HasS2 && S2.size() == 1)
618 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
624 //===---------------------------------------===//
625 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
627 struct StrToOpt : public LibCallOptimization {
628 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
629 FunctionType *FT = Callee->getFunctionType();
630 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
631 !FT->getParamType(0)->isPointerTy() ||
632 !FT->getParamType(1)->isPointerTy())
635 Value *EndPtr = CI->getArgOperand(1);
636 if (isa<ConstantPointerNull>(EndPtr)) {
637 // With a null EndPtr, this function won't capture the main argument.
638 // It would be readonly too, except that it still may write to errno.
639 Attributes::Builder B;
640 B.addAttribute(Attributes::NoCapture);
641 CI->addAttribute(1, Attributes::get(B));
648 //===---------------------------------------===//
649 // 'strspn' Optimizations
651 struct StrSpnOpt : public LibCallOptimization {
652 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
653 FunctionType *FT = Callee->getFunctionType();
654 if (FT->getNumParams() != 2 ||
655 FT->getParamType(0) != B.getInt8PtrTy() ||
656 FT->getParamType(1) != FT->getParamType(0) ||
657 !FT->getReturnType()->isIntegerTy())
661 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
662 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
664 // strspn(s, "") -> 0
665 // strspn("", s) -> 0
666 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
667 return Constant::getNullValue(CI->getType());
670 if (HasS1 && HasS2) {
671 size_t Pos = S1.find_first_not_of(S2);
672 if (Pos == StringRef::npos) Pos = S1.size();
673 return ConstantInt::get(CI->getType(), Pos);
680 //===---------------------------------------===//
681 // 'strcspn' Optimizations
683 struct StrCSpnOpt : public LibCallOptimization {
684 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
685 FunctionType *FT = Callee->getFunctionType();
686 if (FT->getNumParams() != 2 ||
687 FT->getParamType(0) != B.getInt8PtrTy() ||
688 FT->getParamType(1) != FT->getParamType(0) ||
689 !FT->getReturnType()->isIntegerTy())
693 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
694 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
696 // strcspn("", s) -> 0
697 if (HasS1 && S1.empty())
698 return Constant::getNullValue(CI->getType());
701 if (HasS1 && HasS2) {
702 size_t Pos = S1.find_first_of(S2);
703 if (Pos == StringRef::npos) Pos = S1.size();
704 return ConstantInt::get(CI->getType(), Pos);
707 // strcspn(s, "") -> strlen(s)
708 if (TD && HasS2 && S2.empty())
709 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
715 //===---------------------------------------===//
716 // 'strstr' Optimizations
718 struct StrStrOpt : public LibCallOptimization {
719 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
720 FunctionType *FT = Callee->getFunctionType();
721 if (FT->getNumParams() != 2 ||
722 !FT->getParamType(0)->isPointerTy() ||
723 !FT->getParamType(1)->isPointerTy() ||
724 !FT->getReturnType()->isPointerTy())
727 // fold strstr(x, x) -> x.
728 if (CI->getArgOperand(0) == CI->getArgOperand(1))
729 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
731 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
732 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
733 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
736 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
740 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
742 ICmpInst *Old = cast<ICmpInst>(*UI++);
743 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
744 ConstantInt::getNullValue(StrNCmp->getType()),
746 Old->replaceAllUsesWith(Cmp);
747 Old->eraseFromParent();
752 // See if either input string is a constant string.
753 StringRef SearchStr, ToFindStr;
754 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
755 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
757 // fold strstr(x, "") -> x.
758 if (HasStr2 && ToFindStr.empty())
759 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
761 // If both strings are known, constant fold it.
762 if (HasStr1 && HasStr2) {
763 std::string::size_type Offset = SearchStr.find(ToFindStr);
765 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
766 return Constant::getNullValue(CI->getType());
768 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
769 Value *Result = CastToCStr(CI->getArgOperand(0), B);
770 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
771 return B.CreateBitCast(Result, CI->getType());
774 // fold strstr(x, "y") -> strchr(x, 'y').
775 if (HasStr2 && ToFindStr.size() == 1) {
776 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
777 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
784 //===---------------------------------------===//
785 // 'memcmp' Optimizations
787 struct MemCmpOpt : public LibCallOptimization {
788 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
789 FunctionType *FT = Callee->getFunctionType();
790 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
791 !FT->getParamType(1)->isPointerTy() ||
792 !FT->getReturnType()->isIntegerTy(32))
795 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
797 if (LHS == RHS) // memcmp(s,s,x) -> 0
798 return Constant::getNullValue(CI->getType());
800 // Make sure we have a constant length.
801 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
803 uint64_t Len = LenC->getZExtValue();
805 if (Len == 0) // memcmp(s1,s2,0) -> 0
806 return Constant::getNullValue(CI->getType());
808 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
810 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
811 CI->getType(), "lhsv");
812 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
813 CI->getType(), "rhsv");
814 return B.CreateSub(LHSV, RHSV, "chardiff");
817 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
818 StringRef LHSStr, RHSStr;
819 if (getConstantStringInfo(LHS, LHSStr) &&
820 getConstantStringInfo(RHS, RHSStr)) {
821 // Make sure we're not reading out-of-bounds memory.
822 if (Len > LHSStr.size() || Len > RHSStr.size())
824 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
825 return ConstantInt::get(CI->getType(), Ret);
832 //===---------------------------------------===//
833 // 'memcpy' Optimizations
835 struct MemCpyOpt : public LibCallOptimization {
836 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
837 // These optimizations require DataLayout.
840 FunctionType *FT = Callee->getFunctionType();
841 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
842 !FT->getParamType(0)->isPointerTy() ||
843 !FT->getParamType(1)->isPointerTy() ||
844 FT->getParamType(2) != TD->getIntPtrType(*Context))
847 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
848 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
849 CI->getArgOperand(2), 1);
850 return CI->getArgOperand(0);
854 //===---------------------------------------===//
855 // 'memmove' Optimizations
857 struct MemMoveOpt : public LibCallOptimization {
858 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
859 // These optimizations require DataLayout.
862 FunctionType *FT = Callee->getFunctionType();
863 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
864 !FT->getParamType(0)->isPointerTy() ||
865 !FT->getParamType(1)->isPointerTy() ||
866 FT->getParamType(2) != TD->getIntPtrType(*Context))
869 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
870 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
871 CI->getArgOperand(2), 1);
872 return CI->getArgOperand(0);
876 //===---------------------------------------===//
877 // 'memset' Optimizations
879 struct MemSetOpt : public LibCallOptimization {
880 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
881 // These optimizations require DataLayout.
884 FunctionType *FT = Callee->getFunctionType();
885 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
886 !FT->getParamType(0)->isPointerTy() ||
887 !FT->getParamType(1)->isIntegerTy() ||
888 FT->getParamType(2) != TD->getIntPtrType(*Context))
891 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
892 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
893 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
894 return CI->getArgOperand(0);
898 //===----------------------------------------------------------------------===//
899 // Math Library Optimizations
900 //===----------------------------------------------------------------------===//
902 //===---------------------------------------===//
903 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
905 struct UnaryDoubleFPOpt : public LibCallOptimization {
907 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
908 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
909 FunctionType *FT = Callee->getFunctionType();
910 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
911 !FT->getParamType(0)->isDoubleTy())
915 // Check if all the uses for function like 'sin' are converted to float.
916 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
918 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
919 if (Cast == 0 || !Cast->getType()->isFloatTy())
924 // If this is something like 'floor((double)floatval)', convert to floorf.
925 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
926 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
929 // floor((double)floatval) -> (double)floorf(floatval)
930 Value *V = Cast->getOperand(0);
931 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
932 return B.CreateFPExt(V, B.getDoubleTy());
936 //===---------------------------------------===//
937 // 'cos*' Optimizations
938 struct CosOpt : public LibCallOptimization {
939 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
941 if (UnsafeFPShrink && Callee->getName() == "cos" &&
942 TLI->has(LibFunc::cosf)) {
943 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
944 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
947 FunctionType *FT = Callee->getFunctionType();
948 // Just make sure this has 1 argument of FP type, which matches the
950 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
951 !FT->getParamType(0)->isFloatingPointTy())
955 Value *Op1 = CI->getArgOperand(0);
956 if (BinaryOperator::isFNeg(Op1)) {
957 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
958 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
964 //===---------------------------------------===//
965 // 'pow*' Optimizations
967 struct PowOpt : public LibCallOptimization {
968 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
970 if (UnsafeFPShrink && Callee->getName() == "pow" &&
971 TLI->has(LibFunc::powf)) {
972 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
973 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
976 FunctionType *FT = Callee->getFunctionType();
977 // Just make sure this has 2 arguments of the same FP type, which match the
979 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
980 FT->getParamType(0) != FT->getParamType(1) ||
981 !FT->getParamType(0)->isFloatingPointTy())
984 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
985 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
986 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
988 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
989 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
992 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
993 if (Op2C == 0) return Ret;
995 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
996 return ConstantFP::get(CI->getType(), 1.0);
998 if (Op2C->isExactlyValue(0.5)) {
999 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1000 // This is faster than calling pow, and still handles negative zero
1001 // and negative infinity correctly.
1002 // TODO: In fast-math mode, this could be just sqrt(x).
1003 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1004 Value *Inf = ConstantFP::getInfinity(CI->getType());
1005 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1006 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1007 Callee->getAttributes());
1008 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1009 Callee->getAttributes());
1010 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1011 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1015 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1017 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1018 return B.CreateFMul(Op1, Op1, "pow2");
1019 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1020 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1026 //===---------------------------------------===//
1027 // 'exp2' Optimizations
1029 struct Exp2Opt : public LibCallOptimization {
1030 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1032 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1033 TLI->has(LibFunc::exp2)) {
1034 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1035 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
1038 FunctionType *FT = Callee->getFunctionType();
1039 // Just make sure this has 1 argument of FP type, which matches the
1041 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1042 !FT->getParamType(0)->isFloatingPointTy())
1045 Value *Op = CI->getArgOperand(0);
1046 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1047 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1048 Value *LdExpArg = 0;
1049 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1050 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1051 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1052 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1053 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1054 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1059 if (Op->getType()->isFloatTy())
1061 else if (Op->getType()->isDoubleTy())
1066 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1067 if (!Op->getType()->isFloatTy())
1068 One = ConstantExpr::getFPExtend(One, Op->getType());
1070 Module *M = Caller->getParent();
1071 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1073 B.getInt32Ty(), NULL);
1074 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1075 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1076 CI->setCallingConv(F->getCallingConv());
1084 //===----------------------------------------------------------------------===//
1085 // Integer Optimizations
1086 //===----------------------------------------------------------------------===//
1088 //===---------------------------------------===//
1089 // 'ffs*' Optimizations
1091 struct FFSOpt : public LibCallOptimization {
1092 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1093 FunctionType *FT = Callee->getFunctionType();
1094 // Just make sure this has 2 arguments of the same FP type, which match the
1096 if (FT->getNumParams() != 1 ||
1097 !FT->getReturnType()->isIntegerTy(32) ||
1098 !FT->getParamType(0)->isIntegerTy())
1101 Value *Op = CI->getArgOperand(0);
1104 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1105 if (CI->getValue() == 0) // ffs(0) -> 0.
1106 return Constant::getNullValue(CI->getType());
1107 // ffs(c) -> cttz(c)+1
1108 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1111 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1112 Type *ArgType = Op->getType();
1113 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1114 Intrinsic::cttz, ArgType);
1115 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1116 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1117 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1119 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1120 return B.CreateSelect(Cond, V, B.getInt32(0));
1124 //===---------------------------------------===//
1125 // 'isdigit' Optimizations
1127 struct IsDigitOpt : public LibCallOptimization {
1128 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1129 FunctionType *FT = Callee->getFunctionType();
1130 // We require integer(i32)
1131 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1132 !FT->getParamType(0)->isIntegerTy(32))
1135 // isdigit(c) -> (c-'0') <u 10
1136 Value *Op = CI->getArgOperand(0);
1137 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1138 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1139 return B.CreateZExt(Op, CI->getType());
1143 //===---------------------------------------===//
1144 // 'isascii' Optimizations
1146 struct IsAsciiOpt : public LibCallOptimization {
1147 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1148 FunctionType *FT = Callee->getFunctionType();
1149 // We require integer(i32)
1150 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1151 !FT->getParamType(0)->isIntegerTy(32))
1154 // isascii(c) -> c <u 128
1155 Value *Op = CI->getArgOperand(0);
1156 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1157 return B.CreateZExt(Op, CI->getType());
1161 //===---------------------------------------===//
1162 // 'abs', 'labs', 'llabs' Optimizations
1164 struct AbsOpt : public LibCallOptimization {
1165 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1166 FunctionType *FT = Callee->getFunctionType();
1167 // We require integer(integer) where the types agree.
1168 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1169 FT->getParamType(0) != FT->getReturnType())
1172 // abs(x) -> x >s -1 ? x : -x
1173 Value *Op = CI->getArgOperand(0);
1174 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1176 Value *Neg = B.CreateNeg(Op, "neg");
1177 return B.CreateSelect(Pos, Op, Neg);
1182 //===---------------------------------------===//
1183 // 'toascii' Optimizations
1185 struct ToAsciiOpt : public LibCallOptimization {
1186 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1187 FunctionType *FT = Callee->getFunctionType();
1188 // We require i32(i32)
1189 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1190 !FT->getParamType(0)->isIntegerTy(32))
1193 // isascii(c) -> c & 0x7f
1194 return B.CreateAnd(CI->getArgOperand(0),
1195 ConstantInt::get(CI->getType(),0x7F));
1199 //===----------------------------------------------------------------------===//
1200 // Formatting and IO Optimizations
1201 //===----------------------------------------------------------------------===//
1203 //===---------------------------------------===//
1204 // 'printf' Optimizations
1206 struct PrintFOpt : public LibCallOptimization {
1207 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1209 // Check for a fixed format string.
1210 StringRef FormatStr;
1211 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1214 // Empty format string -> noop.
1215 if (FormatStr.empty()) // Tolerate printf's declared void.
1216 return CI->use_empty() ? (Value*)CI :
1217 ConstantInt::get(CI->getType(), 0);
1219 // Do not do any of the following transformations if the printf return value
1220 // is used, in general the printf return value is not compatible with either
1221 // putchar() or puts().
1222 if (!CI->use_empty())
1225 // printf("x") -> putchar('x'), even for '%'.
1226 if (FormatStr.size() == 1) {
1227 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1228 if (CI->use_empty() || !Res) return Res;
1229 return B.CreateIntCast(Res, CI->getType(), true);
1232 // printf("foo\n") --> puts("foo")
1233 if (FormatStr[FormatStr.size()-1] == '\n' &&
1234 FormatStr.find('%') == std::string::npos) { // no format characters.
1235 // Create a string literal with no \n on it. We expect the constant merge
1236 // pass to be run after this pass, to merge duplicate strings.
1237 FormatStr = FormatStr.drop_back();
1238 Value *GV = B.CreateGlobalString(FormatStr, "str");
1239 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1240 return (CI->use_empty() || !NewCI) ?
1242 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1245 // Optimize specific format strings.
1246 // printf("%c", chr) --> putchar(chr)
1247 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1248 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1249 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1251 if (CI->use_empty() || !Res) return Res;
1252 return B.CreateIntCast(Res, CI->getType(), true);
1255 // printf("%s\n", str) --> puts(str)
1256 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1257 CI->getArgOperand(1)->getType()->isPointerTy()) {
1258 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1263 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1264 // Require one fixed pointer argument and an integer/void result.
1265 FunctionType *FT = Callee->getFunctionType();
1266 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1267 !(FT->getReturnType()->isIntegerTy() ||
1268 FT->getReturnType()->isVoidTy()))
1271 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1275 // printf(format, ...) -> iprintf(format, ...) if no floating point
1277 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1278 Module *M = B.GetInsertBlock()->getParent()->getParent();
1279 Constant *IPrintFFn =
1280 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1281 CallInst *New = cast<CallInst>(CI->clone());
1282 New->setCalledFunction(IPrintFFn);
1290 //===---------------------------------------===//
1291 // 'sprintf' Optimizations
1293 struct SPrintFOpt : public LibCallOptimization {
1294 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1296 // Check for a fixed format string.
1297 StringRef FormatStr;
1298 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1301 // If we just have a format string (nothing else crazy) transform it.
1302 if (CI->getNumArgOperands() == 2) {
1303 // Make sure there's no % in the constant array. We could try to handle
1304 // %% -> % in the future if we cared.
1305 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1306 if (FormatStr[i] == '%')
1307 return 0; // we found a format specifier, bail out.
1309 // These optimizations require DataLayout.
1312 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1313 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1314 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1315 FormatStr.size() + 1), 1); // nul byte.
1316 return ConstantInt::get(CI->getType(), FormatStr.size());
1319 // The remaining optimizations require the format string to be "%s" or "%c"
1320 // and have an extra operand.
1321 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1322 CI->getNumArgOperands() < 3)
1325 // Decode the second character of the format string.
1326 if (FormatStr[1] == 'c') {
1327 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1328 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1329 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1330 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1331 B.CreateStore(V, Ptr);
1332 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1333 B.CreateStore(B.getInt8(0), Ptr);
1335 return ConstantInt::get(CI->getType(), 1);
1338 if (FormatStr[1] == 's') {
1339 // These optimizations require DataLayout.
1342 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1343 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1345 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1348 Value *IncLen = B.CreateAdd(Len,
1349 ConstantInt::get(Len->getType(), 1),
1351 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1353 // The sprintf result is the unincremented number of bytes in the string.
1354 return B.CreateIntCast(Len, CI->getType(), false);
1359 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1360 // Require two fixed pointer arguments and an integer result.
1361 FunctionType *FT = Callee->getFunctionType();
1362 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1363 !FT->getParamType(1)->isPointerTy() ||
1364 !FT->getReturnType()->isIntegerTy())
1367 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1371 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1373 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1374 Module *M = B.GetInsertBlock()->getParent()->getParent();
1375 Constant *SIPrintFFn =
1376 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1377 CallInst *New = cast<CallInst>(CI->clone());
1378 New->setCalledFunction(SIPrintFFn);
1386 //===---------------------------------------===//
1387 // 'fwrite' Optimizations
1389 struct FWriteOpt : public LibCallOptimization {
1390 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1391 // Require a pointer, an integer, an integer, a pointer, returning integer.
1392 FunctionType *FT = Callee->getFunctionType();
1393 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1394 !FT->getParamType(1)->isIntegerTy() ||
1395 !FT->getParamType(2)->isIntegerTy() ||
1396 !FT->getParamType(3)->isPointerTy() ||
1397 !FT->getReturnType()->isIntegerTy())
1400 // Get the element size and count.
1401 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1402 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1403 if (!SizeC || !CountC) return 0;
1404 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1406 // If this is writing zero records, remove the call (it's a noop).
1408 return ConstantInt::get(CI->getType(), 0);
1410 // If this is writing one byte, turn it into fputc.
1411 // This optimisation is only valid, if the return value is unused.
1412 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1413 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1414 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1415 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1422 //===---------------------------------------===//
1423 // 'fputs' Optimizations
1425 struct FPutsOpt : public LibCallOptimization {
1426 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1427 // These optimizations require DataLayout.
1430 // Require two pointers. Also, we can't optimize if return value is used.
1431 FunctionType *FT = Callee->getFunctionType();
1432 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1433 !FT->getParamType(1)->isPointerTy() ||
1437 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1438 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1440 // Known to have no uses (see above).
1441 return EmitFWrite(CI->getArgOperand(0),
1442 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1443 CI->getArgOperand(1), B, TD, TLI);
1447 //===---------------------------------------===//
1448 // 'fprintf' Optimizations
1450 struct FPrintFOpt : public LibCallOptimization {
1451 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1453 // All the optimizations depend on the format string.
1454 StringRef FormatStr;
1455 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1458 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1459 if (CI->getNumArgOperands() == 2) {
1460 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1461 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1462 return 0; // We found a format specifier.
1464 // These optimizations require DataLayout.
1467 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1468 ConstantInt::get(TD->getIntPtrType(*Context),
1470 CI->getArgOperand(0), B, TD, TLI);
1471 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
1474 // The remaining optimizations require the format string to be "%s" or "%c"
1475 // and have an extra operand.
1476 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1477 CI->getNumArgOperands() < 3)
1480 // Decode the second character of the format string.
1481 if (FormatStr[1] == 'c') {
1482 // fprintf(F, "%c", chr) --> fputc(chr, F)
1483 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1484 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1486 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1489 if (FormatStr[1] == 's') {
1490 // fprintf(F, "%s", str) --> fputs(str, F)
1491 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1493 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1498 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1499 // Require two fixed paramters as pointers and integer result.
1500 FunctionType *FT = Callee->getFunctionType();
1501 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1502 !FT->getParamType(1)->isPointerTy() ||
1503 !FT->getReturnType()->isIntegerTy())
1506 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1510 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1511 // floating point arguments.
1512 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1513 Module *M = B.GetInsertBlock()->getParent()->getParent();
1514 Constant *FIPrintFFn =
1515 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1516 CallInst *New = cast<CallInst>(CI->clone());
1517 New->setCalledFunction(FIPrintFFn);
1525 //===---------------------------------------===//
1526 // 'puts' Optimizations
1528 struct PutsOpt : public LibCallOptimization {
1529 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1530 // Require one fixed pointer argument and an integer/void result.
1531 FunctionType *FT = Callee->getFunctionType();
1532 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1533 !(FT->getReturnType()->isIntegerTy() ||
1534 FT->getReturnType()->isVoidTy()))
1537 // Check for a constant string.
1539 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1542 if (Str.empty() && CI->use_empty()) {
1543 // puts("") -> putchar('\n')
1544 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1545 if (CI->use_empty() || !Res) return Res;
1546 return B.CreateIntCast(Res, CI->getType(), true);
1553 } // end anonymous namespace.
1555 //===----------------------------------------------------------------------===//
1556 // SimplifyLibCalls Pass Implementation
1557 //===----------------------------------------------------------------------===//
1560 /// This pass optimizes well known library functions from libc and libm.
1562 class SimplifyLibCalls : public FunctionPass {
1563 TargetLibraryInfo *TLI;
1565 StringMap<LibCallOptimization*> Optimizations;
1566 // String and Memory LibCall Optimizations
1567 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1568 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1569 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1570 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1572 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1573 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1574 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1575 // Math Library Optimizations
1576 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1577 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
1578 // Integer Optimizations
1579 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1581 // Formatting and IO Optimizations
1582 SPrintFOpt SPrintF; PrintFOpt PrintF;
1583 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1586 bool Modified; // This is only used by doInitialization.
1588 static char ID; // Pass identification
1589 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1590 StpCpy(false), StpCpyChk(true),
1591 UnaryDoubleFP(false), UnsafeUnaryDoubleFP(true) {
1592 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1594 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1595 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1597 void InitOptimizations();
1598 bool runOnFunction(Function &F);
1600 void setDoesNotAccessMemory(Function &F);
1601 void setOnlyReadsMemory(Function &F);
1602 void setDoesNotThrow(Function &F);
1603 void setDoesNotCapture(Function &F, unsigned n);
1604 void setDoesNotAlias(Function &F, unsigned n);
1605 bool doInitialization(Module &M);
1607 void inferPrototypeAttributes(Function &F);
1608 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1609 AU.addRequired<TargetLibraryInfo>();
1612 } // end anonymous namespace.
1614 char SimplifyLibCalls::ID = 0;
1616 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1617 "Simplify well-known library calls", false, false)
1618 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1619 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1620 "Simplify well-known library calls", false, false)
1622 // Public interface to the Simplify LibCalls pass.
1623 FunctionPass *llvm::createSimplifyLibCallsPass() {
1624 return new SimplifyLibCalls();
1627 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1629 Optimizations[TLI->getName(F)] = Opt;
1632 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1633 LibCallOptimization* Opt) {
1634 if (TLI->has(F1) && TLI->has(F2))
1635 Optimizations[TLI->getName(F1)] = Opt;
1638 /// Optimizations - Populate the Optimizations map with all the optimizations
1640 void SimplifyLibCalls::InitOptimizations() {
1641 // String and Memory LibCall Optimizations
1642 Optimizations["strcat"] = &StrCat;
1643 Optimizations["strncat"] = &StrNCat;
1644 Optimizations["strchr"] = &StrChr;
1645 Optimizations["strrchr"] = &StrRChr;
1646 Optimizations["strcmp"] = &StrCmp;
1647 Optimizations["strncmp"] = &StrNCmp;
1648 Optimizations["strcpy"] = &StrCpy;
1649 Optimizations["strncpy"] = &StrNCpy;
1650 Optimizations["stpcpy"] = &StpCpy;
1651 Optimizations["strlen"] = &StrLen;
1652 Optimizations["strpbrk"] = &StrPBrk;
1653 Optimizations["strtol"] = &StrTo;
1654 Optimizations["strtod"] = &StrTo;
1655 Optimizations["strtof"] = &StrTo;
1656 Optimizations["strtoul"] = &StrTo;
1657 Optimizations["strtoll"] = &StrTo;
1658 Optimizations["strtold"] = &StrTo;
1659 Optimizations["strtoull"] = &StrTo;
1660 Optimizations["strspn"] = &StrSpn;
1661 Optimizations["strcspn"] = &StrCSpn;
1662 Optimizations["strstr"] = &StrStr;
1663 Optimizations["memcmp"] = &MemCmp;
1664 AddOpt(LibFunc::memcpy, &MemCpy);
1665 Optimizations["memmove"] = &MemMove;
1666 AddOpt(LibFunc::memset, &MemSet);
1668 // _chk variants of String and Memory LibCall Optimizations.
1669 Optimizations["__strcpy_chk"] = &StrCpyChk;
1670 Optimizations["__stpcpy_chk"] = &StpCpyChk;
1672 // Math Library Optimizations
1673 Optimizations["cosf"] = &Cos;
1674 Optimizations["cos"] = &Cos;
1675 Optimizations["cosl"] = &Cos;
1676 Optimizations["powf"] = &Pow;
1677 Optimizations["pow"] = &Pow;
1678 Optimizations["powl"] = &Pow;
1679 Optimizations["llvm.pow.f32"] = &Pow;
1680 Optimizations["llvm.pow.f64"] = &Pow;
1681 Optimizations["llvm.pow.f80"] = &Pow;
1682 Optimizations["llvm.pow.f128"] = &Pow;
1683 Optimizations["llvm.pow.ppcf128"] = &Pow;
1684 Optimizations["exp2l"] = &Exp2;
1685 Optimizations["exp2"] = &Exp2;
1686 Optimizations["exp2f"] = &Exp2;
1687 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1688 Optimizations["llvm.exp2.f128"] = &Exp2;
1689 Optimizations["llvm.exp2.f80"] = &Exp2;
1690 Optimizations["llvm.exp2.f64"] = &Exp2;
1691 Optimizations["llvm.exp2.f32"] = &Exp2;
1693 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1694 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
1695 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1696 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1697 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1698 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1699 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
1701 if(UnsafeFPShrink) {
1702 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1703 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1704 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1705 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1706 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1707 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1708 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1709 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1710 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1711 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1712 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1713 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1714 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1715 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1716 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1717 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1718 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1719 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1720 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1721 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1722 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1725 // Integer Optimizations
1726 Optimizations["ffs"] = &FFS;
1727 Optimizations["ffsl"] = &FFS;
1728 Optimizations["ffsll"] = &FFS;
1729 Optimizations["abs"] = &Abs;
1730 Optimizations["labs"] = &Abs;
1731 Optimizations["llabs"] = &Abs;
1732 Optimizations["isdigit"] = &IsDigit;
1733 Optimizations["isascii"] = &IsAscii;
1734 Optimizations["toascii"] = &ToAscii;
1736 // Formatting and IO Optimizations
1737 Optimizations["sprintf"] = &SPrintF;
1738 Optimizations["printf"] = &PrintF;
1739 AddOpt(LibFunc::fwrite, &FWrite);
1740 AddOpt(LibFunc::fputs, &FPuts);
1741 Optimizations["fprintf"] = &FPrintF;
1742 Optimizations["puts"] = &Puts;
1746 /// runOnFunction - Top level algorithm.
1748 bool SimplifyLibCalls::runOnFunction(Function &F) {
1749 TLI = &getAnalysis<TargetLibraryInfo>();
1751 if (Optimizations.empty())
1752 InitOptimizations();
1754 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
1756 IRBuilder<> Builder(F.getContext());
1758 bool Changed = false;
1759 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1760 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1761 // Ignore non-calls.
1762 CallInst *CI = dyn_cast<CallInst>(I++);
1765 // Ignore indirect calls and calls to non-external functions.
1766 Function *Callee = CI->getCalledFunction();
1767 if (Callee == 0 || !Callee->isDeclaration() ||
1768 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1771 // Ignore unknown calls.
1772 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1775 // Set the builder to the instruction after the call.
1776 Builder.SetInsertPoint(BB, I);
1778 // Use debug location of CI for all new instructions.
1779 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1781 // Try to optimize this call.
1782 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1783 if (Result == 0) continue;
1785 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1786 dbgs() << " into: " << *Result << "\n");
1788 // Something changed!
1792 // Inspect the instruction after the call (which was potentially just
1796 if (CI != Result && !CI->use_empty()) {
1797 CI->replaceAllUsesWith(Result);
1798 if (!Result->hasName())
1799 Result->takeName(CI);
1801 CI->eraseFromParent();
1807 // Utility methods for doInitialization.
1809 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1810 if (!F.doesNotAccessMemory()) {
1811 F.setDoesNotAccessMemory();
1816 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1817 if (!F.onlyReadsMemory()) {
1818 F.setOnlyReadsMemory();
1823 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1824 if (!F.doesNotThrow()) {
1825 F.setDoesNotThrow();
1830 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1831 if (!F.doesNotCapture(n)) {
1832 F.setDoesNotCapture(n);
1837 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1838 if (!F.doesNotAlias(n)) {
1839 F.setDoesNotAlias(n);
1846 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1847 FunctionType *FTy = F.getFunctionType();
1849 StringRef Name = F.getName();
1852 if (Name == "strlen") {
1853 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1855 setOnlyReadsMemory(F);
1857 setDoesNotCapture(F, 1);
1858 } else if (Name == "strchr" ||
1859 Name == "strrchr") {
1860 if (FTy->getNumParams() != 2 ||
1861 !FTy->getParamType(0)->isPointerTy() ||
1862 !FTy->getParamType(1)->isIntegerTy())
1864 setOnlyReadsMemory(F);
1866 } else if (Name == "strcpy" ||
1872 Name == "strtoul" ||
1873 Name == "strtoll" ||
1874 Name == "strtold" ||
1875 Name == "strncat" ||
1876 Name == "strncpy" ||
1877 Name == "stpncpy" ||
1878 Name == "strtoull") {
1879 if (FTy->getNumParams() < 2 ||
1880 !FTy->getParamType(1)->isPointerTy())
1883 setDoesNotCapture(F, 2);
1884 } else if (Name == "strxfrm") {
1885 if (FTy->getNumParams() != 3 ||
1886 !FTy->getParamType(0)->isPointerTy() ||
1887 !FTy->getParamType(1)->isPointerTy())
1890 setDoesNotCapture(F, 1);
1891 setDoesNotCapture(F, 2);
1892 } else if (Name == "strcmp" ||
1894 Name == "strncmp" ||
1895 Name == "strcspn" ||
1896 Name == "strcoll" ||
1897 Name == "strcasecmp" ||
1898 Name == "strncasecmp") {
1899 if (FTy->getNumParams() < 2 ||
1900 !FTy->getParamType(0)->isPointerTy() ||
1901 !FTy->getParamType(1)->isPointerTy())
1903 setOnlyReadsMemory(F);
1905 setDoesNotCapture(F, 1);
1906 setDoesNotCapture(F, 2);
1907 } else if (Name == "strstr" ||
1908 Name == "strpbrk") {
1909 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1911 setOnlyReadsMemory(F);
1913 setDoesNotCapture(F, 2);
1914 } else if (Name == "strtok" ||
1915 Name == "strtok_r") {
1916 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1919 setDoesNotCapture(F, 2);
1920 } else if (Name == "scanf" ||
1922 Name == "setvbuf") {
1923 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1926 setDoesNotCapture(F, 1);
1927 } else if (Name == "strdup" ||
1928 Name == "strndup") {
1929 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1930 !FTy->getParamType(0)->isPointerTy())
1933 setDoesNotAlias(F, 0);
1934 setDoesNotCapture(F, 1);
1935 } else if (Name == "stat" ||
1937 Name == "sprintf" ||
1938 Name == "statvfs") {
1939 if (FTy->getNumParams() < 2 ||
1940 !FTy->getParamType(0)->isPointerTy() ||
1941 !FTy->getParamType(1)->isPointerTy())
1944 setDoesNotCapture(F, 1);
1945 setDoesNotCapture(F, 2);
1946 } else if (Name == "snprintf") {
1947 if (FTy->getNumParams() != 3 ||
1948 !FTy->getParamType(0)->isPointerTy() ||
1949 !FTy->getParamType(2)->isPointerTy())
1952 setDoesNotCapture(F, 1);
1953 setDoesNotCapture(F, 3);
1954 } else if (Name == "setitimer") {
1955 if (FTy->getNumParams() != 3 ||
1956 !FTy->getParamType(1)->isPointerTy() ||
1957 !FTy->getParamType(2)->isPointerTy())
1960 setDoesNotCapture(F, 2);
1961 setDoesNotCapture(F, 3);
1962 } else if (Name == "system") {
1963 if (FTy->getNumParams() != 1 ||
1964 !FTy->getParamType(0)->isPointerTy())
1966 // May throw; "system" is a valid pthread cancellation point.
1967 setDoesNotCapture(F, 1);
1971 if (Name == "malloc") {
1972 if (FTy->getNumParams() != 1 ||
1973 !FTy->getReturnType()->isPointerTy())
1976 setDoesNotAlias(F, 0);
1977 } else if (Name == "memcmp") {
1978 if (FTy->getNumParams() != 3 ||
1979 !FTy->getParamType(0)->isPointerTy() ||
1980 !FTy->getParamType(1)->isPointerTy())
1982 setOnlyReadsMemory(F);
1984 setDoesNotCapture(F, 1);
1985 setDoesNotCapture(F, 2);
1986 } else if (Name == "memchr" ||
1987 Name == "memrchr") {
1988 if (FTy->getNumParams() != 3)
1990 setOnlyReadsMemory(F);
1992 } else if (Name == "modf" ||
1996 Name == "memccpy" ||
1997 Name == "memmove") {
1998 if (FTy->getNumParams() < 2 ||
1999 !FTy->getParamType(1)->isPointerTy())
2002 setDoesNotCapture(F, 2);
2003 } else if (Name == "memalign") {
2004 if (!FTy->getReturnType()->isPointerTy())
2006 setDoesNotAlias(F, 0);
2007 } else if (Name == "mkdir" ||
2009 if (FTy->getNumParams() == 0 ||
2010 !FTy->getParamType(0)->isPointerTy())
2013 setDoesNotCapture(F, 1);
2017 if (Name == "realloc") {
2018 if (FTy->getNumParams() != 2 ||
2019 !FTy->getParamType(0)->isPointerTy() ||
2020 !FTy->getReturnType()->isPointerTy())
2023 setDoesNotAlias(F, 0);
2024 setDoesNotCapture(F, 1);
2025 } else if (Name == "read") {
2026 if (FTy->getNumParams() != 3 ||
2027 !FTy->getParamType(1)->isPointerTy())
2029 // May throw; "read" is a valid pthread cancellation point.
2030 setDoesNotCapture(F, 2);
2031 } else if (Name == "rmdir" ||
2034 Name == "realpath") {
2035 if (FTy->getNumParams() < 1 ||
2036 !FTy->getParamType(0)->isPointerTy())
2039 setDoesNotCapture(F, 1);
2040 } else if (Name == "rename" ||
2041 Name == "readlink") {
2042 if (FTy->getNumParams() < 2 ||
2043 !FTy->getParamType(0)->isPointerTy() ||
2044 !FTy->getParamType(1)->isPointerTy())
2047 setDoesNotCapture(F, 1);
2048 setDoesNotCapture(F, 2);
2052 if (Name == "write") {
2053 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
2055 // May throw; "write" is a valid pthread cancellation point.
2056 setDoesNotCapture(F, 2);
2060 if (Name == "bcopy") {
2061 if (FTy->getNumParams() != 3 ||
2062 !FTy->getParamType(0)->isPointerTy() ||
2063 !FTy->getParamType(1)->isPointerTy())
2066 setDoesNotCapture(F, 1);
2067 setDoesNotCapture(F, 2);
2068 } else if (Name == "bcmp") {
2069 if (FTy->getNumParams() != 3 ||
2070 !FTy->getParamType(0)->isPointerTy() ||
2071 !FTy->getParamType(1)->isPointerTy())
2074 setOnlyReadsMemory(F);
2075 setDoesNotCapture(F, 1);
2076 setDoesNotCapture(F, 2);
2077 } else if (Name == "bzero") {
2078 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2081 setDoesNotCapture(F, 1);
2085 if (Name == "calloc") {
2086 if (FTy->getNumParams() != 2 ||
2087 !FTy->getReturnType()->isPointerTy())
2090 setDoesNotAlias(F, 0);
2091 } else if (Name == "chmod" ||
2093 Name == "ctermid" ||
2094 Name == "clearerr" ||
2095 Name == "closedir") {
2096 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2099 setDoesNotCapture(F, 1);
2103 if (Name == "atoi" ||
2107 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2110 setOnlyReadsMemory(F);
2111 setDoesNotCapture(F, 1);
2112 } else if (Name == "access") {
2113 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2116 setDoesNotCapture(F, 1);
2120 if (Name == "fopen") {
2121 if (FTy->getNumParams() != 2 ||
2122 !FTy->getReturnType()->isPointerTy() ||
2123 !FTy->getParamType(0)->isPointerTy() ||
2124 !FTy->getParamType(1)->isPointerTy())
2127 setDoesNotAlias(F, 0);
2128 setDoesNotCapture(F, 1);
2129 setDoesNotCapture(F, 2);
2130 } else if (Name == "fdopen") {
2131 if (FTy->getNumParams() != 2 ||
2132 !FTy->getReturnType()->isPointerTy() ||
2133 !FTy->getParamType(1)->isPointerTy())
2136 setDoesNotAlias(F, 0);
2137 setDoesNotCapture(F, 2);
2138 } else if (Name == "feof" ||
2148 Name == "fsetpos" ||
2149 Name == "flockfile" ||
2150 Name == "funlockfile" ||
2151 Name == "ftrylockfile") {
2152 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2155 setDoesNotCapture(F, 1);
2156 } else if (Name == "ferror") {
2157 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2160 setDoesNotCapture(F, 1);
2161 setOnlyReadsMemory(F);
2162 } else if (Name == "fputc" ||
2167 Name == "fstatvfs") {
2168 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2171 setDoesNotCapture(F, 2);
2172 } else if (Name == "fgets") {
2173 if (FTy->getNumParams() != 3 ||
2174 !FTy->getParamType(0)->isPointerTy() ||
2175 !FTy->getParamType(2)->isPointerTy())
2178 setDoesNotCapture(F, 3);
2179 } else if (Name == "fread" ||
2181 if (FTy->getNumParams() != 4 ||
2182 !FTy->getParamType(0)->isPointerTy() ||
2183 !FTy->getParamType(3)->isPointerTy())
2186 setDoesNotCapture(F, 1);
2187 setDoesNotCapture(F, 4);
2188 } else if (Name == "fputs" ||
2190 Name == "fprintf" ||
2191 Name == "fgetpos") {
2192 if (FTy->getNumParams() < 2 ||
2193 !FTy->getParamType(0)->isPointerTy() ||
2194 !FTy->getParamType(1)->isPointerTy())
2197 setDoesNotCapture(F, 1);
2198 setDoesNotCapture(F, 2);
2202 if (Name == "getc" ||
2203 Name == "getlogin_r" ||
2204 Name == "getc_unlocked") {
2205 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2208 setDoesNotCapture(F, 1);
2209 } else if (Name == "getenv") {
2210 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2213 setOnlyReadsMemory(F);
2214 setDoesNotCapture(F, 1);
2215 } else if (Name == "gets" ||
2216 Name == "getchar") {
2218 } else if (Name == "getitimer") {
2219 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2222 setDoesNotCapture(F, 2);
2223 } else if (Name == "getpwnam") {
2224 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2227 setDoesNotCapture(F, 1);
2231 if (Name == "ungetc") {
2232 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2235 setDoesNotCapture(F, 2);
2236 } else if (Name == "uname" ||
2238 Name == "unsetenv") {
2239 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2242 setDoesNotCapture(F, 1);
2243 } else if (Name == "utime" ||
2245 if (FTy->getNumParams() != 2 ||
2246 !FTy->getParamType(0)->isPointerTy() ||
2247 !FTy->getParamType(1)->isPointerTy())
2250 setDoesNotCapture(F, 1);
2251 setDoesNotCapture(F, 2);
2255 if (Name == "putc") {
2256 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2259 setDoesNotCapture(F, 2);
2260 } else if (Name == "puts" ||
2263 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2266 setDoesNotCapture(F, 1);
2267 } else if (Name == "pread" ||
2269 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2271 // May throw; these are valid pthread cancellation points.
2272 setDoesNotCapture(F, 2);
2273 } else if (Name == "putchar") {
2275 } else if (Name == "popen") {
2276 if (FTy->getNumParams() != 2 ||
2277 !FTy->getReturnType()->isPointerTy() ||
2278 !FTy->getParamType(0)->isPointerTy() ||
2279 !FTy->getParamType(1)->isPointerTy())
2282 setDoesNotAlias(F, 0);
2283 setDoesNotCapture(F, 1);
2284 setDoesNotCapture(F, 2);
2285 } else if (Name == "pclose") {
2286 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2289 setDoesNotCapture(F, 1);
2293 if (Name == "vscanf") {
2294 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2297 setDoesNotCapture(F, 1);
2298 } else if (Name == "vsscanf" ||
2299 Name == "vfscanf") {
2300 if (FTy->getNumParams() != 3 ||
2301 !FTy->getParamType(1)->isPointerTy() ||
2302 !FTy->getParamType(2)->isPointerTy())
2305 setDoesNotCapture(F, 1);
2306 setDoesNotCapture(F, 2);
2307 } else if (Name == "valloc") {
2308 if (!FTy->getReturnType()->isPointerTy())
2311 setDoesNotAlias(F, 0);
2312 } else if (Name == "vprintf") {
2313 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2316 setDoesNotCapture(F, 1);
2317 } else if (Name == "vfprintf" ||
2318 Name == "vsprintf") {
2319 if (FTy->getNumParams() != 3 ||
2320 !FTy->getParamType(0)->isPointerTy() ||
2321 !FTy->getParamType(1)->isPointerTy())
2324 setDoesNotCapture(F, 1);
2325 setDoesNotCapture(F, 2);
2326 } else if (Name == "vsnprintf") {
2327 if (FTy->getNumParams() != 4 ||
2328 !FTy->getParamType(0)->isPointerTy() ||
2329 !FTy->getParamType(2)->isPointerTy())
2332 setDoesNotCapture(F, 1);
2333 setDoesNotCapture(F, 3);
2337 if (Name == "open") {
2338 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2340 // May throw; "open" is a valid pthread cancellation point.
2341 setDoesNotCapture(F, 1);
2342 } else if (Name == "opendir") {
2343 if (FTy->getNumParams() != 1 ||
2344 !FTy->getReturnType()->isPointerTy() ||
2345 !FTy->getParamType(0)->isPointerTy())
2348 setDoesNotAlias(F, 0);
2349 setDoesNotCapture(F, 1);
2353 if (Name == "tmpfile") {
2354 if (!FTy->getReturnType()->isPointerTy())
2357 setDoesNotAlias(F, 0);
2358 } else if (Name == "times") {
2359 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2362 setDoesNotCapture(F, 1);
2366 if (Name == "htonl" ||
2369 setDoesNotAccessMemory(F);
2373 if (Name == "ntohl" ||
2376 setDoesNotAccessMemory(F);
2380 if (Name == "lstat") {
2381 if (FTy->getNumParams() != 2 ||
2382 !FTy->getParamType(0)->isPointerTy() ||
2383 !FTy->getParamType(1)->isPointerTy())
2386 setDoesNotCapture(F, 1);
2387 setDoesNotCapture(F, 2);
2388 } else if (Name == "lchown") {
2389 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2392 setDoesNotCapture(F, 1);
2396 if (Name == "qsort") {
2397 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2399 // May throw; places call through function pointer.
2400 setDoesNotCapture(F, 4);
2404 if (Name == "__strdup" ||
2405 Name == "__strndup") {
2406 if (FTy->getNumParams() < 1 ||
2407 !FTy->getReturnType()->isPointerTy() ||
2408 !FTy->getParamType(0)->isPointerTy())
2411 setDoesNotAlias(F, 0);
2412 setDoesNotCapture(F, 1);
2413 } else if (Name == "__strtok_r") {
2414 if (FTy->getNumParams() != 3 ||
2415 !FTy->getParamType(1)->isPointerTy())
2418 setDoesNotCapture(F, 2);
2419 } else if (Name == "_IO_getc") {
2420 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2423 setDoesNotCapture(F, 1);
2424 } else if (Name == "_IO_putc") {
2425 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2428 setDoesNotCapture(F, 2);
2432 if (Name == "\1__isoc99_scanf") {
2433 if (FTy->getNumParams() < 1 ||
2434 !FTy->getParamType(0)->isPointerTy())
2437 setDoesNotCapture(F, 1);
2438 } else if (Name == "\1stat64" ||
2439 Name == "\1lstat64" ||
2440 Name == "\1statvfs64" ||
2441 Name == "\1__isoc99_sscanf") {
2442 if (FTy->getNumParams() < 1 ||
2443 !FTy->getParamType(0)->isPointerTy() ||
2444 !FTy->getParamType(1)->isPointerTy())
2447 setDoesNotCapture(F, 1);
2448 setDoesNotCapture(F, 2);
2449 } else if (Name == "\1fopen64") {
2450 if (FTy->getNumParams() != 2 ||
2451 !FTy->getReturnType()->isPointerTy() ||
2452 !FTy->getParamType(0)->isPointerTy() ||
2453 !FTy->getParamType(1)->isPointerTy())
2456 setDoesNotAlias(F, 0);
2457 setDoesNotCapture(F, 1);
2458 setDoesNotCapture(F, 2);
2459 } else if (Name == "\1fseeko64" ||
2460 Name == "\1ftello64") {
2461 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2464 setDoesNotCapture(F, 1);
2465 } else if (Name == "\1tmpfile64") {
2466 if (!FTy->getReturnType()->isPointerTy())
2469 setDoesNotAlias(F, 0);
2470 } else if (Name == "\1fstat64" ||
2471 Name == "\1fstatvfs64") {
2472 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2475 setDoesNotCapture(F, 2);
2476 } else if (Name == "\1open64") {
2477 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2479 // May throw; "open" is a valid pthread cancellation point.
2480 setDoesNotCapture(F, 1);
2486 /// doInitialization - Add attributes to well-known functions.
2488 bool SimplifyLibCalls::doInitialization(Module &M) {
2490 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2492 if (F.isDeclaration() && F.hasName())
2493 inferPrototypeAttributes(F);
2499 // Additional cases that we need to add to this file:
2502 // * cbrt(expN(X)) -> expN(x/3)
2503 // * cbrt(sqrt(x)) -> pow(x,1/6)
2504 // * cbrt(sqrt(x)) -> pow(x,1/9)
2507 // * exp(log(x)) -> x
2510 // * log(exp(x)) -> x
2511 // * log(x**y) -> y*log(x)
2512 // * log(exp(y)) -> y*log(e)
2513 // * log(exp2(y)) -> y*log(2)
2514 // * log(exp10(y)) -> y*log(10)
2515 // * log(sqrt(x)) -> 0.5*log(x)
2516 // * log(pow(x,y)) -> y*log(x)
2518 // lround, lroundf, lroundl:
2519 // * lround(cnst) -> cnst'
2522 // * pow(exp(x),y) -> exp(x*y)
2523 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2524 // * pow(pow(x,y),z)-> pow(x,y*z)
2526 // round, roundf, roundl:
2527 // * round(cnst) -> cnst'
2530 // * signbit(cnst) -> cnst'
2531 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2533 // sqrt, sqrtf, sqrtl:
2534 // * sqrt(expN(x)) -> expN(x*0.5)
2535 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2536 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2539 // * strchr(p, 0) -> strlen(p)
2541 // * tan(atan(x)) -> x
2543 // trunc, truncf, truncl:
2544 // * trunc(cnst) -> cnst'