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/Intrinsics.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLibraryInfo.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.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 // 'strncpy' Optimizations
464 struct StrNCpyOpt : public LibCallOptimization {
465 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
466 FunctionType *FT = Callee->getFunctionType();
467 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
468 FT->getParamType(0) != FT->getParamType(1) ||
469 FT->getParamType(0) != B.getInt8PtrTy() ||
470 !FT->getParamType(2)->isIntegerTy())
473 Value *Dst = CI->getArgOperand(0);
474 Value *Src = CI->getArgOperand(1);
475 Value *LenOp = CI->getArgOperand(2);
477 // See if we can get the length of the input string.
478 uint64_t SrcLen = GetStringLength(Src);
479 if (SrcLen == 0) return 0;
483 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
484 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
489 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
490 Len = LengthArg->getZExtValue();
494 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
496 // These optimizations require TargetData.
499 // Let strncpy handle the zero padding
500 if (Len > SrcLen+1) return 0;
502 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
503 B.CreateMemCpy(Dst, Src,
504 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
510 //===---------------------------------------===//
511 // 'strlen' Optimizations
513 struct StrLenOpt : public LibCallOptimization {
514 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
515 FunctionType *FT = Callee->getFunctionType();
516 if (FT->getNumParams() != 1 ||
517 FT->getParamType(0) != B.getInt8PtrTy() ||
518 !FT->getReturnType()->isIntegerTy())
521 Value *Src = CI->getArgOperand(0);
523 // Constant folding: strlen("xyz") -> 3
524 if (uint64_t Len = GetStringLength(Src))
525 return ConstantInt::get(CI->getType(), Len-1);
527 // strlen(x) != 0 --> *x != 0
528 // strlen(x) == 0 --> *x == 0
529 if (IsOnlyUsedInZeroEqualityComparison(CI))
530 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
536 //===---------------------------------------===//
537 // 'strpbrk' Optimizations
539 struct StrPBrkOpt : public LibCallOptimization {
540 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
541 FunctionType *FT = Callee->getFunctionType();
542 if (FT->getNumParams() != 2 ||
543 FT->getParamType(0) != B.getInt8PtrTy() ||
544 FT->getParamType(1) != FT->getParamType(0) ||
545 FT->getReturnType() != FT->getParamType(0))
549 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
550 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
552 // strpbrk(s, "") -> NULL
553 // strpbrk("", s) -> NULL
554 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
555 return Constant::getNullValue(CI->getType());
558 if (HasS1 && HasS2) {
559 size_t I = S1.find_first_of(S2);
560 if (I == std::string::npos) // No match.
561 return Constant::getNullValue(CI->getType());
563 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
566 // strpbrk(s, "a") -> strchr(s, 'a')
567 if (TD && HasS2 && S2.size() == 1)
568 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
574 //===---------------------------------------===//
575 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
577 struct StrToOpt : public LibCallOptimization {
578 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
579 FunctionType *FT = Callee->getFunctionType();
580 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
581 !FT->getParamType(0)->isPointerTy() ||
582 !FT->getParamType(1)->isPointerTy())
585 Value *EndPtr = CI->getArgOperand(1);
586 if (isa<ConstantPointerNull>(EndPtr)) {
587 // With a null EndPtr, this function won't capture the main argument.
588 // It would be readonly too, except that it still may write to errno.
589 CI->addAttribute(1, Attribute::NoCapture);
596 //===---------------------------------------===//
597 // 'strspn' Optimizations
599 struct StrSpnOpt : public LibCallOptimization {
600 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
601 FunctionType *FT = Callee->getFunctionType();
602 if (FT->getNumParams() != 2 ||
603 FT->getParamType(0) != B.getInt8PtrTy() ||
604 FT->getParamType(1) != FT->getParamType(0) ||
605 !FT->getReturnType()->isIntegerTy())
609 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
610 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
612 // strspn(s, "") -> 0
613 // strspn("", s) -> 0
614 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
615 return Constant::getNullValue(CI->getType());
618 if (HasS1 && HasS2) {
619 size_t Pos = S1.find_first_not_of(S2);
620 if (Pos == StringRef::npos) Pos = S1.size();
621 return ConstantInt::get(CI->getType(), Pos);
628 //===---------------------------------------===//
629 // 'strcspn' Optimizations
631 struct StrCSpnOpt : public LibCallOptimization {
632 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
633 FunctionType *FT = Callee->getFunctionType();
634 if (FT->getNumParams() != 2 ||
635 FT->getParamType(0) != B.getInt8PtrTy() ||
636 FT->getParamType(1) != FT->getParamType(0) ||
637 !FT->getReturnType()->isIntegerTy())
641 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
642 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
644 // strcspn("", s) -> 0
645 if (HasS1 && S1.empty())
646 return Constant::getNullValue(CI->getType());
649 if (HasS1 && HasS2) {
650 size_t Pos = S1.find_first_of(S2);
651 if (Pos == StringRef::npos) Pos = S1.size();
652 return ConstantInt::get(CI->getType(), Pos);
655 // strcspn(s, "") -> strlen(s)
656 if (TD && HasS2 && S2.empty())
657 return EmitStrLen(CI->getArgOperand(0), B, TD);
663 //===---------------------------------------===//
664 // 'strstr' Optimizations
666 struct StrStrOpt : public LibCallOptimization {
667 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
668 FunctionType *FT = Callee->getFunctionType();
669 if (FT->getNumParams() != 2 ||
670 !FT->getParamType(0)->isPointerTy() ||
671 !FT->getParamType(1)->isPointerTy() ||
672 !FT->getReturnType()->isPointerTy())
675 // fold strstr(x, x) -> x.
676 if (CI->getArgOperand(0) == CI->getArgOperand(1))
677 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
679 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
680 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
681 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
682 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
684 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
686 ICmpInst *Old = cast<ICmpInst>(*UI++);
687 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
688 ConstantInt::getNullValue(StrNCmp->getType()),
690 Old->replaceAllUsesWith(Cmp);
691 Old->eraseFromParent();
696 // See if either input string is a constant string.
697 StringRef SearchStr, ToFindStr;
698 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
699 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
701 // fold strstr(x, "") -> x.
702 if (HasStr2 && ToFindStr.empty())
703 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
705 // If both strings are known, constant fold it.
706 if (HasStr1 && HasStr2) {
707 std::string::size_type Offset = SearchStr.find(ToFindStr);
709 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
710 return Constant::getNullValue(CI->getType());
712 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
713 Value *Result = CastToCStr(CI->getArgOperand(0), B);
714 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
715 return B.CreateBitCast(Result, CI->getType());
718 // fold strstr(x, "y") -> strchr(x, 'y').
719 if (HasStr2 && ToFindStr.size() == 1)
720 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
721 ToFindStr[0], B, TD), CI->getType());
727 //===---------------------------------------===//
728 // 'memcmp' Optimizations
730 struct MemCmpOpt : public LibCallOptimization {
731 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
732 FunctionType *FT = Callee->getFunctionType();
733 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
734 !FT->getParamType(1)->isPointerTy() ||
735 !FT->getReturnType()->isIntegerTy(32))
738 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
740 if (LHS == RHS) // memcmp(s,s,x) -> 0
741 return Constant::getNullValue(CI->getType());
743 // Make sure we have a constant length.
744 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
746 uint64_t Len = LenC->getZExtValue();
748 if (Len == 0) // memcmp(s1,s2,0) -> 0
749 return Constant::getNullValue(CI->getType());
751 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
753 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
754 CI->getType(), "lhsv");
755 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
756 CI->getType(), "rhsv");
757 return B.CreateSub(LHSV, RHSV, "chardiff");
760 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
761 StringRef LHSStr, RHSStr;
762 if (getConstantStringInfo(LHS, LHSStr) &&
763 getConstantStringInfo(RHS, RHSStr)) {
764 // Make sure we're not reading out-of-bounds memory.
765 if (Len > LHSStr.size() || Len > RHSStr.size())
767 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
768 return ConstantInt::get(CI->getType(), Ret);
775 //===---------------------------------------===//
776 // 'memcpy' Optimizations
778 struct MemCpyOpt : public LibCallOptimization {
779 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
780 // These optimizations require TargetData.
783 FunctionType *FT = Callee->getFunctionType();
784 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
785 !FT->getParamType(0)->isPointerTy() ||
786 !FT->getParamType(1)->isPointerTy() ||
787 FT->getParamType(2) != TD->getIntPtrType(*Context))
790 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
791 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
792 CI->getArgOperand(2), 1);
793 return CI->getArgOperand(0);
797 //===---------------------------------------===//
798 // 'memmove' Optimizations
800 struct MemMoveOpt : public LibCallOptimization {
801 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
802 // These optimizations require TargetData.
805 FunctionType *FT = Callee->getFunctionType();
806 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
807 !FT->getParamType(0)->isPointerTy() ||
808 !FT->getParamType(1)->isPointerTy() ||
809 FT->getParamType(2) != TD->getIntPtrType(*Context))
812 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
813 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
814 CI->getArgOperand(2), 1);
815 return CI->getArgOperand(0);
819 //===---------------------------------------===//
820 // 'memset' Optimizations
822 struct MemSetOpt : 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)->isIntegerTy() ||
831 FT->getParamType(2) != TD->getIntPtrType(*Context))
834 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
835 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
836 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
837 return CI->getArgOperand(0);
841 //===----------------------------------------------------------------------===//
842 // Math Library Optimizations
843 //===----------------------------------------------------------------------===//
845 //===---------------------------------------===//
846 // 'cos*' Optimizations
848 struct CosOpt : public LibCallOptimization {
849 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
850 FunctionType *FT = Callee->getFunctionType();
851 // Just make sure this has 1 argument of FP type, which matches the
853 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
854 !FT->getParamType(0)->isFloatingPointTy())
858 Value *Op1 = CI->getArgOperand(0);
859 if (BinaryOperator::isFNeg(Op1)) {
860 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
861 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
867 //===---------------------------------------===//
868 // 'pow*' Optimizations
870 struct PowOpt : public LibCallOptimization {
871 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
872 FunctionType *FT = Callee->getFunctionType();
873 // Just make sure this has 2 arguments of the same FP type, which match the
875 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
876 FT->getParamType(0) != FT->getParamType(1) ||
877 !FT->getParamType(0)->isFloatingPointTy())
880 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
881 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
882 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
884 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
885 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
888 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
889 if (Op2C == 0) return 0;
891 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
892 return ConstantFP::get(CI->getType(), 1.0);
894 if (Op2C->isExactlyValue(0.5)) {
895 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
896 // This is faster than calling pow, and still handles negative zero
897 // and negative infinity correctly.
898 // TODO: In fast-math mode, this could be just sqrt(x).
899 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
900 Value *Inf = ConstantFP::getInfinity(CI->getType());
901 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
902 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
903 Callee->getAttributes());
904 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
905 Callee->getAttributes());
906 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
907 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
911 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
913 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
914 return B.CreateFMul(Op1, Op1, "pow2");
915 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
916 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
922 //===---------------------------------------===//
923 // 'exp2' Optimizations
925 struct Exp2Opt : public LibCallOptimization {
926 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
927 FunctionType *FT = Callee->getFunctionType();
928 // Just make sure this has 1 argument of FP type, which matches the
930 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
931 !FT->getParamType(0)->isFloatingPointTy())
934 Value *Op = CI->getArgOperand(0);
935 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
936 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
938 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
939 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
940 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
941 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
942 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
943 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
948 if (Op->getType()->isFloatTy())
950 else if (Op->getType()->isDoubleTy())
955 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
956 if (!Op->getType()->isFloatTy())
957 One = ConstantExpr::getFPExtend(One, Op->getType());
959 Module *M = Caller->getParent();
960 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
962 B.getInt32Ty(), NULL);
963 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
964 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
965 CI->setCallingConv(F->getCallingConv());
973 //===---------------------------------------===//
974 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
976 struct UnaryDoubleFPOpt : public LibCallOptimization {
977 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
978 FunctionType *FT = Callee->getFunctionType();
979 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
980 !FT->getParamType(0)->isDoubleTy())
983 // If this is something like 'floor((double)floatval)', convert to floorf.
984 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
985 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
988 // floor((double)floatval) -> (double)floorf(floatval)
989 Value *V = Cast->getOperand(0);
990 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
991 return B.CreateFPExt(V, B.getDoubleTy());
995 //===----------------------------------------------------------------------===//
996 // Integer Optimizations
997 //===----------------------------------------------------------------------===//
999 //===---------------------------------------===//
1000 // 'ffs*' Optimizations
1002 struct FFSOpt : public LibCallOptimization {
1003 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1004 FunctionType *FT = Callee->getFunctionType();
1005 // Just make sure this has 2 arguments of the same FP type, which match the
1007 if (FT->getNumParams() != 1 ||
1008 !FT->getReturnType()->isIntegerTy(32) ||
1009 !FT->getParamType(0)->isIntegerTy())
1012 Value *Op = CI->getArgOperand(0);
1015 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1016 if (CI->getValue() == 0) // ffs(0) -> 0.
1017 return Constant::getNullValue(CI->getType());
1018 // ffs(c) -> cttz(c)+1
1019 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1022 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1023 Type *ArgType = Op->getType();
1024 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1025 Intrinsic::cttz, ArgType);
1026 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1027 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1028 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1030 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1031 return B.CreateSelect(Cond, V, B.getInt32(0));
1035 //===---------------------------------------===//
1036 // 'isdigit' Optimizations
1038 struct IsDigitOpt : public LibCallOptimization {
1039 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1040 FunctionType *FT = Callee->getFunctionType();
1041 // We require integer(i32)
1042 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1043 !FT->getParamType(0)->isIntegerTy(32))
1046 // isdigit(c) -> (c-'0') <u 10
1047 Value *Op = CI->getArgOperand(0);
1048 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1049 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1050 return B.CreateZExt(Op, CI->getType());
1054 //===---------------------------------------===//
1055 // 'isascii' Optimizations
1057 struct IsAsciiOpt : public LibCallOptimization {
1058 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1059 FunctionType *FT = Callee->getFunctionType();
1060 // We require integer(i32)
1061 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1062 !FT->getParamType(0)->isIntegerTy(32))
1065 // isascii(c) -> c <u 128
1066 Value *Op = CI->getArgOperand(0);
1067 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1068 return B.CreateZExt(Op, CI->getType());
1072 //===---------------------------------------===//
1073 // 'abs', 'labs', 'llabs' Optimizations
1075 struct AbsOpt : public LibCallOptimization {
1076 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1077 FunctionType *FT = Callee->getFunctionType();
1078 // We require integer(integer) where the types agree.
1079 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1080 FT->getParamType(0) != FT->getReturnType())
1083 // abs(x) -> x >s -1 ? x : -x
1084 Value *Op = CI->getArgOperand(0);
1085 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1087 Value *Neg = B.CreateNeg(Op, "neg");
1088 return B.CreateSelect(Pos, Op, Neg);
1093 //===---------------------------------------===//
1094 // 'toascii' Optimizations
1096 struct ToAsciiOpt : public LibCallOptimization {
1097 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1098 FunctionType *FT = Callee->getFunctionType();
1099 // We require i32(i32)
1100 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1101 !FT->getParamType(0)->isIntegerTy(32))
1104 // isascii(c) -> c & 0x7f
1105 return B.CreateAnd(CI->getArgOperand(0),
1106 ConstantInt::get(CI->getType(),0x7F));
1110 //===----------------------------------------------------------------------===//
1111 // Formatting and IO Optimizations
1112 //===----------------------------------------------------------------------===//
1114 //===---------------------------------------===//
1115 // 'printf' Optimizations
1117 struct PrintFOpt : public LibCallOptimization {
1118 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1120 // Check for a fixed format string.
1121 StringRef FormatStr;
1122 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1125 // Empty format string -> noop.
1126 if (FormatStr.empty()) // Tolerate printf's declared void.
1127 return CI->use_empty() ? (Value*)CI :
1128 ConstantInt::get(CI->getType(), 0);
1130 // Do not do any of the following transformations if the printf return value
1131 // is used, in general the printf return value is not compatible with either
1132 // putchar() or puts().
1133 if (!CI->use_empty())
1136 // printf("x") -> putchar('x'), even for '%'.
1137 if (FormatStr.size() == 1) {
1138 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
1139 if (CI->use_empty()) return CI;
1140 return B.CreateIntCast(Res, CI->getType(), true);
1143 // printf("foo\n") --> puts("foo")
1144 if (FormatStr[FormatStr.size()-1] == '\n' &&
1145 FormatStr.find('%') == std::string::npos) { // no format characters.
1146 // Create a string literal with no \n on it. We expect the constant merge
1147 // pass to be run after this pass, to merge duplicate strings.
1148 FormatStr = FormatStr.drop_back();
1149 Value *GV = B.CreateGlobalString(FormatStr, "str");
1150 EmitPutS(GV, B, TD);
1151 return CI->use_empty() ? (Value*)CI :
1152 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1155 // Optimize specific format strings.
1156 // printf("%c", chr) --> putchar(chr)
1157 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1158 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1159 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
1161 if (CI->use_empty()) return CI;
1162 return B.CreateIntCast(Res, CI->getType(), true);
1165 // printf("%s\n", str) --> puts(str)
1166 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1167 CI->getArgOperand(1)->getType()->isPointerTy()) {
1168 EmitPutS(CI->getArgOperand(1), B, TD);
1174 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1175 // Require one fixed pointer argument and an integer/void result.
1176 FunctionType *FT = Callee->getFunctionType();
1177 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1178 !(FT->getReturnType()->isIntegerTy() ||
1179 FT->getReturnType()->isVoidTy()))
1182 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1186 // printf(format, ...) -> iprintf(format, ...) if no floating point
1188 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1189 Module *M = B.GetInsertBlock()->getParent()->getParent();
1190 Constant *IPrintFFn =
1191 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1192 CallInst *New = cast<CallInst>(CI->clone());
1193 New->setCalledFunction(IPrintFFn);
1201 //===---------------------------------------===//
1202 // 'sprintf' Optimizations
1204 struct SPrintFOpt : public LibCallOptimization {
1205 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1207 // Check for a fixed format string.
1208 StringRef FormatStr;
1209 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1212 // If we just have a format string (nothing else crazy) transform it.
1213 if (CI->getNumArgOperands() == 2) {
1214 // Make sure there's no % in the constant array. We could try to handle
1215 // %% -> % in the future if we cared.
1216 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1217 if (FormatStr[i] == '%')
1218 return 0; // we found a format specifier, bail out.
1220 // These optimizations require TargetData.
1223 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1224 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1225 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1226 FormatStr.size() + 1), 1); // nul byte.
1227 return ConstantInt::get(CI->getType(), FormatStr.size());
1230 // The remaining optimizations require the format string to be "%s" or "%c"
1231 // and have an extra operand.
1232 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1233 CI->getNumArgOperands() < 3)
1236 // Decode the second character of the format string.
1237 if (FormatStr[1] == 'c') {
1238 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1239 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1240 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1241 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1242 B.CreateStore(V, Ptr);
1243 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1244 B.CreateStore(B.getInt8(0), Ptr);
1246 return ConstantInt::get(CI->getType(), 1);
1249 if (FormatStr[1] == 's') {
1250 // These optimizations require TargetData.
1253 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1254 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1256 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
1257 Value *IncLen = B.CreateAdd(Len,
1258 ConstantInt::get(Len->getType(), 1),
1260 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1262 // The sprintf result is the unincremented number of bytes in the string.
1263 return B.CreateIntCast(Len, CI->getType(), false);
1268 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1269 // Require two fixed pointer arguments and an integer result.
1270 FunctionType *FT = Callee->getFunctionType();
1271 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1272 !FT->getParamType(1)->isPointerTy() ||
1273 !FT->getReturnType()->isIntegerTy())
1276 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1280 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1282 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1283 Module *M = B.GetInsertBlock()->getParent()->getParent();
1284 Constant *SIPrintFFn =
1285 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1286 CallInst *New = cast<CallInst>(CI->clone());
1287 New->setCalledFunction(SIPrintFFn);
1295 //===---------------------------------------===//
1296 // 'fwrite' Optimizations
1298 struct FWriteOpt : public LibCallOptimization {
1299 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1300 // Require a pointer, an integer, an integer, a pointer, returning integer.
1301 FunctionType *FT = Callee->getFunctionType();
1302 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1303 !FT->getParamType(1)->isIntegerTy() ||
1304 !FT->getParamType(2)->isIntegerTy() ||
1305 !FT->getParamType(3)->isPointerTy() ||
1306 !FT->getReturnType()->isIntegerTy())
1309 // Get the element size and count.
1310 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1311 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1312 if (!SizeC || !CountC) return 0;
1313 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1315 // If this is writing zero records, remove the call (it's a noop).
1317 return ConstantInt::get(CI->getType(), 0);
1319 // If this is writing one byte, turn it into fputc.
1320 // This optimisation is only valid, if the return value is unused.
1321 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1322 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1323 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
1324 return ConstantInt::get(CI->getType(), 1);
1331 //===---------------------------------------===//
1332 // 'fputs' Optimizations
1334 struct FPutsOpt : public LibCallOptimization {
1335 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1336 // These optimizations require TargetData.
1339 // Require two pointers. Also, we can't optimize if return value is used.
1340 FunctionType *FT = Callee->getFunctionType();
1341 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1342 !FT->getParamType(1)->isPointerTy() ||
1346 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1347 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1349 EmitFWrite(CI->getArgOperand(0),
1350 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1351 CI->getArgOperand(1), B, TD, TLI);
1352 return CI; // Known to have no uses (see above).
1356 //===---------------------------------------===//
1357 // 'fprintf' Optimizations
1359 struct FPrintFOpt : public LibCallOptimization {
1360 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1362 // All the optimizations depend on the format string.
1363 StringRef FormatStr;
1364 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1367 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1368 if (CI->getNumArgOperands() == 2) {
1369 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1370 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1371 return 0; // We found a format specifier.
1373 // These optimizations require TargetData.
1376 EmitFWrite(CI->getArgOperand(1),
1377 ConstantInt::get(TD->getIntPtrType(*Context),
1379 CI->getArgOperand(0), B, TD, TLI);
1380 return ConstantInt::get(CI->getType(), FormatStr.size());
1383 // The remaining optimizations require the format string to be "%s" or "%c"
1384 // and have an extra operand.
1385 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1386 CI->getNumArgOperands() < 3)
1389 // Decode the second character of the format string.
1390 if (FormatStr[1] == 'c') {
1391 // fprintf(F, "%c", chr) --> fputc(chr, F)
1392 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1393 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1394 return ConstantInt::get(CI->getType(), 1);
1397 if (FormatStr[1] == 's') {
1398 // fprintf(F, "%s", str) --> fputs(str, F)
1399 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1401 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1407 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1408 // Require two fixed paramters as pointers and integer result.
1409 FunctionType *FT = Callee->getFunctionType();
1410 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1411 !FT->getParamType(1)->isPointerTy() ||
1412 !FT->getReturnType()->isIntegerTy())
1415 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1419 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1420 // floating point arguments.
1421 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1422 Module *M = B.GetInsertBlock()->getParent()->getParent();
1423 Constant *FIPrintFFn =
1424 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1425 CallInst *New = cast<CallInst>(CI->clone());
1426 New->setCalledFunction(FIPrintFFn);
1434 //===---------------------------------------===//
1435 // 'puts' Optimizations
1437 struct PutsOpt : public LibCallOptimization {
1438 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1439 // Require one fixed pointer argument and an integer/void result.
1440 FunctionType *FT = Callee->getFunctionType();
1441 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1442 !(FT->getReturnType()->isIntegerTy() ||
1443 FT->getReturnType()->isVoidTy()))
1446 // Check for a constant string.
1448 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1451 if (Str.empty() && CI->use_empty()) {
1452 // puts("") -> putchar('\n')
1453 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1454 if (CI->use_empty()) return CI;
1455 return B.CreateIntCast(Res, CI->getType(), true);
1462 } // end anonymous namespace.
1464 //===----------------------------------------------------------------------===//
1465 // SimplifyLibCalls Pass Implementation
1466 //===----------------------------------------------------------------------===//
1469 /// This pass optimizes well known library functions from libc and libm.
1471 class SimplifyLibCalls : public FunctionPass {
1472 TargetLibraryInfo *TLI;
1474 StringMap<LibCallOptimization*> Optimizations;
1475 // String and Memory LibCall Optimizations
1476 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1477 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1478 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1479 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1480 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1481 // Math Library Optimizations
1482 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1483 // Integer Optimizations
1484 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1486 // Formatting and IO Optimizations
1487 SPrintFOpt SPrintF; PrintFOpt PrintF;
1488 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1491 bool Modified; // This is only used by doInitialization.
1493 static char ID; // Pass identification
1494 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1495 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1497 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1498 void InitOptimizations();
1499 bool runOnFunction(Function &F);
1501 void setDoesNotAccessMemory(Function &F);
1502 void setOnlyReadsMemory(Function &F);
1503 void setDoesNotThrow(Function &F);
1504 void setDoesNotCapture(Function &F, unsigned n);
1505 void setDoesNotAlias(Function &F, unsigned n);
1506 bool doInitialization(Module &M);
1508 void inferPrototypeAttributes(Function &F);
1509 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1510 AU.addRequired<TargetLibraryInfo>();
1513 } // end anonymous namespace.
1515 char SimplifyLibCalls::ID = 0;
1517 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1518 "Simplify well-known library calls", false, false)
1519 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1520 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1521 "Simplify well-known library calls", false, false)
1523 // Public interface to the Simplify LibCalls pass.
1524 FunctionPass *llvm::createSimplifyLibCallsPass() {
1525 return new SimplifyLibCalls();
1528 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1530 Optimizations[TLI->getName(F)] = Opt;
1533 /// Optimizations - Populate the Optimizations map with all the optimizations
1535 void SimplifyLibCalls::InitOptimizations() {
1536 // String and Memory LibCall Optimizations
1537 Optimizations["strcat"] = &StrCat;
1538 Optimizations["strncat"] = &StrNCat;
1539 Optimizations["strchr"] = &StrChr;
1540 Optimizations["strrchr"] = &StrRChr;
1541 Optimizations["strcmp"] = &StrCmp;
1542 Optimizations["strncmp"] = &StrNCmp;
1543 Optimizations["strcpy"] = &StrCpy;
1544 Optimizations["strncpy"] = &StrNCpy;
1545 Optimizations["strlen"] = &StrLen;
1546 Optimizations["strpbrk"] = &StrPBrk;
1547 Optimizations["strtol"] = &StrTo;
1548 Optimizations["strtod"] = &StrTo;
1549 Optimizations["strtof"] = &StrTo;
1550 Optimizations["strtoul"] = &StrTo;
1551 Optimizations["strtoll"] = &StrTo;
1552 Optimizations["strtold"] = &StrTo;
1553 Optimizations["strtoull"] = &StrTo;
1554 Optimizations["strspn"] = &StrSpn;
1555 Optimizations["strcspn"] = &StrCSpn;
1556 Optimizations["strstr"] = &StrStr;
1557 Optimizations["memcmp"] = &MemCmp;
1558 AddOpt(LibFunc::memcpy, &MemCpy);
1559 Optimizations["memmove"] = &MemMove;
1560 AddOpt(LibFunc::memset, &MemSet);
1562 // _chk variants of String and Memory LibCall Optimizations.
1563 Optimizations["__strcpy_chk"] = &StrCpyChk;
1565 // Math Library Optimizations
1566 Optimizations["cosf"] = &Cos;
1567 Optimizations["cos"] = &Cos;
1568 Optimizations["cosl"] = &Cos;
1569 Optimizations["powf"] = &Pow;
1570 Optimizations["pow"] = &Pow;
1571 Optimizations["powl"] = &Pow;
1572 Optimizations["llvm.pow.f32"] = &Pow;
1573 Optimizations["llvm.pow.f64"] = &Pow;
1574 Optimizations["llvm.pow.f80"] = &Pow;
1575 Optimizations["llvm.pow.f128"] = &Pow;
1576 Optimizations["llvm.pow.ppcf128"] = &Pow;
1577 Optimizations["exp2l"] = &Exp2;
1578 Optimizations["exp2"] = &Exp2;
1579 Optimizations["exp2f"] = &Exp2;
1580 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1581 Optimizations["llvm.exp2.f128"] = &Exp2;
1582 Optimizations["llvm.exp2.f80"] = &Exp2;
1583 Optimizations["llvm.exp2.f64"] = &Exp2;
1584 Optimizations["llvm.exp2.f32"] = &Exp2;
1587 Optimizations["floor"] = &UnaryDoubleFP;
1590 Optimizations["ceil"] = &UnaryDoubleFP;
1593 Optimizations["round"] = &UnaryDoubleFP;
1596 Optimizations["rint"] = &UnaryDoubleFP;
1598 #ifdef HAVE_NEARBYINTF
1599 Optimizations["nearbyint"] = &UnaryDoubleFP;
1602 // Integer Optimizations
1603 Optimizations["ffs"] = &FFS;
1604 Optimizations["ffsl"] = &FFS;
1605 Optimizations["ffsll"] = &FFS;
1606 Optimizations["abs"] = &Abs;
1607 Optimizations["labs"] = &Abs;
1608 Optimizations["llabs"] = &Abs;
1609 Optimizations["isdigit"] = &IsDigit;
1610 Optimizations["isascii"] = &IsAscii;
1611 Optimizations["toascii"] = &ToAscii;
1613 // Formatting and IO Optimizations
1614 Optimizations["sprintf"] = &SPrintF;
1615 Optimizations["printf"] = &PrintF;
1616 AddOpt(LibFunc::fwrite, &FWrite);
1617 AddOpt(LibFunc::fputs, &FPuts);
1618 Optimizations["fprintf"] = &FPrintF;
1619 Optimizations["puts"] = &Puts;
1623 /// runOnFunction - Top level algorithm.
1625 bool SimplifyLibCalls::runOnFunction(Function &F) {
1626 TLI = &getAnalysis<TargetLibraryInfo>();
1628 if (Optimizations.empty())
1629 InitOptimizations();
1631 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1633 IRBuilder<> Builder(F.getContext());
1635 bool Changed = false;
1636 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1637 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1638 // Ignore non-calls.
1639 CallInst *CI = dyn_cast<CallInst>(I++);
1642 // Ignore indirect calls and calls to non-external functions.
1643 Function *Callee = CI->getCalledFunction();
1644 if (Callee == 0 || !Callee->isDeclaration() ||
1645 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1648 // Ignore unknown calls.
1649 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1652 // Set the builder to the instruction after the call.
1653 Builder.SetInsertPoint(BB, I);
1655 // Use debug location of CI for all new instructions.
1656 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1658 // Try to optimize this call.
1659 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1660 if (Result == 0) continue;
1662 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1663 dbgs() << " into: " << *Result << "\n");
1665 // Something changed!
1669 // Inspect the instruction after the call (which was potentially just
1673 if (CI != Result && !CI->use_empty()) {
1674 CI->replaceAllUsesWith(Result);
1675 if (!Result->hasName())
1676 Result->takeName(CI);
1678 CI->eraseFromParent();
1684 // Utility methods for doInitialization.
1686 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1687 if (!F.doesNotAccessMemory()) {
1688 F.setDoesNotAccessMemory();
1693 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1694 if (!F.onlyReadsMemory()) {
1695 F.setOnlyReadsMemory();
1700 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1701 if (!F.doesNotThrow()) {
1702 F.setDoesNotThrow();
1707 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1708 if (!F.doesNotCapture(n)) {
1709 F.setDoesNotCapture(n);
1714 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1715 if (!F.doesNotAlias(n)) {
1716 F.setDoesNotAlias(n);
1723 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1724 FunctionType *FTy = F.getFunctionType();
1726 StringRef Name = F.getName();
1729 if (Name == "strlen") {
1730 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1732 setOnlyReadsMemory(F);
1734 setDoesNotCapture(F, 1);
1735 } else if (Name == "strchr" ||
1736 Name == "strrchr") {
1737 if (FTy->getNumParams() != 2 ||
1738 !FTy->getParamType(0)->isPointerTy() ||
1739 !FTy->getParamType(1)->isIntegerTy())
1741 setOnlyReadsMemory(F);
1743 } else if (Name == "strcpy" ||
1749 Name == "strtoul" ||
1750 Name == "strtoll" ||
1751 Name == "strtold" ||
1752 Name == "strncat" ||
1753 Name == "strncpy" ||
1754 Name == "strtoull") {
1755 if (FTy->getNumParams() < 2 ||
1756 !FTy->getParamType(1)->isPointerTy())
1759 setDoesNotCapture(F, 2);
1760 } else if (Name == "strxfrm") {
1761 if (FTy->getNumParams() != 3 ||
1762 !FTy->getParamType(0)->isPointerTy() ||
1763 !FTy->getParamType(1)->isPointerTy())
1766 setDoesNotCapture(F, 1);
1767 setDoesNotCapture(F, 2);
1768 } else if (Name == "strcmp" ||
1770 Name == "strncmp" ||
1771 Name == "strcspn" ||
1772 Name == "strcoll" ||
1773 Name == "strcasecmp" ||
1774 Name == "strncasecmp") {
1775 if (FTy->getNumParams() < 2 ||
1776 !FTy->getParamType(0)->isPointerTy() ||
1777 !FTy->getParamType(1)->isPointerTy())
1779 setOnlyReadsMemory(F);
1781 setDoesNotCapture(F, 1);
1782 setDoesNotCapture(F, 2);
1783 } else if (Name == "strstr" ||
1784 Name == "strpbrk") {
1785 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1787 setOnlyReadsMemory(F);
1789 setDoesNotCapture(F, 2);
1790 } else if (Name == "strtok" ||
1791 Name == "strtok_r") {
1792 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1795 setDoesNotCapture(F, 2);
1796 } else if (Name == "scanf" ||
1798 Name == "setvbuf") {
1799 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1802 setDoesNotCapture(F, 1);
1803 } else if (Name == "strdup" ||
1804 Name == "strndup") {
1805 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1806 !FTy->getParamType(0)->isPointerTy())
1809 setDoesNotAlias(F, 0);
1810 setDoesNotCapture(F, 1);
1811 } else if (Name == "stat" ||
1813 Name == "sprintf" ||
1814 Name == "statvfs") {
1815 if (FTy->getNumParams() < 2 ||
1816 !FTy->getParamType(0)->isPointerTy() ||
1817 !FTy->getParamType(1)->isPointerTy())
1820 setDoesNotCapture(F, 1);
1821 setDoesNotCapture(F, 2);
1822 } else if (Name == "snprintf") {
1823 if (FTy->getNumParams() != 3 ||
1824 !FTy->getParamType(0)->isPointerTy() ||
1825 !FTy->getParamType(2)->isPointerTy())
1828 setDoesNotCapture(F, 1);
1829 setDoesNotCapture(F, 3);
1830 } else if (Name == "setitimer") {
1831 if (FTy->getNumParams() != 3 ||
1832 !FTy->getParamType(1)->isPointerTy() ||
1833 !FTy->getParamType(2)->isPointerTy())
1836 setDoesNotCapture(F, 2);
1837 setDoesNotCapture(F, 3);
1838 } else if (Name == "system") {
1839 if (FTy->getNumParams() != 1 ||
1840 !FTy->getParamType(0)->isPointerTy())
1842 // May throw; "system" is a valid pthread cancellation point.
1843 setDoesNotCapture(F, 1);
1847 if (Name == "malloc") {
1848 if (FTy->getNumParams() != 1 ||
1849 !FTy->getReturnType()->isPointerTy())
1852 setDoesNotAlias(F, 0);
1853 } else if (Name == "memcmp") {
1854 if (FTy->getNumParams() != 3 ||
1855 !FTy->getParamType(0)->isPointerTy() ||
1856 !FTy->getParamType(1)->isPointerTy())
1858 setOnlyReadsMemory(F);
1860 setDoesNotCapture(F, 1);
1861 setDoesNotCapture(F, 2);
1862 } else if (Name == "memchr" ||
1863 Name == "memrchr") {
1864 if (FTy->getNumParams() != 3)
1866 setOnlyReadsMemory(F);
1868 } else if (Name == "modf" ||
1872 Name == "memccpy" ||
1873 Name == "memmove") {
1874 if (FTy->getNumParams() < 2 ||
1875 !FTy->getParamType(1)->isPointerTy())
1878 setDoesNotCapture(F, 2);
1879 } else if (Name == "memalign") {
1880 if (!FTy->getReturnType()->isPointerTy())
1882 setDoesNotAlias(F, 0);
1883 } else if (Name == "mkdir" ||
1885 if (FTy->getNumParams() == 0 ||
1886 !FTy->getParamType(0)->isPointerTy())
1889 setDoesNotCapture(F, 1);
1893 if (Name == "realloc") {
1894 if (FTy->getNumParams() != 2 ||
1895 !FTy->getParamType(0)->isPointerTy() ||
1896 !FTy->getReturnType()->isPointerTy())
1899 setDoesNotAlias(F, 0);
1900 setDoesNotCapture(F, 1);
1901 } else if (Name == "read") {
1902 if (FTy->getNumParams() != 3 ||
1903 !FTy->getParamType(1)->isPointerTy())
1905 // May throw; "read" is a valid pthread cancellation point.
1906 setDoesNotCapture(F, 2);
1907 } else if (Name == "rmdir" ||
1910 Name == "realpath") {
1911 if (FTy->getNumParams() < 1 ||
1912 !FTy->getParamType(0)->isPointerTy())
1915 setDoesNotCapture(F, 1);
1916 } else if (Name == "rename" ||
1917 Name == "readlink") {
1918 if (FTy->getNumParams() < 2 ||
1919 !FTy->getParamType(0)->isPointerTy() ||
1920 !FTy->getParamType(1)->isPointerTy())
1923 setDoesNotCapture(F, 1);
1924 setDoesNotCapture(F, 2);
1928 if (Name == "write") {
1929 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1931 // May throw; "write" is a valid pthread cancellation point.
1932 setDoesNotCapture(F, 2);
1936 if (Name == "bcopy") {
1937 if (FTy->getNumParams() != 3 ||
1938 !FTy->getParamType(0)->isPointerTy() ||
1939 !FTy->getParamType(1)->isPointerTy())
1942 setDoesNotCapture(F, 1);
1943 setDoesNotCapture(F, 2);
1944 } else if (Name == "bcmp") {
1945 if (FTy->getNumParams() != 3 ||
1946 !FTy->getParamType(0)->isPointerTy() ||
1947 !FTy->getParamType(1)->isPointerTy())
1950 setOnlyReadsMemory(F);
1951 setDoesNotCapture(F, 1);
1952 setDoesNotCapture(F, 2);
1953 } else if (Name == "bzero") {
1954 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1957 setDoesNotCapture(F, 1);
1961 if (Name == "calloc") {
1962 if (FTy->getNumParams() != 2 ||
1963 !FTy->getReturnType()->isPointerTy())
1966 setDoesNotAlias(F, 0);
1967 } else if (Name == "chmod" ||
1969 Name == "ctermid" ||
1970 Name == "clearerr" ||
1971 Name == "closedir") {
1972 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1975 setDoesNotCapture(F, 1);
1979 if (Name == "atoi" ||
1983 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1986 setOnlyReadsMemory(F);
1987 setDoesNotCapture(F, 1);
1988 } else if (Name == "access") {
1989 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1992 setDoesNotCapture(F, 1);
1996 if (Name == "fopen") {
1997 if (FTy->getNumParams() != 2 ||
1998 !FTy->getReturnType()->isPointerTy() ||
1999 !FTy->getParamType(0)->isPointerTy() ||
2000 !FTy->getParamType(1)->isPointerTy())
2003 setDoesNotAlias(F, 0);
2004 setDoesNotCapture(F, 1);
2005 setDoesNotCapture(F, 2);
2006 } else if (Name == "fdopen") {
2007 if (FTy->getNumParams() != 2 ||
2008 !FTy->getReturnType()->isPointerTy() ||
2009 !FTy->getParamType(1)->isPointerTy())
2012 setDoesNotAlias(F, 0);
2013 setDoesNotCapture(F, 2);
2014 } else if (Name == "feof" ||
2024 Name == "fsetpos" ||
2025 Name == "flockfile" ||
2026 Name == "funlockfile" ||
2027 Name == "ftrylockfile") {
2028 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2031 setDoesNotCapture(F, 1);
2032 } else if (Name == "ferror") {
2033 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2036 setDoesNotCapture(F, 1);
2037 setOnlyReadsMemory(F);
2038 } else if (Name == "fputc" ||
2043 Name == "fstatvfs") {
2044 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2047 setDoesNotCapture(F, 2);
2048 } else if (Name == "fgets") {
2049 if (FTy->getNumParams() != 3 ||
2050 !FTy->getParamType(0)->isPointerTy() ||
2051 !FTy->getParamType(2)->isPointerTy())
2054 setDoesNotCapture(F, 3);
2055 } else if (Name == "fread" ||
2057 if (FTy->getNumParams() != 4 ||
2058 !FTy->getParamType(0)->isPointerTy() ||
2059 !FTy->getParamType(3)->isPointerTy())
2062 setDoesNotCapture(F, 1);
2063 setDoesNotCapture(F, 4);
2064 } else if (Name == "fputs" ||
2066 Name == "fprintf" ||
2067 Name == "fgetpos") {
2068 if (FTy->getNumParams() < 2 ||
2069 !FTy->getParamType(0)->isPointerTy() ||
2070 !FTy->getParamType(1)->isPointerTy())
2073 setDoesNotCapture(F, 1);
2074 setDoesNotCapture(F, 2);
2078 if (Name == "getc" ||
2079 Name == "getlogin_r" ||
2080 Name == "getc_unlocked") {
2081 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2084 setDoesNotCapture(F, 1);
2085 } else if (Name == "getenv") {
2086 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2089 setOnlyReadsMemory(F);
2090 setDoesNotCapture(F, 1);
2091 } else if (Name == "gets" ||
2092 Name == "getchar") {
2094 } else if (Name == "getitimer") {
2095 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2098 setDoesNotCapture(F, 2);
2099 } else if (Name == "getpwnam") {
2100 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2103 setDoesNotCapture(F, 1);
2107 if (Name == "ungetc") {
2108 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2111 setDoesNotCapture(F, 2);
2112 } else if (Name == "uname" ||
2114 Name == "unsetenv") {
2115 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2118 setDoesNotCapture(F, 1);
2119 } else if (Name == "utime" ||
2121 if (FTy->getNumParams() != 2 ||
2122 !FTy->getParamType(0)->isPointerTy() ||
2123 !FTy->getParamType(1)->isPointerTy())
2126 setDoesNotCapture(F, 1);
2127 setDoesNotCapture(F, 2);
2131 if (Name == "putc") {
2132 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2135 setDoesNotCapture(F, 2);
2136 } else if (Name == "puts" ||
2139 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2142 setDoesNotCapture(F, 1);
2143 } else if (Name == "pread" ||
2145 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2147 // May throw; these are valid pthread cancellation points.
2148 setDoesNotCapture(F, 2);
2149 } else if (Name == "putchar") {
2151 } else if (Name == "popen") {
2152 if (FTy->getNumParams() != 2 ||
2153 !FTy->getReturnType()->isPointerTy() ||
2154 !FTy->getParamType(0)->isPointerTy() ||
2155 !FTy->getParamType(1)->isPointerTy())
2158 setDoesNotAlias(F, 0);
2159 setDoesNotCapture(F, 1);
2160 setDoesNotCapture(F, 2);
2161 } else if (Name == "pclose") {
2162 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2165 setDoesNotCapture(F, 1);
2169 if (Name == "vscanf") {
2170 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2173 setDoesNotCapture(F, 1);
2174 } else if (Name == "vsscanf" ||
2175 Name == "vfscanf") {
2176 if (FTy->getNumParams() != 3 ||
2177 !FTy->getParamType(1)->isPointerTy() ||
2178 !FTy->getParamType(2)->isPointerTy())
2181 setDoesNotCapture(F, 1);
2182 setDoesNotCapture(F, 2);
2183 } else if (Name == "valloc") {
2184 if (!FTy->getReturnType()->isPointerTy())
2187 setDoesNotAlias(F, 0);
2188 } else if (Name == "vprintf") {
2189 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2192 setDoesNotCapture(F, 1);
2193 } else if (Name == "vfprintf" ||
2194 Name == "vsprintf") {
2195 if (FTy->getNumParams() != 3 ||
2196 !FTy->getParamType(0)->isPointerTy() ||
2197 !FTy->getParamType(1)->isPointerTy())
2200 setDoesNotCapture(F, 1);
2201 setDoesNotCapture(F, 2);
2202 } else if (Name == "vsnprintf") {
2203 if (FTy->getNumParams() != 4 ||
2204 !FTy->getParamType(0)->isPointerTy() ||
2205 !FTy->getParamType(2)->isPointerTy())
2208 setDoesNotCapture(F, 1);
2209 setDoesNotCapture(F, 3);
2213 if (Name == "open") {
2214 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2216 // May throw; "open" is a valid pthread cancellation point.
2217 setDoesNotCapture(F, 1);
2218 } else if (Name == "opendir") {
2219 if (FTy->getNumParams() != 1 ||
2220 !FTy->getReturnType()->isPointerTy() ||
2221 !FTy->getParamType(0)->isPointerTy())
2224 setDoesNotAlias(F, 0);
2225 setDoesNotCapture(F, 1);
2229 if (Name == "tmpfile") {
2230 if (!FTy->getReturnType()->isPointerTy())
2233 setDoesNotAlias(F, 0);
2234 } else if (Name == "times") {
2235 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2238 setDoesNotCapture(F, 1);
2242 if (Name == "htonl" ||
2245 setDoesNotAccessMemory(F);
2249 if (Name == "ntohl" ||
2252 setDoesNotAccessMemory(F);
2256 if (Name == "lstat") {
2257 if (FTy->getNumParams() != 2 ||
2258 !FTy->getParamType(0)->isPointerTy() ||
2259 !FTy->getParamType(1)->isPointerTy())
2262 setDoesNotCapture(F, 1);
2263 setDoesNotCapture(F, 2);
2264 } else if (Name == "lchown") {
2265 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2268 setDoesNotCapture(F, 1);
2272 if (Name == "qsort") {
2273 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2275 // May throw; places call through function pointer.
2276 setDoesNotCapture(F, 4);
2280 if (Name == "__strdup" ||
2281 Name == "__strndup") {
2282 if (FTy->getNumParams() < 1 ||
2283 !FTy->getReturnType()->isPointerTy() ||
2284 !FTy->getParamType(0)->isPointerTy())
2287 setDoesNotAlias(F, 0);
2288 setDoesNotCapture(F, 1);
2289 } else if (Name == "__strtok_r") {
2290 if (FTy->getNumParams() != 3 ||
2291 !FTy->getParamType(1)->isPointerTy())
2294 setDoesNotCapture(F, 2);
2295 } else if (Name == "_IO_getc") {
2296 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2299 setDoesNotCapture(F, 1);
2300 } else if (Name == "_IO_putc") {
2301 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2304 setDoesNotCapture(F, 2);
2308 if (Name == "\1__isoc99_scanf") {
2309 if (FTy->getNumParams() < 1 ||
2310 !FTy->getParamType(0)->isPointerTy())
2313 setDoesNotCapture(F, 1);
2314 } else if (Name == "\1stat64" ||
2315 Name == "\1lstat64" ||
2316 Name == "\1statvfs64" ||
2317 Name == "\1__isoc99_sscanf") {
2318 if (FTy->getNumParams() < 1 ||
2319 !FTy->getParamType(0)->isPointerTy() ||
2320 !FTy->getParamType(1)->isPointerTy())
2323 setDoesNotCapture(F, 1);
2324 setDoesNotCapture(F, 2);
2325 } else if (Name == "\1fopen64") {
2326 if (FTy->getNumParams() != 2 ||
2327 !FTy->getReturnType()->isPointerTy() ||
2328 !FTy->getParamType(0)->isPointerTy() ||
2329 !FTy->getParamType(1)->isPointerTy())
2332 setDoesNotAlias(F, 0);
2333 setDoesNotCapture(F, 1);
2334 setDoesNotCapture(F, 2);
2335 } else if (Name == "\1fseeko64" ||
2336 Name == "\1ftello64") {
2337 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2340 setDoesNotCapture(F, 1);
2341 } else if (Name == "\1tmpfile64") {
2342 if (!FTy->getReturnType()->isPointerTy())
2345 setDoesNotAlias(F, 0);
2346 } else if (Name == "\1fstat64" ||
2347 Name == "\1fstatvfs64") {
2348 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2351 setDoesNotCapture(F, 2);
2352 } else if (Name == "\1open64") {
2353 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2355 // May throw; "open" is a valid pthread cancellation point.
2356 setDoesNotCapture(F, 1);
2362 /// doInitialization - Add attributes to well-known functions.
2364 bool SimplifyLibCalls::doInitialization(Module &M) {
2366 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2368 if (F.isDeclaration() && F.hasName())
2369 inferPrototypeAttributes(F);
2375 // Additional cases that we need to add to this file:
2378 // * cbrt(expN(X)) -> expN(x/3)
2379 // * cbrt(sqrt(x)) -> pow(x,1/6)
2380 // * cbrt(sqrt(x)) -> pow(x,1/9)
2383 // * exp(log(x)) -> x
2386 // * log(exp(x)) -> x
2387 // * log(x**y) -> y*log(x)
2388 // * log(exp(y)) -> y*log(e)
2389 // * log(exp2(y)) -> y*log(2)
2390 // * log(exp10(y)) -> y*log(10)
2391 // * log(sqrt(x)) -> 0.5*log(x)
2392 // * log(pow(x,y)) -> y*log(x)
2394 // lround, lroundf, lroundl:
2395 // * lround(cnst) -> cnst'
2398 // * pow(exp(x),y) -> exp(x*y)
2399 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2400 // * pow(pow(x,y),z)-> pow(x,y*z)
2402 // round, roundf, roundl:
2403 // * round(cnst) -> cnst'
2406 // * signbit(cnst) -> cnst'
2407 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2409 // sqrt, sqrtf, sqrtl:
2410 // * sqrt(expN(x)) -> expN(x*0.5)
2411 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2412 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2415 // * stpcpy(str, "literal") ->
2416 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2419 // * strchr(p, 0) -> strlen(p)
2421 // * tan(atan(x)) -> x
2423 // trunc, truncf, truncl:
2424 // * trunc(cnst) -> cnst'