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/DiagnosticInfo.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
37 using namespace PatternMatch;
40 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 static bool ignoreCallingConv(LibFunc::Func Func) {
64 llvm_unreachable("All cases should be covered in the switch.");
67 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
68 /// value is equal or not-equal to zero.
69 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
70 for (User *U : V->users()) {
71 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
73 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
76 // Unknown instruction.
82 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
83 /// comparisons with With.
84 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
85 for (User *U : V->users()) {
86 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
87 if (IC->isEquality() && IC->getOperand(1) == With)
89 // Unknown instruction.
95 static bool callHasFloatingPointArgument(const CallInst *CI) {
96 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
98 if ((*it)->getType()->isFloatingPointTy())
104 /// \brief Check whether the overloaded unary floating point function
105 /// corresponing to \a Ty is available.
106 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
107 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
108 LibFunc::Func LongDoubleFn) {
109 switch (Ty->getTypeID()) {
110 case Type::FloatTyID:
111 return TLI->has(FloatFn);
112 case Type::DoubleTyID:
113 return TLI->has(DoubleFn);
115 return TLI->has(LongDoubleFn);
119 /// \brief Returns whether \p F matches the signature expected for the
120 /// string/memory copying library function \p Func.
121 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
122 /// Their fortified (_chk) counterparts are also accepted.
123 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
124 const DataLayout &DL = F->getParent()->getDataLayout();
125 FunctionType *FT = F->getFunctionType();
126 LLVMContext &Context = F->getContext();
127 Type *PCharTy = Type::getInt8PtrTy(Context);
128 Type *SizeTTy = DL.getIntPtrType(Context);
129 unsigned NumParams = FT->getNumParams();
131 // All string libfuncs return the same type as the first parameter.
132 if (FT->getReturnType() != FT->getParamType(0))
137 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
138 case LibFunc::stpncpy_chk:
139 case LibFunc::strncpy_chk:
140 --NumParams; // fallthrough
141 case LibFunc::stpncpy:
142 case LibFunc::strncpy: {
143 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
144 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
148 case LibFunc::strcpy_chk:
149 case LibFunc::stpcpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpcpy:
152 case LibFunc::strcpy: {
153 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy)
158 case LibFunc::memmove_chk:
159 case LibFunc::memcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::memmove:
162 case LibFunc::memcpy: {
163 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
164 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
168 case LibFunc::memset_chk:
169 --NumParams; // fallthrough
170 case LibFunc::memset: {
171 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
177 // If this is a fortified libcall, the last parameter is a size_t.
178 if (NumParams == FT->getNumParams() - 1)
179 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
183 //===----------------------------------------------------------------------===//
184 // String and Memory Library Call Optimizations
185 //===----------------------------------------------------------------------===//
187 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
188 Function *Callee = CI->getCalledFunction();
189 // Verify the "strcat" function prototype.
190 FunctionType *FT = Callee->getFunctionType();
191 if (FT->getNumParams() != 2||
192 FT->getReturnType() != B.getInt8PtrTy() ||
193 FT->getParamType(0) != FT->getReturnType() ||
194 FT->getParamType(1) != FT->getReturnType())
197 // Extract some information from the instruction
198 Value *Dst = CI->getArgOperand(0);
199 Value *Src = CI->getArgOperand(1);
201 // See if we can get the length of the input string.
202 uint64_t Len = GetStringLength(Src);
205 --Len; // Unbias length.
207 // Handle the simple, do-nothing case: strcat(x, "") -> x
211 return emitStrLenMemCpy(Src, Dst, Len, B);
214 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
216 // We need to find the end of the destination string. That's where the
217 // memory is to be moved to. We just generate a call to strlen.
218 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
222 // Now that we have the destination's length, we must index into the
223 // destination's pointer to get the actual memcpy destination (end of
224 // the string .. we're concatenating).
225 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
227 // We have enough information to now generate the memcpy call to do the
228 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
229 B.CreateMemCpy(CpyDst, Src,
230 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
235 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
236 Function *Callee = CI->getCalledFunction();
237 // Verify the "strncat" function prototype.
238 FunctionType *FT = Callee->getFunctionType();
239 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
240 FT->getParamType(0) != FT->getReturnType() ||
241 FT->getParamType(1) != FT->getReturnType() ||
242 !FT->getParamType(2)->isIntegerTy())
245 // Extract some information from the instruction
246 Value *Dst = CI->getArgOperand(0);
247 Value *Src = CI->getArgOperand(1);
250 // We don't do anything if length is not constant
251 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
252 Len = LengthArg->getZExtValue();
256 // See if we can get the length of the input string.
257 uint64_t SrcLen = GetStringLength(Src);
260 --SrcLen; // Unbias length.
262 // Handle the simple, do-nothing cases:
263 // strncat(x, "", c) -> x
264 // strncat(x, c, 0) -> x
265 if (SrcLen == 0 || Len == 0)
268 // We don't optimize this case
272 // strncat(x, s, c) -> strcat(x, s)
273 // s is constant so the strcat can be optimized further
274 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
277 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
278 Function *Callee = CI->getCalledFunction();
279 // Verify the "strchr" function prototype.
280 FunctionType *FT = Callee->getFunctionType();
281 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
282 FT->getParamType(0) != FT->getReturnType() ||
283 !FT->getParamType(1)->isIntegerTy(32))
286 Value *SrcStr = CI->getArgOperand(0);
288 // If the second operand is non-constant, see if we can compute the length
289 // of the input string and turn this into memchr.
290 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
292 uint64_t Len = GetStringLength(SrcStr);
293 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
296 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
297 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
301 // Otherwise, the character is a constant, see if the first argument is
302 // a string literal. If so, we can constant fold.
304 if (!getConstantStringInfo(SrcStr, Str)) {
305 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
306 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
310 // Compute the offset, make sure to handle the case when we're searching for
311 // zero (a weird way to spell strlen).
312 size_t I = (0xFF & CharC->getSExtValue()) == 0
314 : Str.find(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
316 return Constant::getNullValue(CI->getType());
318 // strchr(s+n,c) -> gep(s+n+i,c)
319 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
322 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
323 Function *Callee = CI->getCalledFunction();
324 // Verify the "strrchr" function prototype.
325 FunctionType *FT = Callee->getFunctionType();
326 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
327 FT->getParamType(0) != FT->getReturnType() ||
328 !FT->getParamType(1)->isIntegerTy(32))
331 Value *SrcStr = CI->getArgOperand(0);
332 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
334 // Cannot fold anything if we're not looking for a constant.
339 if (!getConstantStringInfo(SrcStr, Str)) {
340 // strrchr(s, 0) -> strchr(s, 0)
342 return EmitStrChr(SrcStr, '\0', B, TLI);
346 // Compute the offset.
347 size_t I = (0xFF & CharC->getSExtValue()) == 0
349 : Str.rfind(CharC->getSExtValue());
350 if (I == StringRef::npos) // Didn't find the char. Return null.
351 return Constant::getNullValue(CI->getType());
353 // strrchr(s+n,c) -> gep(s+n+i,c)
354 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
357 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
358 Function *Callee = CI->getCalledFunction();
359 // Verify the "strcmp" function prototype.
360 FunctionType *FT = Callee->getFunctionType();
361 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
362 FT->getParamType(0) != FT->getParamType(1) ||
363 FT->getParamType(0) != B.getInt8PtrTy())
366 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
367 if (Str1P == Str2P) // strcmp(x,x) -> 0
368 return ConstantInt::get(CI->getType(), 0);
370 StringRef Str1, Str2;
371 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
372 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
374 // strcmp(x, y) -> cnst (if both x and y are constant strings)
375 if (HasStr1 && HasStr2)
376 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
378 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
380 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
382 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
383 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
385 // strcmp(P, "x") -> memcmp(P, "x", 2)
386 uint64_t Len1 = GetStringLength(Str1P);
387 uint64_t Len2 = GetStringLength(Str2P);
389 return EmitMemCmp(Str1P, Str2P,
390 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
391 std::min(Len1, Len2)),
398 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
399 Function *Callee = CI->getCalledFunction();
400 // Verify the "strncmp" function prototype.
401 FunctionType *FT = Callee->getFunctionType();
402 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
403 FT->getParamType(0) != FT->getParamType(1) ||
404 FT->getParamType(0) != B.getInt8PtrTy() ||
405 !FT->getParamType(2)->isIntegerTy())
408 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
409 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
410 return ConstantInt::get(CI->getType(), 0);
412 // Get the length argument if it is constant.
414 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
415 Length = LengthArg->getZExtValue();
419 if (Length == 0) // strncmp(x,y,0) -> 0
420 return ConstantInt::get(CI->getType(), 0);
422 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
423 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
425 StringRef Str1, Str2;
426 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
427 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
429 // strncmp(x, y) -> cnst (if both x and y are constant strings)
430 if (HasStr1 && HasStr2) {
431 StringRef SubStr1 = Str1.substr(0, Length);
432 StringRef SubStr2 = Str2.substr(0, Length);
433 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
436 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
438 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
440 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
441 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
446 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
447 Function *Callee = CI->getCalledFunction();
449 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
452 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
453 if (Dst == Src) // strcpy(x,x) -> x
456 // See if we can get the length of the input string.
457 uint64_t Len = GetStringLength(Src);
461 // We have enough information to now generate the memcpy call to do the
462 // copy for us. Make a memcpy to copy the nul byte with align = 1.
463 B.CreateMemCpy(Dst, Src,
464 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
468 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
469 Function *Callee = CI->getCalledFunction();
470 // Verify the "stpcpy" function prototype.
471 FunctionType *FT = Callee->getFunctionType();
473 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
476 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
477 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
478 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
479 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
482 // See if we can get the length of the input string.
483 uint64_t Len = GetStringLength(Src);
487 Type *PT = FT->getParamType(0);
488 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
490 B.CreateGEP(Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
492 // We have enough information to now generate the memcpy call to do the
493 // copy for us. Make a memcpy to copy the nul byte with align = 1.
494 B.CreateMemCpy(Dst, Src, LenV, 1);
498 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
499 Function *Callee = CI->getCalledFunction();
500 FunctionType *FT = Callee->getFunctionType();
502 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
505 Value *Dst = CI->getArgOperand(0);
506 Value *Src = CI->getArgOperand(1);
507 Value *LenOp = CI->getArgOperand(2);
509 // See if we can get the length of the input string.
510 uint64_t SrcLen = GetStringLength(Src);
516 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
517 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
522 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
523 Len = LengthArg->getZExtValue();
528 return Dst; // strncpy(x, y, 0) -> x
530 // Let strncpy handle the zero padding
531 if (Len > SrcLen + 1)
534 Type *PT = FT->getParamType(0);
535 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
536 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
541 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
542 Function *Callee = CI->getCalledFunction();
543 FunctionType *FT = Callee->getFunctionType();
544 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
545 !FT->getReturnType()->isIntegerTy())
548 Value *Src = CI->getArgOperand(0);
550 // Constant folding: strlen("xyz") -> 3
551 if (uint64_t Len = GetStringLength(Src))
552 return ConstantInt::get(CI->getType(), Len - 1);
554 // strlen(x?"foo":"bars") --> x ? 3 : 4
555 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
556 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
557 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
558 if (LenTrue && LenFalse) {
559 Function *Caller = CI->getParent()->getParent();
560 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
562 "folded strlen(select) to select of constants");
563 return B.CreateSelect(SI->getCondition(),
564 ConstantInt::get(CI->getType(), LenTrue - 1),
565 ConstantInt::get(CI->getType(), LenFalse - 1));
569 // strlen(x) != 0 --> *x != 0
570 // strlen(x) == 0 --> *x == 0
571 if (isOnlyUsedInZeroEqualityComparison(CI))
572 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
577 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
578 Function *Callee = CI->getCalledFunction();
579 FunctionType *FT = Callee->getFunctionType();
580 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
581 FT->getParamType(1) != FT->getParamType(0) ||
582 FT->getReturnType() != FT->getParamType(0))
586 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
587 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
589 // strpbrk(s, "") -> nullptr
590 // strpbrk("", s) -> nullptr
591 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
592 return Constant::getNullValue(CI->getType());
595 if (HasS1 && HasS2) {
596 size_t I = S1.find_first_of(S2);
597 if (I == StringRef::npos) // No match.
598 return Constant::getNullValue(CI->getType());
600 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
603 // strpbrk(s, "a") -> strchr(s, 'a')
604 if (HasS2 && S2.size() == 1)
605 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
610 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
611 Function *Callee = CI->getCalledFunction();
612 FunctionType *FT = Callee->getFunctionType();
613 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
614 !FT->getParamType(0)->isPointerTy() ||
615 !FT->getParamType(1)->isPointerTy())
618 Value *EndPtr = CI->getArgOperand(1);
619 if (isa<ConstantPointerNull>(EndPtr)) {
620 // With a null EndPtr, this function won't capture the main argument.
621 // It would be readonly too, except that it still may write to errno.
622 CI->addAttribute(1, Attribute::NoCapture);
628 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
629 Function *Callee = CI->getCalledFunction();
630 FunctionType *FT = Callee->getFunctionType();
631 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
632 FT->getParamType(1) != FT->getParamType(0) ||
633 !FT->getReturnType()->isIntegerTy())
637 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
638 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
640 // strspn(s, "") -> 0
641 // strspn("", s) -> 0
642 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
643 return Constant::getNullValue(CI->getType());
646 if (HasS1 && HasS2) {
647 size_t Pos = S1.find_first_not_of(S2);
648 if (Pos == StringRef::npos)
650 return ConstantInt::get(CI->getType(), Pos);
656 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
657 Function *Callee = CI->getCalledFunction();
658 FunctionType *FT = Callee->getFunctionType();
659 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
660 FT->getParamType(1) != FT->getParamType(0) ||
661 !FT->getReturnType()->isIntegerTy())
665 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
666 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
668 // strcspn("", s) -> 0
669 if (HasS1 && S1.empty())
670 return Constant::getNullValue(CI->getType());
673 if (HasS1 && HasS2) {
674 size_t Pos = S1.find_first_of(S2);
675 if (Pos == StringRef::npos)
677 return ConstantInt::get(CI->getType(), Pos);
680 // strcspn(s, "") -> strlen(s)
681 if (HasS2 && S2.empty())
682 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
687 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
688 Function *Callee = CI->getCalledFunction();
689 FunctionType *FT = Callee->getFunctionType();
690 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
691 !FT->getParamType(1)->isPointerTy() ||
692 !FT->getReturnType()->isPointerTy())
695 // fold strstr(x, x) -> x.
696 if (CI->getArgOperand(0) == CI->getArgOperand(1))
697 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
699 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
700 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
701 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
704 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
708 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
709 ICmpInst *Old = cast<ICmpInst>(*UI++);
711 B.CreateICmp(Old->getPredicate(), StrNCmp,
712 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
713 replaceAllUsesWith(Old, Cmp);
718 // See if either input string is a constant string.
719 StringRef SearchStr, ToFindStr;
720 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
721 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
723 // fold strstr(x, "") -> x.
724 if (HasStr2 && ToFindStr.empty())
725 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
727 // If both strings are known, constant fold it.
728 if (HasStr1 && HasStr2) {
729 size_t Offset = SearchStr.find(ToFindStr);
731 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
732 return Constant::getNullValue(CI->getType());
734 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
735 Value *Result = CastToCStr(CI->getArgOperand(0), B);
736 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
737 return B.CreateBitCast(Result, CI->getType());
740 // fold strstr(x, "y") -> strchr(x, 'y').
741 if (HasStr2 && ToFindStr.size() == 1) {
742 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
743 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
748 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
749 Function *Callee = CI->getCalledFunction();
750 FunctionType *FT = Callee->getFunctionType();
751 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
752 !FT->getParamType(1)->isIntegerTy(32) ||
753 !FT->getParamType(2)->isIntegerTy() ||
754 !FT->getReturnType()->isPointerTy())
757 Value *SrcStr = CI->getArgOperand(0);
758 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
759 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
761 // memchr(x, y, 0) -> null
762 if (LenC && LenC->isNullValue())
763 return Constant::getNullValue(CI->getType());
765 // Check if all arguments are constants. If so, we can constant fold.
767 if (!CharC || !LenC ||
768 !getConstantStringInfo(SrcStr, Str, /*Offset=*/0,
769 /*TrimAtNul=*/false))
772 // Truncate the string to LenC. If Str is smaller than LenC we will still only
773 // scan the string, as reading past the end of it is undefined and we can just
774 // return null if we don't find the char.
775 Str = Str.substr(0, LenC->getZExtValue());
777 // Compute the offset.
778 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
779 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
780 return Constant::getNullValue(CI->getType());
782 // memchr(s+n,c,l) -> gep(s+n+i,c)
783 return B.CreateGEP(SrcStr, B.getInt64(I), "memchr");
786 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
787 Function *Callee = CI->getCalledFunction();
788 FunctionType *FT = Callee->getFunctionType();
789 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
790 !FT->getParamType(1)->isPointerTy() ||
791 !FT->getReturnType()->isIntegerTy(32))
794 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
796 if (LHS == RHS) // memcmp(s,s,x) -> 0
797 return Constant::getNullValue(CI->getType());
799 // Make sure we have a constant length.
800 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
803 uint64_t Len = LenC->getZExtValue();
805 if (Len == 0) // memcmp(s1,s2,0) -> 0
806 return Constant::getNullValue(CI->getType());
808 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
810 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
811 CI->getType(), "lhsv");
812 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
813 CI->getType(), "rhsv");
814 return B.CreateSub(LHSV, RHSV, "chardiff");
817 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
818 StringRef LHSStr, RHSStr;
819 if (getConstantStringInfo(LHS, LHSStr) &&
820 getConstantStringInfo(RHS, RHSStr)) {
821 // Make sure we're not reading out-of-bounds memory.
822 if (Len > LHSStr.size() || Len > RHSStr.size())
824 // Fold the memcmp and normalize the result. This way we get consistent
825 // results across multiple platforms.
827 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
832 return ConstantInt::get(CI->getType(), Ret);
838 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
839 Function *Callee = CI->getCalledFunction();
841 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
844 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
845 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
846 CI->getArgOperand(2), 1);
847 return CI->getArgOperand(0);
850 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
851 Function *Callee = CI->getCalledFunction();
853 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
856 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
857 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
858 CI->getArgOperand(2), 1);
859 return CI->getArgOperand(0);
862 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
863 Function *Callee = CI->getCalledFunction();
865 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
868 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
869 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
870 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
871 return CI->getArgOperand(0);
874 //===----------------------------------------------------------------------===//
875 // Math Library Optimizations
876 //===----------------------------------------------------------------------===//
878 /// Return a variant of Val with float type.
879 /// Currently this works in two cases: If Val is an FPExtension of a float
880 /// value to something bigger, simply return the operand.
881 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
882 /// loss of precision do so.
883 static Value *valueHasFloatPrecision(Value *Val) {
884 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
885 Value *Op = Cast->getOperand(0);
886 if (Op->getType()->isFloatTy())
889 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
890 APFloat F = Const->getValueAPF();
892 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
895 return ConstantFP::get(Const->getContext(), F);
900 //===----------------------------------------------------------------------===//
901 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
903 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
905 Function *Callee = CI->getCalledFunction();
906 FunctionType *FT = Callee->getFunctionType();
907 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
908 !FT->getParamType(0)->isDoubleTy())
912 // Check if all the uses for function like 'sin' are converted to float.
913 for (User *U : CI->users()) {
914 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
915 if (!Cast || !Cast->getType()->isFloatTy())
920 // If this is something like 'floor((double)floatval)', convert to floorf.
921 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
925 // floor((double)floatval) -> (double)floorf(floatval)
926 if (Callee->isIntrinsic()) {
927 Module *M = CI->getParent()->getParent()->getParent();
928 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
929 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
930 V = B.CreateCall(F, V);
932 // The call is a library call rather than an intrinsic.
933 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
936 return B.CreateFPExt(V, B.getDoubleTy());
939 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
940 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
941 Function *Callee = CI->getCalledFunction();
942 FunctionType *FT = Callee->getFunctionType();
943 // Just make sure this has 2 arguments of the same FP type, which match the
945 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
946 FT->getParamType(0) != FT->getParamType(1) ||
947 !FT->getParamType(0)->isFloatingPointTy())
950 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
951 // or fmin(1.0, (double)floatval), then we convert it to fminf.
952 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
955 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
959 // fmin((double)floatval1, (double)floatval2)
960 // -> (double)fminf(floatval1, floatval2)
961 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
962 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
963 Callee->getAttributes());
964 return B.CreateFPExt(V, B.getDoubleTy());
967 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
968 Function *Callee = CI->getCalledFunction();
969 Value *Ret = nullptr;
970 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
971 Ret = optimizeUnaryDoubleFP(CI, B, true);
974 FunctionType *FT = Callee->getFunctionType();
975 // Just make sure this has 1 argument of FP type, which matches the
977 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
978 !FT->getParamType(0)->isFloatingPointTy())
982 Value *Op1 = CI->getArgOperand(0);
983 if (BinaryOperator::isFNeg(Op1)) {
984 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
985 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
990 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
991 Function *Callee = CI->getCalledFunction();
993 Value *Ret = nullptr;
994 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
995 Ret = optimizeUnaryDoubleFP(CI, B, true);
998 FunctionType *FT = Callee->getFunctionType();
999 // Just make sure this has 2 arguments of the same FP type, which match the
1001 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1002 FT->getParamType(0) != FT->getParamType(1) ||
1003 !FT->getParamType(0)->isFloatingPointTy())
1006 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1007 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1008 // pow(1.0, x) -> 1.0
1009 if (Op1C->isExactlyValue(1.0))
1011 // pow(2.0, x) -> exp2(x)
1012 if (Op1C->isExactlyValue(2.0) &&
1013 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1015 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1016 // pow(10.0, x) -> exp10(x)
1017 if (Op1C->isExactlyValue(10.0) &&
1018 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1020 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1021 Callee->getAttributes());
1024 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1028 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1029 return ConstantFP::get(CI->getType(), 1.0);
1031 if (Op2C->isExactlyValue(0.5) &&
1032 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1034 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1036 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1037 // This is faster than calling pow, and still handles negative zero
1038 // and negative infinity correctly.
1039 // TODO: In fast-math mode, this could be just sqrt(x).
1040 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1041 Value *Inf = ConstantFP::getInfinity(CI->getType());
1042 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1043 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1045 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1046 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1047 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1051 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1053 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1054 return B.CreateFMul(Op1, Op1, "pow2");
1055 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1056 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1060 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1061 Function *Callee = CI->getCalledFunction();
1062 Function *Caller = CI->getParent()->getParent();
1064 Value *Ret = nullptr;
1065 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1066 TLI->has(LibFunc::exp2f)) {
1067 Ret = optimizeUnaryDoubleFP(CI, B, true);
1070 FunctionType *FT = Callee->getFunctionType();
1071 // Just make sure this has 1 argument of FP type, which matches the
1073 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1074 !FT->getParamType(0)->isFloatingPointTy())
1077 Value *Op = CI->getArgOperand(0);
1078 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1079 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1080 LibFunc::Func LdExp = LibFunc::ldexpl;
1081 if (Op->getType()->isFloatTy())
1082 LdExp = LibFunc::ldexpf;
1083 else if (Op->getType()->isDoubleTy())
1084 LdExp = LibFunc::ldexp;
1086 if (TLI->has(LdExp)) {
1087 Value *LdExpArg = nullptr;
1088 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1089 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1090 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1091 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1092 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1093 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1097 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1098 if (!Op->getType()->isFloatTy())
1099 One = ConstantExpr::getFPExtend(One, Op->getType());
1101 Module *M = Caller->getParent();
1103 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1104 Op->getType(), B.getInt32Ty(), nullptr);
1105 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1106 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1107 CI->setCallingConv(F->getCallingConv());
1115 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1116 Function *Callee = CI->getCalledFunction();
1118 Value *Ret = nullptr;
1119 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1120 Ret = optimizeUnaryDoubleFP(CI, B, false);
1123 FunctionType *FT = Callee->getFunctionType();
1124 // Make sure this has 1 argument of FP type which matches the result type.
1125 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1126 !FT->getParamType(0)->isFloatingPointTy())
1129 Value *Op = CI->getArgOperand(0);
1130 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1131 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1132 if (I->getOpcode() == Instruction::FMul)
1133 if (I->getOperand(0) == I->getOperand(1))
1139 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1140 Function *Callee = CI->getCalledFunction();
1142 Value *Ret = nullptr;
1143 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1144 Callee->getIntrinsicID() == Intrinsic::sqrt))
1145 Ret = optimizeUnaryDoubleFP(CI, B, true);
1147 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1148 // fast-math flag decorations that are applied to FP instructions. For now,
1149 // we have to rely on the function-level unsafe-fp-math attribute to do this
1150 // optimization because there's no other way to express that the sqrt can be
1152 Function *F = CI->getParent()->getParent();
1153 if (F->hasFnAttribute("unsafe-fp-math")) {
1154 // Check for unsafe-fp-math = true.
1155 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1156 if (Attr.getValueAsString() != "true")
1159 Value *Op = CI->getArgOperand(0);
1160 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1161 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1162 // We're looking for a repeated factor in a multiplication tree,
1163 // so we can do this fold: sqrt(x * x) -> fabs(x);
1164 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1165 Value *Op0 = I->getOperand(0);
1166 Value *Op1 = I->getOperand(1);
1167 Value *RepeatOp = nullptr;
1168 Value *OtherOp = nullptr;
1170 // Simple match: the operands of the multiply are identical.
1173 // Look for a more complicated pattern: one of the operands is itself
1174 // a multiply, so search for a common factor in that multiply.
1175 // Note: We don't bother looking any deeper than this first level or for
1176 // variations of this pattern because instcombine's visitFMUL and/or the
1177 // reassociation pass should give us this form.
1178 Value *OtherMul0, *OtherMul1;
1179 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1180 // Pattern: sqrt((x * y) * z)
1181 if (OtherMul0 == OtherMul1) {
1182 // Matched: sqrt((x * x) * z)
1183 RepeatOp = OtherMul0;
1189 // Fast math flags for any created instructions should match the sqrt
1191 // FIXME: We're not checking the sqrt because it doesn't have
1192 // fast-math-flags (see earlier comment).
1193 IRBuilder<true, ConstantFolder,
1194 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1195 B.SetFastMathFlags(I->getFastMathFlags());
1196 // If we found a repeated factor, hoist it out of the square root and
1197 // replace it with the fabs of that factor.
1198 Module *M = Callee->getParent();
1199 Type *ArgType = Op->getType();
1200 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1201 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1203 // If we found a non-repeated factor, we still need to get its square
1204 // root. We then multiply that by the value that was simplified out
1205 // of the square root calculation.
1206 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1207 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1208 return B.CreateFMul(FabsCall, SqrtCall);
1217 static bool isTrigLibCall(CallInst *CI);
1218 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1219 bool UseFloat, Value *&Sin, Value *&Cos,
1222 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1224 // Make sure the prototype is as expected, otherwise the rest of the
1225 // function is probably invalid and likely to abort.
1226 if (!isTrigLibCall(CI))
1229 Value *Arg = CI->getArgOperand(0);
1230 SmallVector<CallInst *, 1> SinCalls;
1231 SmallVector<CallInst *, 1> CosCalls;
1232 SmallVector<CallInst *, 1> SinCosCalls;
1234 bool IsFloat = Arg->getType()->isFloatTy();
1236 // Look for all compatible sinpi, cospi and sincospi calls with the same
1237 // argument. If there are enough (in some sense) we can make the
1239 for (User *U : Arg->users())
1240 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1243 // It's only worthwhile if both sinpi and cospi are actually used.
1244 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1247 Value *Sin, *Cos, *SinCos;
1248 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1250 replaceTrigInsts(SinCalls, Sin);
1251 replaceTrigInsts(CosCalls, Cos);
1252 replaceTrigInsts(SinCosCalls, SinCos);
1257 static bool isTrigLibCall(CallInst *CI) {
1258 Function *Callee = CI->getCalledFunction();
1259 FunctionType *FT = Callee->getFunctionType();
1261 // We can only hope to do anything useful if we can ignore things like errno
1262 // and floating-point exceptions.
1263 bool AttributesSafe =
1264 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1266 // Other than that we need float(float) or double(double)
1267 return AttributesSafe && FT->getNumParams() == 1 &&
1268 FT->getReturnType() == FT->getParamType(0) &&
1269 (FT->getParamType(0)->isFloatTy() ||
1270 FT->getParamType(0)->isDoubleTy());
1274 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1275 SmallVectorImpl<CallInst *> &SinCalls,
1276 SmallVectorImpl<CallInst *> &CosCalls,
1277 SmallVectorImpl<CallInst *> &SinCosCalls) {
1278 CallInst *CI = dyn_cast<CallInst>(Val);
1283 Function *Callee = CI->getCalledFunction();
1284 StringRef FuncName = Callee->getName();
1286 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1290 if (Func == LibFunc::sinpif)
1291 SinCalls.push_back(CI);
1292 else if (Func == LibFunc::cospif)
1293 CosCalls.push_back(CI);
1294 else if (Func == LibFunc::sincospif_stret)
1295 SinCosCalls.push_back(CI);
1297 if (Func == LibFunc::sinpi)
1298 SinCalls.push_back(CI);
1299 else if (Func == LibFunc::cospi)
1300 CosCalls.push_back(CI);
1301 else if (Func == LibFunc::sincospi_stret)
1302 SinCosCalls.push_back(CI);
1306 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1308 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1310 replaceAllUsesWith(*I, Res);
1314 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1315 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1316 Type *ArgTy = Arg->getType();
1320 Triple T(OrigCallee->getParent()->getTargetTriple());
1322 Name = "__sincospif_stret";
1324 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1325 // x86_64 can't use {float, float} since that would be returned in both
1326 // xmm0 and xmm1, which isn't what a real struct would do.
1327 ResTy = T.getArch() == Triple::x86_64
1328 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1329 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1331 Name = "__sincospi_stret";
1332 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1335 Module *M = OrigCallee->getParent();
1336 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1337 ResTy, ArgTy, nullptr);
1339 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1340 // If the argument is an instruction, it must dominate all uses so put our
1341 // sincos call there.
1342 BasicBlock::iterator Loc = ArgInst;
1343 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1345 // Otherwise (e.g. for a constant) the beginning of the function is as
1346 // good a place as any.
1347 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1348 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1351 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1353 if (SinCos->getType()->isStructTy()) {
1354 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1355 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1357 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1359 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1364 //===----------------------------------------------------------------------===//
1365 // Integer Library Call Optimizations
1366 //===----------------------------------------------------------------------===//
1368 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1369 Function *Callee = CI->getCalledFunction();
1370 FunctionType *FT = Callee->getFunctionType();
1371 // Just make sure this has 2 arguments of the same FP type, which match the
1373 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1374 !FT->getParamType(0)->isIntegerTy())
1377 Value *Op = CI->getArgOperand(0);
1380 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1381 if (CI->isZero()) // ffs(0) -> 0.
1382 return B.getInt32(0);
1383 // ffs(c) -> cttz(c)+1
1384 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1387 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1388 Type *ArgType = Op->getType();
1390 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1391 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1392 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1393 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1395 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1396 return B.CreateSelect(Cond, V, B.getInt32(0));
1399 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1400 Function *Callee = CI->getCalledFunction();
1401 FunctionType *FT = Callee->getFunctionType();
1402 // We require integer(integer) where the types agree.
1403 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1404 FT->getParamType(0) != FT->getReturnType())
1407 // abs(x) -> x >s -1 ? x : -x
1408 Value *Op = CI->getArgOperand(0);
1410 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1411 Value *Neg = B.CreateNeg(Op, "neg");
1412 return B.CreateSelect(Pos, Op, Neg);
1415 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1416 Function *Callee = CI->getCalledFunction();
1417 FunctionType *FT = Callee->getFunctionType();
1418 // We require integer(i32)
1419 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1420 !FT->getParamType(0)->isIntegerTy(32))
1423 // isdigit(c) -> (c-'0') <u 10
1424 Value *Op = CI->getArgOperand(0);
1425 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1426 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1427 return B.CreateZExt(Op, CI->getType());
1430 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1431 Function *Callee = CI->getCalledFunction();
1432 FunctionType *FT = Callee->getFunctionType();
1433 // We require integer(i32)
1434 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1435 !FT->getParamType(0)->isIntegerTy(32))
1438 // isascii(c) -> c <u 128
1439 Value *Op = CI->getArgOperand(0);
1440 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1441 return B.CreateZExt(Op, CI->getType());
1444 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1445 Function *Callee = CI->getCalledFunction();
1446 FunctionType *FT = Callee->getFunctionType();
1447 // We require i32(i32)
1448 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1449 !FT->getParamType(0)->isIntegerTy(32))
1452 // toascii(c) -> c & 0x7f
1453 return B.CreateAnd(CI->getArgOperand(0),
1454 ConstantInt::get(CI->getType(), 0x7F));
1457 //===----------------------------------------------------------------------===//
1458 // Formatting and IO Library Call Optimizations
1459 //===----------------------------------------------------------------------===//
1461 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1463 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1465 // Error reporting calls should be cold, mark them as such.
1466 // This applies even to non-builtin calls: it is only a hint and applies to
1467 // functions that the frontend might not understand as builtins.
1469 // This heuristic was suggested in:
1470 // Improving Static Branch Prediction in a Compiler
1471 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1472 // Proceedings of PACT'98, Oct. 1998, IEEE
1473 Function *Callee = CI->getCalledFunction();
1475 if (!CI->hasFnAttr(Attribute::Cold) &&
1476 isReportingError(Callee, CI, StreamArg)) {
1477 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1483 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1484 if (!ColdErrorCalls)
1487 if (!Callee || !Callee->isDeclaration())
1493 // These functions might be considered cold, but only if their stream
1494 // argument is stderr.
1496 if (StreamArg >= (int)CI->getNumArgOperands())
1498 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1501 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1502 if (!GV || !GV->isDeclaration())
1504 return GV->getName() == "stderr";
1507 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1508 // Check for a fixed format string.
1509 StringRef FormatStr;
1510 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1513 // Empty format string -> noop.
1514 if (FormatStr.empty()) // Tolerate printf's declared void.
1515 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1517 // Do not do any of the following transformations if the printf return value
1518 // is used, in general the printf return value is not compatible with either
1519 // putchar() or puts().
1520 if (!CI->use_empty())
1523 // printf("x") -> putchar('x'), even for '%'.
1524 if (FormatStr.size() == 1) {
1525 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1526 if (CI->use_empty() || !Res)
1528 return B.CreateIntCast(Res, CI->getType(), true);
1531 // printf("foo\n") --> puts("foo")
1532 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1533 FormatStr.find('%') == StringRef::npos) { // No format characters.
1534 // Create a string literal with no \n on it. We expect the constant merge
1535 // pass to be run after this pass, to merge duplicate strings.
1536 FormatStr = FormatStr.drop_back();
1537 Value *GV = B.CreateGlobalString(FormatStr, "str");
1538 Value *NewCI = EmitPutS(GV, B, TLI);
1539 return (CI->use_empty() || !NewCI)
1541 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1544 // Optimize specific format strings.
1545 // printf("%c", chr) --> putchar(chr)
1546 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1547 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1548 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1550 if (CI->use_empty() || !Res)
1552 return B.CreateIntCast(Res, CI->getType(), true);
1555 // printf("%s\n", str) --> puts(str)
1556 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1557 CI->getArgOperand(1)->getType()->isPointerTy()) {
1558 return EmitPutS(CI->getArgOperand(1), B, TLI);
1563 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1565 Function *Callee = CI->getCalledFunction();
1566 // Require one fixed pointer argument and an integer/void result.
1567 FunctionType *FT = Callee->getFunctionType();
1568 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1569 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1572 if (Value *V = optimizePrintFString(CI, B)) {
1576 // printf(format, ...) -> iprintf(format, ...) if no floating point
1578 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1579 Module *M = B.GetInsertBlock()->getParent()->getParent();
1580 Constant *IPrintFFn =
1581 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1582 CallInst *New = cast<CallInst>(CI->clone());
1583 New->setCalledFunction(IPrintFFn);
1590 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1591 // Check for a fixed format string.
1592 StringRef FormatStr;
1593 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1596 // If we just have a format string (nothing else crazy) transform it.
1597 if (CI->getNumArgOperands() == 2) {
1598 // Make sure there's no % in the constant array. We could try to handle
1599 // %% -> % in the future if we cared.
1600 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1601 if (FormatStr[i] == '%')
1602 return nullptr; // we found a format specifier, bail out.
1604 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1605 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1606 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1607 FormatStr.size() + 1),
1608 1); // Copy the null byte.
1609 return ConstantInt::get(CI->getType(), FormatStr.size());
1612 // The remaining optimizations require the format string to be "%s" or "%c"
1613 // and have an extra operand.
1614 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1615 CI->getNumArgOperands() < 3)
1618 // Decode the second character of the format string.
1619 if (FormatStr[1] == 'c') {
1620 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1621 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1623 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1624 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1625 B.CreateStore(V, Ptr);
1626 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1627 B.CreateStore(B.getInt8(0), Ptr);
1629 return ConstantInt::get(CI->getType(), 1);
1632 if (FormatStr[1] == 's') {
1633 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1634 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1637 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1641 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1642 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1644 // The sprintf result is the unincremented number of bytes in the string.
1645 return B.CreateIntCast(Len, CI->getType(), false);
1650 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1651 Function *Callee = CI->getCalledFunction();
1652 // Require two fixed pointer arguments and an integer result.
1653 FunctionType *FT = Callee->getFunctionType();
1654 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1655 !FT->getParamType(1)->isPointerTy() ||
1656 !FT->getReturnType()->isIntegerTy())
1659 if (Value *V = optimizeSPrintFString(CI, B)) {
1663 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1665 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1666 Module *M = B.GetInsertBlock()->getParent()->getParent();
1667 Constant *SIPrintFFn =
1668 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1669 CallInst *New = cast<CallInst>(CI->clone());
1670 New->setCalledFunction(SIPrintFFn);
1677 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1678 optimizeErrorReporting(CI, B, 0);
1680 // All the optimizations depend on the format string.
1681 StringRef FormatStr;
1682 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1685 // Do not do any of the following transformations if the fprintf return
1686 // value is used, in general the fprintf return value is not compatible
1687 // with fwrite(), fputc() or fputs().
1688 if (!CI->use_empty())
1691 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1692 if (CI->getNumArgOperands() == 2) {
1693 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1694 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1695 return nullptr; // We found a format specifier.
1698 CI->getArgOperand(1),
1699 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1700 CI->getArgOperand(0), B, DL, TLI);
1703 // The remaining optimizations require the format string to be "%s" or "%c"
1704 // and have an extra operand.
1705 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1706 CI->getNumArgOperands() < 3)
1709 // Decode the second character of the format string.
1710 if (FormatStr[1] == 'c') {
1711 // fprintf(F, "%c", chr) --> fputc(chr, F)
1712 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1714 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1717 if (FormatStr[1] == 's') {
1718 // fprintf(F, "%s", str) --> fputs(str, F)
1719 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1721 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1726 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1727 Function *Callee = CI->getCalledFunction();
1728 // Require two fixed paramters as pointers and integer result.
1729 FunctionType *FT = Callee->getFunctionType();
1730 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1731 !FT->getParamType(1)->isPointerTy() ||
1732 !FT->getReturnType()->isIntegerTy())
1735 if (Value *V = optimizeFPrintFString(CI, B)) {
1739 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1740 // floating point arguments.
1741 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1742 Module *M = B.GetInsertBlock()->getParent()->getParent();
1743 Constant *FIPrintFFn =
1744 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1745 CallInst *New = cast<CallInst>(CI->clone());
1746 New->setCalledFunction(FIPrintFFn);
1753 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1754 optimizeErrorReporting(CI, B, 3);
1756 Function *Callee = CI->getCalledFunction();
1757 // Require a pointer, an integer, an integer, a pointer, returning integer.
1758 FunctionType *FT = Callee->getFunctionType();
1759 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1760 !FT->getParamType(1)->isIntegerTy() ||
1761 !FT->getParamType(2)->isIntegerTy() ||
1762 !FT->getParamType(3)->isPointerTy() ||
1763 !FT->getReturnType()->isIntegerTy())
1766 // Get the element size and count.
1767 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1768 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1769 if (!SizeC || !CountC)
1771 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1773 // If this is writing zero records, remove the call (it's a noop).
1775 return ConstantInt::get(CI->getType(), 0);
1777 // If this is writing one byte, turn it into fputc.
1778 // This optimisation is only valid, if the return value is unused.
1779 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1780 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1781 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1782 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1788 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1789 optimizeErrorReporting(CI, B, 1);
1791 Function *Callee = CI->getCalledFunction();
1793 // Require two pointers. Also, we can't optimize if return value is used.
1794 FunctionType *FT = Callee->getFunctionType();
1795 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1796 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1799 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1800 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1804 // Known to have no uses (see above).
1806 CI->getArgOperand(0),
1807 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1808 CI->getArgOperand(1), B, DL, TLI);
1811 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1812 Function *Callee = CI->getCalledFunction();
1813 // Require one fixed pointer argument and an integer/void result.
1814 FunctionType *FT = Callee->getFunctionType();
1815 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1816 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1819 // Check for a constant string.
1821 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1824 if (Str.empty() && CI->use_empty()) {
1825 // puts("") -> putchar('\n')
1826 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1827 if (CI->use_empty() || !Res)
1829 return B.CreateIntCast(Res, CI->getType(), true);
1835 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1837 SmallString<20> FloatFuncName = FuncName;
1838 FloatFuncName += 'f';
1839 if (TLI->getLibFunc(FloatFuncName, Func))
1840 return TLI->has(Func);
1844 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1845 IRBuilder<> &Builder) {
1847 Function *Callee = CI->getCalledFunction();
1848 StringRef FuncName = Callee->getName();
1850 // Check for string/memory library functions.
1851 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1852 // Make sure we never change the calling convention.
1853 assert((ignoreCallingConv(Func) ||
1854 CI->getCallingConv() == llvm::CallingConv::C) &&
1855 "Optimizing string/memory libcall would change the calling convention");
1857 case LibFunc::strcat:
1858 return optimizeStrCat(CI, Builder);
1859 case LibFunc::strncat:
1860 return optimizeStrNCat(CI, Builder);
1861 case LibFunc::strchr:
1862 return optimizeStrChr(CI, Builder);
1863 case LibFunc::strrchr:
1864 return optimizeStrRChr(CI, Builder);
1865 case LibFunc::strcmp:
1866 return optimizeStrCmp(CI, Builder);
1867 case LibFunc::strncmp:
1868 return optimizeStrNCmp(CI, Builder);
1869 case LibFunc::strcpy:
1870 return optimizeStrCpy(CI, Builder);
1871 case LibFunc::stpcpy:
1872 return optimizeStpCpy(CI, Builder);
1873 case LibFunc::strncpy:
1874 return optimizeStrNCpy(CI, Builder);
1875 case LibFunc::strlen:
1876 return optimizeStrLen(CI, Builder);
1877 case LibFunc::strpbrk:
1878 return optimizeStrPBrk(CI, Builder);
1879 case LibFunc::strtol:
1880 case LibFunc::strtod:
1881 case LibFunc::strtof:
1882 case LibFunc::strtoul:
1883 case LibFunc::strtoll:
1884 case LibFunc::strtold:
1885 case LibFunc::strtoull:
1886 return optimizeStrTo(CI, Builder);
1887 case LibFunc::strspn:
1888 return optimizeStrSpn(CI, Builder);
1889 case LibFunc::strcspn:
1890 return optimizeStrCSpn(CI, Builder);
1891 case LibFunc::strstr:
1892 return optimizeStrStr(CI, Builder);
1893 case LibFunc::memchr:
1894 return optimizeMemChr(CI, Builder);
1895 case LibFunc::memcmp:
1896 return optimizeMemCmp(CI, Builder);
1897 case LibFunc::memcpy:
1898 return optimizeMemCpy(CI, Builder);
1899 case LibFunc::memmove:
1900 return optimizeMemMove(CI, Builder);
1901 case LibFunc::memset:
1902 return optimizeMemSet(CI, Builder);
1910 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1911 if (CI->isNoBuiltin())
1915 Function *Callee = CI->getCalledFunction();
1916 StringRef FuncName = Callee->getName();
1917 IRBuilder<> Builder(CI);
1918 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1920 // Command-line parameter overrides function attribute.
1921 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1922 UnsafeFPShrink = EnableUnsafeFPShrink;
1923 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
1924 // FIXME: This is the same problem as described in optimizeSqrt().
1925 // If calls gain access to IR-level FMF, then use that instead of a
1926 // function attribute.
1928 // Check for unsafe-fp-math = true.
1929 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
1930 if (Attr.getValueAsString() == "true")
1931 UnsafeFPShrink = true;
1934 // First, check for intrinsics.
1935 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1936 if (!isCallingConvC)
1938 switch (II->getIntrinsicID()) {
1939 case Intrinsic::pow:
1940 return optimizePow(CI, Builder);
1941 case Intrinsic::exp2:
1942 return optimizeExp2(CI, Builder);
1943 case Intrinsic::fabs:
1944 return optimizeFabs(CI, Builder);
1945 case Intrinsic::sqrt:
1946 return optimizeSqrt(CI, Builder);
1952 // Also try to simplify calls to fortified library functions.
1953 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
1954 // Try to further simplify the result.
1955 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
1956 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
1957 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
1958 // If we were able to further simplify, remove the now redundant call.
1959 SimplifiedCI->replaceAllUsesWith(V);
1960 SimplifiedCI->eraseFromParent();
1963 return SimplifiedFortifiedCI;
1966 // Then check for known library functions.
1967 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1968 // We never change the calling convention.
1969 if (!ignoreCallingConv(Func) && !isCallingConvC)
1971 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
1977 return optimizeCos(CI, Builder);
1978 case LibFunc::sinpif:
1979 case LibFunc::sinpi:
1980 case LibFunc::cospif:
1981 case LibFunc::cospi:
1982 return optimizeSinCosPi(CI, Builder);
1986 return optimizePow(CI, Builder);
1987 case LibFunc::exp2l:
1989 case LibFunc::exp2f:
1990 return optimizeExp2(CI, Builder);
1991 case LibFunc::fabsf:
1993 case LibFunc::fabsl:
1994 return optimizeFabs(CI, Builder);
1995 case LibFunc::sqrtf:
1997 case LibFunc::sqrtl:
1998 return optimizeSqrt(CI, Builder);
2001 case LibFunc::ffsll:
2002 return optimizeFFS(CI, Builder);
2005 case LibFunc::llabs:
2006 return optimizeAbs(CI, Builder);
2007 case LibFunc::isdigit:
2008 return optimizeIsDigit(CI, Builder);
2009 case LibFunc::isascii:
2010 return optimizeIsAscii(CI, Builder);
2011 case LibFunc::toascii:
2012 return optimizeToAscii(CI, Builder);
2013 case LibFunc::printf:
2014 return optimizePrintF(CI, Builder);
2015 case LibFunc::sprintf:
2016 return optimizeSPrintF(CI, Builder);
2017 case LibFunc::fprintf:
2018 return optimizeFPrintF(CI, Builder);
2019 case LibFunc::fwrite:
2020 return optimizeFWrite(CI, Builder);
2021 case LibFunc::fputs:
2022 return optimizeFPuts(CI, Builder);
2024 return optimizePuts(CI, Builder);
2025 case LibFunc::perror:
2026 return optimizeErrorReporting(CI, Builder);
2027 case LibFunc::vfprintf:
2028 case LibFunc::fiprintf:
2029 return optimizeErrorReporting(CI, Builder, 0);
2030 case LibFunc::fputc:
2031 return optimizeErrorReporting(CI, Builder, 1);
2033 case LibFunc::floor:
2035 case LibFunc::round:
2036 case LibFunc::nearbyint:
2037 case LibFunc::trunc:
2038 if (hasFloatVersion(FuncName))
2039 return optimizeUnaryDoubleFP(CI, Builder, false);
2042 case LibFunc::acosh:
2044 case LibFunc::asinh:
2046 case LibFunc::atanh:
2050 case LibFunc::exp10:
2051 case LibFunc::expm1:
2053 case LibFunc::log10:
2054 case LibFunc::log1p:
2061 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2062 return optimizeUnaryDoubleFP(CI, Builder, true);
2064 case LibFunc::copysign:
2067 if (hasFloatVersion(FuncName))
2068 return optimizeBinaryDoubleFP(CI, Builder);
2077 LibCallSimplifier::LibCallSimplifier(
2078 const DataLayout &DL, const TargetLibraryInfo *TLI,
2079 function_ref<void(Instruction *, Value *)> Replacer)
2080 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2081 Replacer(Replacer) {}
2083 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2084 // Indirect through the replacer used in this instance.
2088 /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2090 I->replaceAllUsesWith(With);
2091 I->eraseFromParent();
2095 // Additional cases that we need to add to this file:
2098 // * cbrt(expN(X)) -> expN(x/3)
2099 // * cbrt(sqrt(x)) -> pow(x,1/6)
2100 // * cbrt(sqrt(x)) -> pow(x,1/9)
2103 // * exp(log(x)) -> x
2106 // * log(exp(x)) -> x
2107 // * log(x**y) -> y*log(x)
2108 // * log(exp(y)) -> y*log(e)
2109 // * log(exp2(y)) -> y*log(2)
2110 // * log(exp10(y)) -> y*log(10)
2111 // * log(sqrt(x)) -> 0.5*log(x)
2112 // * log(pow(x,y)) -> y*log(x)
2114 // lround, lroundf, lroundl:
2115 // * lround(cnst) -> cnst'
2118 // * pow(exp(x),y) -> exp(x*y)
2119 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2120 // * pow(pow(x,y),z)-> pow(x,y*z)
2122 // round, roundf, roundl:
2123 // * round(cnst) -> cnst'
2126 // * signbit(cnst) -> cnst'
2127 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2129 // sqrt, sqrtf, sqrtl:
2130 // * sqrt(expN(x)) -> expN(x*0.5)
2131 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2132 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2135 // * tan(atan(x)) -> x
2137 // trunc, truncf, truncl:
2138 // * trunc(cnst) -> cnst'
2142 //===----------------------------------------------------------------------===//
2143 // Fortified Library Call Optimizations
2144 //===----------------------------------------------------------------------===//
2146 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2150 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2152 if (ConstantInt *ObjSizeCI =
2153 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2154 if (ObjSizeCI->isAllOnesValue())
2156 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2157 if (OnlyLowerUnknownSize)
2160 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2161 // If the length is 0 we don't know how long it is and so we can't
2162 // remove the check.
2165 return ObjSizeCI->getZExtValue() >= Len;
2167 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2168 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2173 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2174 Function *Callee = CI->getCalledFunction();
2176 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2179 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2180 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2181 CI->getArgOperand(2), 1);
2182 return CI->getArgOperand(0);
2187 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2188 Function *Callee = CI->getCalledFunction();
2190 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2193 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2194 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2195 CI->getArgOperand(2), 1);
2196 return CI->getArgOperand(0);
2201 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2202 Function *Callee = CI->getCalledFunction();
2204 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2207 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2208 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2209 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2210 return CI->getArgOperand(0);
2215 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2217 LibFunc::Func Func) {
2218 Function *Callee = CI->getCalledFunction();
2219 StringRef Name = Callee->getName();
2220 const DataLayout &DL = CI->getModule()->getDataLayout();
2222 if (!checkStringCopyLibFuncSignature(Callee, Func))
2225 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2226 *ObjSize = CI->getArgOperand(2);
2228 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2229 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2230 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2231 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
2234 // If a) we don't have any length information, or b) we know this will
2235 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2236 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2237 // TODO: It might be nice to get a maximum length out of the possible
2238 // string lengths for varying.
2239 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
2240 Value *Ret = EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2242 } else if (!OnlyLowerUnknownSize) {
2243 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2244 uint64_t Len = GetStringLength(Src);
2248 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2249 Value *LenV = ConstantInt::get(SizeTTy, Len);
2250 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2251 // If the function was an __stpcpy_chk, and we were able to fold it into
2252 // a __memcpy_chk, we still need to return the correct end pointer.
2253 if (Ret && Func == LibFunc::stpcpy_chk)
2254 return B.CreateGEP(Dst, ConstantInt::get(SizeTTy, Len - 1));
2260 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2262 LibFunc::Func Func) {
2263 Function *Callee = CI->getCalledFunction();
2264 StringRef Name = Callee->getName();
2266 if (!checkStringCopyLibFuncSignature(Callee, Func))
2268 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2269 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2270 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2276 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2277 if (CI->isNoBuiltin())
2281 Function *Callee = CI->getCalledFunction();
2282 StringRef FuncName = Callee->getName();
2283 IRBuilder<> Builder(CI);
2284 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2286 // First, check that this is a known library functions.
2287 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func))
2290 // We never change the calling convention.
2291 if (!ignoreCallingConv(Func) && !isCallingConvC)
2295 case LibFunc::memcpy_chk:
2296 return optimizeMemCpyChk(CI, Builder);
2297 case LibFunc::memmove_chk:
2298 return optimizeMemMoveChk(CI, Builder);
2299 case LibFunc::memset_chk:
2300 return optimizeMemSetChk(CI, Builder);
2301 case LibFunc::stpcpy_chk:
2302 case LibFunc::strcpy_chk:
2303 return optimizeStrpCpyChk(CI, Builder, Func);
2304 case LibFunc::stpncpy_chk:
2305 case LibFunc::strncpy_chk:
2306 return optimizeStrpNCpyChk(CI, Builder, Func);
2313 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2314 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2315 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}