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);
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);
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);
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);
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);
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 return B.CreateInBoundsGEP(Dst, EmitStrLen(Src, B, TD));
486 // See if we can get the length of the input string.
487 uint64_t Len = GetStringLength(Src);
488 if (Len == 0) return 0;
490 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
491 Value *DstEnd = B.CreateGEP(Dst,
492 ConstantInt::get(TD->getIntPtrType(*Context),
495 // We have enough information to now generate the memcpy call to do the
496 // copy for us. Make a memcpy to copy the nul byte with align = 1.
498 EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD);
500 B.CreateMemCpy(Dst, Src, LenV, 1);
505 //===---------------------------------------===//
506 // 'strncpy' Optimizations
508 struct StrNCpyOpt : public LibCallOptimization {
509 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
510 FunctionType *FT = Callee->getFunctionType();
511 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
512 FT->getParamType(0) != FT->getParamType(1) ||
513 FT->getParamType(0) != B.getInt8PtrTy() ||
514 !FT->getParamType(2)->isIntegerTy())
517 Value *Dst = CI->getArgOperand(0);
518 Value *Src = CI->getArgOperand(1);
519 Value *LenOp = CI->getArgOperand(2);
521 // See if we can get the length of the input string.
522 uint64_t SrcLen = GetStringLength(Src);
523 if (SrcLen == 0) return 0;
527 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
528 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
533 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
534 Len = LengthArg->getZExtValue();
538 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
540 // These optimizations require TargetData.
543 // Let strncpy handle the zero padding
544 if (Len > SrcLen+1) return 0;
546 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
547 B.CreateMemCpy(Dst, Src,
548 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
554 //===---------------------------------------===//
555 // 'strlen' Optimizations
557 struct StrLenOpt : public LibCallOptimization {
558 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
559 FunctionType *FT = Callee->getFunctionType();
560 if (FT->getNumParams() != 1 ||
561 FT->getParamType(0) != B.getInt8PtrTy() ||
562 !FT->getReturnType()->isIntegerTy())
565 Value *Src = CI->getArgOperand(0);
567 // Constant folding: strlen("xyz") -> 3
568 if (uint64_t Len = GetStringLength(Src))
569 return ConstantInt::get(CI->getType(), Len-1);
571 // strlen(x) != 0 --> *x != 0
572 // strlen(x) == 0 --> *x == 0
573 if (IsOnlyUsedInZeroEqualityComparison(CI))
574 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
580 //===---------------------------------------===//
581 // 'strpbrk' Optimizations
583 struct StrPBrkOpt : public LibCallOptimization {
584 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
585 FunctionType *FT = Callee->getFunctionType();
586 if (FT->getNumParams() != 2 ||
587 FT->getParamType(0) != B.getInt8PtrTy() ||
588 FT->getParamType(1) != FT->getParamType(0) ||
589 FT->getReturnType() != FT->getParamType(0))
593 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
594 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
596 // strpbrk(s, "") -> NULL
597 // strpbrk("", s) -> NULL
598 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
599 return Constant::getNullValue(CI->getType());
602 if (HasS1 && HasS2) {
603 size_t I = S1.find_first_of(S2);
604 if (I == std::string::npos) // No match.
605 return Constant::getNullValue(CI->getType());
607 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
610 // strpbrk(s, "a") -> strchr(s, 'a')
611 if (TD && HasS2 && S2.size() == 1)
612 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
618 //===---------------------------------------===//
619 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
621 struct StrToOpt : public LibCallOptimization {
622 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
623 FunctionType *FT = Callee->getFunctionType();
624 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
625 !FT->getParamType(0)->isPointerTy() ||
626 !FT->getParamType(1)->isPointerTy())
629 Value *EndPtr = CI->getArgOperand(1);
630 if (isa<ConstantPointerNull>(EndPtr)) {
631 // With a null EndPtr, this function won't capture the main argument.
632 // It would be readonly too, except that it still may write to errno.
633 CI->addAttribute(1, Attribute::NoCapture);
640 //===---------------------------------------===//
641 // 'strspn' Optimizations
643 struct StrSpnOpt : public LibCallOptimization {
644 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
645 FunctionType *FT = Callee->getFunctionType();
646 if (FT->getNumParams() != 2 ||
647 FT->getParamType(0) != B.getInt8PtrTy() ||
648 FT->getParamType(1) != FT->getParamType(0) ||
649 !FT->getReturnType()->isIntegerTy())
653 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
654 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
656 // strspn(s, "") -> 0
657 // strspn("", s) -> 0
658 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
659 return Constant::getNullValue(CI->getType());
662 if (HasS1 && HasS2) {
663 size_t Pos = S1.find_first_not_of(S2);
664 if (Pos == StringRef::npos) Pos = S1.size();
665 return ConstantInt::get(CI->getType(), Pos);
672 //===---------------------------------------===//
673 // 'strcspn' Optimizations
675 struct StrCSpnOpt : public LibCallOptimization {
676 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
677 FunctionType *FT = Callee->getFunctionType();
678 if (FT->getNumParams() != 2 ||
679 FT->getParamType(0) != B.getInt8PtrTy() ||
680 FT->getParamType(1) != FT->getParamType(0) ||
681 !FT->getReturnType()->isIntegerTy())
685 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
686 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
688 // strcspn("", s) -> 0
689 if (HasS1 && S1.empty())
690 return Constant::getNullValue(CI->getType());
693 if (HasS1 && HasS2) {
694 size_t Pos = S1.find_first_of(S2);
695 if (Pos == StringRef::npos) Pos = S1.size();
696 return ConstantInt::get(CI->getType(), Pos);
699 // strcspn(s, "") -> strlen(s)
700 if (TD && HasS2 && S2.empty())
701 return EmitStrLen(CI->getArgOperand(0), B, TD);
707 //===---------------------------------------===//
708 // 'strstr' Optimizations
710 struct StrStrOpt : public LibCallOptimization {
711 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
712 FunctionType *FT = Callee->getFunctionType();
713 if (FT->getNumParams() != 2 ||
714 !FT->getParamType(0)->isPointerTy() ||
715 !FT->getParamType(1)->isPointerTy() ||
716 !FT->getReturnType()->isPointerTy())
719 // fold strstr(x, x) -> x.
720 if (CI->getArgOperand(0) == CI->getArgOperand(1))
721 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
723 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
724 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
725 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
726 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
728 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
730 ICmpInst *Old = cast<ICmpInst>(*UI++);
731 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
732 ConstantInt::getNullValue(StrNCmp->getType()),
734 Old->replaceAllUsesWith(Cmp);
735 Old->eraseFromParent();
740 // See if either input string is a constant string.
741 StringRef SearchStr, ToFindStr;
742 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
743 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
745 // fold strstr(x, "") -> x.
746 if (HasStr2 && ToFindStr.empty())
747 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
749 // If both strings are known, constant fold it.
750 if (HasStr1 && HasStr2) {
751 std::string::size_type Offset = SearchStr.find(ToFindStr);
753 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
754 return Constant::getNullValue(CI->getType());
756 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
757 Value *Result = CastToCStr(CI->getArgOperand(0), B);
758 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
759 return B.CreateBitCast(Result, CI->getType());
762 // fold strstr(x, "y") -> strchr(x, 'y').
763 if (HasStr2 && ToFindStr.size() == 1)
764 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
765 ToFindStr[0], B, TD), CI->getType());
771 //===---------------------------------------===//
772 // 'memcmp' Optimizations
774 struct MemCmpOpt : public LibCallOptimization {
775 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
776 FunctionType *FT = Callee->getFunctionType();
777 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
778 !FT->getParamType(1)->isPointerTy() ||
779 !FT->getReturnType()->isIntegerTy(32))
782 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
784 if (LHS == RHS) // memcmp(s,s,x) -> 0
785 return Constant::getNullValue(CI->getType());
787 // Make sure we have a constant length.
788 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
790 uint64_t Len = LenC->getZExtValue();
792 if (Len == 0) // memcmp(s1,s2,0) -> 0
793 return Constant::getNullValue(CI->getType());
795 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
797 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
798 CI->getType(), "lhsv");
799 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
800 CI->getType(), "rhsv");
801 return B.CreateSub(LHSV, RHSV, "chardiff");
804 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
805 StringRef LHSStr, RHSStr;
806 if (getConstantStringInfo(LHS, LHSStr) &&
807 getConstantStringInfo(RHS, RHSStr)) {
808 // Make sure we're not reading out-of-bounds memory.
809 if (Len > LHSStr.size() || Len > RHSStr.size())
811 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
812 return ConstantInt::get(CI->getType(), Ret);
819 //===---------------------------------------===//
820 // 'memcpy' Optimizations
822 struct MemCpyOpt : public LibCallOptimization {
823 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
824 // These optimizations require TargetData.
827 FunctionType *FT = Callee->getFunctionType();
828 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
829 !FT->getParamType(0)->isPointerTy() ||
830 !FT->getParamType(1)->isPointerTy() ||
831 FT->getParamType(2) != TD->getIntPtrType(*Context))
834 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
835 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
836 CI->getArgOperand(2), 1);
837 return CI->getArgOperand(0);
841 //===---------------------------------------===//
842 // 'memmove' Optimizations
844 struct MemMoveOpt : public LibCallOptimization {
845 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
846 // These optimizations require TargetData.
849 FunctionType *FT = Callee->getFunctionType();
850 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
851 !FT->getParamType(0)->isPointerTy() ||
852 !FT->getParamType(1)->isPointerTy() ||
853 FT->getParamType(2) != TD->getIntPtrType(*Context))
856 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
857 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
858 CI->getArgOperand(2), 1);
859 return CI->getArgOperand(0);
863 //===---------------------------------------===//
864 // 'memset' Optimizations
866 struct MemSetOpt : public LibCallOptimization {
867 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
868 // These optimizations require TargetData.
871 FunctionType *FT = Callee->getFunctionType();
872 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
873 !FT->getParamType(0)->isPointerTy() ||
874 !FT->getParamType(1)->isIntegerTy() ||
875 FT->getParamType(2) != TD->getIntPtrType(*Context))
878 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
879 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
880 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
881 return CI->getArgOperand(0);
885 //===----------------------------------------------------------------------===//
886 // Math Library Optimizations
887 //===----------------------------------------------------------------------===//
889 //===---------------------------------------===//
890 // 'cos*' Optimizations
892 struct CosOpt : public LibCallOptimization {
893 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
894 FunctionType *FT = Callee->getFunctionType();
895 // Just make sure this has 1 argument of FP type, which matches the
897 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
898 !FT->getParamType(0)->isFloatingPointTy())
902 Value *Op1 = CI->getArgOperand(0);
903 if (BinaryOperator::isFNeg(Op1)) {
904 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
905 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
911 //===---------------------------------------===//
912 // 'pow*' Optimizations
914 struct PowOpt : public LibCallOptimization {
915 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
916 FunctionType *FT = Callee->getFunctionType();
917 // Just make sure this has 2 arguments of the same FP type, which match the
919 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
920 FT->getParamType(0) != FT->getParamType(1) ||
921 !FT->getParamType(0)->isFloatingPointTy())
924 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
925 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
926 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
928 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
929 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
932 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
933 if (Op2C == 0) return 0;
935 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
936 return ConstantFP::get(CI->getType(), 1.0);
938 if (Op2C->isExactlyValue(0.5)) {
939 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
940 // This is faster than calling pow, and still handles negative zero
941 // and negative infinity correctly.
942 // TODO: In fast-math mode, this could be just sqrt(x).
943 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
944 Value *Inf = ConstantFP::getInfinity(CI->getType());
945 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
946 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
947 Callee->getAttributes());
948 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
949 Callee->getAttributes());
950 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
951 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
955 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
957 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
958 return B.CreateFMul(Op1, Op1, "pow2");
959 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
960 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
966 //===---------------------------------------===//
967 // 'exp2' Optimizations
969 struct Exp2Opt : public LibCallOptimization {
970 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
971 FunctionType *FT = Callee->getFunctionType();
972 // Just make sure this has 1 argument of FP type, which matches the
974 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
975 !FT->getParamType(0)->isFloatingPointTy())
978 Value *Op = CI->getArgOperand(0);
979 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
980 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
982 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
983 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
984 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
985 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
986 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
987 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
992 if (Op->getType()->isFloatTy())
994 else if (Op->getType()->isDoubleTy())
999 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1000 if (!Op->getType()->isFloatTy())
1001 One = ConstantExpr::getFPExtend(One, Op->getType());
1003 Module *M = Caller->getParent();
1004 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1006 B.getInt32Ty(), NULL);
1007 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1008 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1009 CI->setCallingConv(F->getCallingConv());
1017 //===---------------------------------------===//
1018 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1020 struct UnaryDoubleFPOpt : public LibCallOptimization {
1021 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1022 FunctionType *FT = Callee->getFunctionType();
1023 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1024 !FT->getParamType(0)->isDoubleTy())
1027 // If this is something like 'floor((double)floatval)', convert to floorf.
1028 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1029 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1032 // floor((double)floatval) -> (double)floorf(floatval)
1033 Value *V = Cast->getOperand(0);
1034 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1035 return B.CreateFPExt(V, B.getDoubleTy());
1039 //===----------------------------------------------------------------------===//
1040 // Integer Optimizations
1041 //===----------------------------------------------------------------------===//
1043 //===---------------------------------------===//
1044 // 'ffs*' Optimizations
1046 struct FFSOpt : public LibCallOptimization {
1047 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1048 FunctionType *FT = Callee->getFunctionType();
1049 // Just make sure this has 2 arguments of the same FP type, which match the
1051 if (FT->getNumParams() != 1 ||
1052 !FT->getReturnType()->isIntegerTy(32) ||
1053 !FT->getParamType(0)->isIntegerTy())
1056 Value *Op = CI->getArgOperand(0);
1059 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1060 if (CI->getValue() == 0) // ffs(0) -> 0.
1061 return Constant::getNullValue(CI->getType());
1062 // ffs(c) -> cttz(c)+1
1063 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1066 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1067 Type *ArgType = Op->getType();
1068 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1069 Intrinsic::cttz, ArgType);
1070 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1071 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1072 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1074 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1075 return B.CreateSelect(Cond, V, B.getInt32(0));
1079 //===---------------------------------------===//
1080 // 'isdigit' Optimizations
1082 struct IsDigitOpt : public LibCallOptimization {
1083 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1084 FunctionType *FT = Callee->getFunctionType();
1085 // We require integer(i32)
1086 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1087 !FT->getParamType(0)->isIntegerTy(32))
1090 // isdigit(c) -> (c-'0') <u 10
1091 Value *Op = CI->getArgOperand(0);
1092 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1093 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1094 return B.CreateZExt(Op, CI->getType());
1098 //===---------------------------------------===//
1099 // 'isascii' Optimizations
1101 struct IsAsciiOpt : public LibCallOptimization {
1102 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1103 FunctionType *FT = Callee->getFunctionType();
1104 // We require integer(i32)
1105 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1106 !FT->getParamType(0)->isIntegerTy(32))
1109 // isascii(c) -> c <u 128
1110 Value *Op = CI->getArgOperand(0);
1111 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1112 return B.CreateZExt(Op, CI->getType());
1116 //===---------------------------------------===//
1117 // 'abs', 'labs', 'llabs' Optimizations
1119 struct AbsOpt : public LibCallOptimization {
1120 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1121 FunctionType *FT = Callee->getFunctionType();
1122 // We require integer(integer) where the types agree.
1123 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1124 FT->getParamType(0) != FT->getReturnType())
1127 // abs(x) -> x >s -1 ? x : -x
1128 Value *Op = CI->getArgOperand(0);
1129 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1131 Value *Neg = B.CreateNeg(Op, "neg");
1132 return B.CreateSelect(Pos, Op, Neg);
1137 //===---------------------------------------===//
1138 // 'toascii' Optimizations
1140 struct ToAsciiOpt : public LibCallOptimization {
1141 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1142 FunctionType *FT = Callee->getFunctionType();
1143 // We require i32(i32)
1144 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1145 !FT->getParamType(0)->isIntegerTy(32))
1148 // isascii(c) -> c & 0x7f
1149 return B.CreateAnd(CI->getArgOperand(0),
1150 ConstantInt::get(CI->getType(),0x7F));
1154 //===----------------------------------------------------------------------===//
1155 // Formatting and IO Optimizations
1156 //===----------------------------------------------------------------------===//
1158 //===---------------------------------------===//
1159 // 'printf' Optimizations
1161 struct PrintFOpt : public LibCallOptimization {
1162 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1164 // Check for a fixed format string.
1165 StringRef FormatStr;
1166 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1169 // Empty format string -> noop.
1170 if (FormatStr.empty()) // Tolerate printf's declared void.
1171 return CI->use_empty() ? (Value*)CI :
1172 ConstantInt::get(CI->getType(), 0);
1174 // Do not do any of the following transformations if the printf return value
1175 // is used, in general the printf return value is not compatible with either
1176 // putchar() or puts().
1177 if (!CI->use_empty())
1180 // printf("x") -> putchar('x'), even for '%'.
1181 if (FormatStr.size() == 1) {
1182 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
1183 if (CI->use_empty()) return CI;
1184 return B.CreateIntCast(Res, CI->getType(), true);
1187 // printf("foo\n") --> puts("foo")
1188 if (FormatStr[FormatStr.size()-1] == '\n' &&
1189 FormatStr.find('%') == std::string::npos) { // no format characters.
1190 // Create a string literal with no \n on it. We expect the constant merge
1191 // pass to be run after this pass, to merge duplicate strings.
1192 FormatStr = FormatStr.drop_back();
1193 Value *GV = B.CreateGlobalString(FormatStr, "str");
1194 EmitPutS(GV, B, TD);
1195 return CI->use_empty() ? (Value*)CI :
1196 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1199 // Optimize specific format strings.
1200 // printf("%c", chr) --> putchar(chr)
1201 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1202 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1203 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
1205 if (CI->use_empty()) return CI;
1206 return B.CreateIntCast(Res, CI->getType(), true);
1209 // printf("%s\n", str) --> puts(str)
1210 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1211 CI->getArgOperand(1)->getType()->isPointerTy()) {
1212 EmitPutS(CI->getArgOperand(1), B, TD);
1218 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1219 // Require one fixed pointer argument and an integer/void result.
1220 FunctionType *FT = Callee->getFunctionType();
1221 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1222 !(FT->getReturnType()->isIntegerTy() ||
1223 FT->getReturnType()->isVoidTy()))
1226 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1230 // printf(format, ...) -> iprintf(format, ...) if no floating point
1232 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1233 Module *M = B.GetInsertBlock()->getParent()->getParent();
1234 Constant *IPrintFFn =
1235 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1236 CallInst *New = cast<CallInst>(CI->clone());
1237 New->setCalledFunction(IPrintFFn);
1245 //===---------------------------------------===//
1246 // 'sprintf' Optimizations
1248 struct SPrintFOpt : public LibCallOptimization {
1249 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1251 // Check for a fixed format string.
1252 StringRef FormatStr;
1253 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1256 // If we just have a format string (nothing else crazy) transform it.
1257 if (CI->getNumArgOperands() == 2) {
1258 // Make sure there's no % in the constant array. We could try to handle
1259 // %% -> % in the future if we cared.
1260 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1261 if (FormatStr[i] == '%')
1262 return 0; // we found a format specifier, bail out.
1264 // These optimizations require TargetData.
1267 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1268 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1269 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1270 FormatStr.size() + 1), 1); // nul byte.
1271 return ConstantInt::get(CI->getType(), FormatStr.size());
1274 // The remaining optimizations require the format string to be "%s" or "%c"
1275 // and have an extra operand.
1276 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1277 CI->getNumArgOperands() < 3)
1280 // Decode the second character of the format string.
1281 if (FormatStr[1] == 'c') {
1282 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1283 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1284 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1285 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1286 B.CreateStore(V, Ptr);
1287 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1288 B.CreateStore(B.getInt8(0), Ptr);
1290 return ConstantInt::get(CI->getType(), 1);
1293 if (FormatStr[1] == 's') {
1294 // These optimizations require TargetData.
1297 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1298 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1300 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
1301 Value *IncLen = B.CreateAdd(Len,
1302 ConstantInt::get(Len->getType(), 1),
1304 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1306 // The sprintf result is the unincremented number of bytes in the string.
1307 return B.CreateIntCast(Len, CI->getType(), false);
1312 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1313 // Require two fixed pointer arguments and an integer result.
1314 FunctionType *FT = Callee->getFunctionType();
1315 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1316 !FT->getParamType(1)->isPointerTy() ||
1317 !FT->getReturnType()->isIntegerTy())
1320 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1324 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1326 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1327 Module *M = B.GetInsertBlock()->getParent()->getParent();
1328 Constant *SIPrintFFn =
1329 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1330 CallInst *New = cast<CallInst>(CI->clone());
1331 New->setCalledFunction(SIPrintFFn);
1339 //===---------------------------------------===//
1340 // 'fwrite' Optimizations
1342 struct FWriteOpt : public LibCallOptimization {
1343 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1344 // Require a pointer, an integer, an integer, a pointer, returning integer.
1345 FunctionType *FT = Callee->getFunctionType();
1346 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1347 !FT->getParamType(1)->isIntegerTy() ||
1348 !FT->getParamType(2)->isIntegerTy() ||
1349 !FT->getParamType(3)->isPointerTy() ||
1350 !FT->getReturnType()->isIntegerTy())
1353 // Get the element size and count.
1354 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1355 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1356 if (!SizeC || !CountC) return 0;
1357 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1359 // If this is writing zero records, remove the call (it's a noop).
1361 return ConstantInt::get(CI->getType(), 0);
1363 // If this is writing one byte, turn it into fputc.
1364 // This optimisation is only valid, if the return value is unused.
1365 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1366 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1367 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
1368 return ConstantInt::get(CI->getType(), 1);
1375 //===---------------------------------------===//
1376 // 'fputs' Optimizations
1378 struct FPutsOpt : public LibCallOptimization {
1379 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1380 // These optimizations require TargetData.
1383 // Require two pointers. Also, we can't optimize if return value is used.
1384 FunctionType *FT = Callee->getFunctionType();
1385 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1386 !FT->getParamType(1)->isPointerTy() ||
1390 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1391 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1393 EmitFWrite(CI->getArgOperand(0),
1394 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1395 CI->getArgOperand(1), B, TD, TLI);
1396 return CI; // Known to have no uses (see above).
1400 //===---------------------------------------===//
1401 // 'fprintf' Optimizations
1403 struct FPrintFOpt : public LibCallOptimization {
1404 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1406 // All the optimizations depend on the format string.
1407 StringRef FormatStr;
1408 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1411 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1412 if (CI->getNumArgOperands() == 2) {
1413 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1414 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1415 return 0; // We found a format specifier.
1417 // These optimizations require TargetData.
1420 EmitFWrite(CI->getArgOperand(1),
1421 ConstantInt::get(TD->getIntPtrType(*Context),
1423 CI->getArgOperand(0), B, TD, TLI);
1424 return ConstantInt::get(CI->getType(), FormatStr.size());
1427 // The remaining optimizations require the format string to be "%s" or "%c"
1428 // and have an extra operand.
1429 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1430 CI->getNumArgOperands() < 3)
1433 // Decode the second character of the format string.
1434 if (FormatStr[1] == 'c') {
1435 // fprintf(F, "%c", chr) --> fputc(chr, F)
1436 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1437 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1438 return ConstantInt::get(CI->getType(), 1);
1441 if (FormatStr[1] == 's') {
1442 // fprintf(F, "%s", str) --> fputs(str, F)
1443 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1445 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1451 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1452 // Require two fixed paramters as pointers and integer result.
1453 FunctionType *FT = Callee->getFunctionType();
1454 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1455 !FT->getParamType(1)->isPointerTy() ||
1456 !FT->getReturnType()->isIntegerTy())
1459 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1463 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1464 // floating point arguments.
1465 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1466 Module *M = B.GetInsertBlock()->getParent()->getParent();
1467 Constant *FIPrintFFn =
1468 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1469 CallInst *New = cast<CallInst>(CI->clone());
1470 New->setCalledFunction(FIPrintFFn);
1478 //===---------------------------------------===//
1479 // 'puts' Optimizations
1481 struct PutsOpt : public LibCallOptimization {
1482 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1483 // Require one fixed pointer argument and an integer/void result.
1484 FunctionType *FT = Callee->getFunctionType();
1485 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1486 !(FT->getReturnType()->isIntegerTy() ||
1487 FT->getReturnType()->isVoidTy()))
1490 // Check for a constant string.
1492 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1495 if (Str.empty() && CI->use_empty()) {
1496 // puts("") -> putchar('\n')
1497 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1498 if (CI->use_empty()) return CI;
1499 return B.CreateIntCast(Res, CI->getType(), true);
1506 } // end anonymous namespace.
1508 //===----------------------------------------------------------------------===//
1509 // SimplifyLibCalls Pass Implementation
1510 //===----------------------------------------------------------------------===//
1513 /// This pass optimizes well known library functions from libc and libm.
1515 class SimplifyLibCalls : public FunctionPass {
1516 TargetLibraryInfo *TLI;
1518 StringMap<LibCallOptimization*> Optimizations;
1519 // String and Memory LibCall Optimizations
1520 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1521 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1522 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1523 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1525 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1526 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1527 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1528 // Math Library Optimizations
1529 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1530 // Integer Optimizations
1531 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1533 // Formatting and IO Optimizations
1534 SPrintFOpt SPrintF; PrintFOpt PrintF;
1535 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1538 bool Modified; // This is only used by doInitialization.
1540 static char ID; // Pass identification
1541 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1542 StpCpy(false), StpCpyChk(true) {
1543 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1545 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1546 void InitOptimizations();
1547 bool runOnFunction(Function &F);
1549 void setDoesNotAccessMemory(Function &F);
1550 void setOnlyReadsMemory(Function &F);
1551 void setDoesNotThrow(Function &F);
1552 void setDoesNotCapture(Function &F, unsigned n);
1553 void setDoesNotAlias(Function &F, unsigned n);
1554 bool doInitialization(Module &M);
1556 void inferPrototypeAttributes(Function &F);
1557 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1558 AU.addRequired<TargetLibraryInfo>();
1561 } // end anonymous namespace.
1563 char SimplifyLibCalls::ID = 0;
1565 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1566 "Simplify well-known library calls", false, false)
1567 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1568 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1569 "Simplify well-known library calls", false, false)
1571 // Public interface to the Simplify LibCalls pass.
1572 FunctionPass *llvm::createSimplifyLibCallsPass() {
1573 return new SimplifyLibCalls();
1576 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1578 Optimizations[TLI->getName(F)] = Opt;
1581 /// Optimizations - Populate the Optimizations map with all the optimizations
1583 void SimplifyLibCalls::InitOptimizations() {
1584 // String and Memory LibCall Optimizations
1585 Optimizations["strcat"] = &StrCat;
1586 Optimizations["strncat"] = &StrNCat;
1587 Optimizations["strchr"] = &StrChr;
1588 Optimizations["strrchr"] = &StrRChr;
1589 Optimizations["strcmp"] = &StrCmp;
1590 Optimizations["strncmp"] = &StrNCmp;
1591 Optimizations["strcpy"] = &StrCpy;
1592 Optimizations["strncpy"] = &StrNCpy;
1593 Optimizations["stpcpy"] = &StpCpy;
1594 Optimizations["strlen"] = &StrLen;
1595 Optimizations["strpbrk"] = &StrPBrk;
1596 Optimizations["strtol"] = &StrTo;
1597 Optimizations["strtod"] = &StrTo;
1598 Optimizations["strtof"] = &StrTo;
1599 Optimizations["strtoul"] = &StrTo;
1600 Optimizations["strtoll"] = &StrTo;
1601 Optimizations["strtold"] = &StrTo;
1602 Optimizations["strtoull"] = &StrTo;
1603 Optimizations["strspn"] = &StrSpn;
1604 Optimizations["strcspn"] = &StrCSpn;
1605 Optimizations["strstr"] = &StrStr;
1606 Optimizations["memcmp"] = &MemCmp;
1607 AddOpt(LibFunc::memcpy, &MemCpy);
1608 Optimizations["memmove"] = &MemMove;
1609 AddOpt(LibFunc::memset, &MemSet);
1611 // _chk variants of String and Memory LibCall Optimizations.
1612 Optimizations["__strcpy_chk"] = &StrCpyChk;
1613 Optimizations["__stpcpy_chk"] = &StpCpyChk;
1615 // Math Library Optimizations
1616 Optimizations["cosf"] = &Cos;
1617 Optimizations["cos"] = &Cos;
1618 Optimizations["cosl"] = &Cos;
1619 Optimizations["powf"] = &Pow;
1620 Optimizations["pow"] = &Pow;
1621 Optimizations["powl"] = &Pow;
1622 Optimizations["llvm.pow.f32"] = &Pow;
1623 Optimizations["llvm.pow.f64"] = &Pow;
1624 Optimizations["llvm.pow.f80"] = &Pow;
1625 Optimizations["llvm.pow.f128"] = &Pow;
1626 Optimizations["llvm.pow.ppcf128"] = &Pow;
1627 Optimizations["exp2l"] = &Exp2;
1628 Optimizations["exp2"] = &Exp2;
1629 Optimizations["exp2f"] = &Exp2;
1630 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1631 Optimizations["llvm.exp2.f128"] = &Exp2;
1632 Optimizations["llvm.exp2.f80"] = &Exp2;
1633 Optimizations["llvm.exp2.f64"] = &Exp2;
1634 Optimizations["llvm.exp2.f32"] = &Exp2;
1636 if (TLI->has(LibFunc::floor) && TLI->has(LibFunc::floorf))
1637 Optimizations["floor"] = &UnaryDoubleFP;
1638 if (TLI->has(LibFunc::ceil) && TLI->has(LibFunc::ceilf))
1639 Optimizations["ceil"] = &UnaryDoubleFP;
1640 if (TLI->has(LibFunc::round) && TLI->has(LibFunc::roundf))
1641 Optimizations["round"] = &UnaryDoubleFP;
1642 if (TLI->has(LibFunc::rint) && TLI->has(LibFunc::rintf))
1643 Optimizations["rint"] = &UnaryDoubleFP;
1644 if (TLI->has(LibFunc::nearbyint) && TLI->has(LibFunc::nearbyintf))
1645 Optimizations["nearbyint"] = &UnaryDoubleFP;
1647 // Integer Optimizations
1648 Optimizations["ffs"] = &FFS;
1649 Optimizations["ffsl"] = &FFS;
1650 Optimizations["ffsll"] = &FFS;
1651 Optimizations["abs"] = &Abs;
1652 Optimizations["labs"] = &Abs;
1653 Optimizations["llabs"] = &Abs;
1654 Optimizations["isdigit"] = &IsDigit;
1655 Optimizations["isascii"] = &IsAscii;
1656 Optimizations["toascii"] = &ToAscii;
1658 // Formatting and IO Optimizations
1659 Optimizations["sprintf"] = &SPrintF;
1660 Optimizations["printf"] = &PrintF;
1661 AddOpt(LibFunc::fwrite, &FWrite);
1662 AddOpt(LibFunc::fputs, &FPuts);
1663 Optimizations["fprintf"] = &FPrintF;
1664 Optimizations["puts"] = &Puts;
1668 /// runOnFunction - Top level algorithm.
1670 bool SimplifyLibCalls::runOnFunction(Function &F) {
1671 TLI = &getAnalysis<TargetLibraryInfo>();
1673 if (Optimizations.empty())
1674 InitOptimizations();
1676 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1678 IRBuilder<> Builder(F.getContext());
1680 bool Changed = false;
1681 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1682 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1683 // Ignore non-calls.
1684 CallInst *CI = dyn_cast<CallInst>(I++);
1687 // Ignore indirect calls and calls to non-external functions.
1688 Function *Callee = CI->getCalledFunction();
1689 if (Callee == 0 || !Callee->isDeclaration() ||
1690 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1693 // Ignore unknown calls.
1694 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1697 // Set the builder to the instruction after the call.
1698 Builder.SetInsertPoint(BB, I);
1700 // Use debug location of CI for all new instructions.
1701 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1703 // Try to optimize this call.
1704 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1705 if (Result == 0) continue;
1707 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1708 dbgs() << " into: " << *Result << "\n");
1710 // Something changed!
1714 // Inspect the instruction after the call (which was potentially just
1718 if (CI != Result && !CI->use_empty()) {
1719 CI->replaceAllUsesWith(Result);
1720 if (!Result->hasName())
1721 Result->takeName(CI);
1723 CI->eraseFromParent();
1729 // Utility methods for doInitialization.
1731 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1732 if (!F.doesNotAccessMemory()) {
1733 F.setDoesNotAccessMemory();
1738 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1739 if (!F.onlyReadsMemory()) {
1740 F.setOnlyReadsMemory();
1745 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1746 if (!F.doesNotThrow()) {
1747 F.setDoesNotThrow();
1752 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1753 if (!F.doesNotCapture(n)) {
1754 F.setDoesNotCapture(n);
1759 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1760 if (!F.doesNotAlias(n)) {
1761 F.setDoesNotAlias(n);
1768 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1769 FunctionType *FTy = F.getFunctionType();
1771 StringRef Name = F.getName();
1774 if (Name == "strlen") {
1775 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1777 setOnlyReadsMemory(F);
1779 setDoesNotCapture(F, 1);
1780 } else if (Name == "strchr" ||
1781 Name == "strrchr") {
1782 if (FTy->getNumParams() != 2 ||
1783 !FTy->getParamType(0)->isPointerTy() ||
1784 !FTy->getParamType(1)->isIntegerTy())
1786 setOnlyReadsMemory(F);
1788 } else if (Name == "strcpy" ||
1794 Name == "strtoul" ||
1795 Name == "strtoll" ||
1796 Name == "strtold" ||
1797 Name == "strncat" ||
1798 Name == "strncpy" ||
1799 Name == "stpncpy" ||
1800 Name == "strtoull") {
1801 if (FTy->getNumParams() < 2 ||
1802 !FTy->getParamType(1)->isPointerTy())
1805 setDoesNotCapture(F, 2);
1806 } else if (Name == "strxfrm") {
1807 if (FTy->getNumParams() != 3 ||
1808 !FTy->getParamType(0)->isPointerTy() ||
1809 !FTy->getParamType(1)->isPointerTy())
1812 setDoesNotCapture(F, 1);
1813 setDoesNotCapture(F, 2);
1814 } else if (Name == "strcmp" ||
1816 Name == "strncmp" ||
1817 Name == "strcspn" ||
1818 Name == "strcoll" ||
1819 Name == "strcasecmp" ||
1820 Name == "strncasecmp") {
1821 if (FTy->getNumParams() < 2 ||
1822 !FTy->getParamType(0)->isPointerTy() ||
1823 !FTy->getParamType(1)->isPointerTy())
1825 setOnlyReadsMemory(F);
1827 setDoesNotCapture(F, 1);
1828 setDoesNotCapture(F, 2);
1829 } else if (Name == "strstr" ||
1830 Name == "strpbrk") {
1831 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1833 setOnlyReadsMemory(F);
1835 setDoesNotCapture(F, 2);
1836 } else if (Name == "strtok" ||
1837 Name == "strtok_r") {
1838 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1841 setDoesNotCapture(F, 2);
1842 } else if (Name == "scanf" ||
1844 Name == "setvbuf") {
1845 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1848 setDoesNotCapture(F, 1);
1849 } else if (Name == "strdup" ||
1850 Name == "strndup") {
1851 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1852 !FTy->getParamType(0)->isPointerTy())
1855 setDoesNotAlias(F, 0);
1856 setDoesNotCapture(F, 1);
1857 } else if (Name == "stat" ||
1859 Name == "sprintf" ||
1860 Name == "statvfs") {
1861 if (FTy->getNumParams() < 2 ||
1862 !FTy->getParamType(0)->isPointerTy() ||
1863 !FTy->getParamType(1)->isPointerTy())
1866 setDoesNotCapture(F, 1);
1867 setDoesNotCapture(F, 2);
1868 } else if (Name == "snprintf") {
1869 if (FTy->getNumParams() != 3 ||
1870 !FTy->getParamType(0)->isPointerTy() ||
1871 !FTy->getParamType(2)->isPointerTy())
1874 setDoesNotCapture(F, 1);
1875 setDoesNotCapture(F, 3);
1876 } else if (Name == "setitimer") {
1877 if (FTy->getNumParams() != 3 ||
1878 !FTy->getParamType(1)->isPointerTy() ||
1879 !FTy->getParamType(2)->isPointerTy())
1882 setDoesNotCapture(F, 2);
1883 setDoesNotCapture(F, 3);
1884 } else if (Name == "system") {
1885 if (FTy->getNumParams() != 1 ||
1886 !FTy->getParamType(0)->isPointerTy())
1888 // May throw; "system" is a valid pthread cancellation point.
1889 setDoesNotCapture(F, 1);
1893 if (Name == "malloc") {
1894 if (FTy->getNumParams() != 1 ||
1895 !FTy->getReturnType()->isPointerTy())
1898 setDoesNotAlias(F, 0);
1899 } else if (Name == "memcmp") {
1900 if (FTy->getNumParams() != 3 ||
1901 !FTy->getParamType(0)->isPointerTy() ||
1902 !FTy->getParamType(1)->isPointerTy())
1904 setOnlyReadsMemory(F);
1906 setDoesNotCapture(F, 1);
1907 setDoesNotCapture(F, 2);
1908 } else if (Name == "memchr" ||
1909 Name == "memrchr") {
1910 if (FTy->getNumParams() != 3)
1912 setOnlyReadsMemory(F);
1914 } else if (Name == "modf" ||
1918 Name == "memccpy" ||
1919 Name == "memmove") {
1920 if (FTy->getNumParams() < 2 ||
1921 !FTy->getParamType(1)->isPointerTy())
1924 setDoesNotCapture(F, 2);
1925 } else if (Name == "memalign") {
1926 if (!FTy->getReturnType()->isPointerTy())
1928 setDoesNotAlias(F, 0);
1929 } else if (Name == "mkdir" ||
1931 if (FTy->getNumParams() == 0 ||
1932 !FTy->getParamType(0)->isPointerTy())
1935 setDoesNotCapture(F, 1);
1939 if (Name == "realloc") {
1940 if (FTy->getNumParams() != 2 ||
1941 !FTy->getParamType(0)->isPointerTy() ||
1942 !FTy->getReturnType()->isPointerTy())
1945 setDoesNotAlias(F, 0);
1946 setDoesNotCapture(F, 1);
1947 } else if (Name == "read") {
1948 if (FTy->getNumParams() != 3 ||
1949 !FTy->getParamType(1)->isPointerTy())
1951 // May throw; "read" is a valid pthread cancellation point.
1952 setDoesNotCapture(F, 2);
1953 } else if (Name == "rmdir" ||
1956 Name == "realpath") {
1957 if (FTy->getNumParams() < 1 ||
1958 !FTy->getParamType(0)->isPointerTy())
1961 setDoesNotCapture(F, 1);
1962 } else if (Name == "rename" ||
1963 Name == "readlink") {
1964 if (FTy->getNumParams() < 2 ||
1965 !FTy->getParamType(0)->isPointerTy() ||
1966 !FTy->getParamType(1)->isPointerTy())
1969 setDoesNotCapture(F, 1);
1970 setDoesNotCapture(F, 2);
1974 if (Name == "write") {
1975 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1977 // May throw; "write" is a valid pthread cancellation point.
1978 setDoesNotCapture(F, 2);
1982 if (Name == "bcopy") {
1983 if (FTy->getNumParams() != 3 ||
1984 !FTy->getParamType(0)->isPointerTy() ||
1985 !FTy->getParamType(1)->isPointerTy())
1988 setDoesNotCapture(F, 1);
1989 setDoesNotCapture(F, 2);
1990 } else if (Name == "bcmp") {
1991 if (FTy->getNumParams() != 3 ||
1992 !FTy->getParamType(0)->isPointerTy() ||
1993 !FTy->getParamType(1)->isPointerTy())
1996 setOnlyReadsMemory(F);
1997 setDoesNotCapture(F, 1);
1998 setDoesNotCapture(F, 2);
1999 } else if (Name == "bzero") {
2000 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2003 setDoesNotCapture(F, 1);
2007 if (Name == "calloc") {
2008 if (FTy->getNumParams() != 2 ||
2009 !FTy->getReturnType()->isPointerTy())
2012 setDoesNotAlias(F, 0);
2013 } else if (Name == "chmod" ||
2015 Name == "ctermid" ||
2016 Name == "clearerr" ||
2017 Name == "closedir") {
2018 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2021 setDoesNotCapture(F, 1);
2025 if (Name == "atoi" ||
2029 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2032 setOnlyReadsMemory(F);
2033 setDoesNotCapture(F, 1);
2034 } else if (Name == "access") {
2035 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2038 setDoesNotCapture(F, 1);
2042 if (Name == "fopen") {
2043 if (FTy->getNumParams() != 2 ||
2044 !FTy->getReturnType()->isPointerTy() ||
2045 !FTy->getParamType(0)->isPointerTy() ||
2046 !FTy->getParamType(1)->isPointerTy())
2049 setDoesNotAlias(F, 0);
2050 setDoesNotCapture(F, 1);
2051 setDoesNotCapture(F, 2);
2052 } else if (Name == "fdopen") {
2053 if (FTy->getNumParams() != 2 ||
2054 !FTy->getReturnType()->isPointerTy() ||
2055 !FTy->getParamType(1)->isPointerTy())
2058 setDoesNotAlias(F, 0);
2059 setDoesNotCapture(F, 2);
2060 } else if (Name == "feof" ||
2070 Name == "fsetpos" ||
2071 Name == "flockfile" ||
2072 Name == "funlockfile" ||
2073 Name == "ftrylockfile") {
2074 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2077 setDoesNotCapture(F, 1);
2078 } else if (Name == "ferror") {
2079 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2082 setDoesNotCapture(F, 1);
2083 setOnlyReadsMemory(F);
2084 } else if (Name == "fputc" ||
2089 Name == "fstatvfs") {
2090 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2093 setDoesNotCapture(F, 2);
2094 } else if (Name == "fgets") {
2095 if (FTy->getNumParams() != 3 ||
2096 !FTy->getParamType(0)->isPointerTy() ||
2097 !FTy->getParamType(2)->isPointerTy())
2100 setDoesNotCapture(F, 3);
2101 } else if (Name == "fread" ||
2103 if (FTy->getNumParams() != 4 ||
2104 !FTy->getParamType(0)->isPointerTy() ||
2105 !FTy->getParamType(3)->isPointerTy())
2108 setDoesNotCapture(F, 1);
2109 setDoesNotCapture(F, 4);
2110 } else if (Name == "fputs" ||
2112 Name == "fprintf" ||
2113 Name == "fgetpos") {
2114 if (FTy->getNumParams() < 2 ||
2115 !FTy->getParamType(0)->isPointerTy() ||
2116 !FTy->getParamType(1)->isPointerTy())
2119 setDoesNotCapture(F, 1);
2120 setDoesNotCapture(F, 2);
2124 if (Name == "getc" ||
2125 Name == "getlogin_r" ||
2126 Name == "getc_unlocked") {
2127 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2130 setDoesNotCapture(F, 1);
2131 } else if (Name == "getenv") {
2132 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2135 setOnlyReadsMemory(F);
2136 setDoesNotCapture(F, 1);
2137 } else if (Name == "gets" ||
2138 Name == "getchar") {
2140 } else if (Name == "getitimer") {
2141 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2144 setDoesNotCapture(F, 2);
2145 } else if (Name == "getpwnam") {
2146 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2149 setDoesNotCapture(F, 1);
2153 if (Name == "ungetc") {
2154 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2157 setDoesNotCapture(F, 2);
2158 } else if (Name == "uname" ||
2160 Name == "unsetenv") {
2161 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2164 setDoesNotCapture(F, 1);
2165 } else if (Name == "utime" ||
2167 if (FTy->getNumParams() != 2 ||
2168 !FTy->getParamType(0)->isPointerTy() ||
2169 !FTy->getParamType(1)->isPointerTy())
2172 setDoesNotCapture(F, 1);
2173 setDoesNotCapture(F, 2);
2177 if (Name == "putc") {
2178 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2181 setDoesNotCapture(F, 2);
2182 } else if (Name == "puts" ||
2185 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2188 setDoesNotCapture(F, 1);
2189 } else if (Name == "pread" ||
2191 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2193 // May throw; these are valid pthread cancellation points.
2194 setDoesNotCapture(F, 2);
2195 } else if (Name == "putchar") {
2197 } else if (Name == "popen") {
2198 if (FTy->getNumParams() != 2 ||
2199 !FTy->getReturnType()->isPointerTy() ||
2200 !FTy->getParamType(0)->isPointerTy() ||
2201 !FTy->getParamType(1)->isPointerTy())
2204 setDoesNotAlias(F, 0);
2205 setDoesNotCapture(F, 1);
2206 setDoesNotCapture(F, 2);
2207 } else if (Name == "pclose") {
2208 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2211 setDoesNotCapture(F, 1);
2215 if (Name == "vscanf") {
2216 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2219 setDoesNotCapture(F, 1);
2220 } else if (Name == "vsscanf" ||
2221 Name == "vfscanf") {
2222 if (FTy->getNumParams() != 3 ||
2223 !FTy->getParamType(1)->isPointerTy() ||
2224 !FTy->getParamType(2)->isPointerTy())
2227 setDoesNotCapture(F, 1);
2228 setDoesNotCapture(F, 2);
2229 } else if (Name == "valloc") {
2230 if (!FTy->getReturnType()->isPointerTy())
2233 setDoesNotAlias(F, 0);
2234 } else if (Name == "vprintf") {
2235 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2238 setDoesNotCapture(F, 1);
2239 } else if (Name == "vfprintf" ||
2240 Name == "vsprintf") {
2241 if (FTy->getNumParams() != 3 ||
2242 !FTy->getParamType(0)->isPointerTy() ||
2243 !FTy->getParamType(1)->isPointerTy())
2246 setDoesNotCapture(F, 1);
2247 setDoesNotCapture(F, 2);
2248 } else if (Name == "vsnprintf") {
2249 if (FTy->getNumParams() != 4 ||
2250 !FTy->getParamType(0)->isPointerTy() ||
2251 !FTy->getParamType(2)->isPointerTy())
2254 setDoesNotCapture(F, 1);
2255 setDoesNotCapture(F, 3);
2259 if (Name == "open") {
2260 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2262 // May throw; "open" is a valid pthread cancellation point.
2263 setDoesNotCapture(F, 1);
2264 } else if (Name == "opendir") {
2265 if (FTy->getNumParams() != 1 ||
2266 !FTy->getReturnType()->isPointerTy() ||
2267 !FTy->getParamType(0)->isPointerTy())
2270 setDoesNotAlias(F, 0);
2271 setDoesNotCapture(F, 1);
2275 if (Name == "tmpfile") {
2276 if (!FTy->getReturnType()->isPointerTy())
2279 setDoesNotAlias(F, 0);
2280 } else if (Name == "times") {
2281 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2284 setDoesNotCapture(F, 1);
2288 if (Name == "htonl" ||
2291 setDoesNotAccessMemory(F);
2295 if (Name == "ntohl" ||
2298 setDoesNotAccessMemory(F);
2302 if (Name == "lstat") {
2303 if (FTy->getNumParams() != 2 ||
2304 !FTy->getParamType(0)->isPointerTy() ||
2305 !FTy->getParamType(1)->isPointerTy())
2308 setDoesNotCapture(F, 1);
2309 setDoesNotCapture(F, 2);
2310 } else if (Name == "lchown") {
2311 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2314 setDoesNotCapture(F, 1);
2318 if (Name == "qsort") {
2319 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2321 // May throw; places call through function pointer.
2322 setDoesNotCapture(F, 4);
2326 if (Name == "__strdup" ||
2327 Name == "__strndup") {
2328 if (FTy->getNumParams() < 1 ||
2329 !FTy->getReturnType()->isPointerTy() ||
2330 !FTy->getParamType(0)->isPointerTy())
2333 setDoesNotAlias(F, 0);
2334 setDoesNotCapture(F, 1);
2335 } else if (Name == "__strtok_r") {
2336 if (FTy->getNumParams() != 3 ||
2337 !FTy->getParamType(1)->isPointerTy())
2340 setDoesNotCapture(F, 2);
2341 } else if (Name == "_IO_getc") {
2342 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2345 setDoesNotCapture(F, 1);
2346 } else if (Name == "_IO_putc") {
2347 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2350 setDoesNotCapture(F, 2);
2354 if (Name == "\1__isoc99_scanf") {
2355 if (FTy->getNumParams() < 1 ||
2356 !FTy->getParamType(0)->isPointerTy())
2359 setDoesNotCapture(F, 1);
2360 } else if (Name == "\1stat64" ||
2361 Name == "\1lstat64" ||
2362 Name == "\1statvfs64" ||
2363 Name == "\1__isoc99_sscanf") {
2364 if (FTy->getNumParams() < 1 ||
2365 !FTy->getParamType(0)->isPointerTy() ||
2366 !FTy->getParamType(1)->isPointerTy())
2369 setDoesNotCapture(F, 1);
2370 setDoesNotCapture(F, 2);
2371 } else if (Name == "\1fopen64") {
2372 if (FTy->getNumParams() != 2 ||
2373 !FTy->getReturnType()->isPointerTy() ||
2374 !FTy->getParamType(0)->isPointerTy() ||
2375 !FTy->getParamType(1)->isPointerTy())
2378 setDoesNotAlias(F, 0);
2379 setDoesNotCapture(F, 1);
2380 setDoesNotCapture(F, 2);
2381 } else if (Name == "\1fseeko64" ||
2382 Name == "\1ftello64") {
2383 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2386 setDoesNotCapture(F, 1);
2387 } else if (Name == "\1tmpfile64") {
2388 if (!FTy->getReturnType()->isPointerTy())
2391 setDoesNotAlias(F, 0);
2392 } else if (Name == "\1fstat64" ||
2393 Name == "\1fstatvfs64") {
2394 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2397 setDoesNotCapture(F, 2);
2398 } else if (Name == "\1open64") {
2399 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2401 // May throw; "open" is a valid pthread cancellation point.
2402 setDoesNotCapture(F, 1);
2408 /// doInitialization - Add attributes to well-known functions.
2410 bool SimplifyLibCalls::doInitialization(Module &M) {
2412 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2414 if (F.isDeclaration() && F.hasName())
2415 inferPrototypeAttributes(F);
2421 // Additional cases that we need to add to this file:
2424 // * cbrt(expN(X)) -> expN(x/3)
2425 // * cbrt(sqrt(x)) -> pow(x,1/6)
2426 // * cbrt(sqrt(x)) -> pow(x,1/9)
2429 // * exp(log(x)) -> x
2432 // * log(exp(x)) -> x
2433 // * log(x**y) -> y*log(x)
2434 // * log(exp(y)) -> y*log(e)
2435 // * log(exp2(y)) -> y*log(2)
2436 // * log(exp10(y)) -> y*log(10)
2437 // * log(sqrt(x)) -> 0.5*log(x)
2438 // * log(pow(x,y)) -> y*log(x)
2440 // lround, lroundf, lroundl:
2441 // * lround(cnst) -> cnst'
2444 // * pow(exp(x),y) -> exp(x*y)
2445 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2446 // * pow(pow(x,y),z)-> pow(x,y*z)
2448 // round, roundf, roundl:
2449 // * round(cnst) -> cnst'
2452 // * signbit(cnst) -> cnst'
2453 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2455 // sqrt, sqrtf, sqrtl:
2456 // * sqrt(expN(x)) -> expN(x*0.5)
2457 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2458 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2461 // * strchr(p, 0) -> strlen(p)
2463 // * tan(atan(x)) -> x
2465 // trunc, truncf, truncl:
2466 // * trunc(cnst) -> cnst'