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))
499 // Compute the offset, make sure to handle the case when we're searching for
500 // zero (a weird way to spell strlen).
501 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
502 Str.size() : Str.find(CharC->getSExtValue());
503 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
504 return Constant::getNullValue(CI->getType());
506 // strchr(s+n,c) -> gep(s+n+i,c)
507 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
511 struct StrRChrOpt : public LibCallOptimization {
512 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
513 // Verify the "strrchr" function prototype.
514 FunctionType *FT = Callee->getFunctionType();
515 if (FT->getNumParams() != 2 ||
516 FT->getReturnType() != B.getInt8PtrTy() ||
517 FT->getParamType(0) != FT->getReturnType() ||
518 !FT->getParamType(1)->isIntegerTy(32))
521 Value *SrcStr = CI->getArgOperand(0);
522 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
524 // Cannot fold anything if we're not looking for a constant.
529 if (!getConstantStringInfo(SrcStr, Str)) {
530 // strrchr(s, 0) -> strchr(s, 0)
531 if (TD && CharC->isZero())
532 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
536 // Compute the offset.
537 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
538 Str.size() : Str.rfind(CharC->getSExtValue());
539 if (I == StringRef::npos) // Didn't find the char. Return null.
540 return Constant::getNullValue(CI->getType());
542 // strrchr(s+n,c) -> gep(s+n+i,c)
543 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
547 struct StrCmpOpt : public LibCallOptimization {
548 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
549 // Verify the "strcmp" function prototype.
550 FunctionType *FT = Callee->getFunctionType();
551 if (FT->getNumParams() != 2 ||
552 !FT->getReturnType()->isIntegerTy(32) ||
553 FT->getParamType(0) != FT->getParamType(1) ||
554 FT->getParamType(0) != B.getInt8PtrTy())
557 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
558 if (Str1P == Str2P) // strcmp(x,x) -> 0
559 return ConstantInt::get(CI->getType(), 0);
561 StringRef Str1, Str2;
562 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
563 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
565 // strcmp(x, y) -> cnst (if both x and y are constant strings)
566 if (HasStr1 && HasStr2)
567 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
569 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
570 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
573 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
574 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
576 // strcmp(P, "x") -> memcmp(P, "x", 2)
577 uint64_t Len1 = GetStringLength(Str1P);
578 uint64_t Len2 = GetStringLength(Str2P);
580 // These optimizations require DataLayout.
583 return EmitMemCmp(Str1P, Str2P,
584 ConstantInt::get(TD->getIntPtrType(*Context),
585 std::min(Len1, Len2)), B, TD, TLI);
592 struct StrNCmpOpt : public LibCallOptimization {
593 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
594 // Verify the "strncmp" function prototype.
595 FunctionType *FT = Callee->getFunctionType();
596 if (FT->getNumParams() != 3 ||
597 !FT->getReturnType()->isIntegerTy(32) ||
598 FT->getParamType(0) != FT->getParamType(1) ||
599 FT->getParamType(0) != B.getInt8PtrTy() ||
600 !FT->getParamType(2)->isIntegerTy())
603 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
604 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
605 return ConstantInt::get(CI->getType(), 0);
607 // Get the length argument if it is constant.
609 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
610 Length = LengthArg->getZExtValue();
614 if (Length == 0) // strncmp(x,y,0) -> 0
615 return ConstantInt::get(CI->getType(), 0);
617 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
618 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
620 StringRef Str1, Str2;
621 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
622 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
624 // strncmp(x, y) -> cnst (if both x and y are constant strings)
625 if (HasStr1 && HasStr2) {
626 StringRef SubStr1 = Str1.substr(0, Length);
627 StringRef SubStr2 = Str2.substr(0, Length);
628 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
631 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
632 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
635 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
636 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
642 struct StrCpyOpt : public LibCallOptimization {
643 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
644 // Verify the "strcpy" function prototype.
645 FunctionType *FT = Callee->getFunctionType();
646 if (FT->getNumParams() != 2 ||
647 FT->getReturnType() != FT->getParamType(0) ||
648 FT->getParamType(0) != FT->getParamType(1) ||
649 FT->getParamType(0) != B.getInt8PtrTy())
652 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
653 if (Dst == Src) // strcpy(x,x) -> x
656 // These optimizations require DataLayout.
659 // See if we can get the length of the input string.
660 uint64_t Len = GetStringLength(Src);
661 if (Len == 0) return 0;
663 // We have enough information to now generate the memcpy call to do the
664 // copy for us. Make a memcpy to copy the nul byte with align = 1.
665 B.CreateMemCpy(Dst, Src,
666 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
671 struct StpCpyOpt: public LibCallOptimization {
672 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
673 // Verify the "stpcpy" function prototype.
674 FunctionType *FT = Callee->getFunctionType();
675 if (FT->getNumParams() != 2 ||
676 FT->getReturnType() != FT->getParamType(0) ||
677 FT->getParamType(0) != FT->getParamType(1) ||
678 FT->getParamType(0) != B.getInt8PtrTy())
681 // These optimizations require DataLayout.
684 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
685 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
686 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
687 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
690 // See if we can get the length of the input string.
691 uint64_t Len = GetStringLength(Src);
692 if (Len == 0) return 0;
694 Type *PT = FT->getParamType(0);
695 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
696 Value *DstEnd = B.CreateGEP(Dst,
697 ConstantInt::get(TD->getIntPtrType(PT),
700 // We have enough information to now generate the memcpy call to do the
701 // copy for us. Make a memcpy to copy the nul byte with align = 1.
702 B.CreateMemCpy(Dst, Src, LenV, 1);
707 struct StrNCpyOpt : public LibCallOptimization {
708 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
709 FunctionType *FT = Callee->getFunctionType();
710 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
711 FT->getParamType(0) != FT->getParamType(1) ||
712 FT->getParamType(0) != B.getInt8PtrTy() ||
713 !FT->getParamType(2)->isIntegerTy())
716 Value *Dst = CI->getArgOperand(0);
717 Value *Src = CI->getArgOperand(1);
718 Value *LenOp = CI->getArgOperand(2);
720 // See if we can get the length of the input string.
721 uint64_t SrcLen = GetStringLength(Src);
722 if (SrcLen == 0) return 0;
726 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
727 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
732 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
733 Len = LengthArg->getZExtValue();
737 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
739 // These optimizations require DataLayout.
742 // Let strncpy handle the zero padding
743 if (Len > SrcLen+1) return 0;
745 Type *PT = FT->getParamType(0);
746 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
747 B.CreateMemCpy(Dst, Src,
748 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
754 struct StrLenOpt : public LibCallOptimization {
755 virtual bool ignoreCallingConv() { return true; }
756 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
757 FunctionType *FT = Callee->getFunctionType();
758 if (FT->getNumParams() != 1 ||
759 FT->getParamType(0) != B.getInt8PtrTy() ||
760 !FT->getReturnType()->isIntegerTy())
763 Value *Src = CI->getArgOperand(0);
765 // Constant folding: strlen("xyz") -> 3
766 if (uint64_t Len = GetStringLength(Src))
767 return ConstantInt::get(CI->getType(), Len-1);
769 // strlen(x) != 0 --> *x != 0
770 // strlen(x) == 0 --> *x == 0
771 if (isOnlyUsedInZeroEqualityComparison(CI))
772 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
777 struct StrPBrkOpt : public LibCallOptimization {
778 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
779 FunctionType *FT = Callee->getFunctionType();
780 if (FT->getNumParams() != 2 ||
781 FT->getParamType(0) != B.getInt8PtrTy() ||
782 FT->getParamType(1) != FT->getParamType(0) ||
783 FT->getReturnType() != FT->getParamType(0))
787 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
788 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
790 // strpbrk(s, "") -> NULL
791 // strpbrk("", s) -> NULL
792 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
793 return Constant::getNullValue(CI->getType());
796 if (HasS1 && HasS2) {
797 size_t I = S1.find_first_of(S2);
798 if (I == StringRef::npos) // No match.
799 return Constant::getNullValue(CI->getType());
801 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
804 // strpbrk(s, "a") -> strchr(s, 'a')
805 if (TD && HasS2 && S2.size() == 1)
806 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
812 struct StrToOpt : public LibCallOptimization {
813 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
814 FunctionType *FT = Callee->getFunctionType();
815 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
816 !FT->getParamType(0)->isPointerTy() ||
817 !FT->getParamType(1)->isPointerTy())
820 Value *EndPtr = CI->getArgOperand(1);
821 if (isa<ConstantPointerNull>(EndPtr)) {
822 // With a null EndPtr, this function won't capture the main argument.
823 // It would be readonly too, except that it still may write to errno.
824 CI->addAttribute(1, Attribute::NoCapture);
831 struct StrSpnOpt : public LibCallOptimization {
832 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
833 FunctionType *FT = Callee->getFunctionType();
834 if (FT->getNumParams() != 2 ||
835 FT->getParamType(0) != B.getInt8PtrTy() ||
836 FT->getParamType(1) != FT->getParamType(0) ||
837 !FT->getReturnType()->isIntegerTy())
841 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
842 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
844 // strspn(s, "") -> 0
845 // strspn("", s) -> 0
846 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
847 return Constant::getNullValue(CI->getType());
850 if (HasS1 && HasS2) {
851 size_t Pos = S1.find_first_not_of(S2);
852 if (Pos == StringRef::npos) Pos = S1.size();
853 return ConstantInt::get(CI->getType(), Pos);
860 struct StrCSpnOpt : public LibCallOptimization {
861 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
862 FunctionType *FT = Callee->getFunctionType();
863 if (FT->getNumParams() != 2 ||
864 FT->getParamType(0) != B.getInt8PtrTy() ||
865 FT->getParamType(1) != FT->getParamType(0) ||
866 !FT->getReturnType()->isIntegerTy())
870 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
871 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
873 // strcspn("", s) -> 0
874 if (HasS1 && S1.empty())
875 return Constant::getNullValue(CI->getType());
878 if (HasS1 && HasS2) {
879 size_t Pos = S1.find_first_of(S2);
880 if (Pos == StringRef::npos) Pos = S1.size();
881 return ConstantInt::get(CI->getType(), Pos);
884 // strcspn(s, "") -> strlen(s)
885 if (TD && HasS2 && S2.empty())
886 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
892 struct StrStrOpt : public LibCallOptimization {
893 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
894 FunctionType *FT = Callee->getFunctionType();
895 if (FT->getNumParams() != 2 ||
896 !FT->getParamType(0)->isPointerTy() ||
897 !FT->getParamType(1)->isPointerTy() ||
898 !FT->getReturnType()->isPointerTy())
901 // fold strstr(x, x) -> x.
902 if (CI->getArgOperand(0) == CI->getArgOperand(1))
903 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
905 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
906 if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
907 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
910 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
914 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
916 ICmpInst *Old = cast<ICmpInst>(*UI++);
917 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
918 ConstantInt::getNullValue(StrNCmp->getType()),
920 LCS->replaceAllUsesWith(Old, Cmp);
925 // See if either input string is a constant string.
926 StringRef SearchStr, ToFindStr;
927 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
928 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
930 // fold strstr(x, "") -> x.
931 if (HasStr2 && ToFindStr.empty())
932 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
934 // If both strings are known, constant fold it.
935 if (HasStr1 && HasStr2) {
936 size_t Offset = SearchStr.find(ToFindStr);
938 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
939 return Constant::getNullValue(CI->getType());
941 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
942 Value *Result = CastToCStr(CI->getArgOperand(0), B);
943 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
944 return B.CreateBitCast(Result, CI->getType());
947 // fold strstr(x, "y") -> strchr(x, 'y').
948 if (HasStr2 && ToFindStr.size() == 1) {
949 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
950 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
956 struct MemCmpOpt : public LibCallOptimization {
957 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
958 FunctionType *FT = Callee->getFunctionType();
959 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
960 !FT->getParamType(1)->isPointerTy() ||
961 !FT->getReturnType()->isIntegerTy(32))
964 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
966 if (LHS == RHS) // memcmp(s,s,x) -> 0
967 return Constant::getNullValue(CI->getType());
969 // Make sure we have a constant length.
970 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
972 uint64_t Len = LenC->getZExtValue();
974 if (Len == 0) // memcmp(s1,s2,0) -> 0
975 return Constant::getNullValue(CI->getType());
977 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
979 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
980 CI->getType(), "lhsv");
981 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
982 CI->getType(), "rhsv");
983 return B.CreateSub(LHSV, RHSV, "chardiff");
986 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
987 StringRef LHSStr, RHSStr;
988 if (getConstantStringInfo(LHS, LHSStr) &&
989 getConstantStringInfo(RHS, RHSStr)) {
990 // Make sure we're not reading out-of-bounds memory.
991 if (Len > LHSStr.size() || Len > RHSStr.size())
993 // Fold the memcmp and normalize the result. This way we get consistent
994 // results across multiple platforms.
996 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1001 return ConstantInt::get(CI->getType(), Ret);
1008 struct MemCpyOpt : public LibCallOptimization {
1009 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1010 // These optimizations require DataLayout.
1013 FunctionType *FT = Callee->getFunctionType();
1014 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1015 !FT->getParamType(0)->isPointerTy() ||
1016 !FT->getParamType(1)->isPointerTy() ||
1017 FT->getParamType(2) != TD->getIntPtrType(*Context))
1020 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1021 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1022 CI->getArgOperand(2), 1);
1023 return CI->getArgOperand(0);
1027 struct MemMoveOpt : public LibCallOptimization {
1028 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1029 // These optimizations require DataLayout.
1032 FunctionType *FT = Callee->getFunctionType();
1033 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1034 !FT->getParamType(0)->isPointerTy() ||
1035 !FT->getParamType(1)->isPointerTy() ||
1036 FT->getParamType(2) != TD->getIntPtrType(*Context))
1039 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1040 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1041 CI->getArgOperand(2), 1);
1042 return CI->getArgOperand(0);
1046 struct MemSetOpt : public LibCallOptimization {
1047 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1048 // These optimizations require DataLayout.
1051 FunctionType *FT = Callee->getFunctionType();
1052 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1053 !FT->getParamType(0)->isPointerTy() ||
1054 !FT->getParamType(1)->isIntegerTy() ||
1055 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
1058 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1059 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1060 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1061 return CI->getArgOperand(0);
1065 //===----------------------------------------------------------------------===//
1066 // Math Library Optimizations
1067 //===----------------------------------------------------------------------===//
1069 //===----------------------------------------------------------------------===//
1070 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1072 struct UnaryDoubleFPOpt : public LibCallOptimization {
1074 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1075 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1076 FunctionType *FT = Callee->getFunctionType();
1077 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1078 !FT->getParamType(0)->isDoubleTy())
1082 // Check if all the uses for function like 'sin' are converted to float.
1083 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1085 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1086 if (Cast == 0 || !Cast->getType()->isFloatTy())
1091 // If this is something like 'floor((double)floatval)', convert to floorf.
1092 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1093 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1096 // floor((double)floatval) -> (double)floorf(floatval)
1097 Value *V = Cast->getOperand(0);
1098 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1099 return B.CreateFPExt(V, B.getDoubleTy());
1103 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1104 bool UnsafeFPShrink;
1105 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1106 this->UnsafeFPShrink = UnsafeFPShrink;
1110 struct CosOpt : public UnsafeFPLibCallOptimization {
1111 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1112 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1114 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1115 TLI->has(LibFunc::cosf)) {
1116 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1117 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1120 FunctionType *FT = Callee->getFunctionType();
1121 // Just make sure this has 1 argument of FP type, which matches the
1123 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1124 !FT->getParamType(0)->isFloatingPointTy())
1127 // cos(-x) -> cos(x)
1128 Value *Op1 = CI->getArgOperand(0);
1129 if (BinaryOperator::isFNeg(Op1)) {
1130 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1131 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1137 struct PowOpt : public UnsafeFPLibCallOptimization {
1138 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1139 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1141 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1142 TLI->has(LibFunc::powf)) {
1143 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1144 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1147 FunctionType *FT = Callee->getFunctionType();
1148 // Just make sure this has 2 arguments of the same FP type, which match the
1150 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1151 FT->getParamType(0) != FT->getParamType(1) ||
1152 !FT->getParamType(0)->isFloatingPointTy())
1155 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1156 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1157 // pow(1.0, x) -> 1.0
1158 if (Op1C->isExactlyValue(1.0))
1160 // pow(2.0, x) -> exp2(x)
1161 if (Op1C->isExactlyValue(2.0) &&
1162 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1164 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1165 // pow(10.0, x) -> exp10(x)
1166 if (Op1C->isExactlyValue(10.0) &&
1167 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1169 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1170 Callee->getAttributes());
1173 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1174 if (Op2C == 0) return Ret;
1176 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1177 return ConstantFP::get(CI->getType(), 1.0);
1179 if (Op2C->isExactlyValue(0.5) &&
1180 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1182 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1184 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1185 // This is faster than calling pow, and still handles negative zero
1186 // and negative infinity correctly.
1187 // TODO: In fast-math mode, this could be just sqrt(x).
1188 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1189 Value *Inf = ConstantFP::getInfinity(CI->getType());
1190 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1191 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1192 Callee->getAttributes());
1193 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1194 Callee->getAttributes());
1195 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1196 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1200 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1202 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1203 return B.CreateFMul(Op1, Op1, "pow2");
1204 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1205 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1211 struct Exp2Opt : public UnsafeFPLibCallOptimization {
1212 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1213 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1215 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1216 TLI->has(LibFunc::exp2f)) {
1217 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1218 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1221 FunctionType *FT = Callee->getFunctionType();
1222 // Just make sure this has 1 argument of FP type, which matches the
1224 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1225 !FT->getParamType(0)->isFloatingPointTy())
1228 Value *Op = CI->getArgOperand(0);
1229 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1230 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1231 Value *LdExpArg = 0;
1232 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1233 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1234 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1235 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1236 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1237 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1242 if (Op->getType()->isFloatTy())
1244 else if (Op->getType()->isDoubleTy())
1249 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1250 if (!Op->getType()->isFloatTy())
1251 One = ConstantExpr::getFPExtend(One, Op->getType());
1253 Module *M = Caller->getParent();
1254 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1256 B.getInt32Ty(), NULL);
1257 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1258 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1259 CI->setCallingConv(F->getCallingConv());
1267 struct SinCosPiOpt : public LibCallOptimization {
1270 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1271 // Make sure the prototype is as expected, otherwise the rest of the
1272 // function is probably invalid and likely to abort.
1273 if (!isTrigLibCall(CI))
1276 Value *Arg = CI->getArgOperand(0);
1277 SmallVector<CallInst *, 1> SinCalls;
1278 SmallVector<CallInst *, 1> CosCalls;
1279 SmallVector<CallInst *, 1> SinCosCalls;
1281 bool IsFloat = Arg->getType()->isFloatTy();
1283 // Look for all compatible sinpi, cospi and sincospi calls with the same
1284 // argument. If there are enough (in some sense) we can make the
1286 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
1288 classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls,
1291 // It's only worthwhile if both sinpi and cospi are actually used.
1292 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1295 Value *Sin, *Cos, *SinCos;
1296 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1299 replaceTrigInsts(SinCalls, Sin);
1300 replaceTrigInsts(CosCalls, Cos);
1301 replaceTrigInsts(SinCosCalls, SinCos);
1306 bool isTrigLibCall(CallInst *CI) {
1307 Function *Callee = CI->getCalledFunction();
1308 FunctionType *FT = Callee->getFunctionType();
1310 // We can only hope to do anything useful if we can ignore things like errno
1311 // and floating-point exceptions.
1312 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1313 CI->hasFnAttr(Attribute::ReadNone);
1315 // Other than that we need float(float) or double(double)
1316 return AttributesSafe && FT->getNumParams() == 1 &&
1317 FT->getReturnType() == FT->getParamType(0) &&
1318 (FT->getParamType(0)->isFloatTy() ||
1319 FT->getParamType(0)->isDoubleTy());
1322 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1323 SmallVectorImpl<CallInst *> &SinCalls,
1324 SmallVectorImpl<CallInst *> &CosCalls,
1325 SmallVectorImpl<CallInst *> &SinCosCalls) {
1326 CallInst *CI = dyn_cast<CallInst>(Val);
1331 Function *Callee = CI->getCalledFunction();
1332 StringRef FuncName = Callee->getName();
1334 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1339 if (Func == LibFunc::sinpif)
1340 SinCalls.push_back(CI);
1341 else if (Func == LibFunc::cospif)
1342 CosCalls.push_back(CI);
1343 else if (Func == LibFunc::sincospi_stretf)
1344 SinCosCalls.push_back(CI);
1346 if (Func == LibFunc::sinpi)
1347 SinCalls.push_back(CI);
1348 else if (Func == LibFunc::cospi)
1349 CosCalls.push_back(CI);
1350 else if (Func == LibFunc::sincospi_stret)
1351 SinCosCalls.push_back(CI);
1355 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1356 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1359 LCS->replaceAllUsesWith(*I, Res);
1363 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1364 bool UseFloat, Value *&Sin, Value *&Cos,
1366 Type *ArgTy = Arg->getType();
1370 Triple T(OrigCallee->getParent()->getTargetTriple());
1372 Name = "__sincospi_stretf";
1374 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1375 // x86_64 can't use {float, float} since that would be returned in both
1376 // xmm0 and xmm1, which isn't what a real struct would do.
1377 ResTy = T.getArch() == Triple::x86_64
1378 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1379 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1381 Name = "__sincospi_stret";
1382 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1385 Module *M = OrigCallee->getParent();
1386 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1387 ResTy, ArgTy, NULL);
1389 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1390 // If the argument is an instruction, it must dominate all uses so put our
1391 // sincos call there.
1392 BasicBlock::iterator Loc = ArgInst;
1393 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1395 // Otherwise (e.g. for a constant) the beginning of the function is as
1396 // good a place as any.
1397 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1398 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1401 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1403 if (SinCos->getType()->isStructTy()) {
1404 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1405 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1407 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1409 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1416 //===----------------------------------------------------------------------===//
1417 // Integer Library Call Optimizations
1418 //===----------------------------------------------------------------------===//
1420 struct FFSOpt : public LibCallOptimization {
1421 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1422 FunctionType *FT = Callee->getFunctionType();
1423 // Just make sure this has 2 arguments of the same FP type, which match the
1425 if (FT->getNumParams() != 1 ||
1426 !FT->getReturnType()->isIntegerTy(32) ||
1427 !FT->getParamType(0)->isIntegerTy())
1430 Value *Op = CI->getArgOperand(0);
1433 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1434 if (CI->isZero()) // ffs(0) -> 0.
1435 return B.getInt32(0);
1436 // ffs(c) -> cttz(c)+1
1437 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1440 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1441 Type *ArgType = Op->getType();
1442 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1443 Intrinsic::cttz, ArgType);
1444 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1445 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1446 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1448 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1449 return B.CreateSelect(Cond, V, B.getInt32(0));
1453 struct AbsOpt : public LibCallOptimization {
1454 virtual bool ignoreCallingConv() { return true; }
1455 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1456 FunctionType *FT = Callee->getFunctionType();
1457 // We require integer(integer) where the types agree.
1458 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1459 FT->getParamType(0) != FT->getReturnType())
1462 // abs(x) -> x >s -1 ? x : -x
1463 Value *Op = CI->getArgOperand(0);
1464 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1466 Value *Neg = B.CreateNeg(Op, "neg");
1467 return B.CreateSelect(Pos, Op, Neg);
1471 struct IsDigitOpt : public LibCallOptimization {
1472 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1473 FunctionType *FT = Callee->getFunctionType();
1474 // We require integer(i32)
1475 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1476 !FT->getParamType(0)->isIntegerTy(32))
1479 // isdigit(c) -> (c-'0') <u 10
1480 Value *Op = CI->getArgOperand(0);
1481 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1482 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1483 return B.CreateZExt(Op, CI->getType());
1487 struct IsAsciiOpt : public LibCallOptimization {
1488 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1489 FunctionType *FT = Callee->getFunctionType();
1490 // We require integer(i32)
1491 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1492 !FT->getParamType(0)->isIntegerTy(32))
1495 // isascii(c) -> c <u 128
1496 Value *Op = CI->getArgOperand(0);
1497 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1498 return B.CreateZExt(Op, CI->getType());
1502 struct ToAsciiOpt : public LibCallOptimization {
1503 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1504 FunctionType *FT = Callee->getFunctionType();
1505 // We require i32(i32)
1506 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1507 !FT->getParamType(0)->isIntegerTy(32))
1510 // toascii(c) -> c & 0x7f
1511 return B.CreateAnd(CI->getArgOperand(0),
1512 ConstantInt::get(CI->getType(),0x7F));
1516 //===----------------------------------------------------------------------===//
1517 // Formatting and IO Library Call Optimizations
1518 //===----------------------------------------------------------------------===//
1520 struct ErrorReportingOpt : public LibCallOptimization {
1521 ErrorReportingOpt(int S = -1) : StreamArg(S) {}
1523 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &) {
1524 // Error reporting calls should be cold, mark them as such.
1525 // This applies even to non-builtin calls: it is only a hint and applies to
1526 // functions that the frontend might not understand as builtins.
1528 // This heuristic was suggested in:
1529 // Improving Static Branch Prediction in a Compiler
1530 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1531 // Proceedings of PACT'98, Oct. 1998, IEEE
1533 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) {
1534 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1541 bool isReportingError(Function *Callee, CallInst *CI) {
1542 if (!ColdErrorCalls)
1545 if (!Callee || !Callee->isDeclaration())
1551 // These functions might be considered cold, but only if their stream
1552 // argument is stderr.
1554 if (StreamArg >= (int) CI->getNumArgOperands())
1556 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1559 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1560 if (!GV || !GV->isDeclaration())
1562 return GV->getName() == "stderr";
1568 struct PrintFOpt : public LibCallOptimization {
1569 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1571 // Check for a fixed format string.
1572 StringRef FormatStr;
1573 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1576 // Empty format string -> noop.
1577 if (FormatStr.empty()) // Tolerate printf's declared void.
1578 return CI->use_empty() ? (Value*)CI :
1579 ConstantInt::get(CI->getType(), 0);
1581 // Do not do any of the following transformations if the printf return value
1582 // is used, in general the printf return value is not compatible with either
1583 // putchar() or puts().
1584 if (!CI->use_empty())
1587 // printf("x") -> putchar('x'), even for '%'.
1588 if (FormatStr.size() == 1) {
1589 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1590 if (CI->use_empty() || !Res) return Res;
1591 return B.CreateIntCast(Res, CI->getType(), true);
1594 // printf("foo\n") --> puts("foo")
1595 if (FormatStr[FormatStr.size()-1] == '\n' &&
1596 FormatStr.find('%') == StringRef::npos) { // No format characters.
1597 // Create a string literal with no \n on it. We expect the constant merge
1598 // pass to be run after this pass, to merge duplicate strings.
1599 FormatStr = FormatStr.drop_back();
1600 Value *GV = B.CreateGlobalString(FormatStr, "str");
1601 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1602 return (CI->use_empty() || !NewCI) ?
1604 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1607 // Optimize specific format strings.
1608 // printf("%c", chr) --> putchar(chr)
1609 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1610 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1611 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1613 if (CI->use_empty() || !Res) return Res;
1614 return B.CreateIntCast(Res, CI->getType(), true);
1617 // printf("%s\n", str) --> puts(str)
1618 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1619 CI->getArgOperand(1)->getType()->isPointerTy()) {
1620 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1625 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1626 // Require one fixed pointer argument and an integer/void result.
1627 FunctionType *FT = Callee->getFunctionType();
1628 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1629 !(FT->getReturnType()->isIntegerTy() ||
1630 FT->getReturnType()->isVoidTy()))
1633 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1637 // printf(format, ...) -> iprintf(format, ...) if no floating point
1639 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1640 Module *M = B.GetInsertBlock()->getParent()->getParent();
1641 Constant *IPrintFFn =
1642 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1643 CallInst *New = cast<CallInst>(CI->clone());
1644 New->setCalledFunction(IPrintFFn);
1652 struct SPrintFOpt : public LibCallOptimization {
1653 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1655 // Check for a fixed format string.
1656 StringRef FormatStr;
1657 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1660 // If we just have a format string (nothing else crazy) transform it.
1661 if (CI->getNumArgOperands() == 2) {
1662 // Make sure there's no % in the constant array. We could try to handle
1663 // %% -> % in the future if we cared.
1664 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1665 if (FormatStr[i] == '%')
1666 return 0; // we found a format specifier, bail out.
1668 // These optimizations require DataLayout.
1671 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1672 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1673 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1674 FormatStr.size() + 1), 1); // nul byte.
1675 return ConstantInt::get(CI->getType(), FormatStr.size());
1678 // The remaining optimizations require the format string to be "%s" or "%c"
1679 // and have an extra operand.
1680 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1681 CI->getNumArgOperands() < 3)
1684 // Decode the second character of the format string.
1685 if (FormatStr[1] == 'c') {
1686 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1687 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1688 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1689 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1690 B.CreateStore(V, Ptr);
1691 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1692 B.CreateStore(B.getInt8(0), Ptr);
1694 return ConstantInt::get(CI->getType(), 1);
1697 if (FormatStr[1] == 's') {
1698 // These optimizations require DataLayout.
1701 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1702 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1704 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1707 Value *IncLen = B.CreateAdd(Len,
1708 ConstantInt::get(Len->getType(), 1),
1710 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1712 // The sprintf result is the unincremented number of bytes in the string.
1713 return B.CreateIntCast(Len, CI->getType(), false);
1718 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1719 // Require two fixed pointer arguments and an integer result.
1720 FunctionType *FT = Callee->getFunctionType();
1721 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1722 !FT->getParamType(1)->isPointerTy() ||
1723 !FT->getReturnType()->isIntegerTy())
1726 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1730 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1732 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1733 Module *M = B.GetInsertBlock()->getParent()->getParent();
1734 Constant *SIPrintFFn =
1735 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1736 CallInst *New = cast<CallInst>(CI->clone());
1737 New->setCalledFunction(SIPrintFFn);
1745 struct FPrintFOpt : public LibCallOptimization {
1746 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1748 ErrorReportingOpt ER(/* StreamArg = */ 0);
1749 (void) ER.callOptimizer(Callee, CI, B);
1751 // All the optimizations depend on the format string.
1752 StringRef FormatStr;
1753 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1756 // Do not do any of the following transformations if the fprintf return
1757 // value is used, in general the fprintf return value is not compatible
1758 // with fwrite(), fputc() or fputs().
1759 if (!CI->use_empty())
1762 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1763 if (CI->getNumArgOperands() == 2) {
1764 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1765 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1766 return 0; // We found a format specifier.
1768 // These optimizations require DataLayout.
1771 return EmitFWrite(CI->getArgOperand(1),
1772 ConstantInt::get(TD->getIntPtrType(*Context),
1774 CI->getArgOperand(0), B, TD, TLI);
1777 // The remaining optimizations require the format string to be "%s" or "%c"
1778 // and have an extra operand.
1779 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1780 CI->getNumArgOperands() < 3)
1783 // Decode the second character of the format string.
1784 if (FormatStr[1] == 'c') {
1785 // fprintf(F, "%c", chr) --> fputc(chr, F)
1786 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1787 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1790 if (FormatStr[1] == 's') {
1791 // fprintf(F, "%s", str) --> fputs(str, F)
1792 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1794 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1799 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1800 // Require two fixed paramters as pointers and integer result.
1801 FunctionType *FT = Callee->getFunctionType();
1802 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1803 !FT->getParamType(1)->isPointerTy() ||
1804 !FT->getReturnType()->isIntegerTy())
1807 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1811 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1812 // floating point arguments.
1813 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1814 Module *M = B.GetInsertBlock()->getParent()->getParent();
1815 Constant *FIPrintFFn =
1816 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1817 CallInst *New = cast<CallInst>(CI->clone());
1818 New->setCalledFunction(FIPrintFFn);
1826 struct FWriteOpt : public LibCallOptimization {
1827 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1828 ErrorReportingOpt ER(/* StreamArg = */ 3);
1829 (void) ER.callOptimizer(Callee, CI, B);
1831 // Require a pointer, an integer, an integer, a pointer, returning integer.
1832 FunctionType *FT = Callee->getFunctionType();
1833 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1834 !FT->getParamType(1)->isIntegerTy() ||
1835 !FT->getParamType(2)->isIntegerTy() ||
1836 !FT->getParamType(3)->isPointerTy() ||
1837 !FT->getReturnType()->isIntegerTy())
1840 // Get the element size and count.
1841 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1842 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1843 if (!SizeC || !CountC) return 0;
1844 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1846 // If this is writing zero records, remove the call (it's a noop).
1848 return ConstantInt::get(CI->getType(), 0);
1850 // If this is writing one byte, turn it into fputc.
1851 // This optimisation is only valid, if the return value is unused.
1852 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1853 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1854 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1855 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1862 struct FPutsOpt : public LibCallOptimization {
1863 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1864 ErrorReportingOpt ER(/* StreamArg = */ 1);
1865 (void) ER.callOptimizer(Callee, CI, B);
1867 // These optimizations require DataLayout.
1870 // Require two pointers. Also, we can't optimize if return value is used.
1871 FunctionType *FT = Callee->getFunctionType();
1872 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1873 !FT->getParamType(1)->isPointerTy() ||
1877 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1878 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1880 // Known to have no uses (see above).
1881 return EmitFWrite(CI->getArgOperand(0),
1882 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1883 CI->getArgOperand(1), B, TD, TLI);
1887 struct PutsOpt : public LibCallOptimization {
1888 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1889 // Require one fixed pointer argument and an integer/void result.
1890 FunctionType *FT = Callee->getFunctionType();
1891 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1892 !(FT->getReturnType()->isIntegerTy() ||
1893 FT->getReturnType()->isVoidTy()))
1896 // Check for a constant string.
1898 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1901 if (Str.empty() && CI->use_empty()) {
1902 // puts("") -> putchar('\n')
1903 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1904 if (CI->use_empty() || !Res) return Res;
1905 return B.CreateIntCast(Res, CI->getType(), true);
1912 } // End anonymous namespace.
1916 class LibCallSimplifierImpl {
1917 const DataLayout *TD;
1918 const TargetLibraryInfo *TLI;
1919 const LibCallSimplifier *LCS;
1920 bool UnsafeFPShrink;
1922 // Math library call optimizations.
1927 LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
1928 const LibCallSimplifier *LCS,
1929 bool UnsafeFPShrink = false)
1930 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
1934 this->UnsafeFPShrink = UnsafeFPShrink;
1937 Value *optimizeCall(CallInst *CI);
1938 LibCallOptimization *lookupOptimization(CallInst *CI);
1939 bool hasFloatVersion(StringRef FuncName);
1942 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
1944 SmallString<20> FloatFuncName = FuncName;
1945 FloatFuncName += 'f';
1946 if (TLI->getLibFunc(FloatFuncName, Func))
1947 return TLI->has(Func);
1951 // Fortified library call optimizations.
1952 static MemCpyChkOpt MemCpyChk;
1953 static MemMoveChkOpt MemMoveChk;
1954 static MemSetChkOpt MemSetChk;
1955 static StrCpyChkOpt StrCpyChk;
1956 static StpCpyChkOpt StpCpyChk;
1957 static StrNCpyChkOpt StrNCpyChk;
1959 // String library call optimizations.
1960 static StrCatOpt StrCat;
1961 static StrNCatOpt StrNCat;
1962 static StrChrOpt StrChr;
1963 static StrRChrOpt StrRChr;
1964 static StrCmpOpt StrCmp;
1965 static StrNCmpOpt StrNCmp;
1966 static StrCpyOpt StrCpy;
1967 static StpCpyOpt StpCpy;
1968 static StrNCpyOpt StrNCpy;
1969 static StrLenOpt StrLen;
1970 static StrPBrkOpt StrPBrk;
1971 static StrToOpt StrTo;
1972 static StrSpnOpt StrSpn;
1973 static StrCSpnOpt StrCSpn;
1974 static StrStrOpt StrStr;
1976 // Memory library call optimizations.
1977 static MemCmpOpt MemCmp;
1978 static MemCpyOpt MemCpy;
1979 static MemMoveOpt MemMove;
1980 static MemSetOpt MemSet;
1982 // Math library call optimizations.
1983 static UnaryDoubleFPOpt UnaryDoubleFP(false);
1984 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1985 static SinCosPiOpt SinCosPi;
1987 // Integer library call optimizations.
1990 static IsDigitOpt IsDigit;
1991 static IsAsciiOpt IsAscii;
1992 static ToAsciiOpt ToAscii;
1994 // Formatting and IO library call optimizations.
1995 static ErrorReportingOpt ErrorReporting;
1996 static ErrorReportingOpt ErrorReporting0(0);
1997 static ErrorReportingOpt ErrorReporting1(1);
1998 static PrintFOpt PrintF;
1999 static SPrintFOpt SPrintF;
2000 static FPrintFOpt FPrintF;
2001 static FWriteOpt FWrite;
2002 static FPutsOpt FPuts;
2003 static PutsOpt Puts;
2005 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
2007 Function *Callee = CI->getCalledFunction();
2008 StringRef FuncName = Callee->getName();
2010 // Next check for intrinsics.
2011 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2012 switch (II->getIntrinsicID()) {
2013 case Intrinsic::pow:
2015 case Intrinsic::exp2:
2022 // Then check for known library functions.
2023 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2025 case LibFunc::strcat:
2027 case LibFunc::strncat:
2029 case LibFunc::strchr:
2031 case LibFunc::strrchr:
2033 case LibFunc::strcmp:
2035 case LibFunc::strncmp:
2037 case LibFunc::strcpy:
2039 case LibFunc::stpcpy:
2041 case LibFunc::strncpy:
2043 case LibFunc::strlen:
2045 case LibFunc::strpbrk:
2047 case LibFunc::strtol:
2048 case LibFunc::strtod:
2049 case LibFunc::strtof:
2050 case LibFunc::strtoul:
2051 case LibFunc::strtoll:
2052 case LibFunc::strtold:
2053 case LibFunc::strtoull:
2055 case LibFunc::strspn:
2057 case LibFunc::strcspn:
2059 case LibFunc::strstr:
2061 case LibFunc::memcmp:
2063 case LibFunc::memcpy:
2065 case LibFunc::memmove:
2067 case LibFunc::memset:
2073 case LibFunc::sinpif:
2074 case LibFunc::sinpi:
2075 case LibFunc::cospif:
2076 case LibFunc::cospi:
2082 case LibFunc::exp2l:
2084 case LibFunc::exp2f:
2088 case LibFunc::ffsll:
2092 case LibFunc::llabs:
2094 case LibFunc::isdigit:
2096 case LibFunc::isascii:
2098 case LibFunc::toascii:
2100 case LibFunc::printf:
2102 case LibFunc::sprintf:
2104 case LibFunc::fprintf:
2106 case LibFunc::fwrite:
2108 case LibFunc::fputs:
2112 case LibFunc::perror:
2113 return &ErrorReporting;
2114 case LibFunc::vfprintf:
2115 case LibFunc::fiprintf:
2116 return &ErrorReporting0;
2117 case LibFunc::fputc:
2118 return &ErrorReporting1;
2121 case LibFunc::floor:
2123 case LibFunc::round:
2124 case LibFunc::nearbyint:
2125 case LibFunc::trunc:
2126 if (hasFloatVersion(FuncName))
2127 return &UnaryDoubleFP;
2130 case LibFunc::acosh:
2132 case LibFunc::asinh:
2134 case LibFunc::atanh:
2138 case LibFunc::exp10:
2139 case LibFunc::expm1:
2141 case LibFunc::log10:
2142 case LibFunc::log1p:
2150 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2151 return &UnsafeUnaryDoubleFP;
2153 case LibFunc::memcpy_chk:
2160 // Finally check for fortified library calls.
2161 if (FuncName.endswith("_chk")) {
2162 if (FuncName == "__memmove_chk")
2164 else if (FuncName == "__memset_chk")
2166 else if (FuncName == "__strcpy_chk")
2168 else if (FuncName == "__stpcpy_chk")
2170 else if (FuncName == "__strncpy_chk")
2172 else if (FuncName == "__stpncpy_chk")
2180 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
2181 LibCallOptimization *LCO = lookupOptimization(CI);
2183 IRBuilder<> Builder(CI);
2184 return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
2189 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
2190 const TargetLibraryInfo *TLI,
2191 bool UnsafeFPShrink) {
2192 Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink);
2195 LibCallSimplifier::~LibCallSimplifier() {
2199 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2200 if (CI->isNoBuiltin()) return 0;
2201 return Impl->optimizeCall(CI);
2204 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2205 I->replaceAllUsesWith(With);
2206 I->eraseFromParent();
2212 // Additional cases that we need to add to this file:
2215 // * cbrt(expN(X)) -> expN(x/3)
2216 // * cbrt(sqrt(x)) -> pow(x,1/6)
2217 // * cbrt(sqrt(x)) -> pow(x,1/9)
2220 // * exp(log(x)) -> x
2223 // * log(exp(x)) -> x
2224 // * log(x**y) -> y*log(x)
2225 // * log(exp(y)) -> y*log(e)
2226 // * log(exp2(y)) -> y*log(2)
2227 // * log(exp10(y)) -> y*log(10)
2228 // * log(sqrt(x)) -> 0.5*log(x)
2229 // * log(pow(x,y)) -> y*log(x)
2231 // lround, lroundf, lroundl:
2232 // * lround(cnst) -> cnst'
2235 // * pow(exp(x),y) -> exp(x*y)
2236 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2237 // * pow(pow(x,y),z)-> pow(x,y*z)
2239 // round, roundf, roundl:
2240 // * round(cnst) -> cnst'
2243 // * signbit(cnst) -> cnst'
2244 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2246 // sqrt, sqrtf, sqrtl:
2247 // * sqrt(expN(x)) -> expN(x*0.5)
2248 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2249 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2252 // * strchr(p, 0) -> strlen(p)
2254 // * tan(atan(x)) -> x
2256 // trunc, truncf, truncl:
2257 // * trunc(cnst) -> cnst'