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) {
125 FunctionType *FT = F->getFunctionType();
126 LLVMContext &Context = F->getContext();
127 Type *PCharTy = Type::getInt8PtrTy(Context);
128 Type *SizeTTy = DL ? DL->getIntPtrType(Context) : nullptr;
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 // These optimizations require DataLayout.
215 return emitStrLenMemCpy(Src, Dst, Len, B);
218 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
220 // We need to find the end of the destination string. That's where the
221 // memory is to be moved to. We just generate a call to strlen.
222 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
226 // Now that we have the destination's length, we must index into the
227 // destination's pointer to get the actual memcpy destination (end of
228 // the string .. we're concatenating).
229 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
231 // We have enough information to now generate the memcpy call to do the
232 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
235 ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
239 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
240 Function *Callee = CI->getCalledFunction();
241 // Verify the "strncat" function prototype.
242 FunctionType *FT = Callee->getFunctionType();
243 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
244 FT->getParamType(0) != FT->getReturnType() ||
245 FT->getParamType(1) != FT->getReturnType() ||
246 !FT->getParamType(2)->isIntegerTy())
249 // Extract some information from the instruction
250 Value *Dst = CI->getArgOperand(0);
251 Value *Src = CI->getArgOperand(1);
254 // We don't do anything if length is not constant
255 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
256 Len = LengthArg->getZExtValue();
260 // See if we can get the length of the input string.
261 uint64_t SrcLen = GetStringLength(Src);
264 --SrcLen; // Unbias length.
266 // Handle the simple, do-nothing cases:
267 // strncat(x, "", c) -> x
268 // strncat(x, c, 0) -> x
269 if (SrcLen == 0 || Len == 0)
272 // These optimizations require DataLayout.
276 // We don't optimize this case
280 // strncat(x, s, c) -> strcat(x, s)
281 // s is constant so the strcat can be optimized further
282 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
285 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
286 Function *Callee = CI->getCalledFunction();
287 // Verify the "strchr" function prototype.
288 FunctionType *FT = Callee->getFunctionType();
289 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
290 FT->getParamType(0) != FT->getReturnType() ||
291 !FT->getParamType(1)->isIntegerTy(32))
294 Value *SrcStr = CI->getArgOperand(0);
296 // If the second operand is non-constant, see if we can compute the length
297 // of the input string and turn this into memchr.
298 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
300 // These optimizations require DataLayout.
304 uint64_t Len = GetStringLength(SrcStr);
305 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
309 SrcStr, CI->getArgOperand(1), // include nul.
310 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
313 // Otherwise, the character is a constant, see if the first argument is
314 // a string literal. If so, we can constant fold.
316 if (!getConstantStringInfo(SrcStr, Str)) {
317 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
318 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
322 // Compute the offset, make sure to handle the case when we're searching for
323 // zero (a weird way to spell strlen).
324 size_t I = (0xFF & CharC->getSExtValue()) == 0
326 : Str.find(CharC->getSExtValue());
327 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
328 return Constant::getNullValue(CI->getType());
330 // strchr(s+n,c) -> gep(s+n+i,c)
331 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
334 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
335 Function *Callee = CI->getCalledFunction();
336 // Verify the "strrchr" function prototype.
337 FunctionType *FT = Callee->getFunctionType();
338 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
339 FT->getParamType(0) != FT->getReturnType() ||
340 !FT->getParamType(1)->isIntegerTy(32))
343 Value *SrcStr = CI->getArgOperand(0);
344 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
346 // Cannot fold anything if we're not looking for a constant.
351 if (!getConstantStringInfo(SrcStr, Str)) {
352 // strrchr(s, 0) -> strchr(s, 0)
353 if (DL && CharC->isZero())
354 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
358 // Compute the offset.
359 size_t I = (0xFF & CharC->getSExtValue()) == 0
361 : Str.rfind(CharC->getSExtValue());
362 if (I == StringRef::npos) // Didn't find the char. Return null.
363 return Constant::getNullValue(CI->getType());
365 // strrchr(s+n,c) -> gep(s+n+i,c)
366 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
369 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
370 Function *Callee = CI->getCalledFunction();
371 // Verify the "strcmp" function prototype.
372 FunctionType *FT = Callee->getFunctionType();
373 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
374 FT->getParamType(0) != FT->getParamType(1) ||
375 FT->getParamType(0) != B.getInt8PtrTy())
378 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
379 if (Str1P == Str2P) // strcmp(x,x) -> 0
380 return ConstantInt::get(CI->getType(), 0);
382 StringRef Str1, Str2;
383 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
384 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
386 // strcmp(x, y) -> cnst (if both x and y are constant strings)
387 if (HasStr1 && HasStr2)
388 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
390 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
392 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
394 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
395 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
397 // strcmp(P, "x") -> memcmp(P, "x", 2)
398 uint64_t Len1 = GetStringLength(Str1P);
399 uint64_t Len2 = GetStringLength(Str2P);
401 // These optimizations require DataLayout.
405 return EmitMemCmp(Str1P, Str2P,
406 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
407 std::min(Len1, Len2)),
414 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
415 Function *Callee = CI->getCalledFunction();
416 // Verify the "strncmp" function prototype.
417 FunctionType *FT = Callee->getFunctionType();
418 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
419 FT->getParamType(0) != FT->getParamType(1) ||
420 FT->getParamType(0) != B.getInt8PtrTy() ||
421 !FT->getParamType(2)->isIntegerTy())
424 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
425 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
426 return ConstantInt::get(CI->getType(), 0);
428 // Get the length argument if it is constant.
430 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
431 Length = LengthArg->getZExtValue();
435 if (Length == 0) // strncmp(x,y,0) -> 0
436 return ConstantInt::get(CI->getType(), 0);
438 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
439 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
441 StringRef Str1, Str2;
442 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
443 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
445 // strncmp(x, y) -> cnst (if both x and y are constant strings)
446 if (HasStr1 && HasStr2) {
447 StringRef SubStr1 = Str1.substr(0, Length);
448 StringRef SubStr2 = Str2.substr(0, Length);
449 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
452 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
454 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
456 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
457 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
462 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
463 Function *Callee = CI->getCalledFunction();
465 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy, DL))
468 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
469 if (Dst == Src) // strcpy(x,x) -> x
472 // These optimizations require DataLayout.
476 // See if we can get the length of the input string.
477 uint64_t Len = GetStringLength(Src);
481 // We have enough information to now generate the memcpy call to do the
482 // copy for us. Make a memcpy to copy the nul byte with align = 1.
483 B.CreateMemCpy(Dst, Src,
484 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
488 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
489 Function *Callee = CI->getCalledFunction();
490 // Verify the "stpcpy" function prototype.
491 FunctionType *FT = Callee->getFunctionType();
493 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy, DL))
496 // These optimizations require DataLayout.
500 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
501 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
502 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
503 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
506 // See if we can get the length of the input string.
507 uint64_t Len = GetStringLength(Src);
511 Type *PT = FT->getParamType(0);
512 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
514 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
516 // We have enough information to now generate the memcpy call to do the
517 // copy for us. Make a memcpy to copy the nul byte with align = 1.
518 B.CreateMemCpy(Dst, Src, LenV, 1);
522 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
523 Function *Callee = CI->getCalledFunction();
524 FunctionType *FT = Callee->getFunctionType();
526 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy, DL))
529 Value *Dst = CI->getArgOperand(0);
530 Value *Src = CI->getArgOperand(1);
531 Value *LenOp = CI->getArgOperand(2);
533 // See if we can get the length of the input string.
534 uint64_t SrcLen = GetStringLength(Src);
540 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
541 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
546 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
547 Len = LengthArg->getZExtValue();
552 return Dst; // strncpy(x, y, 0) -> x
554 // These optimizations require DataLayout.
558 // Let strncpy handle the zero padding
559 if (Len > SrcLen + 1)
562 Type *PT = FT->getParamType(0);
563 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
564 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
569 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
570 Function *Callee = CI->getCalledFunction();
571 FunctionType *FT = Callee->getFunctionType();
572 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
573 !FT->getReturnType()->isIntegerTy())
576 Value *Src = CI->getArgOperand(0);
578 // Constant folding: strlen("xyz") -> 3
579 if (uint64_t Len = GetStringLength(Src))
580 return ConstantInt::get(CI->getType(), Len - 1);
582 // strlen(x?"foo":"bars") --> x ? 3 : 4
583 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
584 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
585 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
586 if (LenTrue && LenFalse) {
587 Function *Caller = CI->getParent()->getParent();
588 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
590 "folded strlen(select) to select of constants");
591 return B.CreateSelect(SI->getCondition(),
592 ConstantInt::get(CI->getType(), LenTrue - 1),
593 ConstantInt::get(CI->getType(), LenFalse - 1));
597 // strlen(x) != 0 --> *x != 0
598 // strlen(x) == 0 --> *x == 0
599 if (isOnlyUsedInZeroEqualityComparison(CI))
600 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
605 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
606 Function *Callee = CI->getCalledFunction();
607 FunctionType *FT = Callee->getFunctionType();
608 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
609 FT->getParamType(1) != FT->getParamType(0) ||
610 FT->getReturnType() != FT->getParamType(0))
614 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
615 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
617 // strpbrk(s, "") -> nullptr
618 // strpbrk("", s) -> nullptr
619 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
620 return Constant::getNullValue(CI->getType());
623 if (HasS1 && HasS2) {
624 size_t I = S1.find_first_of(S2);
625 if (I == StringRef::npos) // No match.
626 return Constant::getNullValue(CI->getType());
628 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
631 // strpbrk(s, "a") -> strchr(s, 'a')
632 if (DL && HasS2 && S2.size() == 1)
633 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
638 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
639 Function *Callee = CI->getCalledFunction();
640 FunctionType *FT = Callee->getFunctionType();
641 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
642 !FT->getParamType(0)->isPointerTy() ||
643 !FT->getParamType(1)->isPointerTy())
646 Value *EndPtr = CI->getArgOperand(1);
647 if (isa<ConstantPointerNull>(EndPtr)) {
648 // With a null EndPtr, this function won't capture the main argument.
649 // It would be readonly too, except that it still may write to errno.
650 CI->addAttribute(1, Attribute::NoCapture);
656 Value *LibCallSimplifier::optimizeStrSpn(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 // strspn(s, "") -> 0
669 // strspn("", s) -> 0
670 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
671 return Constant::getNullValue(CI->getType());
674 if (HasS1 && HasS2) {
675 size_t Pos = S1.find_first_not_of(S2);
676 if (Pos == StringRef::npos)
678 return ConstantInt::get(CI->getType(), Pos);
684 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
685 Function *Callee = CI->getCalledFunction();
686 FunctionType *FT = Callee->getFunctionType();
687 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
688 FT->getParamType(1) != FT->getParamType(0) ||
689 !FT->getReturnType()->isIntegerTy())
693 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
694 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
696 // strcspn("", s) -> 0
697 if (HasS1 && S1.empty())
698 return Constant::getNullValue(CI->getType());
701 if (HasS1 && HasS2) {
702 size_t Pos = S1.find_first_of(S2);
703 if (Pos == StringRef::npos)
705 return ConstantInt::get(CI->getType(), Pos);
708 // strcspn(s, "") -> strlen(s)
709 if (DL && HasS2 && S2.empty())
710 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
715 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
716 Function *Callee = CI->getCalledFunction();
717 FunctionType *FT = Callee->getFunctionType();
718 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
719 !FT->getParamType(1)->isPointerTy() ||
720 !FT->getReturnType()->isPointerTy())
723 // fold strstr(x, x) -> x.
724 if (CI->getArgOperand(0) == CI->getArgOperand(1))
725 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
727 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
728 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
729 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
732 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
736 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
737 ICmpInst *Old = cast<ICmpInst>(*UI++);
739 B.CreateICmp(Old->getPredicate(), StrNCmp,
740 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
741 replaceAllUsesWith(Old, Cmp);
746 // See if either input string is a constant string.
747 StringRef SearchStr, ToFindStr;
748 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
749 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
751 // fold strstr(x, "") -> x.
752 if (HasStr2 && ToFindStr.empty())
753 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
755 // If both strings are known, constant fold it.
756 if (HasStr1 && HasStr2) {
757 size_t Offset = SearchStr.find(ToFindStr);
759 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
760 return Constant::getNullValue(CI->getType());
762 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
763 Value *Result = CastToCStr(CI->getArgOperand(0), B);
764 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
765 return B.CreateBitCast(Result, CI->getType());
768 // fold strstr(x, "y") -> strchr(x, 'y').
769 if (HasStr2 && ToFindStr.size() == 1) {
770 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
771 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
776 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
777 Function *Callee = CI->getCalledFunction();
778 FunctionType *FT = Callee->getFunctionType();
779 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
780 !FT->getParamType(1)->isPointerTy() ||
781 !FT->getReturnType()->isIntegerTy(32))
784 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
786 if (LHS == RHS) // memcmp(s,s,x) -> 0
787 return Constant::getNullValue(CI->getType());
789 // Make sure we have a constant length.
790 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
793 uint64_t Len = LenC->getZExtValue();
795 if (Len == 0) // memcmp(s1,s2,0) -> 0
796 return Constant::getNullValue(CI->getType());
798 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
800 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
801 CI->getType(), "lhsv");
802 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
803 CI->getType(), "rhsv");
804 return B.CreateSub(LHSV, RHSV, "chardiff");
807 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
808 StringRef LHSStr, RHSStr;
809 if (getConstantStringInfo(LHS, LHSStr) &&
810 getConstantStringInfo(RHS, RHSStr)) {
811 // Make sure we're not reading out-of-bounds memory.
812 if (Len > LHSStr.size() || Len > RHSStr.size())
814 // Fold the memcmp and normalize the result. This way we get consistent
815 // results across multiple platforms.
817 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
822 return ConstantInt::get(CI->getType(), Ret);
828 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
829 Function *Callee = CI->getCalledFunction();
830 // These optimizations require DataLayout.
834 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy, DL))
837 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
838 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
839 CI->getArgOperand(2), 1);
840 return CI->getArgOperand(0);
843 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
844 Function *Callee = CI->getCalledFunction();
845 // These optimizations require DataLayout.
849 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove, DL))
852 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
853 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
854 CI->getArgOperand(2), 1);
855 return CI->getArgOperand(0);
858 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
859 Function *Callee = CI->getCalledFunction();
860 // These optimizations require DataLayout.
864 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset, DL))
867 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
868 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
869 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
870 return CI->getArgOperand(0);
873 //===----------------------------------------------------------------------===//
874 // Math Library Optimizations
875 //===----------------------------------------------------------------------===//
877 /// Return a variant of Val with float type.
878 /// Currently this works in two cases: If Val is an FPExtension of a float
879 /// value to something bigger, simply return the operand.
880 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
881 /// loss of precision do so.
882 static Value *valueHasFloatPrecision(Value *Val) {
883 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
884 Value *Op = Cast->getOperand(0);
885 if (Op->getType()->isFloatTy())
888 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
889 APFloat F = Const->getValueAPF();
891 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
894 return ConstantFP::get(Const->getContext(), F);
899 //===----------------------------------------------------------------------===//
900 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
902 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
904 Function *Callee = CI->getCalledFunction();
905 FunctionType *FT = Callee->getFunctionType();
906 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
907 !FT->getParamType(0)->isDoubleTy())
911 // Check if all the uses for function like 'sin' are converted to float.
912 for (User *U : CI->users()) {
913 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
914 if (!Cast || !Cast->getType()->isFloatTy())
919 // If this is something like 'floor((double)floatval)', convert to floorf.
920 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
924 // floor((double)floatval) -> (double)floorf(floatval)
925 if (Callee->isIntrinsic()) {
926 Module *M = CI->getParent()->getParent()->getParent();
927 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
928 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
929 V = B.CreateCall(F, V);
931 // The call is a library call rather than an intrinsic.
932 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
935 return B.CreateFPExt(V, B.getDoubleTy());
938 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
939 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
940 Function *Callee = CI->getCalledFunction();
941 FunctionType *FT = Callee->getFunctionType();
942 // Just make sure this has 2 arguments of the same FP type, which match the
944 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
945 FT->getParamType(0) != FT->getParamType(1) ||
946 !FT->getParamType(0)->isFloatingPointTy())
949 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
950 // or fmin(1.0, (double)floatval), then we convert it to fminf.
951 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
954 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
958 // fmin((double)floatval1, (double)floatval2)
959 // -> (double)fminf(floatval1, floatval2)
960 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
961 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
962 Callee->getAttributes());
963 return B.CreateFPExt(V, B.getDoubleTy());
966 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
967 Function *Callee = CI->getCalledFunction();
968 Value *Ret = nullptr;
969 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
970 Ret = optimizeUnaryDoubleFP(CI, B, true);
973 FunctionType *FT = Callee->getFunctionType();
974 // Just make sure this has 1 argument of FP type, which matches the
976 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
977 !FT->getParamType(0)->isFloatingPointTy())
981 Value *Op1 = CI->getArgOperand(0);
982 if (BinaryOperator::isFNeg(Op1)) {
983 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
984 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
989 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
990 Function *Callee = CI->getCalledFunction();
992 Value *Ret = nullptr;
993 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
994 Ret = optimizeUnaryDoubleFP(CI, B, true);
997 FunctionType *FT = Callee->getFunctionType();
998 // Just make sure this has 2 arguments of the same FP type, which match the
1000 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1001 FT->getParamType(0) != FT->getParamType(1) ||
1002 !FT->getParamType(0)->isFloatingPointTy())
1005 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1006 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1007 // pow(1.0, x) -> 1.0
1008 if (Op1C->isExactlyValue(1.0))
1010 // pow(2.0, x) -> exp2(x)
1011 if (Op1C->isExactlyValue(2.0) &&
1012 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1014 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1015 // pow(10.0, x) -> exp10(x)
1016 if (Op1C->isExactlyValue(10.0) &&
1017 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1019 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1020 Callee->getAttributes());
1023 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1027 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1028 return ConstantFP::get(CI->getType(), 1.0);
1030 if (Op2C->isExactlyValue(0.5) &&
1031 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1033 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1035 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1036 // This is faster than calling pow, and still handles negative zero
1037 // and negative infinity correctly.
1038 // TODO: In fast-math mode, this could be just sqrt(x).
1039 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1040 Value *Inf = ConstantFP::getInfinity(CI->getType());
1041 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1042 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1044 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1045 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1046 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1050 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1052 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1053 return B.CreateFMul(Op1, Op1, "pow2");
1054 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1055 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1059 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1060 Function *Callee = CI->getCalledFunction();
1061 Function *Caller = CI->getParent()->getParent();
1063 Value *Ret = nullptr;
1064 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1065 TLI->has(LibFunc::exp2f)) {
1066 Ret = optimizeUnaryDoubleFP(CI, B, true);
1069 FunctionType *FT = Callee->getFunctionType();
1070 // Just make sure this has 1 argument of FP type, which matches the
1072 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1073 !FT->getParamType(0)->isFloatingPointTy())
1076 Value *Op = CI->getArgOperand(0);
1077 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1078 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1079 LibFunc::Func LdExp = LibFunc::ldexpl;
1080 if (Op->getType()->isFloatTy())
1081 LdExp = LibFunc::ldexpf;
1082 else if (Op->getType()->isDoubleTy())
1083 LdExp = LibFunc::ldexp;
1085 if (TLI->has(LdExp)) {
1086 Value *LdExpArg = nullptr;
1087 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1088 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1089 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1090 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1091 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1092 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1096 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1097 if (!Op->getType()->isFloatTy())
1098 One = ConstantExpr::getFPExtend(One, Op->getType());
1100 Module *M = Caller->getParent();
1102 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1103 Op->getType(), B.getInt32Ty(), nullptr);
1104 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1105 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1106 CI->setCallingConv(F->getCallingConv());
1114 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1115 Function *Callee = CI->getCalledFunction();
1117 Value *Ret = nullptr;
1118 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1119 Ret = optimizeUnaryDoubleFP(CI, B, false);
1122 FunctionType *FT = Callee->getFunctionType();
1123 // Make sure this has 1 argument of FP type which matches the result type.
1124 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1125 !FT->getParamType(0)->isFloatingPointTy())
1128 Value *Op = CI->getArgOperand(0);
1129 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1130 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1131 if (I->getOpcode() == Instruction::FMul)
1132 if (I->getOperand(0) == I->getOperand(1))
1138 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1139 Function *Callee = CI->getCalledFunction();
1141 Value *Ret = nullptr;
1142 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1143 Callee->getIntrinsicID() == Intrinsic::sqrt))
1144 Ret = optimizeUnaryDoubleFP(CI, B, true);
1146 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1147 // fast-math flag decorations that are applied to FP instructions. For now,
1148 // we have to rely on the function-level unsafe-fp-math attribute to do this
1149 // optimization because there's no other way to express that the sqrt can be
1151 Function *F = CI->getParent()->getParent();
1152 if (F->hasFnAttribute("unsafe-fp-math")) {
1153 // Check for unsafe-fp-math = true.
1154 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1155 if (Attr.getValueAsString() != "true")
1158 Value *Op = CI->getArgOperand(0);
1159 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1160 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1161 // We're looking for a repeated factor in a multiplication tree,
1162 // so we can do this fold: sqrt(x * x) -> fabs(x);
1163 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1164 Value *Op0 = I->getOperand(0);
1165 Value *Op1 = I->getOperand(1);
1166 Value *RepeatOp = nullptr;
1167 Value *OtherOp = nullptr;
1169 // Simple match: the operands of the multiply are identical.
1172 // Look for a more complicated pattern: one of the operands is itself
1173 // a multiply, so search for a common factor in that multiply.
1174 // Note: We don't bother looking any deeper than this first level or for
1175 // variations of this pattern because instcombine's visitFMUL and/or the
1176 // reassociation pass should give us this form.
1177 Value *OtherMul0, *OtherMul1;
1178 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1179 // Pattern: sqrt((x * y) * z)
1180 if (OtherMul0 == OtherMul1) {
1181 // Matched: sqrt((x * x) * z)
1182 RepeatOp = OtherMul0;
1188 // Fast math flags for any created instructions should match the sqrt
1190 // FIXME: We're not checking the sqrt because it doesn't have
1191 // fast-math-flags (see earlier comment).
1192 IRBuilder<true, ConstantFolder,
1193 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1194 B.SetFastMathFlags(I->getFastMathFlags());
1195 // If we found a repeated factor, hoist it out of the square root and
1196 // replace it with the fabs of that factor.
1197 Module *M = Callee->getParent();
1198 Type *ArgType = Op->getType();
1199 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1200 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1202 // If we found a non-repeated factor, we still need to get its square
1203 // root. We then multiply that by the value that was simplified out
1204 // of the square root calculation.
1205 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1206 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1207 return B.CreateFMul(FabsCall, SqrtCall);
1216 static bool isTrigLibCall(CallInst *CI);
1217 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1218 bool UseFloat, Value *&Sin, Value *&Cos,
1221 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1223 // Make sure the prototype is as expected, otherwise the rest of the
1224 // function is probably invalid and likely to abort.
1225 if (!isTrigLibCall(CI))
1228 Value *Arg = CI->getArgOperand(0);
1229 SmallVector<CallInst *, 1> SinCalls;
1230 SmallVector<CallInst *, 1> CosCalls;
1231 SmallVector<CallInst *, 1> SinCosCalls;
1233 bool IsFloat = Arg->getType()->isFloatTy();
1235 // Look for all compatible sinpi, cospi and sincospi calls with the same
1236 // argument. If there are enough (in some sense) we can make the
1238 for (User *U : Arg->users())
1239 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1242 // It's only worthwhile if both sinpi and cospi are actually used.
1243 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1246 Value *Sin, *Cos, *SinCos;
1247 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1249 replaceTrigInsts(SinCalls, Sin);
1250 replaceTrigInsts(CosCalls, Cos);
1251 replaceTrigInsts(SinCosCalls, SinCos);
1256 static bool isTrigLibCall(CallInst *CI) {
1257 Function *Callee = CI->getCalledFunction();
1258 FunctionType *FT = Callee->getFunctionType();
1260 // We can only hope to do anything useful if we can ignore things like errno
1261 // and floating-point exceptions.
1262 bool AttributesSafe =
1263 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1265 // Other than that we need float(float) or double(double)
1266 return AttributesSafe && FT->getNumParams() == 1 &&
1267 FT->getReturnType() == FT->getParamType(0) &&
1268 (FT->getParamType(0)->isFloatTy() ||
1269 FT->getParamType(0)->isDoubleTy());
1273 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1274 SmallVectorImpl<CallInst *> &SinCalls,
1275 SmallVectorImpl<CallInst *> &CosCalls,
1276 SmallVectorImpl<CallInst *> &SinCosCalls) {
1277 CallInst *CI = dyn_cast<CallInst>(Val);
1282 Function *Callee = CI->getCalledFunction();
1283 StringRef FuncName = Callee->getName();
1285 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1289 if (Func == LibFunc::sinpif)
1290 SinCalls.push_back(CI);
1291 else if (Func == LibFunc::cospif)
1292 CosCalls.push_back(CI);
1293 else if (Func == LibFunc::sincospif_stret)
1294 SinCosCalls.push_back(CI);
1296 if (Func == LibFunc::sinpi)
1297 SinCalls.push_back(CI);
1298 else if (Func == LibFunc::cospi)
1299 CosCalls.push_back(CI);
1300 else if (Func == LibFunc::sincospi_stret)
1301 SinCosCalls.push_back(CI);
1305 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1307 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1309 replaceAllUsesWith(*I, Res);
1313 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1314 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1315 Type *ArgTy = Arg->getType();
1319 Triple T(OrigCallee->getParent()->getTargetTriple());
1321 Name = "__sincospif_stret";
1323 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1324 // x86_64 can't use {float, float} since that would be returned in both
1325 // xmm0 and xmm1, which isn't what a real struct would do.
1326 ResTy = T.getArch() == Triple::x86_64
1327 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1328 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1330 Name = "__sincospi_stret";
1331 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1334 Module *M = OrigCallee->getParent();
1335 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1336 ResTy, ArgTy, nullptr);
1338 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1339 // If the argument is an instruction, it must dominate all uses so put our
1340 // sincos call there.
1341 BasicBlock::iterator Loc = ArgInst;
1342 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1344 // Otherwise (e.g. for a constant) the beginning of the function is as
1345 // good a place as any.
1346 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1347 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1350 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1352 if (SinCos->getType()->isStructTy()) {
1353 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1354 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1356 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1358 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1363 //===----------------------------------------------------------------------===//
1364 // Integer Library Call Optimizations
1365 //===----------------------------------------------------------------------===//
1367 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1368 Function *Callee = CI->getCalledFunction();
1369 FunctionType *FT = Callee->getFunctionType();
1370 // Just make sure this has 2 arguments of the same FP type, which match the
1372 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1373 !FT->getParamType(0)->isIntegerTy())
1376 Value *Op = CI->getArgOperand(0);
1379 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1380 if (CI->isZero()) // ffs(0) -> 0.
1381 return B.getInt32(0);
1382 // ffs(c) -> cttz(c)+1
1383 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1386 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1387 Type *ArgType = Op->getType();
1389 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1390 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1391 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1392 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1394 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1395 return B.CreateSelect(Cond, V, B.getInt32(0));
1398 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1399 Function *Callee = CI->getCalledFunction();
1400 FunctionType *FT = Callee->getFunctionType();
1401 // We require integer(integer) where the types agree.
1402 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1403 FT->getParamType(0) != FT->getReturnType())
1406 // abs(x) -> x >s -1 ? x : -x
1407 Value *Op = CI->getArgOperand(0);
1409 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1410 Value *Neg = B.CreateNeg(Op, "neg");
1411 return B.CreateSelect(Pos, Op, Neg);
1414 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1415 Function *Callee = CI->getCalledFunction();
1416 FunctionType *FT = Callee->getFunctionType();
1417 // We require integer(i32)
1418 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1419 !FT->getParamType(0)->isIntegerTy(32))
1422 // isdigit(c) -> (c-'0') <u 10
1423 Value *Op = CI->getArgOperand(0);
1424 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1425 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1426 return B.CreateZExt(Op, CI->getType());
1429 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1430 Function *Callee = CI->getCalledFunction();
1431 FunctionType *FT = Callee->getFunctionType();
1432 // We require integer(i32)
1433 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1434 !FT->getParamType(0)->isIntegerTy(32))
1437 // isascii(c) -> c <u 128
1438 Value *Op = CI->getArgOperand(0);
1439 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1440 return B.CreateZExt(Op, CI->getType());
1443 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1444 Function *Callee = CI->getCalledFunction();
1445 FunctionType *FT = Callee->getFunctionType();
1446 // We require i32(i32)
1447 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1448 !FT->getParamType(0)->isIntegerTy(32))
1451 // toascii(c) -> c & 0x7f
1452 return B.CreateAnd(CI->getArgOperand(0),
1453 ConstantInt::get(CI->getType(), 0x7F));
1456 //===----------------------------------------------------------------------===//
1457 // Formatting and IO Library Call Optimizations
1458 //===----------------------------------------------------------------------===//
1460 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1462 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1464 // Error reporting calls should be cold, mark them as such.
1465 // This applies even to non-builtin calls: it is only a hint and applies to
1466 // functions that the frontend might not understand as builtins.
1468 // This heuristic was suggested in:
1469 // Improving Static Branch Prediction in a Compiler
1470 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1471 // Proceedings of PACT'98, Oct. 1998, IEEE
1472 Function *Callee = CI->getCalledFunction();
1474 if (!CI->hasFnAttr(Attribute::Cold) &&
1475 isReportingError(Callee, CI, StreamArg)) {
1476 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1482 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1483 if (!ColdErrorCalls)
1486 if (!Callee || !Callee->isDeclaration())
1492 // These functions might be considered cold, but only if their stream
1493 // argument is stderr.
1495 if (StreamArg >= (int)CI->getNumArgOperands())
1497 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1500 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1501 if (!GV || !GV->isDeclaration())
1503 return GV->getName() == "stderr";
1506 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1507 // Check for a fixed format string.
1508 StringRef FormatStr;
1509 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1512 // Empty format string -> noop.
1513 if (FormatStr.empty()) // Tolerate printf's declared void.
1514 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1516 // Do not do any of the following transformations if the printf return value
1517 // is used, in general the printf return value is not compatible with either
1518 // putchar() or puts().
1519 if (!CI->use_empty())
1522 // printf("x") -> putchar('x'), even for '%'.
1523 if (FormatStr.size() == 1) {
1524 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1525 if (CI->use_empty() || !Res)
1527 return B.CreateIntCast(Res, CI->getType(), true);
1530 // printf("foo\n") --> puts("foo")
1531 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1532 FormatStr.find('%') == StringRef::npos) { // No format characters.
1533 // Create a string literal with no \n on it. We expect the constant merge
1534 // pass to be run after this pass, to merge duplicate strings.
1535 FormatStr = FormatStr.drop_back();
1536 Value *GV = B.CreateGlobalString(FormatStr, "str");
1537 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1538 return (CI->use_empty() || !NewCI)
1540 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1543 // Optimize specific format strings.
1544 // printf("%c", chr) --> putchar(chr)
1545 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1546 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1547 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1549 if (CI->use_empty() || !Res)
1551 return B.CreateIntCast(Res, CI->getType(), true);
1554 // printf("%s\n", str) --> puts(str)
1555 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1556 CI->getArgOperand(1)->getType()->isPointerTy()) {
1557 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1562 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1564 Function *Callee = CI->getCalledFunction();
1565 // Require one fixed pointer argument and an integer/void result.
1566 FunctionType *FT = Callee->getFunctionType();
1567 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1568 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1571 if (Value *V = optimizePrintFString(CI, B)) {
1575 // printf(format, ...) -> iprintf(format, ...) if no floating point
1577 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1578 Module *M = B.GetInsertBlock()->getParent()->getParent();
1579 Constant *IPrintFFn =
1580 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1581 CallInst *New = cast<CallInst>(CI->clone());
1582 New->setCalledFunction(IPrintFFn);
1589 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1590 // Check for a fixed format string.
1591 StringRef FormatStr;
1592 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1595 // If we just have a format string (nothing else crazy) transform it.
1596 if (CI->getNumArgOperands() == 2) {
1597 // Make sure there's no % in the constant array. We could try to handle
1598 // %% -> % in the future if we cared.
1599 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1600 if (FormatStr[i] == '%')
1601 return nullptr; // we found a format specifier, bail out.
1603 // These optimizations require DataLayout.
1607 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1609 CI->getArgOperand(0), CI->getArgOperand(1),
1610 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1611 FormatStr.size() + 1),
1612 1); // Copy the null byte.
1613 return ConstantInt::get(CI->getType(), FormatStr.size());
1616 // The remaining optimizations require the format string to be "%s" or "%c"
1617 // and have an extra operand.
1618 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1619 CI->getNumArgOperands() < 3)
1622 // Decode the second character of the format string.
1623 if (FormatStr[1] == 'c') {
1624 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1625 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1627 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1628 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1629 B.CreateStore(V, Ptr);
1630 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1631 B.CreateStore(B.getInt8(0), Ptr);
1633 return ConstantInt::get(CI->getType(), 1);
1636 if (FormatStr[1] == 's') {
1637 // These optimizations require DataLayout.
1641 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1642 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1645 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1649 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1650 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1652 // The sprintf result is the unincremented number of bytes in the string.
1653 return B.CreateIntCast(Len, CI->getType(), false);
1658 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1659 Function *Callee = CI->getCalledFunction();
1660 // Require two fixed pointer arguments and an integer result.
1661 FunctionType *FT = Callee->getFunctionType();
1662 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1663 !FT->getParamType(1)->isPointerTy() ||
1664 !FT->getReturnType()->isIntegerTy())
1667 if (Value *V = optimizeSPrintFString(CI, B)) {
1671 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1673 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1674 Module *M = B.GetInsertBlock()->getParent()->getParent();
1675 Constant *SIPrintFFn =
1676 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1677 CallInst *New = cast<CallInst>(CI->clone());
1678 New->setCalledFunction(SIPrintFFn);
1685 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1686 optimizeErrorReporting(CI, B, 0);
1688 // All the optimizations depend on the format string.
1689 StringRef FormatStr;
1690 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1693 // Do not do any of the following transformations if the fprintf return
1694 // value is used, in general the fprintf return value is not compatible
1695 // with fwrite(), fputc() or fputs().
1696 if (!CI->use_empty())
1699 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1700 if (CI->getNumArgOperands() == 2) {
1701 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1702 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1703 return nullptr; // We found a format specifier.
1705 // These optimizations require DataLayout.
1710 CI->getArgOperand(1),
1711 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1712 CI->getArgOperand(0), B, DL, TLI);
1715 // The remaining optimizations require the format string to be "%s" or "%c"
1716 // and have an extra operand.
1717 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1718 CI->getNumArgOperands() < 3)
1721 // Decode the second character of the format string.
1722 if (FormatStr[1] == 'c') {
1723 // fprintf(F, "%c", chr) --> fputc(chr, F)
1724 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1726 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1729 if (FormatStr[1] == 's') {
1730 // fprintf(F, "%s", str) --> fputs(str, F)
1731 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1733 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1738 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1739 Function *Callee = CI->getCalledFunction();
1740 // Require two fixed paramters as pointers and integer result.
1741 FunctionType *FT = Callee->getFunctionType();
1742 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1743 !FT->getParamType(1)->isPointerTy() ||
1744 !FT->getReturnType()->isIntegerTy())
1747 if (Value *V = optimizeFPrintFString(CI, B)) {
1751 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1752 // floating point arguments.
1753 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1754 Module *M = B.GetInsertBlock()->getParent()->getParent();
1755 Constant *FIPrintFFn =
1756 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1757 CallInst *New = cast<CallInst>(CI->clone());
1758 New->setCalledFunction(FIPrintFFn);
1765 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1766 optimizeErrorReporting(CI, B, 3);
1768 Function *Callee = CI->getCalledFunction();
1769 // Require a pointer, an integer, an integer, a pointer, returning integer.
1770 FunctionType *FT = Callee->getFunctionType();
1771 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1772 !FT->getParamType(1)->isIntegerTy() ||
1773 !FT->getParamType(2)->isIntegerTy() ||
1774 !FT->getParamType(3)->isPointerTy() ||
1775 !FT->getReturnType()->isIntegerTy())
1778 // Get the element size and count.
1779 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1780 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1781 if (!SizeC || !CountC)
1783 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1785 // If this is writing zero records, remove the call (it's a noop).
1787 return ConstantInt::get(CI->getType(), 0);
1789 // If this is writing one byte, turn it into fputc.
1790 // This optimisation is only valid, if the return value is unused.
1791 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1792 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1793 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1794 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1800 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1801 optimizeErrorReporting(CI, B, 1);
1803 Function *Callee = CI->getCalledFunction();
1805 // These optimizations require DataLayout.
1809 // Require two pointers. Also, we can't optimize if return value is used.
1810 FunctionType *FT = Callee->getFunctionType();
1811 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1812 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1815 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1816 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1820 // Known to have no uses (see above).
1822 CI->getArgOperand(0),
1823 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1824 CI->getArgOperand(1), B, DL, TLI);
1827 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1828 Function *Callee = CI->getCalledFunction();
1829 // Require one fixed pointer argument and an integer/void result.
1830 FunctionType *FT = Callee->getFunctionType();
1831 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1832 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1835 // Check for a constant string.
1837 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1840 if (Str.empty() && CI->use_empty()) {
1841 // puts("") -> putchar('\n')
1842 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
1843 if (CI->use_empty() || !Res)
1845 return B.CreateIntCast(Res, CI->getType(), true);
1851 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1853 SmallString<20> FloatFuncName = FuncName;
1854 FloatFuncName += 'f';
1855 if (TLI->getLibFunc(FloatFuncName, Func))
1856 return TLI->has(Func);
1860 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1861 IRBuilder<> &Builder) {
1863 Function *Callee = CI->getCalledFunction();
1864 StringRef FuncName = Callee->getName();
1866 // Check for string/memory library functions.
1867 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1868 // Make sure we never change the calling convention.
1869 assert((ignoreCallingConv(Func) ||
1870 CI->getCallingConv() == llvm::CallingConv::C) &&
1871 "Optimizing string/memory libcall would change the calling convention");
1873 case LibFunc::strcat:
1874 return optimizeStrCat(CI, Builder);
1875 case LibFunc::strncat:
1876 return optimizeStrNCat(CI, Builder);
1877 case LibFunc::strchr:
1878 return optimizeStrChr(CI, Builder);
1879 case LibFunc::strrchr:
1880 return optimizeStrRChr(CI, Builder);
1881 case LibFunc::strcmp:
1882 return optimizeStrCmp(CI, Builder);
1883 case LibFunc::strncmp:
1884 return optimizeStrNCmp(CI, Builder);
1885 case LibFunc::strcpy:
1886 return optimizeStrCpy(CI, Builder);
1887 case LibFunc::stpcpy:
1888 return optimizeStpCpy(CI, Builder);
1889 case LibFunc::strncpy:
1890 return optimizeStrNCpy(CI, Builder);
1891 case LibFunc::strlen:
1892 return optimizeStrLen(CI, Builder);
1893 case LibFunc::strpbrk:
1894 return optimizeStrPBrk(CI, Builder);
1895 case LibFunc::strtol:
1896 case LibFunc::strtod:
1897 case LibFunc::strtof:
1898 case LibFunc::strtoul:
1899 case LibFunc::strtoll:
1900 case LibFunc::strtold:
1901 case LibFunc::strtoull:
1902 return optimizeStrTo(CI, Builder);
1903 case LibFunc::strspn:
1904 return optimizeStrSpn(CI, Builder);
1905 case LibFunc::strcspn:
1906 return optimizeStrCSpn(CI, Builder);
1907 case LibFunc::strstr:
1908 return optimizeStrStr(CI, Builder);
1909 case LibFunc::memcmp:
1910 return optimizeMemCmp(CI, Builder);
1911 case LibFunc::memcpy:
1912 return optimizeMemCpy(CI, Builder);
1913 case LibFunc::memmove:
1914 return optimizeMemMove(CI, Builder);
1915 case LibFunc::memset:
1916 return optimizeMemSet(CI, Builder);
1924 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1925 if (CI->isNoBuiltin())
1929 Function *Callee = CI->getCalledFunction();
1930 StringRef FuncName = Callee->getName();
1931 IRBuilder<> Builder(CI);
1932 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1934 // Command-line parameter overrides function attribute.
1935 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1936 UnsafeFPShrink = EnableUnsafeFPShrink;
1937 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
1938 // FIXME: This is the same problem as described in optimizeSqrt().
1939 // If calls gain access to IR-level FMF, then use that instead of a
1940 // function attribute.
1942 // Check for unsafe-fp-math = true.
1943 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
1944 if (Attr.getValueAsString() == "true")
1945 UnsafeFPShrink = true;
1948 // First, check for intrinsics.
1949 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1950 if (!isCallingConvC)
1952 switch (II->getIntrinsicID()) {
1953 case Intrinsic::pow:
1954 return optimizePow(CI, Builder);
1955 case Intrinsic::exp2:
1956 return optimizeExp2(CI, Builder);
1957 case Intrinsic::fabs:
1958 return optimizeFabs(CI, Builder);
1959 case Intrinsic::sqrt:
1960 return optimizeSqrt(CI, Builder);
1966 // Also try to simplify calls to fortified library functions.
1967 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
1968 // Try to further simplify the result.
1969 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
1970 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
1971 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder))
1973 return SimplifiedFortifiedCI;
1976 // Then check for known library functions.
1977 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1978 // We never change the calling convention.
1979 if (!ignoreCallingConv(Func) && !isCallingConvC)
1981 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
1987 return optimizeCos(CI, Builder);
1988 case LibFunc::sinpif:
1989 case LibFunc::sinpi:
1990 case LibFunc::cospif:
1991 case LibFunc::cospi:
1992 return optimizeSinCosPi(CI, Builder);
1996 return optimizePow(CI, Builder);
1997 case LibFunc::exp2l:
1999 case LibFunc::exp2f:
2000 return optimizeExp2(CI, Builder);
2001 case LibFunc::fabsf:
2003 case LibFunc::fabsl:
2004 return optimizeFabs(CI, Builder);
2005 case LibFunc::sqrtf:
2007 case LibFunc::sqrtl:
2008 return optimizeSqrt(CI, Builder);
2011 case LibFunc::ffsll:
2012 return optimizeFFS(CI, Builder);
2015 case LibFunc::llabs:
2016 return optimizeAbs(CI, Builder);
2017 case LibFunc::isdigit:
2018 return optimizeIsDigit(CI, Builder);
2019 case LibFunc::isascii:
2020 return optimizeIsAscii(CI, Builder);
2021 case LibFunc::toascii:
2022 return optimizeToAscii(CI, Builder);
2023 case LibFunc::printf:
2024 return optimizePrintF(CI, Builder);
2025 case LibFunc::sprintf:
2026 return optimizeSPrintF(CI, Builder);
2027 case LibFunc::fprintf:
2028 return optimizeFPrintF(CI, Builder);
2029 case LibFunc::fwrite:
2030 return optimizeFWrite(CI, Builder);
2031 case LibFunc::fputs:
2032 return optimizeFPuts(CI, Builder);
2034 return optimizePuts(CI, Builder);
2035 case LibFunc::perror:
2036 return optimizeErrorReporting(CI, Builder);
2037 case LibFunc::vfprintf:
2038 case LibFunc::fiprintf:
2039 return optimizeErrorReporting(CI, Builder, 0);
2040 case LibFunc::fputc:
2041 return optimizeErrorReporting(CI, Builder, 1);
2043 case LibFunc::floor:
2045 case LibFunc::round:
2046 case LibFunc::nearbyint:
2047 case LibFunc::trunc:
2048 if (hasFloatVersion(FuncName))
2049 return optimizeUnaryDoubleFP(CI, Builder, false);
2052 case LibFunc::acosh:
2054 case LibFunc::asinh:
2056 case LibFunc::atanh:
2060 case LibFunc::exp10:
2061 case LibFunc::expm1:
2063 case LibFunc::log10:
2064 case LibFunc::log1p:
2071 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2072 return optimizeUnaryDoubleFP(CI, Builder, true);
2074 case LibFunc::copysign:
2077 if (hasFloatVersion(FuncName))
2078 return optimizeBinaryDoubleFP(CI, Builder);
2087 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2088 const TargetLibraryInfo *TLI) :
2089 FortifiedSimplifier(DL, TLI),
2092 UnsafeFPShrink(false) {
2095 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2096 I->replaceAllUsesWith(With);
2097 I->eraseFromParent();
2101 // Additional cases that we need to add to this file:
2104 // * cbrt(expN(X)) -> expN(x/3)
2105 // * cbrt(sqrt(x)) -> pow(x,1/6)
2106 // * cbrt(sqrt(x)) -> pow(x,1/9)
2109 // * exp(log(x)) -> x
2112 // * log(exp(x)) -> x
2113 // * log(x**y) -> y*log(x)
2114 // * log(exp(y)) -> y*log(e)
2115 // * log(exp2(y)) -> y*log(2)
2116 // * log(exp10(y)) -> y*log(10)
2117 // * log(sqrt(x)) -> 0.5*log(x)
2118 // * log(pow(x,y)) -> y*log(x)
2120 // lround, lroundf, lroundl:
2121 // * lround(cnst) -> cnst'
2124 // * pow(exp(x),y) -> exp(x*y)
2125 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2126 // * pow(pow(x,y),z)-> pow(x,y*z)
2128 // round, roundf, roundl:
2129 // * round(cnst) -> cnst'
2132 // * signbit(cnst) -> cnst'
2133 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2135 // sqrt, sqrtf, sqrtl:
2136 // * sqrt(expN(x)) -> expN(x*0.5)
2137 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2138 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2141 // * tan(atan(x)) -> x
2143 // trunc, truncf, truncl:
2144 // * trunc(cnst) -> cnst'
2148 //===----------------------------------------------------------------------===//
2149 // Fortified Library Call Optimizations
2150 //===----------------------------------------------------------------------===//
2152 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2156 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2158 if (ConstantInt *ObjSizeCI =
2159 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2160 if (ObjSizeCI->isAllOnesValue())
2162 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2163 if (OnlyLowerUnknownSize)
2166 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2167 // If the length is 0 we don't know how long it is and so we can't
2168 // remove the check.
2171 return ObjSizeCI->getZExtValue() >= Len;
2173 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2174 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2179 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2180 Function *Callee = CI->getCalledFunction();
2182 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk, DL))
2185 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2186 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2187 CI->getArgOperand(2), 1);
2188 return CI->getArgOperand(0);
2193 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2194 Function *Callee = CI->getCalledFunction();
2196 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk, DL))
2199 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2200 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2201 CI->getArgOperand(2), 1);
2202 return CI->getArgOperand(0);
2207 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2208 Function *Callee = CI->getCalledFunction();
2210 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk, DL))
2213 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2214 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2215 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2216 return CI->getArgOperand(0);
2221 Value *FortifiedLibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
2222 Function *Callee = CI->getCalledFunction();
2223 StringRef Name = Callee->getName();
2224 LibFunc::Func Func =
2225 Name.startswith("str") ? LibFunc::strcpy_chk : LibFunc::stpcpy_chk;
2227 if (!checkStringCopyLibFuncSignature(Callee, Func, DL))
2230 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2231 *ObjSize = CI->getArgOperand(2);
2233 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2234 if (!OnlyLowerUnknownSize && Dst == Src) {
2235 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2236 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
2239 // If a) we don't have any length information, or b) we know this will
2240 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2241 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2242 // TODO: It might be nice to get a maximum length out of the possible
2243 // string lengths for varying.
2244 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
2245 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
2247 } else if (!OnlyLowerUnknownSize) {
2248 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2249 uint64_t Len = GetStringLength(Src);
2253 // This optimization requires DataLayout.
2257 Type *SizeTTy = DL->getIntPtrType(CI->getContext());
2258 Value *LenV = ConstantInt::get(SizeTTy, Len);
2259 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2260 // If the function was an __stpcpy_chk, and we were able to fold it into
2261 // a __memcpy_chk, we still need to return the correct end pointer.
2262 if (Ret && Func == LibFunc::stpcpy_chk)
2263 return B.CreateGEP(Dst, ConstantInt::get(SizeTTy, Len - 1));
2269 Value *FortifiedLibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
2270 Function *Callee = CI->getCalledFunction();
2271 StringRef Name = Callee->getName();
2272 LibFunc::Func Func =
2273 Name.startswith("str") ? LibFunc::strncpy_chk : LibFunc::stpncpy_chk;
2275 if (!checkStringCopyLibFuncSignature(Callee, Func, DL))
2277 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2279 EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2280 CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
2286 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2287 if (CI->isNoBuiltin())
2291 Function *Callee = CI->getCalledFunction();
2292 StringRef FuncName = Callee->getName();
2293 IRBuilder<> Builder(CI);
2294 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2296 // First, check that this is a known library functions.
2297 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func))
2300 // We never change the calling convention.
2301 if (!ignoreCallingConv(Func) && !isCallingConvC)
2305 case LibFunc::memcpy_chk:
2306 return optimizeMemCpyChk(CI, Builder);
2307 case LibFunc::memmove_chk:
2308 return optimizeMemMoveChk(CI, Builder);
2309 case LibFunc::memset_chk:
2310 return optimizeMemSetChk(CI, Builder);
2311 case LibFunc::stpcpy_chk:
2312 case LibFunc::strcpy_chk:
2313 return optimizeStrCpyChk(CI, Builder);
2314 case LibFunc::stpncpy_chk:
2315 case LibFunc::strncpy_chk:
2316 return optimizeStrNCpyChk(CI, Builder);
2323 FortifiedLibCallSimplifier::
2324 FortifiedLibCallSimplifier(const DataLayout *DL, const TargetLibraryInfo *TLI,
2325 bool OnlyLowerUnknownSize)
2326 : DL(DL), TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {