1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
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 is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification. If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Transforms/Utils/BuildLibCalls.h"
37 ColdErrorCalls("error-reporting-is-cold", cl::init(true),
38 cl::Hidden, cl::desc("Treat error-reporting calls as cold"));
40 /// This class is the abstract base class for the set of optimizations that
41 /// corresponds to one library call.
43 class LibCallOptimization {
47 const TargetLibraryInfo *TLI;
48 const LibCallSimplifier *LCS;
51 LibCallOptimization() { }
52 virtual ~LibCallOptimization() {}
54 /// callOptimizer - This pure virtual method is implemented by base classes to
55 /// do various optimizations. If this returns null then no transformation was
56 /// performed. If it returns CI, then it transformed the call and CI is to be
57 /// deleted. If it returns something else, replace CI with the new value and
59 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
62 /// ignoreCallingConv - Returns false if this transformation could possibly
63 /// change the calling convention.
64 virtual bool ignoreCallingConv() { return false; }
66 Value *optimizeCall(CallInst *CI, const DataLayout *TD,
67 const TargetLibraryInfo *TLI,
68 const LibCallSimplifier *LCS, IRBuilder<> &B) {
69 Caller = CI->getParent()->getParent();
73 if (CI->getCalledFunction())
74 Context = &CI->getCalledFunction()->getContext();
76 // We never change the calling convention.
77 if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
80 return callOptimizer(CI->getCalledFunction(), CI, B);
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 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
105 /// comparisons with With.
106 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
107 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
109 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
110 if (IC->isEquality() && IC->getOperand(1) == With)
112 // Unknown instruction.
118 static bool callHasFloatingPointArgument(const CallInst *CI) {
119 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
121 if ((*it)->getType()->isFloatingPointTy())
127 /// \brief Check whether the overloaded unary floating point function
128 /// corresponing to \a Ty is available.
129 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
130 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
131 LibFunc::Func LongDoubleFn) {
132 switch (Ty->getTypeID()) {
133 case Type::FloatTyID:
134 return TLI->has(FloatFn);
135 case Type::DoubleTyID:
136 return TLI->has(DoubleFn);
138 return TLI->has(LongDoubleFn);
142 //===----------------------------------------------------------------------===//
143 // Fortified Library Call Optimizations
144 //===----------------------------------------------------------------------===//
146 struct FortifiedLibCallOptimization : public LibCallOptimization {
148 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
149 bool isString) const = 0;
152 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
155 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
156 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
158 if (ConstantInt *SizeCI =
159 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
160 if (SizeCI->isAllOnesValue())
163 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
164 // If the length is 0 we don't know how long it is and so we can't
166 if (Len == 0) return false;
167 return SizeCI->getZExtValue() >= Len;
169 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
170 CI->getArgOperand(SizeArgOp)))
171 return SizeCI->getZExtValue() >= Arg->getZExtValue();
177 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
178 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
180 FunctionType *FT = Callee->getFunctionType();
181 LLVMContext &Context = CI->getParent()->getContext();
183 // Check if this has the right signature.
184 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
185 !FT->getParamType(0)->isPointerTy() ||
186 !FT->getParamType(1)->isPointerTy() ||
187 FT->getParamType(2) != TD->getIntPtrType(Context) ||
188 FT->getParamType(3) != TD->getIntPtrType(Context))
191 if (isFoldable(3, 2, false)) {
192 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
193 CI->getArgOperand(2), 1);
194 return CI->getArgOperand(0);
200 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
201 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
203 FunctionType *FT = Callee->getFunctionType();
204 LLVMContext &Context = CI->getParent()->getContext();
206 // Check if this has the right signature.
207 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
208 !FT->getParamType(0)->isPointerTy() ||
209 !FT->getParamType(1)->isPointerTy() ||
210 FT->getParamType(2) != TD->getIntPtrType(Context) ||
211 FT->getParamType(3) != TD->getIntPtrType(Context))
214 if (isFoldable(3, 2, false)) {
215 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
216 CI->getArgOperand(2), 1);
217 return CI->getArgOperand(0);
223 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
224 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
226 FunctionType *FT = Callee->getFunctionType();
227 LLVMContext &Context = CI->getParent()->getContext();
229 // Check if this has the right signature.
230 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
231 !FT->getParamType(0)->isPointerTy() ||
232 !FT->getParamType(1)->isIntegerTy() ||
233 FT->getParamType(2) != TD->getIntPtrType(Context) ||
234 FT->getParamType(3) != TD->getIntPtrType(Context))
237 if (isFoldable(3, 2, false)) {
238 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
240 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
241 return CI->getArgOperand(0);
247 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
248 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
250 StringRef Name = Callee->getName();
251 FunctionType *FT = Callee->getFunctionType();
252 LLVMContext &Context = CI->getParent()->getContext();
254 // Check if this has the right signature.
255 if (FT->getNumParams() != 3 ||
256 FT->getReturnType() != FT->getParamType(0) ||
257 FT->getParamType(0) != FT->getParamType(1) ||
258 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
259 FT->getParamType(2) != TD->getIntPtrType(Context))
262 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
263 if (Dst == Src) // __strcpy_chk(x,x) -> x
266 // If a) we don't have any length information, or b) we know this will
267 // fit then just lower to a plain strcpy. Otherwise we'll keep our
268 // strcpy_chk call which may fail at runtime if the size is too long.
269 // TODO: It might be nice to get a maximum length out of the possible
270 // string lengths for varying.
271 if (isFoldable(2, 1, true)) {
272 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
275 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
276 uint64_t Len = GetStringLength(Src);
277 if (Len == 0) return 0;
279 // This optimization require DataLayout.
283 EmitMemCpyChk(Dst, Src,
284 ConstantInt::get(TD->getIntPtrType(Context), Len),
285 CI->getArgOperand(2), B, TD, TLI);
292 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
293 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
295 StringRef Name = Callee->getName();
296 FunctionType *FT = Callee->getFunctionType();
297 LLVMContext &Context = CI->getParent()->getContext();
299 // Check if this has the right signature.
300 if (FT->getNumParams() != 3 ||
301 FT->getReturnType() != FT->getParamType(0) ||
302 FT->getParamType(0) != FT->getParamType(1) ||
303 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
304 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
307 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
308 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
309 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
310 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
313 // If a) we don't have any length information, or b) we know this will
314 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
315 // stpcpy_chk call which may fail at runtime if the size is too long.
316 // TODO: It might be nice to get a maximum length out of the possible
317 // string lengths for varying.
318 if (isFoldable(2, 1, true)) {
319 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
322 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
323 uint64_t Len = GetStringLength(Src);
324 if (Len == 0) return 0;
326 // This optimization require DataLayout.
329 Type *PT = FT->getParamType(0);
330 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
331 Value *DstEnd = B.CreateGEP(Dst,
332 ConstantInt::get(TD->getIntPtrType(PT),
334 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI))
342 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
343 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
345 StringRef Name = Callee->getName();
346 FunctionType *FT = Callee->getFunctionType();
347 LLVMContext &Context = CI->getParent()->getContext();
349 // Check if this has the right signature.
350 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
351 FT->getParamType(0) != FT->getParamType(1) ||
352 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
353 !FT->getParamType(2)->isIntegerTy() ||
354 FT->getParamType(3) != TD->getIntPtrType(Context))
357 if (isFoldable(3, 2, false)) {
358 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
359 CI->getArgOperand(2), B, TD, TLI,
367 //===----------------------------------------------------------------------===//
368 // String and Memory Library Call Optimizations
369 //===----------------------------------------------------------------------===//
371 struct StrCatOpt : public LibCallOptimization {
372 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
373 // Verify the "strcat" function prototype.
374 FunctionType *FT = Callee->getFunctionType();
375 if (FT->getNumParams() != 2 ||
376 FT->getReturnType() != B.getInt8PtrTy() ||
377 FT->getParamType(0) != FT->getReturnType() ||
378 FT->getParamType(1) != FT->getReturnType())
381 // Extract some information from the instruction
382 Value *Dst = CI->getArgOperand(0);
383 Value *Src = CI->getArgOperand(1);
385 // See if we can get the length of the input string.
386 uint64_t Len = GetStringLength(Src);
387 if (Len == 0) return 0;
388 --Len; // Unbias length.
390 // Handle the simple, do-nothing case: strcat(x, "") -> x
394 // These optimizations require DataLayout.
397 return emitStrLenMemCpy(Src, Dst, Len, B);
400 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
402 // We need to find the end of the destination string. That's where the
403 // memory is to be moved to. We just generate a call to strlen.
404 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
408 // Now that we have the destination's length, we must index into the
409 // destination's pointer to get the actual memcpy destination (end of
410 // the string .. we're concatenating).
411 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
413 // We have enough information to now generate the memcpy call to do the
414 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
415 B.CreateMemCpy(CpyDst, Src,
416 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
421 struct StrNCatOpt : public StrCatOpt {
422 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
423 // Verify the "strncat" function prototype.
424 FunctionType *FT = Callee->getFunctionType();
425 if (FT->getNumParams() != 3 ||
426 FT->getReturnType() != B.getInt8PtrTy() ||
427 FT->getParamType(0) != FT->getReturnType() ||
428 FT->getParamType(1) != FT->getReturnType() ||
429 !FT->getParamType(2)->isIntegerTy())
432 // Extract some information from the instruction
433 Value *Dst = CI->getArgOperand(0);
434 Value *Src = CI->getArgOperand(1);
437 // We don't do anything if length is not constant
438 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
439 Len = LengthArg->getZExtValue();
443 // See if we can get the length of the input string.
444 uint64_t SrcLen = GetStringLength(Src);
445 if (SrcLen == 0) return 0;
446 --SrcLen; // Unbias length.
448 // Handle the simple, do-nothing cases:
449 // strncat(x, "", c) -> x
450 // strncat(x, c, 0) -> x
451 if (SrcLen == 0 || Len == 0) return Dst;
453 // These optimizations require DataLayout.
456 // We don't optimize this case
457 if (Len < SrcLen) return 0;
459 // strncat(x, s, c) -> strcat(x, s)
460 // s is constant so the strcat can be optimized further
461 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
465 struct StrChrOpt : public LibCallOptimization {
466 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
467 // Verify the "strchr" function prototype.
468 FunctionType *FT = Callee->getFunctionType();
469 if (FT->getNumParams() != 2 ||
470 FT->getReturnType() != B.getInt8PtrTy() ||
471 FT->getParamType(0) != FT->getReturnType() ||
472 !FT->getParamType(1)->isIntegerTy(32))
475 Value *SrcStr = CI->getArgOperand(0);
477 // If the second operand is non-constant, see if we can compute the length
478 // of the input string and turn this into memchr.
479 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
481 // These optimizations require DataLayout.
484 uint64_t Len = GetStringLength(SrcStr);
485 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
488 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
489 ConstantInt::get(TD->getIntPtrType(*Context), Len),
493 // Otherwise, the character is a constant, see if the first argument is
494 // a string literal. If so, we can constant fold.
496 if (!getConstantStringInfo(SrcStr, Str)) {
497 if (TD && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
498 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, TD, TLI), "strchr");
502 // Compute the offset, make sure to handle the case when we're searching for
503 // zero (a weird way to spell strlen).
504 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
505 Str.size() : Str.find(CharC->getSExtValue());
506 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
507 return Constant::getNullValue(CI->getType());
509 // strchr(s+n,c) -> gep(s+n+i,c)
510 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
514 struct StrRChrOpt : public LibCallOptimization {
515 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
516 // Verify the "strrchr" function prototype.
517 FunctionType *FT = Callee->getFunctionType();
518 if (FT->getNumParams() != 2 ||
519 FT->getReturnType() != B.getInt8PtrTy() ||
520 FT->getParamType(0) != FT->getReturnType() ||
521 !FT->getParamType(1)->isIntegerTy(32))
524 Value *SrcStr = CI->getArgOperand(0);
525 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
527 // Cannot fold anything if we're not looking for a constant.
532 if (!getConstantStringInfo(SrcStr, Str)) {
533 // strrchr(s, 0) -> strchr(s, 0)
534 if (TD && CharC->isZero())
535 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
539 // Compute the offset.
540 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
541 Str.size() : Str.rfind(CharC->getSExtValue());
542 if (I == StringRef::npos) // Didn't find the char. Return null.
543 return Constant::getNullValue(CI->getType());
545 // strrchr(s+n,c) -> gep(s+n+i,c)
546 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
550 struct StrCmpOpt : public LibCallOptimization {
551 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
552 // Verify the "strcmp" function prototype.
553 FunctionType *FT = Callee->getFunctionType();
554 if (FT->getNumParams() != 2 ||
555 !FT->getReturnType()->isIntegerTy(32) ||
556 FT->getParamType(0) != FT->getParamType(1) ||
557 FT->getParamType(0) != B.getInt8PtrTy())
560 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
561 if (Str1P == Str2P) // strcmp(x,x) -> 0
562 return ConstantInt::get(CI->getType(), 0);
564 StringRef Str1, Str2;
565 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
566 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
568 // strcmp(x, y) -> cnst (if both x and y are constant strings)
569 if (HasStr1 && HasStr2)
570 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
572 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
573 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
576 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
577 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
579 // strcmp(P, "x") -> memcmp(P, "x", 2)
580 uint64_t Len1 = GetStringLength(Str1P);
581 uint64_t Len2 = GetStringLength(Str2P);
583 // These optimizations require DataLayout.
586 return EmitMemCmp(Str1P, Str2P,
587 ConstantInt::get(TD->getIntPtrType(*Context),
588 std::min(Len1, Len2)), B, TD, TLI);
595 struct StrNCmpOpt : public LibCallOptimization {
596 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
597 // Verify the "strncmp" function prototype.
598 FunctionType *FT = Callee->getFunctionType();
599 if (FT->getNumParams() != 3 ||
600 !FT->getReturnType()->isIntegerTy(32) ||
601 FT->getParamType(0) != FT->getParamType(1) ||
602 FT->getParamType(0) != B.getInt8PtrTy() ||
603 !FT->getParamType(2)->isIntegerTy())
606 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
607 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
608 return ConstantInt::get(CI->getType(), 0);
610 // Get the length argument if it is constant.
612 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
613 Length = LengthArg->getZExtValue();
617 if (Length == 0) // strncmp(x,y,0) -> 0
618 return ConstantInt::get(CI->getType(), 0);
620 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
621 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
623 StringRef Str1, Str2;
624 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
625 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
627 // strncmp(x, y) -> cnst (if both x and y are constant strings)
628 if (HasStr1 && HasStr2) {
629 StringRef SubStr1 = Str1.substr(0, Length);
630 StringRef SubStr2 = Str2.substr(0, Length);
631 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
634 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
635 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
638 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
639 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
645 struct StrCpyOpt : public LibCallOptimization {
646 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
647 // Verify the "strcpy" function prototype.
648 FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 ||
650 FT->getReturnType() != FT->getParamType(0) ||
651 FT->getParamType(0) != FT->getParamType(1) ||
652 FT->getParamType(0) != B.getInt8PtrTy())
655 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
656 if (Dst == Src) // strcpy(x,x) -> x
659 // These optimizations require DataLayout.
662 // See if we can get the length of the input string.
663 uint64_t Len = GetStringLength(Src);
664 if (Len == 0) return 0;
666 // We have enough information to now generate the memcpy call to do the
667 // copy for us. Make a memcpy to copy the nul byte with align = 1.
668 B.CreateMemCpy(Dst, Src,
669 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
674 struct StpCpyOpt: public LibCallOptimization {
675 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
676 // Verify the "stpcpy" function prototype.
677 FunctionType *FT = Callee->getFunctionType();
678 if (FT->getNumParams() != 2 ||
679 FT->getReturnType() != FT->getParamType(0) ||
680 FT->getParamType(0) != FT->getParamType(1) ||
681 FT->getParamType(0) != B.getInt8PtrTy())
684 // These optimizations require DataLayout.
687 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
688 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
689 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
690 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
693 // See if we can get the length of the input string.
694 uint64_t Len = GetStringLength(Src);
695 if (Len == 0) return 0;
697 Type *PT = FT->getParamType(0);
698 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
699 Value *DstEnd = B.CreateGEP(Dst,
700 ConstantInt::get(TD->getIntPtrType(PT),
703 // We have enough information to now generate the memcpy call to do the
704 // copy for us. Make a memcpy to copy the nul byte with align = 1.
705 B.CreateMemCpy(Dst, Src, LenV, 1);
710 struct StrNCpyOpt : public LibCallOptimization {
711 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
712 FunctionType *FT = Callee->getFunctionType();
713 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
714 FT->getParamType(0) != FT->getParamType(1) ||
715 FT->getParamType(0) != B.getInt8PtrTy() ||
716 !FT->getParamType(2)->isIntegerTy())
719 Value *Dst = CI->getArgOperand(0);
720 Value *Src = CI->getArgOperand(1);
721 Value *LenOp = CI->getArgOperand(2);
723 // See if we can get the length of the input string.
724 uint64_t SrcLen = GetStringLength(Src);
725 if (SrcLen == 0) return 0;
729 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
730 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
735 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
736 Len = LengthArg->getZExtValue();
740 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
742 // These optimizations require DataLayout.
745 // Let strncpy handle the zero padding
746 if (Len > SrcLen+1) return 0;
748 Type *PT = FT->getParamType(0);
749 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
750 B.CreateMemCpy(Dst, Src,
751 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
757 struct StrLenOpt : public LibCallOptimization {
758 virtual bool ignoreCallingConv() { return true; }
759 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
760 FunctionType *FT = Callee->getFunctionType();
761 if (FT->getNumParams() != 1 ||
762 FT->getParamType(0) != B.getInt8PtrTy() ||
763 !FT->getReturnType()->isIntegerTy())
766 Value *Src = CI->getArgOperand(0);
768 // Constant folding: strlen("xyz") -> 3
769 if (uint64_t Len = GetStringLength(Src))
770 return ConstantInt::get(CI->getType(), Len-1);
772 // strlen(x) != 0 --> *x != 0
773 // strlen(x) == 0 --> *x == 0
774 if (isOnlyUsedInZeroEqualityComparison(CI))
775 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
780 struct StrPBrkOpt : public LibCallOptimization {
781 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
782 FunctionType *FT = Callee->getFunctionType();
783 if (FT->getNumParams() != 2 ||
784 FT->getParamType(0) != B.getInt8PtrTy() ||
785 FT->getParamType(1) != FT->getParamType(0) ||
786 FT->getReturnType() != FT->getParamType(0))
790 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
791 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
793 // strpbrk(s, "") -> NULL
794 // strpbrk("", s) -> NULL
795 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
796 return Constant::getNullValue(CI->getType());
799 if (HasS1 && HasS2) {
800 size_t I = S1.find_first_of(S2);
801 if (I == StringRef::npos) // No match.
802 return Constant::getNullValue(CI->getType());
804 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
807 // strpbrk(s, "a") -> strchr(s, 'a')
808 if (TD && HasS2 && S2.size() == 1)
809 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
815 struct StrToOpt : public LibCallOptimization {
816 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
817 FunctionType *FT = Callee->getFunctionType();
818 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
819 !FT->getParamType(0)->isPointerTy() ||
820 !FT->getParamType(1)->isPointerTy())
823 Value *EndPtr = CI->getArgOperand(1);
824 if (isa<ConstantPointerNull>(EndPtr)) {
825 // With a null EndPtr, this function won't capture the main argument.
826 // It would be readonly too, except that it still may write to errno.
827 CI->addAttribute(1, Attribute::NoCapture);
834 struct StrSpnOpt : public LibCallOptimization {
835 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
836 FunctionType *FT = Callee->getFunctionType();
837 if (FT->getNumParams() != 2 ||
838 FT->getParamType(0) != B.getInt8PtrTy() ||
839 FT->getParamType(1) != FT->getParamType(0) ||
840 !FT->getReturnType()->isIntegerTy())
844 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
845 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
847 // strspn(s, "") -> 0
848 // strspn("", s) -> 0
849 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
850 return Constant::getNullValue(CI->getType());
853 if (HasS1 && HasS2) {
854 size_t Pos = S1.find_first_not_of(S2);
855 if (Pos == StringRef::npos) Pos = S1.size();
856 return ConstantInt::get(CI->getType(), Pos);
863 struct StrCSpnOpt : public LibCallOptimization {
864 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
865 FunctionType *FT = Callee->getFunctionType();
866 if (FT->getNumParams() != 2 ||
867 FT->getParamType(0) != B.getInt8PtrTy() ||
868 FT->getParamType(1) != FT->getParamType(0) ||
869 !FT->getReturnType()->isIntegerTy())
873 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
874 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
876 // strcspn("", s) -> 0
877 if (HasS1 && S1.empty())
878 return Constant::getNullValue(CI->getType());
881 if (HasS1 && HasS2) {
882 size_t Pos = S1.find_first_of(S2);
883 if (Pos == StringRef::npos) Pos = S1.size();
884 return ConstantInt::get(CI->getType(), Pos);
887 // strcspn(s, "") -> strlen(s)
888 if (TD && HasS2 && S2.empty())
889 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
895 struct StrStrOpt : public LibCallOptimization {
896 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
897 FunctionType *FT = Callee->getFunctionType();
898 if (FT->getNumParams() != 2 ||
899 !FT->getParamType(0)->isPointerTy() ||
900 !FT->getParamType(1)->isPointerTy() ||
901 !FT->getReturnType()->isPointerTy())
904 // fold strstr(x, x) -> x.
905 if (CI->getArgOperand(0) == CI->getArgOperand(1))
906 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
908 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
909 if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
910 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
913 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
917 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
919 ICmpInst *Old = cast<ICmpInst>(*UI++);
920 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
921 ConstantInt::getNullValue(StrNCmp->getType()),
923 LCS->replaceAllUsesWith(Old, Cmp);
928 // See if either input string is a constant string.
929 StringRef SearchStr, ToFindStr;
930 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
931 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
933 // fold strstr(x, "") -> x.
934 if (HasStr2 && ToFindStr.empty())
935 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
937 // If both strings are known, constant fold it.
938 if (HasStr1 && HasStr2) {
939 size_t Offset = SearchStr.find(ToFindStr);
941 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
942 return Constant::getNullValue(CI->getType());
944 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
945 Value *Result = CastToCStr(CI->getArgOperand(0), B);
946 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
947 return B.CreateBitCast(Result, CI->getType());
950 // fold strstr(x, "y") -> strchr(x, 'y').
951 if (HasStr2 && ToFindStr.size() == 1) {
952 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
953 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
959 struct MemCmpOpt : public LibCallOptimization {
960 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
961 FunctionType *FT = Callee->getFunctionType();
962 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
963 !FT->getParamType(1)->isPointerTy() ||
964 !FT->getReturnType()->isIntegerTy(32))
967 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
969 if (LHS == RHS) // memcmp(s,s,x) -> 0
970 return Constant::getNullValue(CI->getType());
972 // Make sure we have a constant length.
973 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
975 uint64_t Len = LenC->getZExtValue();
977 if (Len == 0) // memcmp(s1,s2,0) -> 0
978 return Constant::getNullValue(CI->getType());
980 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
982 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
983 CI->getType(), "lhsv");
984 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
985 CI->getType(), "rhsv");
986 return B.CreateSub(LHSV, RHSV, "chardiff");
989 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
990 StringRef LHSStr, RHSStr;
991 if (getConstantStringInfo(LHS, LHSStr) &&
992 getConstantStringInfo(RHS, RHSStr)) {
993 // Make sure we're not reading out-of-bounds memory.
994 if (Len > LHSStr.size() || Len > RHSStr.size())
996 // Fold the memcmp and normalize the result. This way we get consistent
997 // results across multiple platforms.
999 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1004 return ConstantInt::get(CI->getType(), Ret);
1011 struct MemCpyOpt : public LibCallOptimization {
1012 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1013 // These optimizations require DataLayout.
1016 FunctionType *FT = Callee->getFunctionType();
1017 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1018 !FT->getParamType(0)->isPointerTy() ||
1019 !FT->getParamType(1)->isPointerTy() ||
1020 FT->getParamType(2) != TD->getIntPtrType(*Context))
1023 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1024 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1025 CI->getArgOperand(2), 1);
1026 return CI->getArgOperand(0);
1030 struct MemMoveOpt : public LibCallOptimization {
1031 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1032 // These optimizations require DataLayout.
1035 FunctionType *FT = Callee->getFunctionType();
1036 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1037 !FT->getParamType(0)->isPointerTy() ||
1038 !FT->getParamType(1)->isPointerTy() ||
1039 FT->getParamType(2) != TD->getIntPtrType(*Context))
1042 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1043 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1044 CI->getArgOperand(2), 1);
1045 return CI->getArgOperand(0);
1049 struct MemSetOpt : public LibCallOptimization {
1050 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1051 // These optimizations require DataLayout.
1054 FunctionType *FT = Callee->getFunctionType();
1055 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1056 !FT->getParamType(0)->isPointerTy() ||
1057 !FT->getParamType(1)->isIntegerTy() ||
1058 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
1061 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1062 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1063 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1064 return CI->getArgOperand(0);
1068 //===----------------------------------------------------------------------===//
1069 // Math Library Optimizations
1070 //===----------------------------------------------------------------------===//
1072 //===----------------------------------------------------------------------===//
1073 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1075 struct UnaryDoubleFPOpt : public LibCallOptimization {
1077 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1078 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1079 FunctionType *FT = Callee->getFunctionType();
1080 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1081 !FT->getParamType(0)->isDoubleTy())
1085 // Check if all the uses for function like 'sin' are converted to float.
1086 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1088 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1089 if (Cast == 0 || !Cast->getType()->isFloatTy())
1094 // If this is something like 'floor((double)floatval)', convert to floorf.
1095 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1096 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1099 // floor((double)floatval) -> (double)floorf(floatval)
1100 Value *V = Cast->getOperand(0);
1101 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1102 return B.CreateFPExt(V, B.getDoubleTy());
1106 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1107 struct BinaryDoubleFPOpt : public LibCallOptimization {
1109 BinaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1110 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1111 FunctionType *FT = Callee->getFunctionType();
1112 // Just make sure this has 2 arguments of the same FP type, which match the
1114 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1115 FT->getParamType(0) != FT->getParamType(1) ||
1116 !FT->getParamType(0)->isFloatingPointTy())
1120 // Check if all the uses for function like 'fmin/fmax' are converted to
1122 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1124 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1125 if (Cast == 0 || !Cast->getType()->isFloatTy())
1130 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1131 // we convert it to fminf.
1132 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1133 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1134 if (Cast1 == 0 || !Cast1->getOperand(0)->getType()->isFloatTy() ||
1135 Cast2 == 0 || !Cast2->getOperand(0)->getType()->isFloatTy())
1138 // fmin((double)floatval1, (double)floatval2)
1139 // -> (double)fmin(floatval1, floatval2)
1141 Value *V1 = Cast1->getOperand(0);
1142 Value *V2 = Cast2->getOperand(0);
1143 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1144 Callee->getAttributes());
1145 return B.CreateFPExt(V, B.getDoubleTy());
1149 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1150 bool UnsafeFPShrink;
1151 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1152 this->UnsafeFPShrink = UnsafeFPShrink;
1156 struct CosOpt : public UnsafeFPLibCallOptimization {
1157 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1158 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1160 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1161 TLI->has(LibFunc::cosf)) {
1162 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1163 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1166 FunctionType *FT = Callee->getFunctionType();
1167 // Just make sure this has 1 argument of FP type, which matches the
1169 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1170 !FT->getParamType(0)->isFloatingPointTy())
1173 // cos(-x) -> cos(x)
1174 Value *Op1 = CI->getArgOperand(0);
1175 if (BinaryOperator::isFNeg(Op1)) {
1176 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1177 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1183 struct PowOpt : public UnsafeFPLibCallOptimization {
1184 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1185 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1187 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1188 TLI->has(LibFunc::powf)) {
1189 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1190 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1193 FunctionType *FT = Callee->getFunctionType();
1194 // Just make sure this has 2 arguments of the same FP type, which match the
1196 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1197 FT->getParamType(0) != FT->getParamType(1) ||
1198 !FT->getParamType(0)->isFloatingPointTy())
1201 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1202 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1203 // pow(1.0, x) -> 1.0
1204 if (Op1C->isExactlyValue(1.0))
1206 // pow(2.0, x) -> exp2(x)
1207 if (Op1C->isExactlyValue(2.0) &&
1208 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1210 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1211 // pow(10.0, x) -> exp10(x)
1212 if (Op1C->isExactlyValue(10.0) &&
1213 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1215 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1216 Callee->getAttributes());
1219 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1220 if (Op2C == 0) return Ret;
1222 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1223 return ConstantFP::get(CI->getType(), 1.0);
1225 if (Op2C->isExactlyValue(0.5) &&
1226 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1228 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1230 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1231 // This is faster than calling pow, and still handles negative zero
1232 // and negative infinity correctly.
1233 // TODO: In fast-math mode, this could be just sqrt(x).
1234 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1235 Value *Inf = ConstantFP::getInfinity(CI->getType());
1236 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1237 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1238 Callee->getAttributes());
1239 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1240 Callee->getAttributes());
1241 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1242 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1246 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1248 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1249 return B.CreateFMul(Op1, Op1, "pow2");
1250 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1251 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1257 struct Exp2Opt : public UnsafeFPLibCallOptimization {
1258 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1259 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1261 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1262 TLI->has(LibFunc::exp2f)) {
1263 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1264 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1267 FunctionType *FT = Callee->getFunctionType();
1268 // Just make sure this has 1 argument of FP type, which matches the
1270 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1271 !FT->getParamType(0)->isFloatingPointTy())
1274 Value *Op = CI->getArgOperand(0);
1275 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1276 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1277 Value *LdExpArg = 0;
1278 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1279 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1280 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1281 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1282 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1283 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1288 if (Op->getType()->isFloatTy())
1290 else if (Op->getType()->isDoubleTy())
1295 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1296 if (!Op->getType()->isFloatTy())
1297 One = ConstantExpr::getFPExtend(One, Op->getType());
1299 Module *M = Caller->getParent();
1300 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1302 B.getInt32Ty(), NULL);
1303 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1304 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1305 CI->setCallingConv(F->getCallingConv());
1313 struct SinCosPiOpt : public LibCallOptimization {
1316 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1317 // Make sure the prototype is as expected, otherwise the rest of the
1318 // function is probably invalid and likely to abort.
1319 if (!isTrigLibCall(CI))
1322 Value *Arg = CI->getArgOperand(0);
1323 SmallVector<CallInst *, 1> SinCalls;
1324 SmallVector<CallInst *, 1> CosCalls;
1325 SmallVector<CallInst *, 1> SinCosCalls;
1327 bool IsFloat = Arg->getType()->isFloatTy();
1329 // Look for all compatible sinpi, cospi and sincospi calls with the same
1330 // argument. If there are enough (in some sense) we can make the
1332 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
1334 classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls,
1337 // It's only worthwhile if both sinpi and cospi are actually used.
1338 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1341 Value *Sin, *Cos, *SinCos;
1342 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1345 replaceTrigInsts(SinCalls, Sin);
1346 replaceTrigInsts(CosCalls, Cos);
1347 replaceTrigInsts(SinCosCalls, SinCos);
1352 bool isTrigLibCall(CallInst *CI) {
1353 Function *Callee = CI->getCalledFunction();
1354 FunctionType *FT = Callee->getFunctionType();
1356 // We can only hope to do anything useful if we can ignore things like errno
1357 // and floating-point exceptions.
1358 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1359 CI->hasFnAttr(Attribute::ReadNone);
1361 // Other than that we need float(float) or double(double)
1362 return AttributesSafe && FT->getNumParams() == 1 &&
1363 FT->getReturnType() == FT->getParamType(0) &&
1364 (FT->getParamType(0)->isFloatTy() ||
1365 FT->getParamType(0)->isDoubleTy());
1368 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1369 SmallVectorImpl<CallInst *> &SinCalls,
1370 SmallVectorImpl<CallInst *> &CosCalls,
1371 SmallVectorImpl<CallInst *> &SinCosCalls) {
1372 CallInst *CI = dyn_cast<CallInst>(Val);
1377 Function *Callee = CI->getCalledFunction();
1378 StringRef FuncName = Callee->getName();
1380 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1385 if (Func == LibFunc::sinpif)
1386 SinCalls.push_back(CI);
1387 else if (Func == LibFunc::cospif)
1388 CosCalls.push_back(CI);
1389 else if (Func == LibFunc::sincospi_stretf)
1390 SinCosCalls.push_back(CI);
1392 if (Func == LibFunc::sinpi)
1393 SinCalls.push_back(CI);
1394 else if (Func == LibFunc::cospi)
1395 CosCalls.push_back(CI);
1396 else if (Func == LibFunc::sincospi_stret)
1397 SinCosCalls.push_back(CI);
1401 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1402 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1405 LCS->replaceAllUsesWith(*I, Res);
1409 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1410 bool UseFloat, Value *&Sin, Value *&Cos,
1412 Type *ArgTy = Arg->getType();
1416 Triple T(OrigCallee->getParent()->getTargetTriple());
1418 Name = "__sincospi_stretf";
1420 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1421 // x86_64 can't use {float, float} since that would be returned in both
1422 // xmm0 and xmm1, which isn't what a real struct would do.
1423 ResTy = T.getArch() == Triple::x86_64
1424 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1425 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1427 Name = "__sincospi_stret";
1428 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1431 Module *M = OrigCallee->getParent();
1432 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1433 ResTy, ArgTy, NULL);
1435 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1436 // If the argument is an instruction, it must dominate all uses so put our
1437 // sincos call there.
1438 BasicBlock::iterator Loc = ArgInst;
1439 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1441 // Otherwise (e.g. for a constant) the beginning of the function is as
1442 // good a place as any.
1443 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1444 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1447 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1449 if (SinCos->getType()->isStructTy()) {
1450 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1451 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1453 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1455 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1462 //===----------------------------------------------------------------------===//
1463 // Integer Library Call Optimizations
1464 //===----------------------------------------------------------------------===//
1466 struct FFSOpt : public LibCallOptimization {
1467 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1468 FunctionType *FT = Callee->getFunctionType();
1469 // Just make sure this has 2 arguments of the same FP type, which match the
1471 if (FT->getNumParams() != 1 ||
1472 !FT->getReturnType()->isIntegerTy(32) ||
1473 !FT->getParamType(0)->isIntegerTy())
1476 Value *Op = CI->getArgOperand(0);
1479 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1480 if (CI->isZero()) // ffs(0) -> 0.
1481 return B.getInt32(0);
1482 // ffs(c) -> cttz(c)+1
1483 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1486 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1487 Type *ArgType = Op->getType();
1488 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1489 Intrinsic::cttz, ArgType);
1490 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1491 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1492 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1494 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1495 return B.CreateSelect(Cond, V, B.getInt32(0));
1499 struct AbsOpt : public LibCallOptimization {
1500 virtual bool ignoreCallingConv() { return true; }
1501 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1502 FunctionType *FT = Callee->getFunctionType();
1503 // We require integer(integer) where the types agree.
1504 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1505 FT->getParamType(0) != FT->getReturnType())
1508 // abs(x) -> x >s -1 ? x : -x
1509 Value *Op = CI->getArgOperand(0);
1510 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1512 Value *Neg = B.CreateNeg(Op, "neg");
1513 return B.CreateSelect(Pos, Op, Neg);
1517 struct IsDigitOpt : public LibCallOptimization {
1518 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1519 FunctionType *FT = Callee->getFunctionType();
1520 // We require integer(i32)
1521 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1522 !FT->getParamType(0)->isIntegerTy(32))
1525 // isdigit(c) -> (c-'0') <u 10
1526 Value *Op = CI->getArgOperand(0);
1527 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1528 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1529 return B.CreateZExt(Op, CI->getType());
1533 struct IsAsciiOpt : public LibCallOptimization {
1534 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1535 FunctionType *FT = Callee->getFunctionType();
1536 // We require integer(i32)
1537 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1538 !FT->getParamType(0)->isIntegerTy(32))
1541 // isascii(c) -> c <u 128
1542 Value *Op = CI->getArgOperand(0);
1543 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1544 return B.CreateZExt(Op, CI->getType());
1548 struct ToAsciiOpt : public LibCallOptimization {
1549 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1550 FunctionType *FT = Callee->getFunctionType();
1551 // We require i32(i32)
1552 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1553 !FT->getParamType(0)->isIntegerTy(32))
1556 // toascii(c) -> c & 0x7f
1557 return B.CreateAnd(CI->getArgOperand(0),
1558 ConstantInt::get(CI->getType(),0x7F));
1562 //===----------------------------------------------------------------------===//
1563 // Formatting and IO Library Call Optimizations
1564 //===----------------------------------------------------------------------===//
1566 struct ErrorReportingOpt : public LibCallOptimization {
1567 ErrorReportingOpt(int S = -1) : StreamArg(S) {}
1569 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &) {
1570 // Error reporting calls should be cold, mark them as such.
1571 // This applies even to non-builtin calls: it is only a hint and applies to
1572 // functions that the frontend might not understand as builtins.
1574 // This heuristic was suggested in:
1575 // Improving Static Branch Prediction in a Compiler
1576 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1577 // Proceedings of PACT'98, Oct. 1998, IEEE
1579 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) {
1580 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1587 bool isReportingError(Function *Callee, CallInst *CI) {
1588 if (!ColdErrorCalls)
1591 if (!Callee || !Callee->isDeclaration())
1597 // These functions might be considered cold, but only if their stream
1598 // argument is stderr.
1600 if (StreamArg >= (int) CI->getNumArgOperands())
1602 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1605 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1606 if (!GV || !GV->isDeclaration())
1608 return GV->getName() == "stderr";
1614 struct PrintFOpt : public LibCallOptimization {
1615 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1617 // Check for a fixed format string.
1618 StringRef FormatStr;
1619 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1622 // Empty format string -> noop.
1623 if (FormatStr.empty()) // Tolerate printf's declared void.
1624 return CI->use_empty() ? (Value*)CI :
1625 ConstantInt::get(CI->getType(), 0);
1627 // Do not do any of the following transformations if the printf return value
1628 // is used, in general the printf return value is not compatible with either
1629 // putchar() or puts().
1630 if (!CI->use_empty())
1633 // printf("x") -> putchar('x'), even for '%'.
1634 if (FormatStr.size() == 1) {
1635 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1636 if (CI->use_empty() || !Res) return Res;
1637 return B.CreateIntCast(Res, CI->getType(), true);
1640 // printf("foo\n") --> puts("foo")
1641 if (FormatStr[FormatStr.size()-1] == '\n' &&
1642 FormatStr.find('%') == StringRef::npos) { // No format characters.
1643 // Create a string literal with no \n on it. We expect the constant merge
1644 // pass to be run after this pass, to merge duplicate strings.
1645 FormatStr = FormatStr.drop_back();
1646 Value *GV = B.CreateGlobalString(FormatStr, "str");
1647 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1648 return (CI->use_empty() || !NewCI) ?
1650 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1653 // Optimize specific format strings.
1654 // printf("%c", chr) --> putchar(chr)
1655 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1656 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1657 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1659 if (CI->use_empty() || !Res) return Res;
1660 return B.CreateIntCast(Res, CI->getType(), true);
1663 // printf("%s\n", str) --> puts(str)
1664 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1665 CI->getArgOperand(1)->getType()->isPointerTy()) {
1666 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1671 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1672 // Require one fixed pointer argument and an integer/void result.
1673 FunctionType *FT = Callee->getFunctionType();
1674 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1675 !(FT->getReturnType()->isIntegerTy() ||
1676 FT->getReturnType()->isVoidTy()))
1679 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1683 // printf(format, ...) -> iprintf(format, ...) if no floating point
1685 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1686 Module *M = B.GetInsertBlock()->getParent()->getParent();
1687 Constant *IPrintFFn =
1688 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1689 CallInst *New = cast<CallInst>(CI->clone());
1690 New->setCalledFunction(IPrintFFn);
1698 struct SPrintFOpt : public LibCallOptimization {
1699 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1701 // Check for a fixed format string.
1702 StringRef FormatStr;
1703 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1706 // If we just have a format string (nothing else crazy) transform it.
1707 if (CI->getNumArgOperands() == 2) {
1708 // Make sure there's no % in the constant array. We could try to handle
1709 // %% -> % in the future if we cared.
1710 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1711 if (FormatStr[i] == '%')
1712 return 0; // we found a format specifier, bail out.
1714 // These optimizations require DataLayout.
1717 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1718 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1719 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1720 FormatStr.size() + 1), 1); // nul byte.
1721 return ConstantInt::get(CI->getType(), FormatStr.size());
1724 // The remaining optimizations require the format string to be "%s" or "%c"
1725 // and have an extra operand.
1726 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1727 CI->getNumArgOperands() < 3)
1730 // Decode the second character of the format string.
1731 if (FormatStr[1] == 'c') {
1732 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1733 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1734 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1735 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1736 B.CreateStore(V, Ptr);
1737 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1738 B.CreateStore(B.getInt8(0), Ptr);
1740 return ConstantInt::get(CI->getType(), 1);
1743 if (FormatStr[1] == 's') {
1744 // These optimizations require DataLayout.
1747 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1748 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1750 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1753 Value *IncLen = B.CreateAdd(Len,
1754 ConstantInt::get(Len->getType(), 1),
1756 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1758 // The sprintf result is the unincremented number of bytes in the string.
1759 return B.CreateIntCast(Len, CI->getType(), false);
1764 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1765 // Require two fixed pointer arguments and an integer result.
1766 FunctionType *FT = Callee->getFunctionType();
1767 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1768 !FT->getParamType(1)->isPointerTy() ||
1769 !FT->getReturnType()->isIntegerTy())
1772 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1776 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1778 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1779 Module *M = B.GetInsertBlock()->getParent()->getParent();
1780 Constant *SIPrintFFn =
1781 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1782 CallInst *New = cast<CallInst>(CI->clone());
1783 New->setCalledFunction(SIPrintFFn);
1791 struct FPrintFOpt : public LibCallOptimization {
1792 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1794 ErrorReportingOpt ER(/* StreamArg = */ 0);
1795 (void) ER.callOptimizer(Callee, CI, B);
1797 // All the optimizations depend on the format string.
1798 StringRef FormatStr;
1799 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1802 // Do not do any of the following transformations if the fprintf return
1803 // value is used, in general the fprintf return value is not compatible
1804 // with fwrite(), fputc() or fputs().
1805 if (!CI->use_empty())
1808 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1809 if (CI->getNumArgOperands() == 2) {
1810 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1811 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1812 return 0; // We found a format specifier.
1814 // These optimizations require DataLayout.
1817 return EmitFWrite(CI->getArgOperand(1),
1818 ConstantInt::get(TD->getIntPtrType(*Context),
1820 CI->getArgOperand(0), B, TD, TLI);
1823 // The remaining optimizations require the format string to be "%s" or "%c"
1824 // and have an extra operand.
1825 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1826 CI->getNumArgOperands() < 3)
1829 // Decode the second character of the format string.
1830 if (FormatStr[1] == 'c') {
1831 // fprintf(F, "%c", chr) --> fputc(chr, F)
1832 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1833 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1836 if (FormatStr[1] == 's') {
1837 // fprintf(F, "%s", str) --> fputs(str, F)
1838 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1840 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1845 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1846 // Require two fixed paramters as pointers and integer result.
1847 FunctionType *FT = Callee->getFunctionType();
1848 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1849 !FT->getParamType(1)->isPointerTy() ||
1850 !FT->getReturnType()->isIntegerTy())
1853 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1857 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1858 // floating point arguments.
1859 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1860 Module *M = B.GetInsertBlock()->getParent()->getParent();
1861 Constant *FIPrintFFn =
1862 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1863 CallInst *New = cast<CallInst>(CI->clone());
1864 New->setCalledFunction(FIPrintFFn);
1872 struct FWriteOpt : public LibCallOptimization {
1873 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1874 ErrorReportingOpt ER(/* StreamArg = */ 3);
1875 (void) ER.callOptimizer(Callee, CI, B);
1877 // Require a pointer, an integer, an integer, a pointer, returning integer.
1878 FunctionType *FT = Callee->getFunctionType();
1879 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1880 !FT->getParamType(1)->isIntegerTy() ||
1881 !FT->getParamType(2)->isIntegerTy() ||
1882 !FT->getParamType(3)->isPointerTy() ||
1883 !FT->getReturnType()->isIntegerTy())
1886 // Get the element size and count.
1887 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1888 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1889 if (!SizeC || !CountC) return 0;
1890 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1892 // If this is writing zero records, remove the call (it's a noop).
1894 return ConstantInt::get(CI->getType(), 0);
1896 // If this is writing one byte, turn it into fputc.
1897 // This optimisation is only valid, if the return value is unused.
1898 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1899 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1900 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1901 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1908 struct FPutsOpt : public LibCallOptimization {
1909 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1910 ErrorReportingOpt ER(/* StreamArg = */ 1);
1911 (void) ER.callOptimizer(Callee, CI, B);
1913 // These optimizations require DataLayout.
1916 // Require two pointers. Also, we can't optimize if return value is used.
1917 FunctionType *FT = Callee->getFunctionType();
1918 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1919 !FT->getParamType(1)->isPointerTy() ||
1923 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1924 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1926 // Known to have no uses (see above).
1927 return EmitFWrite(CI->getArgOperand(0),
1928 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1929 CI->getArgOperand(1), B, TD, TLI);
1933 struct PutsOpt : public LibCallOptimization {
1934 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1935 // Require one fixed pointer argument and an integer/void result.
1936 FunctionType *FT = Callee->getFunctionType();
1937 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1938 !(FT->getReturnType()->isIntegerTy() ||
1939 FT->getReturnType()->isVoidTy()))
1942 // Check for a constant string.
1944 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1947 if (Str.empty() && CI->use_empty()) {
1948 // puts("") -> putchar('\n')
1949 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1950 if (CI->use_empty() || !Res) return Res;
1951 return B.CreateIntCast(Res, CI->getType(), true);
1958 } // End anonymous namespace.
1962 class LibCallSimplifierImpl {
1963 const DataLayout *TD;
1964 const TargetLibraryInfo *TLI;
1965 const LibCallSimplifier *LCS;
1966 bool UnsafeFPShrink;
1968 // Math library call optimizations.
1973 LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
1974 const LibCallSimplifier *LCS,
1975 bool UnsafeFPShrink = false)
1976 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
1980 this->UnsafeFPShrink = UnsafeFPShrink;
1983 Value *optimizeCall(CallInst *CI);
1984 LibCallOptimization *lookupOptimization(CallInst *CI);
1985 bool hasFloatVersion(StringRef FuncName);
1988 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
1990 SmallString<20> FloatFuncName = FuncName;
1991 FloatFuncName += 'f';
1992 if (TLI->getLibFunc(FloatFuncName, Func))
1993 return TLI->has(Func);
1997 // Fortified library call optimizations.
1998 static MemCpyChkOpt MemCpyChk;
1999 static MemMoveChkOpt MemMoveChk;
2000 static MemSetChkOpt MemSetChk;
2001 static StrCpyChkOpt StrCpyChk;
2002 static StpCpyChkOpt StpCpyChk;
2003 static StrNCpyChkOpt StrNCpyChk;
2005 // String library call optimizations.
2006 static StrCatOpt StrCat;
2007 static StrNCatOpt StrNCat;
2008 static StrChrOpt StrChr;
2009 static StrRChrOpt StrRChr;
2010 static StrCmpOpt StrCmp;
2011 static StrNCmpOpt StrNCmp;
2012 static StrCpyOpt StrCpy;
2013 static StpCpyOpt StpCpy;
2014 static StrNCpyOpt StrNCpy;
2015 static StrLenOpt StrLen;
2016 static StrPBrkOpt StrPBrk;
2017 static StrToOpt StrTo;
2018 static StrSpnOpt StrSpn;
2019 static StrCSpnOpt StrCSpn;
2020 static StrStrOpt StrStr;
2022 // Memory library call optimizations.
2023 static MemCmpOpt MemCmp;
2024 static MemCpyOpt MemCpy;
2025 static MemMoveOpt MemMove;
2026 static MemSetOpt MemSet;
2028 // Math library call optimizations.
2029 static UnaryDoubleFPOpt UnaryDoubleFP(false);
2030 static BinaryDoubleFPOpt BinaryDoubleFP(false);
2031 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
2032 static SinCosPiOpt SinCosPi;
2034 // Integer library call optimizations.
2037 static IsDigitOpt IsDigit;
2038 static IsAsciiOpt IsAscii;
2039 static ToAsciiOpt ToAscii;
2041 // Formatting and IO library call optimizations.
2042 static ErrorReportingOpt ErrorReporting;
2043 static ErrorReportingOpt ErrorReporting0(0);
2044 static ErrorReportingOpt ErrorReporting1(1);
2045 static PrintFOpt PrintF;
2046 static SPrintFOpt SPrintF;
2047 static FPrintFOpt FPrintF;
2048 static FWriteOpt FWrite;
2049 static FPutsOpt FPuts;
2050 static PutsOpt Puts;
2052 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
2054 Function *Callee = CI->getCalledFunction();
2055 StringRef FuncName = Callee->getName();
2057 // Next check for intrinsics.
2058 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2059 switch (II->getIntrinsicID()) {
2060 case Intrinsic::pow:
2062 case Intrinsic::exp2:
2069 // Then check for known library functions.
2070 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2072 case LibFunc::strcat:
2074 case LibFunc::strncat:
2076 case LibFunc::strchr:
2078 case LibFunc::strrchr:
2080 case LibFunc::strcmp:
2082 case LibFunc::strncmp:
2084 case LibFunc::strcpy:
2086 case LibFunc::stpcpy:
2088 case LibFunc::strncpy:
2090 case LibFunc::strlen:
2092 case LibFunc::strpbrk:
2094 case LibFunc::strtol:
2095 case LibFunc::strtod:
2096 case LibFunc::strtof:
2097 case LibFunc::strtoul:
2098 case LibFunc::strtoll:
2099 case LibFunc::strtold:
2100 case LibFunc::strtoull:
2102 case LibFunc::strspn:
2104 case LibFunc::strcspn:
2106 case LibFunc::strstr:
2108 case LibFunc::memcmp:
2110 case LibFunc::memcpy:
2112 case LibFunc::memmove:
2114 case LibFunc::memset:
2120 case LibFunc::sinpif:
2121 case LibFunc::sinpi:
2122 case LibFunc::cospif:
2123 case LibFunc::cospi:
2129 case LibFunc::exp2l:
2131 case LibFunc::exp2f:
2135 case LibFunc::ffsll:
2139 case LibFunc::llabs:
2141 case LibFunc::isdigit:
2143 case LibFunc::isascii:
2145 case LibFunc::toascii:
2147 case LibFunc::printf:
2149 case LibFunc::sprintf:
2151 case LibFunc::fprintf:
2153 case LibFunc::fwrite:
2155 case LibFunc::fputs:
2159 case LibFunc::perror:
2160 return &ErrorReporting;
2161 case LibFunc::vfprintf:
2162 case LibFunc::fiprintf:
2163 return &ErrorReporting0;
2164 case LibFunc::fputc:
2165 return &ErrorReporting1;
2168 case LibFunc::floor:
2170 case LibFunc::round:
2171 case LibFunc::nearbyint:
2172 case LibFunc::trunc:
2173 if (hasFloatVersion(FuncName))
2174 return &UnaryDoubleFP;
2177 case LibFunc::acosh:
2179 case LibFunc::asinh:
2181 case LibFunc::atanh:
2185 case LibFunc::exp10:
2186 case LibFunc::expm1:
2188 case LibFunc::log10:
2189 case LibFunc::log1p:
2197 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2198 return &UnsafeUnaryDoubleFP;
2202 if (hasFloatVersion(FuncName))
2203 return &BinaryDoubleFP;
2205 case LibFunc::memcpy_chk:
2212 // Finally check for fortified library calls.
2213 if (FuncName.endswith("_chk")) {
2214 if (FuncName == "__memmove_chk")
2216 else if (FuncName == "__memset_chk")
2218 else if (FuncName == "__strcpy_chk")
2220 else if (FuncName == "__stpcpy_chk")
2222 else if (FuncName == "__strncpy_chk")
2224 else if (FuncName == "__stpncpy_chk")
2232 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
2233 LibCallOptimization *LCO = lookupOptimization(CI);
2235 IRBuilder<> Builder(CI);
2236 return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
2241 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
2242 const TargetLibraryInfo *TLI,
2243 bool UnsafeFPShrink) {
2244 Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink);
2247 LibCallSimplifier::~LibCallSimplifier() {
2251 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2252 if (CI->isNoBuiltin()) return 0;
2253 return Impl->optimizeCall(CI);
2256 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2257 I->replaceAllUsesWith(With);
2258 I->eraseFromParent();
2264 // Additional cases that we need to add to this file:
2267 // * cbrt(expN(X)) -> expN(x/3)
2268 // * cbrt(sqrt(x)) -> pow(x,1/6)
2269 // * cbrt(sqrt(x)) -> pow(x,1/9)
2272 // * exp(log(x)) -> x
2275 // * log(exp(x)) -> x
2276 // * log(x**y) -> y*log(x)
2277 // * log(exp(y)) -> y*log(e)
2278 // * log(exp2(y)) -> y*log(2)
2279 // * log(exp10(y)) -> y*log(10)
2280 // * log(sqrt(x)) -> 0.5*log(x)
2281 // * log(pow(x,y)) -> y*log(x)
2283 // lround, lroundf, lroundl:
2284 // * lround(cnst) -> cnst'
2287 // * pow(exp(x),y) -> exp(x*y)
2288 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2289 // * pow(pow(x,y),z)-> pow(x,y*z)
2291 // round, roundf, roundl:
2292 // * round(cnst) -> cnst'
2295 // * signbit(cnst) -> cnst'
2296 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2298 // sqrt, sqrtf, sqrtl:
2299 // * sqrt(expN(x)) -> expN(x*0.5)
2300 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2301 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2304 // * tan(atan(x)) -> x
2306 // trunc, truncf, truncl:
2307 // * trunc(cnst) -> cnst'