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/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
48 class LibCallOptimization {
52 const TargetLibraryInfo *TLI;
55 LibCallOptimization() { }
56 virtual ~LibCallOptimization() {}
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
63 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
66 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
68 Caller = CI->getParent()->getParent();
71 if (CI->getCalledFunction())
72 Context = &CI->getCalledFunction()->getContext();
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
78 return CallOptimizer(CI->getCalledFunction(), CI, B);
81 } // End anonymous namespace.
84 //===----------------------------------------------------------------------===//
86 //===----------------------------------------------------------------------===//
88 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
89 /// value is equal or not-equal to zero.
90 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
98 // Unknown instruction.
104 static bool CallHasFloatingPointArgument(const CallInst *CI) {
105 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
107 if ((*it)->getType()->isFloatingPointTy())
113 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
114 /// comparisons with With.
115 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
116 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
118 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
119 if (IC->isEquality() && IC->getOperand(1) == With)
121 // Unknown instruction.
127 //===----------------------------------------------------------------------===//
128 // String and Memory LibCall Optimizations
129 //===----------------------------------------------------------------------===//
131 //===---------------------------------------===//
132 // 'strcat' Optimizations
134 struct StrCatOpt : public LibCallOptimization {
135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
136 // Verify the "strcat" function prototype.
137 FunctionType *FT = Callee->getFunctionType();
138 if (FT->getNumParams() != 2 ||
139 FT->getReturnType() != B.getInt8PtrTy() ||
140 FT->getParamType(0) != FT->getReturnType() ||
141 FT->getParamType(1) != FT->getReturnType())
144 // Extract some information from the instruction
145 Value *Dst = CI->getArgOperand(0);
146 Value *Src = CI->getArgOperand(1);
148 // See if we can get the length of the input string.
149 uint64_t Len = GetStringLength(Src);
150 if (Len == 0) return 0;
151 --Len; // Unbias length.
153 // Handle the simple, do-nothing case: strcat(x, "") -> x
157 // These optimizations require TargetData.
160 EmitStrLenMemCpy(Src, Dst, Len, B);
164 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
165 // We need to find the end of the destination string. That's where the
166 // memory is to be moved to. We just generate a call to strlen.
167 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
169 // Now that we have the destination's length, we must index into the
170 // destination's pointer to get the actual memcpy destination (end of
171 // the string .. we're concatenating).
172 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
174 // We have enough information to now generate the memcpy call to do the
175 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
176 B.CreateMemCpy(CpyDst, Src,
177 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
181 //===---------------------------------------===//
182 // 'strncat' Optimizations
184 struct StrNCatOpt : public StrCatOpt {
185 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
186 // Verify the "strncat" function prototype.
187 FunctionType *FT = Callee->getFunctionType();
188 if (FT->getNumParams() != 3 ||
189 FT->getReturnType() != B.getInt8PtrTy() ||
190 FT->getParamType(0) != FT->getReturnType() ||
191 FT->getParamType(1) != FT->getReturnType() ||
192 !FT->getParamType(2)->isIntegerTy())
195 // Extract some information from the instruction
196 Value *Dst = CI->getArgOperand(0);
197 Value *Src = CI->getArgOperand(1);
200 // We don't do anything if length is not constant
201 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
202 Len = LengthArg->getZExtValue();
206 // See if we can get the length of the input string.
207 uint64_t SrcLen = GetStringLength(Src);
208 if (SrcLen == 0) return 0;
209 --SrcLen; // Unbias length.
211 // Handle the simple, do-nothing cases:
212 // strncat(x, "", c) -> x
213 // strncat(x, c, 0) -> x
214 if (SrcLen == 0 || Len == 0) return Dst;
216 // These optimizations require TargetData.
219 // We don't optimize this case
220 if (Len < SrcLen) return 0;
222 // strncat(x, s, c) -> strcat(x, s)
223 // s is constant so the strcat can be optimized further
224 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
229 //===---------------------------------------===//
230 // 'strchr' Optimizations
232 struct StrChrOpt : public LibCallOptimization {
233 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
234 // Verify the "strchr" function prototype.
235 FunctionType *FT = Callee->getFunctionType();
236 if (FT->getNumParams() != 2 ||
237 FT->getReturnType() != B.getInt8PtrTy() ||
238 FT->getParamType(0) != FT->getReturnType() ||
239 !FT->getParamType(1)->isIntegerTy(32))
242 Value *SrcStr = CI->getArgOperand(0);
244 // If the second operand is non-constant, see if we can compute the length
245 // of the input string and turn this into memchr.
246 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
248 // These optimizations require TargetData.
251 uint64_t Len = GetStringLength(SrcStr);
252 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
255 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
256 ConstantInt::get(TD->getIntPtrType(*Context), Len),
260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
263 if (!getConstantStringInfo(SrcStr, Str))
266 // Compute the offset, make sure to handle the case when we're searching for
267 // zero (a weird way to spell strlen).
268 size_t I = CharC->getSExtValue() == 0 ?
269 Str.size() : Str.find(CharC->getSExtValue());
270 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
271 return Constant::getNullValue(CI->getType());
273 // strchr(s+n,c) -> gep(s+n+i,c)
274 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
278 //===---------------------------------------===//
279 // 'strrchr' Optimizations
281 struct StrRChrOpt : public LibCallOptimization {
282 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
283 // Verify the "strrchr" function prototype.
284 FunctionType *FT = Callee->getFunctionType();
285 if (FT->getNumParams() != 2 ||
286 FT->getReturnType() != B.getInt8PtrTy() ||
287 FT->getParamType(0) != FT->getReturnType() ||
288 !FT->getParamType(1)->isIntegerTy(32))
291 Value *SrcStr = CI->getArgOperand(0);
292 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
294 // Cannot fold anything if we're not looking for a constant.
299 if (!getConstantStringInfo(SrcStr, Str)) {
300 // strrchr(s, 0) -> strchr(s, 0)
301 if (TD && CharC->isZero())
302 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
306 // Compute the offset.
307 size_t I = CharC->getSExtValue() == 0 ?
308 Str.size() : Str.rfind(CharC->getSExtValue());
309 if (I == StringRef::npos) // Didn't find the char. Return null.
310 return Constant::getNullValue(CI->getType());
312 // strrchr(s+n,c) -> gep(s+n+i,c)
313 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
317 //===---------------------------------------===//
318 // 'strcmp' Optimizations
320 struct StrCmpOpt : public LibCallOptimization {
321 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
322 // Verify the "strcmp" function prototype.
323 FunctionType *FT = Callee->getFunctionType();
324 if (FT->getNumParams() != 2 ||
325 !FT->getReturnType()->isIntegerTy(32) ||
326 FT->getParamType(0) != FT->getParamType(1) ||
327 FT->getParamType(0) != B.getInt8PtrTy())
330 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
331 if (Str1P == Str2P) // strcmp(x,x) -> 0
332 return ConstantInt::get(CI->getType(), 0);
334 StringRef Str1, Str2;
335 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
336 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
338 // strcmp(x, y) -> cnst (if both x and y are constant strings)
339 if (HasStr1 && HasStr2)
340 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
342 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
343 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
346 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
347 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
349 // strcmp(P, "x") -> memcmp(P, "x", 2)
350 uint64_t Len1 = GetStringLength(Str1P);
351 uint64_t Len2 = GetStringLength(Str2P);
353 // These optimizations require TargetData.
356 return EmitMemCmp(Str1P, Str2P,
357 ConstantInt::get(TD->getIntPtrType(*Context),
358 std::min(Len1, Len2)), B, TD, TLI);
365 //===---------------------------------------===//
366 // 'strncmp' Optimizations
368 struct StrNCmpOpt : public LibCallOptimization {
369 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
370 // Verify the "strncmp" function prototype.
371 FunctionType *FT = Callee->getFunctionType();
372 if (FT->getNumParams() != 3 ||
373 !FT->getReturnType()->isIntegerTy(32) ||
374 FT->getParamType(0) != FT->getParamType(1) ||
375 FT->getParamType(0) != B.getInt8PtrTy() ||
376 !FT->getParamType(2)->isIntegerTy())
379 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
380 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
381 return ConstantInt::get(CI->getType(), 0);
383 // Get the length argument if it is constant.
385 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
386 Length = LengthArg->getZExtValue();
390 if (Length == 0) // strncmp(x,y,0) -> 0
391 return ConstantInt::get(CI->getType(), 0);
393 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
394 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
396 StringRef Str1, Str2;
397 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
398 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
400 // strncmp(x, y) -> cnst (if both x and y are constant strings)
401 if (HasStr1 && HasStr2) {
402 StringRef SubStr1 = Str1.substr(0, Length);
403 StringRef SubStr2 = Str2.substr(0, Length);
404 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
407 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
408 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
411 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
412 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
419 //===---------------------------------------===//
420 // 'strcpy' Optimizations
422 struct StrCpyOpt : public LibCallOptimization {
423 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
425 StrCpyOpt(bool c) : OptChkCall(c) {}
427 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
428 // Verify the "strcpy" function prototype.
429 unsigned NumParams = OptChkCall ? 3 : 2;
430 FunctionType *FT = Callee->getFunctionType();
431 if (FT->getNumParams() != NumParams ||
432 FT->getReturnType() != FT->getParamType(0) ||
433 FT->getParamType(0) != FT->getParamType(1) ||
434 FT->getParamType(0) != B.getInt8PtrTy())
437 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
438 if (Dst == Src) // strcpy(x,x) -> x
441 // These optimizations require TargetData.
444 // See if we can get the length of the input string.
445 uint64_t Len = GetStringLength(Src);
446 if (Len == 0) return 0;
448 // We have enough information to now generate the memcpy call to do the
449 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
451 EmitMemCpyChk(Dst, Src,
452 ConstantInt::get(TD->getIntPtrType(*Context), Len),
453 CI->getArgOperand(2), B, TD, TLI);
455 B.CreateMemCpy(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
461 //===---------------------------------------===//
462 // 'stpcpy' Optimizations
464 struct StpCpyOpt: public LibCallOptimization {
465 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
467 StpCpyOpt(bool c) : OptChkCall(c) {}
469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
470 // Verify the "stpcpy" function prototype.
471 unsigned NumParams = OptChkCall ? 3 : 2;
472 FunctionType *FT = Callee->getFunctionType();
473 if (FT->getNumParams() != NumParams ||
474 FT->getReturnType() != FT->getParamType(0) ||
475 FT->getParamType(0) != FT->getParamType(1) ||
476 FT->getParamType(0) != B.getInt8PtrTy())
479 // These optimizations require TargetData.
482 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
483 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
484 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
485 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
488 // See if we can get the length of the input string.
489 uint64_t Len = GetStringLength(Src);
490 if (Len == 0) return 0;
492 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
493 Value *DstEnd = B.CreateGEP(Dst,
494 ConstantInt::get(TD->getIntPtrType(*Context),
497 // We have enough information to now generate the memcpy call to do the
498 // copy for us. Make a memcpy to copy the nul byte with align = 1.
500 EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI);
502 B.CreateMemCpy(Dst, Src, LenV, 1);
507 //===---------------------------------------===//
508 // 'strncpy' Optimizations
510 struct StrNCpyOpt : public LibCallOptimization {
511 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
512 FunctionType *FT = Callee->getFunctionType();
513 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
514 FT->getParamType(0) != FT->getParamType(1) ||
515 FT->getParamType(0) != B.getInt8PtrTy() ||
516 !FT->getParamType(2)->isIntegerTy())
519 Value *Dst = CI->getArgOperand(0);
520 Value *Src = CI->getArgOperand(1);
521 Value *LenOp = CI->getArgOperand(2);
523 // See if we can get the length of the input string.
524 uint64_t SrcLen = GetStringLength(Src);
525 if (SrcLen == 0) return 0;
529 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
530 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
535 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
536 Len = LengthArg->getZExtValue();
540 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
542 // These optimizations require TargetData.
545 // Let strncpy handle the zero padding
546 if (Len > SrcLen+1) return 0;
548 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
549 B.CreateMemCpy(Dst, Src,
550 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
556 //===---------------------------------------===//
557 // 'strlen' Optimizations
559 struct StrLenOpt : public LibCallOptimization {
560 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
561 FunctionType *FT = Callee->getFunctionType();
562 if (FT->getNumParams() != 1 ||
563 FT->getParamType(0) != B.getInt8PtrTy() ||
564 !FT->getReturnType()->isIntegerTy())
567 Value *Src = CI->getArgOperand(0);
569 // Constant folding: strlen("xyz") -> 3
570 if (uint64_t Len = GetStringLength(Src))
571 return ConstantInt::get(CI->getType(), Len-1);
573 // strlen(x) != 0 --> *x != 0
574 // strlen(x) == 0 --> *x == 0
575 if (IsOnlyUsedInZeroEqualityComparison(CI))
576 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
582 //===---------------------------------------===//
583 // 'strpbrk' Optimizations
585 struct StrPBrkOpt : public LibCallOptimization {
586 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
587 FunctionType *FT = Callee->getFunctionType();
588 if (FT->getNumParams() != 2 ||
589 FT->getParamType(0) != B.getInt8PtrTy() ||
590 FT->getParamType(1) != FT->getParamType(0) ||
591 FT->getReturnType() != FT->getParamType(0))
595 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
596 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
598 // strpbrk(s, "") -> NULL
599 // strpbrk("", s) -> NULL
600 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
601 return Constant::getNullValue(CI->getType());
604 if (HasS1 && HasS2) {
605 size_t I = S1.find_first_of(S2);
606 if (I == std::string::npos) // No match.
607 return Constant::getNullValue(CI->getType());
609 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
612 // strpbrk(s, "a") -> strchr(s, 'a')
613 if (TD && HasS2 && S2.size() == 1)
614 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
620 //===---------------------------------------===//
621 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
623 struct StrToOpt : public LibCallOptimization {
624 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
625 FunctionType *FT = Callee->getFunctionType();
626 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
627 !FT->getParamType(0)->isPointerTy() ||
628 !FT->getParamType(1)->isPointerTy())
631 Value *EndPtr = CI->getArgOperand(1);
632 if (isa<ConstantPointerNull>(EndPtr)) {
633 // With a null EndPtr, this function won't capture the main argument.
634 // It would be readonly too, except that it still may write to errno.
635 CI->addAttribute(1, Attribute::NoCapture);
642 //===---------------------------------------===//
643 // 'strspn' Optimizations
645 struct StrSpnOpt : public LibCallOptimization {
646 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
647 FunctionType *FT = Callee->getFunctionType();
648 if (FT->getNumParams() != 2 ||
649 FT->getParamType(0) != B.getInt8PtrTy() ||
650 FT->getParamType(1) != FT->getParamType(0) ||
651 !FT->getReturnType()->isIntegerTy())
655 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
656 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
658 // strspn(s, "") -> 0
659 // strspn("", s) -> 0
660 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
661 return Constant::getNullValue(CI->getType());
664 if (HasS1 && HasS2) {
665 size_t Pos = S1.find_first_not_of(S2);
666 if (Pos == StringRef::npos) Pos = S1.size();
667 return ConstantInt::get(CI->getType(), Pos);
674 //===---------------------------------------===//
675 // 'strcspn' Optimizations
677 struct StrCSpnOpt : public LibCallOptimization {
678 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
679 FunctionType *FT = Callee->getFunctionType();
680 if (FT->getNumParams() != 2 ||
681 FT->getParamType(0) != B.getInt8PtrTy() ||
682 FT->getParamType(1) != FT->getParamType(0) ||
683 !FT->getReturnType()->isIntegerTy())
687 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
688 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
690 // strcspn("", s) -> 0
691 if (HasS1 && S1.empty())
692 return Constant::getNullValue(CI->getType());
695 if (HasS1 && HasS2) {
696 size_t Pos = S1.find_first_of(S2);
697 if (Pos == StringRef::npos) Pos = S1.size();
698 return ConstantInt::get(CI->getType(), Pos);
701 // strcspn(s, "") -> strlen(s)
702 if (TD && HasS2 && S2.empty())
703 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
709 //===---------------------------------------===//
710 // 'strstr' Optimizations
712 struct StrStrOpt : public LibCallOptimization {
713 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
714 FunctionType *FT = Callee->getFunctionType();
715 if (FT->getNumParams() != 2 ||
716 !FT->getParamType(0)->isPointerTy() ||
717 !FT->getParamType(1)->isPointerTy() ||
718 !FT->getReturnType()->isPointerTy())
721 // fold strstr(x, x) -> x.
722 if (CI->getArgOperand(0) == CI->getArgOperand(1))
723 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
725 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
726 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
727 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
730 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
734 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
736 ICmpInst *Old = cast<ICmpInst>(*UI++);
737 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
738 ConstantInt::getNullValue(StrNCmp->getType()),
740 Old->replaceAllUsesWith(Cmp);
741 Old->eraseFromParent();
746 // See if either input string is a constant string.
747 StringRef SearchStr, ToFindStr;
748 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
749 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
751 // fold strstr(x, "") -> x.
752 if (HasStr2 && ToFindStr.empty())
753 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
755 // If both strings are known, constant fold it.
756 if (HasStr1 && HasStr2) {
757 std::string::size_type Offset = SearchStr.find(ToFindStr);
759 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
760 return Constant::getNullValue(CI->getType());
762 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
763 Value *Result = CastToCStr(CI->getArgOperand(0), B);
764 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
765 return B.CreateBitCast(Result, CI->getType());
768 // fold strstr(x, "y") -> strchr(x, 'y').
769 if (HasStr2 && ToFindStr.size() == 1) {
770 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
771 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
778 //===---------------------------------------===//
779 // 'memcmp' Optimizations
781 struct MemCmpOpt : public LibCallOptimization {
782 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
783 FunctionType *FT = Callee->getFunctionType();
784 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
785 !FT->getParamType(1)->isPointerTy() ||
786 !FT->getReturnType()->isIntegerTy(32))
789 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
791 if (LHS == RHS) // memcmp(s,s,x) -> 0
792 return Constant::getNullValue(CI->getType());
794 // Make sure we have a constant length.
795 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
797 uint64_t Len = LenC->getZExtValue();
799 if (Len == 0) // memcmp(s1,s2,0) -> 0
800 return Constant::getNullValue(CI->getType());
802 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
804 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
805 CI->getType(), "lhsv");
806 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
807 CI->getType(), "rhsv");
808 return B.CreateSub(LHSV, RHSV, "chardiff");
811 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
812 StringRef LHSStr, RHSStr;
813 if (getConstantStringInfo(LHS, LHSStr) &&
814 getConstantStringInfo(RHS, RHSStr)) {
815 // Make sure we're not reading out-of-bounds memory.
816 if (Len > LHSStr.size() || Len > RHSStr.size())
818 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
819 return ConstantInt::get(CI->getType(), Ret);
826 //===---------------------------------------===//
827 // 'memcpy' Optimizations
829 struct MemCpyOpt : public LibCallOptimization {
830 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
831 // These optimizations require TargetData.
834 FunctionType *FT = Callee->getFunctionType();
835 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
836 !FT->getParamType(0)->isPointerTy() ||
837 !FT->getParamType(1)->isPointerTy() ||
838 FT->getParamType(2) != TD->getIntPtrType(*Context))
841 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
842 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
843 CI->getArgOperand(2), 1);
844 return CI->getArgOperand(0);
848 //===---------------------------------------===//
849 // 'memmove' Optimizations
851 struct MemMoveOpt : public LibCallOptimization {
852 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
853 // These optimizations require TargetData.
856 FunctionType *FT = Callee->getFunctionType();
857 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
858 !FT->getParamType(0)->isPointerTy() ||
859 !FT->getParamType(1)->isPointerTy() ||
860 FT->getParamType(2) != TD->getIntPtrType(*Context))
863 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
864 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
865 CI->getArgOperand(2), 1);
866 return CI->getArgOperand(0);
870 //===---------------------------------------===//
871 // 'memset' Optimizations
873 struct MemSetOpt : public LibCallOptimization {
874 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
875 // These optimizations require TargetData.
878 FunctionType *FT = Callee->getFunctionType();
879 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
880 !FT->getParamType(0)->isPointerTy() ||
881 !FT->getParamType(1)->isIntegerTy() ||
882 FT->getParamType(2) != TD->getIntPtrType(*Context))
885 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
886 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
887 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
888 return CI->getArgOperand(0);
892 //===----------------------------------------------------------------------===//
893 // Math Library Optimizations
894 //===----------------------------------------------------------------------===//
896 //===---------------------------------------===//
897 // 'cos*' Optimizations
899 struct CosOpt : public LibCallOptimization {
900 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
901 FunctionType *FT = Callee->getFunctionType();
902 // Just make sure this has 1 argument of FP type, which matches the
904 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
905 !FT->getParamType(0)->isFloatingPointTy())
909 Value *Op1 = CI->getArgOperand(0);
910 if (BinaryOperator::isFNeg(Op1)) {
911 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
912 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
918 //===---------------------------------------===//
919 // 'pow*' Optimizations
921 struct PowOpt : public LibCallOptimization {
922 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
923 FunctionType *FT = Callee->getFunctionType();
924 // Just make sure this has 2 arguments of the same FP type, which match the
926 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
927 FT->getParamType(0) != FT->getParamType(1) ||
928 !FT->getParamType(0)->isFloatingPointTy())
931 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
932 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
933 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
935 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
936 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
939 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
940 if (Op2C == 0) return 0;
942 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
943 return ConstantFP::get(CI->getType(), 1.0);
945 if (Op2C->isExactlyValue(0.5)) {
946 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
947 // This is faster than calling pow, and still handles negative zero
948 // and negative infinity correctly.
949 // TODO: In fast-math mode, this could be just sqrt(x).
950 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
951 Value *Inf = ConstantFP::getInfinity(CI->getType());
952 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
953 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
954 Callee->getAttributes());
955 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
956 Callee->getAttributes());
957 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
958 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
962 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
964 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
965 return B.CreateFMul(Op1, Op1, "pow2");
966 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
967 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
973 //===---------------------------------------===//
974 // 'exp2' Optimizations
976 struct Exp2Opt : public LibCallOptimization {
977 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
978 FunctionType *FT = Callee->getFunctionType();
979 // Just make sure this has 1 argument of FP type, which matches the
981 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
982 !FT->getParamType(0)->isFloatingPointTy())
985 Value *Op = CI->getArgOperand(0);
986 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
987 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
989 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
990 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
991 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
992 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
993 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
994 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
999 if (Op->getType()->isFloatTy())
1001 else if (Op->getType()->isDoubleTy())
1006 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1007 if (!Op->getType()->isFloatTy())
1008 One = ConstantExpr::getFPExtend(One, Op->getType());
1010 Module *M = Caller->getParent();
1011 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1013 B.getInt32Ty(), NULL);
1014 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1015 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1016 CI->setCallingConv(F->getCallingConv());
1024 //===---------------------------------------===//
1025 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1027 struct UnaryDoubleFPOpt : public LibCallOptimization {
1028 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1029 FunctionType *FT = Callee->getFunctionType();
1030 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1031 !FT->getParamType(0)->isDoubleTy())
1034 // If this is something like 'floor((double)floatval)', convert to floorf.
1035 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1036 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1039 // floor((double)floatval) -> (double)floorf(floatval)
1040 Value *V = Cast->getOperand(0);
1041 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1042 return B.CreateFPExt(V, B.getDoubleTy());
1046 //===----------------------------------------------------------------------===//
1047 // Integer Optimizations
1048 //===----------------------------------------------------------------------===//
1050 //===---------------------------------------===//
1051 // 'ffs*' Optimizations
1053 struct FFSOpt : public LibCallOptimization {
1054 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1055 FunctionType *FT = Callee->getFunctionType();
1056 // Just make sure this has 2 arguments of the same FP type, which match the
1058 if (FT->getNumParams() != 1 ||
1059 !FT->getReturnType()->isIntegerTy(32) ||
1060 !FT->getParamType(0)->isIntegerTy())
1063 Value *Op = CI->getArgOperand(0);
1066 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1067 if (CI->getValue() == 0) // ffs(0) -> 0.
1068 return Constant::getNullValue(CI->getType());
1069 // ffs(c) -> cttz(c)+1
1070 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1073 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1074 Type *ArgType = Op->getType();
1075 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1076 Intrinsic::cttz, ArgType);
1077 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1078 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1079 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1081 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1082 return B.CreateSelect(Cond, V, B.getInt32(0));
1086 //===---------------------------------------===//
1087 // 'isdigit' Optimizations
1089 struct IsDigitOpt : public LibCallOptimization {
1090 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1091 FunctionType *FT = Callee->getFunctionType();
1092 // We require integer(i32)
1093 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1094 !FT->getParamType(0)->isIntegerTy(32))
1097 // isdigit(c) -> (c-'0') <u 10
1098 Value *Op = CI->getArgOperand(0);
1099 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1100 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1101 return B.CreateZExt(Op, CI->getType());
1105 //===---------------------------------------===//
1106 // 'isascii' Optimizations
1108 struct IsAsciiOpt : public LibCallOptimization {
1109 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1110 FunctionType *FT = Callee->getFunctionType();
1111 // We require integer(i32)
1112 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1113 !FT->getParamType(0)->isIntegerTy(32))
1116 // isascii(c) -> c <u 128
1117 Value *Op = CI->getArgOperand(0);
1118 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1119 return B.CreateZExt(Op, CI->getType());
1123 //===---------------------------------------===//
1124 // 'abs', 'labs', 'llabs' Optimizations
1126 struct AbsOpt : public LibCallOptimization {
1127 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1128 FunctionType *FT = Callee->getFunctionType();
1129 // We require integer(integer) where the types agree.
1130 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1131 FT->getParamType(0) != FT->getReturnType())
1134 // abs(x) -> x >s -1 ? x : -x
1135 Value *Op = CI->getArgOperand(0);
1136 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1138 Value *Neg = B.CreateNeg(Op, "neg");
1139 return B.CreateSelect(Pos, Op, Neg);
1144 //===---------------------------------------===//
1145 // 'toascii' Optimizations
1147 struct ToAsciiOpt : public LibCallOptimization {
1148 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1149 FunctionType *FT = Callee->getFunctionType();
1150 // We require i32(i32)
1151 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1152 !FT->getParamType(0)->isIntegerTy(32))
1155 // isascii(c) -> c & 0x7f
1156 return B.CreateAnd(CI->getArgOperand(0),
1157 ConstantInt::get(CI->getType(),0x7F));
1161 //===----------------------------------------------------------------------===//
1162 // Formatting and IO Optimizations
1163 //===----------------------------------------------------------------------===//
1165 //===---------------------------------------===//
1166 // 'printf' Optimizations
1168 struct PrintFOpt : public LibCallOptimization {
1169 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1171 // Check for a fixed format string.
1172 StringRef FormatStr;
1173 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1176 // Empty format string -> noop.
1177 if (FormatStr.empty()) // Tolerate printf's declared void.
1178 return CI->use_empty() ? (Value*)CI :
1179 ConstantInt::get(CI->getType(), 0);
1181 // Do not do any of the following transformations if the printf return value
1182 // is used, in general the printf return value is not compatible with either
1183 // putchar() or puts().
1184 if (!CI->use_empty())
1187 // printf("x") -> putchar('x'), even for '%'.
1188 if (FormatStr.size() == 1) {
1189 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1190 if (CI->use_empty()) return CI;
1191 return B.CreateIntCast(Res, CI->getType(), true);
1194 // printf("foo\n") --> puts("foo")
1195 if (FormatStr[FormatStr.size()-1] == '\n' &&
1196 FormatStr.find('%') == std::string::npos) { // no format characters.
1197 // Create a string literal with no \n on it. We expect the constant merge
1198 // pass to be run after this pass, to merge duplicate strings.
1199 FormatStr = FormatStr.drop_back();
1200 Value *GV = B.CreateGlobalString(FormatStr, "str");
1201 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1202 return (CI->use_empty() || !NewCI) ?
1204 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1207 // Optimize specific format strings.
1208 // printf("%c", chr) --> putchar(chr)
1209 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1210 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1211 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1213 if (CI->use_empty()) return CI;
1214 return B.CreateIntCast(Res, CI->getType(), true);
1217 // printf("%s\n", str) --> puts(str)
1218 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1219 CI->getArgOperand(1)->getType()->isPointerTy()) {
1220 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1225 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1226 // Require one fixed pointer argument and an integer/void result.
1227 FunctionType *FT = Callee->getFunctionType();
1228 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1229 !(FT->getReturnType()->isIntegerTy() ||
1230 FT->getReturnType()->isVoidTy()))
1233 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1237 // printf(format, ...) -> iprintf(format, ...) if no floating point
1239 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1240 Module *M = B.GetInsertBlock()->getParent()->getParent();
1241 Constant *IPrintFFn =
1242 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1243 CallInst *New = cast<CallInst>(CI->clone());
1244 New->setCalledFunction(IPrintFFn);
1252 //===---------------------------------------===//
1253 // 'sprintf' Optimizations
1255 struct SPrintFOpt : public LibCallOptimization {
1256 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1258 // Check for a fixed format string.
1259 StringRef FormatStr;
1260 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1263 // If we just have a format string (nothing else crazy) transform it.
1264 if (CI->getNumArgOperands() == 2) {
1265 // Make sure there's no % in the constant array. We could try to handle
1266 // %% -> % in the future if we cared.
1267 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1268 if (FormatStr[i] == '%')
1269 return 0; // we found a format specifier, bail out.
1271 // These optimizations require TargetData.
1274 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1275 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1276 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1277 FormatStr.size() + 1), 1); // nul byte.
1278 return ConstantInt::get(CI->getType(), FormatStr.size());
1281 // The remaining optimizations require the format string to be "%s" or "%c"
1282 // and have an extra operand.
1283 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1284 CI->getNumArgOperands() < 3)
1287 // Decode the second character of the format string.
1288 if (FormatStr[1] == 'c') {
1289 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1290 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1291 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1292 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1293 B.CreateStore(V, Ptr);
1294 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1295 B.CreateStore(B.getInt8(0), Ptr);
1297 return ConstantInt::get(CI->getType(), 1);
1300 if (FormatStr[1] == 's') {
1301 // These optimizations require TargetData.
1304 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1305 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1307 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1310 Value *IncLen = B.CreateAdd(Len,
1311 ConstantInt::get(Len->getType(), 1),
1313 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1315 // The sprintf result is the unincremented number of bytes in the string.
1316 return B.CreateIntCast(Len, CI->getType(), false);
1321 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1322 // Require two fixed pointer arguments and an integer result.
1323 FunctionType *FT = Callee->getFunctionType();
1324 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1325 !FT->getParamType(1)->isPointerTy() ||
1326 !FT->getReturnType()->isIntegerTy())
1329 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1333 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1335 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1336 Module *M = B.GetInsertBlock()->getParent()->getParent();
1337 Constant *SIPrintFFn =
1338 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1339 CallInst *New = cast<CallInst>(CI->clone());
1340 New->setCalledFunction(SIPrintFFn);
1348 //===---------------------------------------===//
1349 // 'fwrite' Optimizations
1351 struct FWriteOpt : public LibCallOptimization {
1352 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1353 // Require a pointer, an integer, an integer, a pointer, returning integer.
1354 FunctionType *FT = Callee->getFunctionType();
1355 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1356 !FT->getParamType(1)->isIntegerTy() ||
1357 !FT->getParamType(2)->isIntegerTy() ||
1358 !FT->getParamType(3)->isPointerTy() ||
1359 !FT->getReturnType()->isIntegerTy())
1362 // Get the element size and count.
1363 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1364 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1365 if (!SizeC || !CountC) return 0;
1366 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1368 // If this is writing zero records, remove the call (it's a noop).
1370 return ConstantInt::get(CI->getType(), 0);
1372 // If this is writing one byte, turn it into fputc.
1373 // This optimisation is only valid, if the return value is unused.
1374 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1375 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1376 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1377 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1384 //===---------------------------------------===//
1385 // 'fputs' Optimizations
1387 struct FPutsOpt : public LibCallOptimization {
1388 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1389 // These optimizations require TargetData.
1392 // Require two pointers. Also, we can't optimize if return value is used.
1393 FunctionType *FT = Callee->getFunctionType();
1394 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1395 !FT->getParamType(1)->isPointerTy() ||
1399 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1400 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1402 // Known to have no uses (see above).
1403 return EmitFWrite(CI->getArgOperand(0),
1404 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1405 CI->getArgOperand(1), B, TD, TLI);
1409 //===---------------------------------------===//
1410 // 'fprintf' Optimizations
1412 struct FPrintFOpt : public LibCallOptimization {
1413 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1415 // All the optimizations depend on the format string.
1416 StringRef FormatStr;
1417 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1420 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1421 if (CI->getNumArgOperands() == 2) {
1422 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1423 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1424 return 0; // We found a format specifier.
1426 // These optimizations require TargetData.
1429 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1430 ConstantInt::get(TD->getIntPtrType(*Context),
1432 CI->getArgOperand(0), B, TD, TLI);
1433 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
1436 // The remaining optimizations require the format string to be "%s" or "%c"
1437 // and have an extra operand.
1438 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1439 CI->getNumArgOperands() < 3)
1442 // Decode the second character of the format string.
1443 if (FormatStr[1] == 'c') {
1444 // fprintf(F, "%c", chr) --> fputc(chr, F)
1445 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1446 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1448 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1451 if (FormatStr[1] == 's') {
1452 // fprintf(F, "%s", str) --> fputs(str, F)
1453 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1455 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1460 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1461 // Require two fixed paramters as pointers and integer result.
1462 FunctionType *FT = Callee->getFunctionType();
1463 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1464 !FT->getParamType(1)->isPointerTy() ||
1465 !FT->getReturnType()->isIntegerTy())
1468 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1472 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1473 // floating point arguments.
1474 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1475 Module *M = B.GetInsertBlock()->getParent()->getParent();
1476 Constant *FIPrintFFn =
1477 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1478 CallInst *New = cast<CallInst>(CI->clone());
1479 New->setCalledFunction(FIPrintFFn);
1487 //===---------------------------------------===//
1488 // 'puts' Optimizations
1490 struct PutsOpt : public LibCallOptimization {
1491 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1492 // Require one fixed pointer argument and an integer/void result.
1493 FunctionType *FT = Callee->getFunctionType();
1494 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1495 !(FT->getReturnType()->isIntegerTy() ||
1496 FT->getReturnType()->isVoidTy()))
1499 // Check for a constant string.
1501 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1504 if (Str.empty() && CI->use_empty()) {
1505 // puts("") -> putchar('\n')
1506 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1508 if (CI->use_empty()) return CI;
1509 return B.CreateIntCast(Res, CI->getType(), true);
1516 } // end anonymous namespace.
1518 //===----------------------------------------------------------------------===//
1519 // SimplifyLibCalls Pass Implementation
1520 //===----------------------------------------------------------------------===//
1523 /// This pass optimizes well known library functions from libc and libm.
1525 class SimplifyLibCalls : public FunctionPass {
1526 TargetLibraryInfo *TLI;
1528 StringMap<LibCallOptimization*> Optimizations;
1529 // String and Memory LibCall Optimizations
1530 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1531 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1532 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1533 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1535 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1536 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1537 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1538 // Math Library Optimizations
1539 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1540 // Integer Optimizations
1541 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1543 // Formatting and IO Optimizations
1544 SPrintFOpt SPrintF; PrintFOpt PrintF;
1545 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1548 bool Modified; // This is only used by doInitialization.
1550 static char ID; // Pass identification
1551 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1552 StpCpy(false), StpCpyChk(true) {
1553 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1555 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1556 void InitOptimizations();
1557 bool runOnFunction(Function &F);
1559 void setDoesNotAccessMemory(Function &F);
1560 void setOnlyReadsMemory(Function &F);
1561 void setDoesNotThrow(Function &F);
1562 void setDoesNotCapture(Function &F, unsigned n);
1563 void setDoesNotAlias(Function &F, unsigned n);
1564 bool doInitialization(Module &M);
1566 void inferPrototypeAttributes(Function &F);
1567 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1568 AU.addRequired<TargetLibraryInfo>();
1571 } // end anonymous namespace.
1573 char SimplifyLibCalls::ID = 0;
1575 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1576 "Simplify well-known library calls", false, false)
1577 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1578 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1579 "Simplify well-known library calls", false, false)
1581 // Public interface to the Simplify LibCalls pass.
1582 FunctionPass *llvm::createSimplifyLibCallsPass() {
1583 return new SimplifyLibCalls();
1586 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1588 Optimizations[TLI->getName(F)] = Opt;
1591 /// Optimizations - Populate the Optimizations map with all the optimizations
1593 void SimplifyLibCalls::InitOptimizations() {
1594 // String and Memory LibCall Optimizations
1595 Optimizations["strcat"] = &StrCat;
1596 Optimizations["strncat"] = &StrNCat;
1597 Optimizations["strchr"] = &StrChr;
1598 Optimizations["strrchr"] = &StrRChr;
1599 Optimizations["strcmp"] = &StrCmp;
1600 Optimizations["strncmp"] = &StrNCmp;
1601 Optimizations["strcpy"] = &StrCpy;
1602 Optimizations["strncpy"] = &StrNCpy;
1603 Optimizations["stpcpy"] = &StpCpy;
1604 Optimizations["strlen"] = &StrLen;
1605 Optimizations["strpbrk"] = &StrPBrk;
1606 Optimizations["strtol"] = &StrTo;
1607 Optimizations["strtod"] = &StrTo;
1608 Optimizations["strtof"] = &StrTo;
1609 Optimizations["strtoul"] = &StrTo;
1610 Optimizations["strtoll"] = &StrTo;
1611 Optimizations["strtold"] = &StrTo;
1612 Optimizations["strtoull"] = &StrTo;
1613 Optimizations["strspn"] = &StrSpn;
1614 Optimizations["strcspn"] = &StrCSpn;
1615 Optimizations["strstr"] = &StrStr;
1616 Optimizations["memcmp"] = &MemCmp;
1617 AddOpt(LibFunc::memcpy, &MemCpy);
1618 Optimizations["memmove"] = &MemMove;
1619 AddOpt(LibFunc::memset, &MemSet);
1621 // _chk variants of String and Memory LibCall Optimizations.
1622 Optimizations["__strcpy_chk"] = &StrCpyChk;
1623 Optimizations["__stpcpy_chk"] = &StpCpyChk;
1625 // Math Library Optimizations
1626 Optimizations["cosf"] = &Cos;
1627 Optimizations["cos"] = &Cos;
1628 Optimizations["cosl"] = &Cos;
1629 Optimizations["powf"] = &Pow;
1630 Optimizations["pow"] = &Pow;
1631 Optimizations["powl"] = &Pow;
1632 Optimizations["llvm.pow.f32"] = &Pow;
1633 Optimizations["llvm.pow.f64"] = &Pow;
1634 Optimizations["llvm.pow.f80"] = &Pow;
1635 Optimizations["llvm.pow.f128"] = &Pow;
1636 Optimizations["llvm.pow.ppcf128"] = &Pow;
1637 Optimizations["exp2l"] = &Exp2;
1638 Optimizations["exp2"] = &Exp2;
1639 Optimizations["exp2f"] = &Exp2;
1640 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1641 Optimizations["llvm.exp2.f128"] = &Exp2;
1642 Optimizations["llvm.exp2.f80"] = &Exp2;
1643 Optimizations["llvm.exp2.f64"] = &Exp2;
1644 Optimizations["llvm.exp2.f32"] = &Exp2;
1646 if (TLI->has(LibFunc::floor) && TLI->has(LibFunc::floorf))
1647 Optimizations["floor"] = &UnaryDoubleFP;
1648 if (TLI->has(LibFunc::ceil) && TLI->has(LibFunc::ceilf))
1649 Optimizations["ceil"] = &UnaryDoubleFP;
1650 if (TLI->has(LibFunc::round) && TLI->has(LibFunc::roundf))
1651 Optimizations["round"] = &UnaryDoubleFP;
1652 if (TLI->has(LibFunc::rint) && TLI->has(LibFunc::rintf))
1653 Optimizations["rint"] = &UnaryDoubleFP;
1654 if (TLI->has(LibFunc::nearbyint) && TLI->has(LibFunc::nearbyintf))
1655 Optimizations["nearbyint"] = &UnaryDoubleFP;
1657 // Integer Optimizations
1658 Optimizations["ffs"] = &FFS;
1659 Optimizations["ffsl"] = &FFS;
1660 Optimizations["ffsll"] = &FFS;
1661 Optimizations["abs"] = &Abs;
1662 Optimizations["labs"] = &Abs;
1663 Optimizations["llabs"] = &Abs;
1664 Optimizations["isdigit"] = &IsDigit;
1665 Optimizations["isascii"] = &IsAscii;
1666 Optimizations["toascii"] = &ToAscii;
1668 // Formatting and IO Optimizations
1669 Optimizations["sprintf"] = &SPrintF;
1670 Optimizations["printf"] = &PrintF;
1671 AddOpt(LibFunc::fwrite, &FWrite);
1672 AddOpt(LibFunc::fputs, &FPuts);
1673 Optimizations["fprintf"] = &FPrintF;
1674 Optimizations["puts"] = &Puts;
1678 /// runOnFunction - Top level algorithm.
1680 bool SimplifyLibCalls::runOnFunction(Function &F) {
1681 TLI = &getAnalysis<TargetLibraryInfo>();
1683 if (Optimizations.empty())
1684 InitOptimizations();
1686 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1688 IRBuilder<> Builder(F.getContext());
1690 bool Changed = false;
1691 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1692 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1693 // Ignore non-calls.
1694 CallInst *CI = dyn_cast<CallInst>(I++);
1697 // Ignore indirect calls and calls to non-external functions.
1698 Function *Callee = CI->getCalledFunction();
1699 if (Callee == 0 || !Callee->isDeclaration() ||
1700 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1703 // Ignore unknown calls.
1704 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1707 // Set the builder to the instruction after the call.
1708 Builder.SetInsertPoint(BB, I);
1710 // Use debug location of CI for all new instructions.
1711 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1713 // Try to optimize this call.
1714 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1715 if (Result == 0) continue;
1717 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1718 dbgs() << " into: " << *Result << "\n");
1720 // Something changed!
1724 // Inspect the instruction after the call (which was potentially just
1728 if (CI != Result && !CI->use_empty()) {
1729 CI->replaceAllUsesWith(Result);
1730 if (!Result->hasName())
1731 Result->takeName(CI);
1733 CI->eraseFromParent();
1739 // Utility methods for doInitialization.
1741 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1742 if (!F.doesNotAccessMemory()) {
1743 F.setDoesNotAccessMemory();
1748 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1749 if (!F.onlyReadsMemory()) {
1750 F.setOnlyReadsMemory();
1755 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1756 if (!F.doesNotThrow()) {
1757 F.setDoesNotThrow();
1762 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1763 if (!F.doesNotCapture(n)) {
1764 F.setDoesNotCapture(n);
1769 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1770 if (!F.doesNotAlias(n)) {
1771 F.setDoesNotAlias(n);
1778 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1779 FunctionType *FTy = F.getFunctionType();
1781 StringRef Name = F.getName();
1784 if (Name == "strlen") {
1785 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1787 setOnlyReadsMemory(F);
1789 setDoesNotCapture(F, 1);
1790 } else if (Name == "strchr" ||
1791 Name == "strrchr") {
1792 if (FTy->getNumParams() != 2 ||
1793 !FTy->getParamType(0)->isPointerTy() ||
1794 !FTy->getParamType(1)->isIntegerTy())
1796 setOnlyReadsMemory(F);
1798 } else if (Name == "strcpy" ||
1804 Name == "strtoul" ||
1805 Name == "strtoll" ||
1806 Name == "strtold" ||
1807 Name == "strncat" ||
1808 Name == "strncpy" ||
1809 Name == "stpncpy" ||
1810 Name == "strtoull") {
1811 if (FTy->getNumParams() < 2 ||
1812 !FTy->getParamType(1)->isPointerTy())
1815 setDoesNotCapture(F, 2);
1816 } else if (Name == "strxfrm") {
1817 if (FTy->getNumParams() != 3 ||
1818 !FTy->getParamType(0)->isPointerTy() ||
1819 !FTy->getParamType(1)->isPointerTy())
1822 setDoesNotCapture(F, 1);
1823 setDoesNotCapture(F, 2);
1824 } else if (Name == "strcmp" ||
1826 Name == "strncmp" ||
1827 Name == "strcspn" ||
1828 Name == "strcoll" ||
1829 Name == "strcasecmp" ||
1830 Name == "strncasecmp") {
1831 if (FTy->getNumParams() < 2 ||
1832 !FTy->getParamType(0)->isPointerTy() ||
1833 !FTy->getParamType(1)->isPointerTy())
1835 setOnlyReadsMemory(F);
1837 setDoesNotCapture(F, 1);
1838 setDoesNotCapture(F, 2);
1839 } else if (Name == "strstr" ||
1840 Name == "strpbrk") {
1841 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1843 setOnlyReadsMemory(F);
1845 setDoesNotCapture(F, 2);
1846 } else if (Name == "strtok" ||
1847 Name == "strtok_r") {
1848 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1851 setDoesNotCapture(F, 2);
1852 } else if (Name == "scanf" ||
1854 Name == "setvbuf") {
1855 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1858 setDoesNotCapture(F, 1);
1859 } else if (Name == "strdup" ||
1860 Name == "strndup") {
1861 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1862 !FTy->getParamType(0)->isPointerTy())
1865 setDoesNotAlias(F, 0);
1866 setDoesNotCapture(F, 1);
1867 } else if (Name == "stat" ||
1869 Name == "sprintf" ||
1870 Name == "statvfs") {
1871 if (FTy->getNumParams() < 2 ||
1872 !FTy->getParamType(0)->isPointerTy() ||
1873 !FTy->getParamType(1)->isPointerTy())
1876 setDoesNotCapture(F, 1);
1877 setDoesNotCapture(F, 2);
1878 } else if (Name == "snprintf") {
1879 if (FTy->getNumParams() != 3 ||
1880 !FTy->getParamType(0)->isPointerTy() ||
1881 !FTy->getParamType(2)->isPointerTy())
1884 setDoesNotCapture(F, 1);
1885 setDoesNotCapture(F, 3);
1886 } else if (Name == "setitimer") {
1887 if (FTy->getNumParams() != 3 ||
1888 !FTy->getParamType(1)->isPointerTy() ||
1889 !FTy->getParamType(2)->isPointerTy())
1892 setDoesNotCapture(F, 2);
1893 setDoesNotCapture(F, 3);
1894 } else if (Name == "system") {
1895 if (FTy->getNumParams() != 1 ||
1896 !FTy->getParamType(0)->isPointerTy())
1898 // May throw; "system" is a valid pthread cancellation point.
1899 setDoesNotCapture(F, 1);
1903 if (Name == "malloc") {
1904 if (FTy->getNumParams() != 1 ||
1905 !FTy->getReturnType()->isPointerTy())
1908 setDoesNotAlias(F, 0);
1909 } else if (Name == "memcmp") {
1910 if (FTy->getNumParams() != 3 ||
1911 !FTy->getParamType(0)->isPointerTy() ||
1912 !FTy->getParamType(1)->isPointerTy())
1914 setOnlyReadsMemory(F);
1916 setDoesNotCapture(F, 1);
1917 setDoesNotCapture(F, 2);
1918 } else if (Name == "memchr" ||
1919 Name == "memrchr") {
1920 if (FTy->getNumParams() != 3)
1922 setOnlyReadsMemory(F);
1924 } else if (Name == "modf" ||
1928 Name == "memccpy" ||
1929 Name == "memmove") {
1930 if (FTy->getNumParams() < 2 ||
1931 !FTy->getParamType(1)->isPointerTy())
1934 setDoesNotCapture(F, 2);
1935 } else if (Name == "memalign") {
1936 if (!FTy->getReturnType()->isPointerTy())
1938 setDoesNotAlias(F, 0);
1939 } else if (Name == "mkdir" ||
1941 if (FTy->getNumParams() == 0 ||
1942 !FTy->getParamType(0)->isPointerTy())
1945 setDoesNotCapture(F, 1);
1949 if (Name == "realloc") {
1950 if (FTy->getNumParams() != 2 ||
1951 !FTy->getParamType(0)->isPointerTy() ||
1952 !FTy->getReturnType()->isPointerTy())
1955 setDoesNotAlias(F, 0);
1956 setDoesNotCapture(F, 1);
1957 } else if (Name == "read") {
1958 if (FTy->getNumParams() != 3 ||
1959 !FTy->getParamType(1)->isPointerTy())
1961 // May throw; "read" is a valid pthread cancellation point.
1962 setDoesNotCapture(F, 2);
1963 } else if (Name == "rmdir" ||
1966 Name == "realpath") {
1967 if (FTy->getNumParams() < 1 ||
1968 !FTy->getParamType(0)->isPointerTy())
1971 setDoesNotCapture(F, 1);
1972 } else if (Name == "rename" ||
1973 Name == "readlink") {
1974 if (FTy->getNumParams() < 2 ||
1975 !FTy->getParamType(0)->isPointerTy() ||
1976 !FTy->getParamType(1)->isPointerTy())
1979 setDoesNotCapture(F, 1);
1980 setDoesNotCapture(F, 2);
1984 if (Name == "write") {
1985 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1987 // May throw; "write" is a valid pthread cancellation point.
1988 setDoesNotCapture(F, 2);
1992 if (Name == "bcopy") {
1993 if (FTy->getNumParams() != 3 ||
1994 !FTy->getParamType(0)->isPointerTy() ||
1995 !FTy->getParamType(1)->isPointerTy())
1998 setDoesNotCapture(F, 1);
1999 setDoesNotCapture(F, 2);
2000 } else if (Name == "bcmp") {
2001 if (FTy->getNumParams() != 3 ||
2002 !FTy->getParamType(0)->isPointerTy() ||
2003 !FTy->getParamType(1)->isPointerTy())
2006 setOnlyReadsMemory(F);
2007 setDoesNotCapture(F, 1);
2008 setDoesNotCapture(F, 2);
2009 } else if (Name == "bzero") {
2010 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2013 setDoesNotCapture(F, 1);
2017 if (Name == "calloc") {
2018 if (FTy->getNumParams() != 2 ||
2019 !FTy->getReturnType()->isPointerTy())
2022 setDoesNotAlias(F, 0);
2023 } else if (Name == "chmod" ||
2025 Name == "ctermid" ||
2026 Name == "clearerr" ||
2027 Name == "closedir") {
2028 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2031 setDoesNotCapture(F, 1);
2035 if (Name == "atoi" ||
2039 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2042 setOnlyReadsMemory(F);
2043 setDoesNotCapture(F, 1);
2044 } else if (Name == "access") {
2045 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2048 setDoesNotCapture(F, 1);
2052 if (Name == "fopen") {
2053 if (FTy->getNumParams() != 2 ||
2054 !FTy->getReturnType()->isPointerTy() ||
2055 !FTy->getParamType(0)->isPointerTy() ||
2056 !FTy->getParamType(1)->isPointerTy())
2059 setDoesNotAlias(F, 0);
2060 setDoesNotCapture(F, 1);
2061 setDoesNotCapture(F, 2);
2062 } else if (Name == "fdopen") {
2063 if (FTy->getNumParams() != 2 ||
2064 !FTy->getReturnType()->isPointerTy() ||
2065 !FTy->getParamType(1)->isPointerTy())
2068 setDoesNotAlias(F, 0);
2069 setDoesNotCapture(F, 2);
2070 } else if (Name == "feof" ||
2080 Name == "fsetpos" ||
2081 Name == "flockfile" ||
2082 Name == "funlockfile" ||
2083 Name == "ftrylockfile") {
2084 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2087 setDoesNotCapture(F, 1);
2088 } else if (Name == "ferror") {
2089 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2092 setDoesNotCapture(F, 1);
2093 setOnlyReadsMemory(F);
2094 } else if (Name == "fputc" ||
2099 Name == "fstatvfs") {
2100 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2103 setDoesNotCapture(F, 2);
2104 } else if (Name == "fgets") {
2105 if (FTy->getNumParams() != 3 ||
2106 !FTy->getParamType(0)->isPointerTy() ||
2107 !FTy->getParamType(2)->isPointerTy())
2110 setDoesNotCapture(F, 3);
2111 } else if (Name == "fread" ||
2113 if (FTy->getNumParams() != 4 ||
2114 !FTy->getParamType(0)->isPointerTy() ||
2115 !FTy->getParamType(3)->isPointerTy())
2118 setDoesNotCapture(F, 1);
2119 setDoesNotCapture(F, 4);
2120 } else if (Name == "fputs" ||
2122 Name == "fprintf" ||
2123 Name == "fgetpos") {
2124 if (FTy->getNumParams() < 2 ||
2125 !FTy->getParamType(0)->isPointerTy() ||
2126 !FTy->getParamType(1)->isPointerTy())
2129 setDoesNotCapture(F, 1);
2130 setDoesNotCapture(F, 2);
2134 if (Name == "getc" ||
2135 Name == "getlogin_r" ||
2136 Name == "getc_unlocked") {
2137 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2140 setDoesNotCapture(F, 1);
2141 } else if (Name == "getenv") {
2142 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2145 setOnlyReadsMemory(F);
2146 setDoesNotCapture(F, 1);
2147 } else if (Name == "gets" ||
2148 Name == "getchar") {
2150 } else if (Name == "getitimer") {
2151 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2154 setDoesNotCapture(F, 2);
2155 } else if (Name == "getpwnam") {
2156 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2159 setDoesNotCapture(F, 1);
2163 if (Name == "ungetc") {
2164 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2167 setDoesNotCapture(F, 2);
2168 } else if (Name == "uname" ||
2170 Name == "unsetenv") {
2171 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2174 setDoesNotCapture(F, 1);
2175 } else if (Name == "utime" ||
2177 if (FTy->getNumParams() != 2 ||
2178 !FTy->getParamType(0)->isPointerTy() ||
2179 !FTy->getParamType(1)->isPointerTy())
2182 setDoesNotCapture(F, 1);
2183 setDoesNotCapture(F, 2);
2187 if (Name == "putc") {
2188 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2191 setDoesNotCapture(F, 2);
2192 } else if (Name == "puts" ||
2195 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2198 setDoesNotCapture(F, 1);
2199 } else if (Name == "pread" ||
2201 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2203 // May throw; these are valid pthread cancellation points.
2204 setDoesNotCapture(F, 2);
2205 } else if (Name == "putchar") {
2207 } else if (Name == "popen") {
2208 if (FTy->getNumParams() != 2 ||
2209 !FTy->getReturnType()->isPointerTy() ||
2210 !FTy->getParamType(0)->isPointerTy() ||
2211 !FTy->getParamType(1)->isPointerTy())
2214 setDoesNotAlias(F, 0);
2215 setDoesNotCapture(F, 1);
2216 setDoesNotCapture(F, 2);
2217 } else if (Name == "pclose") {
2218 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2221 setDoesNotCapture(F, 1);
2225 if (Name == "vscanf") {
2226 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2229 setDoesNotCapture(F, 1);
2230 } else if (Name == "vsscanf" ||
2231 Name == "vfscanf") {
2232 if (FTy->getNumParams() != 3 ||
2233 !FTy->getParamType(1)->isPointerTy() ||
2234 !FTy->getParamType(2)->isPointerTy())
2237 setDoesNotCapture(F, 1);
2238 setDoesNotCapture(F, 2);
2239 } else if (Name == "valloc") {
2240 if (!FTy->getReturnType()->isPointerTy())
2243 setDoesNotAlias(F, 0);
2244 } else if (Name == "vprintf") {
2245 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2248 setDoesNotCapture(F, 1);
2249 } else if (Name == "vfprintf" ||
2250 Name == "vsprintf") {
2251 if (FTy->getNumParams() != 3 ||
2252 !FTy->getParamType(0)->isPointerTy() ||
2253 !FTy->getParamType(1)->isPointerTy())
2256 setDoesNotCapture(F, 1);
2257 setDoesNotCapture(F, 2);
2258 } else if (Name == "vsnprintf") {
2259 if (FTy->getNumParams() != 4 ||
2260 !FTy->getParamType(0)->isPointerTy() ||
2261 !FTy->getParamType(2)->isPointerTy())
2264 setDoesNotCapture(F, 1);
2265 setDoesNotCapture(F, 3);
2269 if (Name == "open") {
2270 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2272 // May throw; "open" is a valid pthread cancellation point.
2273 setDoesNotCapture(F, 1);
2274 } else if (Name == "opendir") {
2275 if (FTy->getNumParams() != 1 ||
2276 !FTy->getReturnType()->isPointerTy() ||
2277 !FTy->getParamType(0)->isPointerTy())
2280 setDoesNotAlias(F, 0);
2281 setDoesNotCapture(F, 1);
2285 if (Name == "tmpfile") {
2286 if (!FTy->getReturnType()->isPointerTy())
2289 setDoesNotAlias(F, 0);
2290 } else if (Name == "times") {
2291 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2294 setDoesNotCapture(F, 1);
2298 if (Name == "htonl" ||
2301 setDoesNotAccessMemory(F);
2305 if (Name == "ntohl" ||
2308 setDoesNotAccessMemory(F);
2312 if (Name == "lstat") {
2313 if (FTy->getNumParams() != 2 ||
2314 !FTy->getParamType(0)->isPointerTy() ||
2315 !FTy->getParamType(1)->isPointerTy())
2318 setDoesNotCapture(F, 1);
2319 setDoesNotCapture(F, 2);
2320 } else if (Name == "lchown") {
2321 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2324 setDoesNotCapture(F, 1);
2328 if (Name == "qsort") {
2329 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2331 // May throw; places call through function pointer.
2332 setDoesNotCapture(F, 4);
2336 if (Name == "__strdup" ||
2337 Name == "__strndup") {
2338 if (FTy->getNumParams() < 1 ||
2339 !FTy->getReturnType()->isPointerTy() ||
2340 !FTy->getParamType(0)->isPointerTy())
2343 setDoesNotAlias(F, 0);
2344 setDoesNotCapture(F, 1);
2345 } else if (Name == "__strtok_r") {
2346 if (FTy->getNumParams() != 3 ||
2347 !FTy->getParamType(1)->isPointerTy())
2350 setDoesNotCapture(F, 2);
2351 } else if (Name == "_IO_getc") {
2352 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2355 setDoesNotCapture(F, 1);
2356 } else if (Name == "_IO_putc") {
2357 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2360 setDoesNotCapture(F, 2);
2364 if (Name == "\1__isoc99_scanf") {
2365 if (FTy->getNumParams() < 1 ||
2366 !FTy->getParamType(0)->isPointerTy())
2369 setDoesNotCapture(F, 1);
2370 } else if (Name == "\1stat64" ||
2371 Name == "\1lstat64" ||
2372 Name == "\1statvfs64" ||
2373 Name == "\1__isoc99_sscanf") {
2374 if (FTy->getNumParams() < 1 ||
2375 !FTy->getParamType(0)->isPointerTy() ||
2376 !FTy->getParamType(1)->isPointerTy())
2379 setDoesNotCapture(F, 1);
2380 setDoesNotCapture(F, 2);
2381 } else if (Name == "\1fopen64") {
2382 if (FTy->getNumParams() != 2 ||
2383 !FTy->getReturnType()->isPointerTy() ||
2384 !FTy->getParamType(0)->isPointerTy() ||
2385 !FTy->getParamType(1)->isPointerTy())
2388 setDoesNotAlias(F, 0);
2389 setDoesNotCapture(F, 1);
2390 setDoesNotCapture(F, 2);
2391 } else if (Name == "\1fseeko64" ||
2392 Name == "\1ftello64") {
2393 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2396 setDoesNotCapture(F, 1);
2397 } else if (Name == "\1tmpfile64") {
2398 if (!FTy->getReturnType()->isPointerTy())
2401 setDoesNotAlias(F, 0);
2402 } else if (Name == "\1fstat64" ||
2403 Name == "\1fstatvfs64") {
2404 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2407 setDoesNotCapture(F, 2);
2408 } else if (Name == "\1open64") {
2409 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2411 // May throw; "open" is a valid pthread cancellation point.
2412 setDoesNotCapture(F, 1);
2418 /// doInitialization - Add attributes to well-known functions.
2420 bool SimplifyLibCalls::doInitialization(Module &M) {
2422 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2424 if (F.isDeclaration() && F.hasName())
2425 inferPrototypeAttributes(F);
2431 // Additional cases that we need to add to this file:
2434 // * cbrt(expN(X)) -> expN(x/3)
2435 // * cbrt(sqrt(x)) -> pow(x,1/6)
2436 // * cbrt(sqrt(x)) -> pow(x,1/9)
2439 // * exp(log(x)) -> x
2442 // * log(exp(x)) -> x
2443 // * log(x**y) -> y*log(x)
2444 // * log(exp(y)) -> y*log(e)
2445 // * log(exp2(y)) -> y*log(2)
2446 // * log(exp10(y)) -> y*log(10)
2447 // * log(sqrt(x)) -> 0.5*log(x)
2448 // * log(pow(x,y)) -> y*log(x)
2450 // lround, lroundf, lroundl:
2451 // * lround(cnst) -> cnst'
2454 // * pow(exp(x),y) -> exp(x*y)
2455 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2456 // * pow(pow(x,y),z)-> pow(x,y*z)
2458 // round, roundf, roundl:
2459 // * round(cnst) -> cnst'
2462 // * signbit(cnst) -> cnst'
2463 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2465 // sqrt, sqrtf, sqrtl:
2466 // * sqrt(expN(x)) -> expN(x*0.5)
2467 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2468 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2471 // * strchr(p, 0) -> strlen(p)
2473 // * tan(atan(x)) -> x
2475 // trunc, truncf, truncl:
2476 // * trunc(cnst) -> cnst'