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"
35 #include "llvm/Transforms/Utils/Local.h"
38 using namespace PatternMatch;
41 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static bool ignoreCallingConv(LibFunc::Func Func) {
65 llvm_unreachable("All cases should be covered in the switch.");
68 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
69 /// value is equal or not-equal to zero.
70 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
71 for (User *U : V->users()) {
72 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
74 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
77 // Unknown instruction.
83 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
84 /// comparisons with With.
85 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
86 for (User *U : V->users()) {
87 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
88 if (IC->isEquality() && IC->getOperand(1) == With)
90 // Unknown instruction.
96 static bool callHasFloatingPointArgument(const CallInst *CI) {
97 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
99 if ((*it)->getType()->isFloatingPointTy())
105 /// \brief Check whether the overloaded unary floating point function
106 /// corresponding to \a Ty is available.
107 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
108 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
109 LibFunc::Func LongDoubleFn) {
110 switch (Ty->getTypeID()) {
111 case Type::FloatTyID:
112 return TLI->has(FloatFn);
113 case Type::DoubleTyID:
114 return TLI->has(DoubleFn);
116 return TLI->has(LongDoubleFn);
120 /// \brief Check whether we can use unsafe floating point math for
121 /// the function passed as input.
122 static bool canUseUnsafeFPMath(Function *F) {
124 // FIXME: For finer-grain optimization, we need intrinsics to have the same
125 // fast-math flag decorations that are applied to FP instructions. For now,
126 // we have to rely on the function-level unsafe-fp-math attribute to do this
127 // optimization because there's no other way to express that the sqrt can be
129 if (F->hasFnAttribute("unsafe-fp-math")) {
130 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
131 if (Attr.getValueAsString() == "true")
137 /// \brief Returns whether \p F matches the signature expected for the
138 /// string/memory copying library function \p Func.
139 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
140 /// Their fortified (_chk) counterparts are also accepted.
141 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
142 const DataLayout &DL = F->getParent()->getDataLayout();
143 FunctionType *FT = F->getFunctionType();
144 LLVMContext &Context = F->getContext();
145 Type *PCharTy = Type::getInt8PtrTy(Context);
146 Type *SizeTTy = DL.getIntPtrType(Context);
147 unsigned NumParams = FT->getNumParams();
149 // All string libfuncs return the same type as the first parameter.
150 if (FT->getReturnType() != FT->getParamType(0))
155 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
156 case LibFunc::stpncpy_chk:
157 case LibFunc::strncpy_chk:
158 --NumParams; // fallthrough
159 case LibFunc::stpncpy:
160 case LibFunc::strncpy: {
161 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
162 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
166 case LibFunc::strcpy_chk:
167 case LibFunc::stpcpy_chk:
168 --NumParams; // fallthrough
169 case LibFunc::stpcpy:
170 case LibFunc::strcpy: {
171 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
172 FT->getParamType(0) != PCharTy)
176 case LibFunc::memmove_chk:
177 case LibFunc::memcpy_chk:
178 --NumParams; // fallthrough
179 case LibFunc::memmove:
180 case LibFunc::memcpy: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
186 case LibFunc::memset_chk:
187 --NumParams; // fallthrough
188 case LibFunc::memset: {
189 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
190 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
195 // If this is a fortified libcall, the last parameter is a size_t.
196 if (NumParams == FT->getNumParams() - 1)
197 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
201 //===----------------------------------------------------------------------===//
202 // String and Memory Library Call Optimizations
203 //===----------------------------------------------------------------------===//
205 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
206 Function *Callee = CI->getCalledFunction();
207 // Verify the "strcat" function prototype.
208 FunctionType *FT = Callee->getFunctionType();
209 if (FT->getNumParams() != 2||
210 FT->getReturnType() != B.getInt8PtrTy() ||
211 FT->getParamType(0) != FT->getReturnType() ||
212 FT->getParamType(1) != FT->getReturnType())
215 // Extract some information from the instruction
216 Value *Dst = CI->getArgOperand(0);
217 Value *Src = CI->getArgOperand(1);
219 // See if we can get the length of the input string.
220 uint64_t Len = GetStringLength(Src);
223 --Len; // Unbias length.
225 // Handle the simple, do-nothing case: strcat(x, "") -> x
229 return emitStrLenMemCpy(Src, Dst, Len, B);
232 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
234 // We need to find the end of the destination string. That's where the
235 // memory is to be moved to. We just generate a call to strlen.
236 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
240 // Now that we have the destination's length, we must index into the
241 // destination's pointer to get the actual memcpy destination (end of
242 // the string .. we're concatenating).
243 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
245 // We have enough information to now generate the memcpy call to do the
246 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
247 B.CreateMemCpy(CpyDst, Src,
248 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
253 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
254 Function *Callee = CI->getCalledFunction();
255 // Verify the "strncat" function prototype.
256 FunctionType *FT = Callee->getFunctionType();
257 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
258 FT->getParamType(0) != FT->getReturnType() ||
259 FT->getParamType(1) != FT->getReturnType() ||
260 !FT->getParamType(2)->isIntegerTy())
263 // Extract some information from the instruction
264 Value *Dst = CI->getArgOperand(0);
265 Value *Src = CI->getArgOperand(1);
268 // We don't do anything if length is not constant
269 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
270 Len = LengthArg->getZExtValue();
274 // See if we can get the length of the input string.
275 uint64_t SrcLen = GetStringLength(Src);
278 --SrcLen; // Unbias length.
280 // Handle the simple, do-nothing cases:
281 // strncat(x, "", c) -> x
282 // strncat(x, c, 0) -> x
283 if (SrcLen == 0 || Len == 0)
286 // We don't optimize this case
290 // strncat(x, s, c) -> strcat(x, s)
291 // s is constant so the strcat can be optimized further
292 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
295 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
296 Function *Callee = CI->getCalledFunction();
297 // Verify the "strchr" function prototype.
298 FunctionType *FT = Callee->getFunctionType();
299 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
300 FT->getParamType(0) != FT->getReturnType() ||
301 !FT->getParamType(1)->isIntegerTy(32))
304 Value *SrcStr = CI->getArgOperand(0);
306 // If the second operand is non-constant, see if we can compute the length
307 // of the input string and turn this into memchr.
308 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
310 uint64_t Len = GetStringLength(SrcStr);
311 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
314 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
315 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
319 // Otherwise, the character is a constant, see if the first argument is
320 // a string literal. If so, we can constant fold.
322 if (!getConstantStringInfo(SrcStr, Str)) {
323 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
324 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
328 // Compute the offset, make sure to handle the case when we're searching for
329 // zero (a weird way to spell strlen).
330 size_t I = (0xFF & CharC->getSExtValue()) == 0
332 : Str.find(CharC->getSExtValue());
333 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
334 return Constant::getNullValue(CI->getType());
336 // strchr(s+n,c) -> gep(s+n+i,c)
337 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
340 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
341 Function *Callee = CI->getCalledFunction();
342 // Verify the "strrchr" function prototype.
343 FunctionType *FT = Callee->getFunctionType();
344 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
345 FT->getParamType(0) != FT->getReturnType() ||
346 !FT->getParamType(1)->isIntegerTy(32))
349 Value *SrcStr = CI->getArgOperand(0);
350 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
352 // Cannot fold anything if we're not looking for a constant.
357 if (!getConstantStringInfo(SrcStr, Str)) {
358 // strrchr(s, 0) -> strchr(s, 0)
360 return EmitStrChr(SrcStr, '\0', B, TLI);
364 // Compute the offset.
365 size_t I = (0xFF & CharC->getSExtValue()) == 0
367 : Str.rfind(CharC->getSExtValue());
368 if (I == StringRef::npos) // Didn't find the char. Return null.
369 return Constant::getNullValue(CI->getType());
371 // strrchr(s+n,c) -> gep(s+n+i,c)
372 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
375 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
376 Function *Callee = CI->getCalledFunction();
377 // Verify the "strcmp" function prototype.
378 FunctionType *FT = Callee->getFunctionType();
379 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
380 FT->getParamType(0) != FT->getParamType(1) ||
381 FT->getParamType(0) != B.getInt8PtrTy())
384 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
385 if (Str1P == Str2P) // strcmp(x,x) -> 0
386 return ConstantInt::get(CI->getType(), 0);
388 StringRef Str1, Str2;
389 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
390 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
392 // strcmp(x, y) -> cnst (if both x and y are constant strings)
393 if (HasStr1 && HasStr2)
394 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
396 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
398 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
400 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
401 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
403 // strcmp(P, "x") -> memcmp(P, "x", 2)
404 uint64_t Len1 = GetStringLength(Str1P);
405 uint64_t Len2 = GetStringLength(Str2P);
407 return EmitMemCmp(Str1P, Str2P,
408 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
409 std::min(Len1, Len2)),
416 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
417 Function *Callee = CI->getCalledFunction();
418 // Verify the "strncmp" function prototype.
419 FunctionType *FT = Callee->getFunctionType();
420 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
421 FT->getParamType(0) != FT->getParamType(1) ||
422 FT->getParamType(0) != B.getInt8PtrTy() ||
423 !FT->getParamType(2)->isIntegerTy())
426 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
427 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
428 return ConstantInt::get(CI->getType(), 0);
430 // Get the length argument if it is constant.
432 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
433 Length = LengthArg->getZExtValue();
437 if (Length == 0) // strncmp(x,y,0) -> 0
438 return ConstantInt::get(CI->getType(), 0);
440 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
441 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
443 StringRef Str1, Str2;
444 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
445 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
447 // strncmp(x, y) -> cnst (if both x and y are constant strings)
448 if (HasStr1 && HasStr2) {
449 StringRef SubStr1 = Str1.substr(0, Length);
450 StringRef SubStr2 = Str2.substr(0, Length);
451 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
454 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
456 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
458 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
459 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
464 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
465 Function *Callee = CI->getCalledFunction();
467 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
470 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
471 if (Dst == Src) // strcpy(x,x) -> x
474 // See if we can get the length of the input string.
475 uint64_t Len = GetStringLength(Src);
479 // We have enough information to now generate the memcpy call to do the
480 // copy for us. Make a memcpy to copy the nul byte with align = 1.
481 B.CreateMemCpy(Dst, Src,
482 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
486 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
487 Function *Callee = CI->getCalledFunction();
488 // Verify the "stpcpy" function prototype.
489 FunctionType *FT = Callee->getFunctionType();
491 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
494 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
495 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
496 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
497 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
500 // See if we can get the length of the input string.
501 uint64_t Len = GetStringLength(Src);
505 Type *PT = FT->getParamType(0);
506 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
508 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
510 // We have enough information to now generate the memcpy call to do the
511 // copy for us. Make a memcpy to copy the nul byte with align = 1.
512 B.CreateMemCpy(Dst, Src, LenV, 1);
516 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
517 Function *Callee = CI->getCalledFunction();
518 FunctionType *FT = Callee->getFunctionType();
520 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
523 Value *Dst = CI->getArgOperand(0);
524 Value *Src = CI->getArgOperand(1);
525 Value *LenOp = CI->getArgOperand(2);
527 // See if we can get the length of the input string.
528 uint64_t SrcLen = GetStringLength(Src);
534 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
535 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
540 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
541 Len = LengthArg->getZExtValue();
546 return Dst; // strncpy(x, y, 0) -> x
548 // Let strncpy handle the zero padding
549 if (Len > SrcLen + 1)
552 Type *PT = FT->getParamType(0);
553 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
554 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
559 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
560 Function *Callee = CI->getCalledFunction();
561 FunctionType *FT = Callee->getFunctionType();
562 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
563 !FT->getReturnType()->isIntegerTy())
566 Value *Src = CI->getArgOperand(0);
568 // Constant folding: strlen("xyz") -> 3
569 if (uint64_t Len = GetStringLength(Src))
570 return ConstantInt::get(CI->getType(), Len - 1);
572 // strlen(x?"foo":"bars") --> x ? 3 : 4
573 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
574 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
575 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
576 if (LenTrue && LenFalse) {
577 Function *Caller = CI->getParent()->getParent();
578 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
580 "folded strlen(select) to select of constants");
581 return B.CreateSelect(SI->getCondition(),
582 ConstantInt::get(CI->getType(), LenTrue - 1),
583 ConstantInt::get(CI->getType(), LenFalse - 1));
587 // strlen(x) != 0 --> *x != 0
588 // strlen(x) == 0 --> *x == 0
589 if (isOnlyUsedInZeroEqualityComparison(CI))
590 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
595 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
596 Function *Callee = CI->getCalledFunction();
597 FunctionType *FT = Callee->getFunctionType();
598 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
599 FT->getParamType(1) != FT->getParamType(0) ||
600 FT->getReturnType() != FT->getParamType(0))
604 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
605 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
607 // strpbrk(s, "") -> nullptr
608 // strpbrk("", s) -> nullptr
609 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
610 return Constant::getNullValue(CI->getType());
613 if (HasS1 && HasS2) {
614 size_t I = S1.find_first_of(S2);
615 if (I == StringRef::npos) // No match.
616 return Constant::getNullValue(CI->getType());
618 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
621 // strpbrk(s, "a") -> strchr(s, 'a')
622 if (HasS2 && S2.size() == 1)
623 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
628 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
629 Function *Callee = CI->getCalledFunction();
630 FunctionType *FT = Callee->getFunctionType();
631 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
632 !FT->getParamType(0)->isPointerTy() ||
633 !FT->getParamType(1)->isPointerTy())
636 Value *EndPtr = CI->getArgOperand(1);
637 if (isa<ConstantPointerNull>(EndPtr)) {
638 // With a null EndPtr, this function won't capture the main argument.
639 // It would be readonly too, except that it still may write to errno.
640 CI->addAttribute(1, Attribute::NoCapture);
646 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
647 Function *Callee = CI->getCalledFunction();
648 FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
650 FT->getParamType(1) != FT->getParamType(0) ||
651 !FT->getReturnType()->isIntegerTy())
655 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
656 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
658 // strspn(s, "") -> 0
659 // strspn("", s) -> 0
660 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
661 return Constant::getNullValue(CI->getType());
664 if (HasS1 && HasS2) {
665 size_t Pos = S1.find_first_not_of(S2);
666 if (Pos == StringRef::npos)
668 return ConstantInt::get(CI->getType(), Pos);
674 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
675 Function *Callee = CI->getCalledFunction();
676 FunctionType *FT = Callee->getFunctionType();
677 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
678 FT->getParamType(1) != FT->getParamType(0) ||
679 !FT->getReturnType()->isIntegerTy())
683 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
684 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
686 // strcspn("", s) -> 0
687 if (HasS1 && S1.empty())
688 return Constant::getNullValue(CI->getType());
691 if (HasS1 && HasS2) {
692 size_t Pos = S1.find_first_of(S2);
693 if (Pos == StringRef::npos)
695 return ConstantInt::get(CI->getType(), Pos);
698 // strcspn(s, "") -> strlen(s)
699 if (HasS2 && S2.empty())
700 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
705 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
706 Function *Callee = CI->getCalledFunction();
707 FunctionType *FT = Callee->getFunctionType();
708 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
709 !FT->getParamType(1)->isPointerTy() ||
710 !FT->getReturnType()->isPointerTy())
713 // fold strstr(x, x) -> x.
714 if (CI->getArgOperand(0) == CI->getArgOperand(1))
715 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
717 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
718 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
719 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
722 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
726 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
727 ICmpInst *Old = cast<ICmpInst>(*UI++);
729 B.CreateICmp(Old->getPredicate(), StrNCmp,
730 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
731 replaceAllUsesWith(Old, Cmp);
736 // See if either input string is a constant string.
737 StringRef SearchStr, ToFindStr;
738 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
739 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
741 // fold strstr(x, "") -> x.
742 if (HasStr2 && ToFindStr.empty())
743 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
745 // If both strings are known, constant fold it.
746 if (HasStr1 && HasStr2) {
747 size_t Offset = SearchStr.find(ToFindStr);
749 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
750 return Constant::getNullValue(CI->getType());
752 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
753 Value *Result = CastToCStr(CI->getArgOperand(0), B);
754 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
755 return B.CreateBitCast(Result, CI->getType());
758 // fold strstr(x, "y") -> strchr(x, 'y').
759 if (HasStr2 && ToFindStr.size() == 1) {
760 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
761 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
766 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
767 Function *Callee = CI->getCalledFunction();
768 FunctionType *FT = Callee->getFunctionType();
769 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
770 !FT->getParamType(1)->isIntegerTy(32) ||
771 !FT->getParamType(2)->isIntegerTy() ||
772 !FT->getReturnType()->isPointerTy())
775 Value *SrcStr = CI->getArgOperand(0);
776 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
777 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
779 // memchr(x, y, 0) -> null
780 if (LenC && LenC->isNullValue())
781 return Constant::getNullValue(CI->getType());
783 // From now on we need at least constant length and string.
785 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
788 // Truncate the string to LenC. If Str is smaller than LenC we will still only
789 // scan the string, as reading past the end of it is undefined and we can just
790 // return null if we don't find the char.
791 Str = Str.substr(0, LenC->getZExtValue());
793 // If the char is variable but the input str and length are not we can turn
794 // this memchr call into a simple bit field test. Of course this only works
795 // when the return value is only checked against null.
797 // It would be really nice to reuse switch lowering here but we can't change
798 // the CFG at this point.
800 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
801 // after bounds check.
802 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
804 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
805 reinterpret_cast<const unsigned char *>(Str.end()));
807 // Make sure the bit field we're about to create fits in a register on the
809 // FIXME: On a 64 bit architecture this prevents us from using the
810 // interesting range of alpha ascii chars. We could do better by emitting
811 // two bitfields or shifting the range by 64 if no lower chars are used.
812 if (!DL.fitsInLegalInteger(Max + 1))
815 // For the bit field use a power-of-2 type with at least 8 bits to avoid
816 // creating unnecessary illegal types.
817 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
819 // Now build the bit field.
820 APInt Bitfield(Width, 0);
822 Bitfield.setBit((unsigned char)C);
823 Value *BitfieldC = B.getInt(Bitfield);
825 // First check that the bit field access is within bounds.
826 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
827 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
830 // Create code that checks if the given bit is set in the field.
831 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
832 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
834 // Finally merge both checks and cast to pointer type. The inttoptr
835 // implicitly zexts the i1 to intptr type.
836 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
839 // Check if all arguments are constants. If so, we can constant fold.
843 // Compute the offset.
844 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
845 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
846 return Constant::getNullValue(CI->getType());
848 // memchr(s+n,c,l) -> gep(s+n+i,c)
849 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
852 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
853 Function *Callee = CI->getCalledFunction();
854 FunctionType *FT = Callee->getFunctionType();
855 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
856 !FT->getParamType(1)->isPointerTy() ||
857 !FT->getReturnType()->isIntegerTy(32))
860 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
862 if (LHS == RHS) // memcmp(s,s,x) -> 0
863 return Constant::getNullValue(CI->getType());
865 // Make sure we have a constant length.
866 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
869 uint64_t Len = LenC->getZExtValue();
871 if (Len == 0) // memcmp(s1,s2,0) -> 0
872 return Constant::getNullValue(CI->getType());
874 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
876 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
877 CI->getType(), "lhsv");
878 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
879 CI->getType(), "rhsv");
880 return B.CreateSub(LHSV, RHSV, "chardiff");
883 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
884 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
886 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
887 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
889 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
890 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
893 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
895 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
897 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
898 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
900 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
904 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
905 StringRef LHSStr, RHSStr;
906 if (getConstantStringInfo(LHS, LHSStr) &&
907 getConstantStringInfo(RHS, RHSStr)) {
908 // Make sure we're not reading out-of-bounds memory.
909 if (Len > LHSStr.size() || Len > RHSStr.size())
911 // Fold the memcmp and normalize the result. This way we get consistent
912 // results across multiple platforms.
914 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
919 return ConstantInt::get(CI->getType(), Ret);
925 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
926 Function *Callee = CI->getCalledFunction();
928 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
931 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
932 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
933 CI->getArgOperand(2), 1);
934 return CI->getArgOperand(0);
937 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
938 Function *Callee = CI->getCalledFunction();
940 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
943 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
944 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
945 CI->getArgOperand(2), 1);
946 return CI->getArgOperand(0);
949 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
950 Function *Callee = CI->getCalledFunction();
952 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
955 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
956 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
957 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
958 return CI->getArgOperand(0);
961 //===----------------------------------------------------------------------===//
962 // Math Library Optimizations
963 //===----------------------------------------------------------------------===//
965 /// Return a variant of Val with float type.
966 /// Currently this works in two cases: If Val is an FPExtension of a float
967 /// value to something bigger, simply return the operand.
968 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
969 /// loss of precision do so.
970 static Value *valueHasFloatPrecision(Value *Val) {
971 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
972 Value *Op = Cast->getOperand(0);
973 if (Op->getType()->isFloatTy())
976 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
977 APFloat F = Const->getValueAPF();
979 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
982 return ConstantFP::get(Const->getContext(), F);
987 //===----------------------------------------------------------------------===//
988 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
990 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
992 Function *Callee = CI->getCalledFunction();
993 FunctionType *FT = Callee->getFunctionType();
994 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
995 !FT->getParamType(0)->isDoubleTy())
999 // Check if all the uses for function like 'sin' are converted to float.
1000 for (User *U : CI->users()) {
1001 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1002 if (!Cast || !Cast->getType()->isFloatTy())
1007 // If this is something like 'floor((double)floatval)', convert to floorf.
1008 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1012 // floor((double)floatval) -> (double)floorf(floatval)
1013 if (Callee->isIntrinsic()) {
1014 Module *M = CI->getParent()->getParent()->getParent();
1015 Intrinsic::ID IID = Callee->getIntrinsicID();
1016 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1017 V = B.CreateCall(F, V);
1019 // The call is a library call rather than an intrinsic.
1020 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1023 return B.CreateFPExt(V, B.getDoubleTy());
1026 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1027 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1028 Function *Callee = CI->getCalledFunction();
1029 FunctionType *FT = Callee->getFunctionType();
1030 // Just make sure this has 2 arguments of the same FP type, which match the
1032 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1033 FT->getParamType(0) != FT->getParamType(1) ||
1034 !FT->getParamType(0)->isFloatingPointTy())
1037 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1038 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1039 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1042 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1046 // fmin((double)floatval1, (double)floatval2)
1047 // -> (double)fminf(floatval1, floatval2)
1048 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1049 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1050 Callee->getAttributes());
1051 return B.CreateFPExt(V, B.getDoubleTy());
1054 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1055 Function *Callee = CI->getCalledFunction();
1056 Value *Ret = nullptr;
1057 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1058 Ret = optimizeUnaryDoubleFP(CI, B, true);
1061 FunctionType *FT = Callee->getFunctionType();
1062 // Just make sure this has 1 argument of FP type, which matches the
1064 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1065 !FT->getParamType(0)->isFloatingPointTy())
1068 // cos(-x) -> cos(x)
1069 Value *Op1 = CI->getArgOperand(0);
1070 if (BinaryOperator::isFNeg(Op1)) {
1071 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1072 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1077 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1078 Function *Callee = CI->getCalledFunction();
1080 Value *Ret = nullptr;
1081 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1082 Ret = optimizeUnaryDoubleFP(CI, B, true);
1085 FunctionType *FT = Callee->getFunctionType();
1086 // Just make sure this has 2 arguments of the same FP type, which match the
1088 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1089 FT->getParamType(0) != FT->getParamType(1) ||
1090 !FT->getParamType(0)->isFloatingPointTy())
1093 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1094 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1095 // pow(1.0, x) -> 1.0
1096 if (Op1C->isExactlyValue(1.0))
1098 // pow(2.0, x) -> exp2(x)
1099 if (Op1C->isExactlyValue(2.0) &&
1100 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1102 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1103 // pow(10.0, x) -> exp10(x)
1104 if (Op1C->isExactlyValue(10.0) &&
1105 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1107 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1108 Callee->getAttributes());
1111 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1115 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1116 return ConstantFP::get(CI->getType(), 1.0);
1118 if (Op2C->isExactlyValue(0.5) &&
1119 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1121 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1123 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1124 // This is faster than calling pow, and still handles negative zero
1125 // and negative infinity correctly.
1126 // TODO: In fast-math mode, this could be just sqrt(x).
1127 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1128 Value *Inf = ConstantFP::getInfinity(CI->getType());
1129 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1130 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1132 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1133 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1134 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1138 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1140 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1141 return B.CreateFMul(Op1, Op1, "pow2");
1142 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1143 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1147 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1148 Function *Callee = CI->getCalledFunction();
1149 Function *Caller = CI->getParent()->getParent();
1151 Value *Ret = nullptr;
1152 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1153 TLI->has(LibFunc::exp2f)) {
1154 Ret = optimizeUnaryDoubleFP(CI, B, true);
1157 FunctionType *FT = Callee->getFunctionType();
1158 // Just make sure this has 1 argument of FP type, which matches the
1160 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1161 !FT->getParamType(0)->isFloatingPointTy())
1164 Value *Op = CI->getArgOperand(0);
1165 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1166 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1167 LibFunc::Func LdExp = LibFunc::ldexpl;
1168 if (Op->getType()->isFloatTy())
1169 LdExp = LibFunc::ldexpf;
1170 else if (Op->getType()->isDoubleTy())
1171 LdExp = LibFunc::ldexp;
1173 if (TLI->has(LdExp)) {
1174 Value *LdExpArg = nullptr;
1175 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1176 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1177 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1178 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1179 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1180 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1184 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1185 if (!Op->getType()->isFloatTy())
1186 One = ConstantExpr::getFPExtend(One, Op->getType());
1188 Module *M = Caller->getParent();
1190 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1191 Op->getType(), B.getInt32Ty(), nullptr);
1192 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1193 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1194 CI->setCallingConv(F->getCallingConv());
1202 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1203 Function *Callee = CI->getCalledFunction();
1205 Value *Ret = nullptr;
1206 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1207 Ret = optimizeUnaryDoubleFP(CI, B, false);
1210 FunctionType *FT = Callee->getFunctionType();
1211 // Make sure this has 1 argument of FP type which matches the result type.
1212 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1213 !FT->getParamType(0)->isFloatingPointTy())
1216 Value *Op = CI->getArgOperand(0);
1217 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1218 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1219 if (I->getOpcode() == Instruction::FMul)
1220 if (I->getOperand(0) == I->getOperand(1))
1226 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1227 // If we can shrink the call to a float function rather than a double
1228 // function, do that first.
1229 Function *Callee = CI->getCalledFunction();
1230 if ((Callee->getName() == "fmin" && TLI->has(LibFunc::fminf)) ||
1231 (Callee->getName() == "fmax" && TLI->has(LibFunc::fmaxf))) {
1232 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1237 // Make sure this has 2 arguments of FP type which match the result type.
1238 FunctionType *FT = Callee->getFunctionType();
1239 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1240 FT->getParamType(0) != FT->getParamType(1) ||
1241 !FT->getParamType(0)->isFloatingPointTy())
1244 IRBuilder<>::FastMathFlagGuard Guard(B);
1246 Function *F = CI->getParent()->getParent();
1247 if (canUseUnsafeFPMath(F)) {
1248 // Unsafe algebra sets all fast-math-flags to true.
1249 FMF.setUnsafeAlgebra();
1251 // At a minimum, no-nans-fp-math must be true.
1252 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
1253 if (Attr.getValueAsString() != "true")
1255 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1256 // "Ideally, fmax would be sensitive to the sign of zero, for example
1257 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1258 // might be impractical."
1259 FMF.setNoSignedZeros();
1262 B.SetFastMathFlags(FMF);
1264 // We have a relaxed floating-point environment. We can ignore NaN-handling
1265 // and transform to a compare and select. We do not have to consider errno or
1266 // exceptions, because fmin/fmax do not have those.
1267 Value *Op0 = CI->getArgOperand(0);
1268 Value *Op1 = CI->getArgOperand(1);
1269 Value *Cmp = Callee->getName().startswith("fmin") ?
1270 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1271 return B.CreateSelect(Cmp, Op0, Op1);
1274 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1275 Function *Callee = CI->getCalledFunction();
1277 Value *Ret = nullptr;
1278 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1279 Callee->getIntrinsicID() == Intrinsic::sqrt))
1280 Ret = optimizeUnaryDoubleFP(CI, B, true);
1281 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1284 Value *Op = CI->getArgOperand(0);
1285 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1286 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1287 // We're looking for a repeated factor in a multiplication tree,
1288 // so we can do this fold: sqrt(x * x) -> fabs(x);
1289 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1290 Value *Op0 = I->getOperand(0);
1291 Value *Op1 = I->getOperand(1);
1292 Value *RepeatOp = nullptr;
1293 Value *OtherOp = nullptr;
1295 // Simple match: the operands of the multiply are identical.
1298 // Look for a more complicated pattern: one of the operands is itself
1299 // a multiply, so search for a common factor in that multiply.
1300 // Note: We don't bother looking any deeper than this first level or for
1301 // variations of this pattern because instcombine's visitFMUL and/or the
1302 // reassociation pass should give us this form.
1303 Value *OtherMul0, *OtherMul1;
1304 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1305 // Pattern: sqrt((x * y) * z)
1306 if (OtherMul0 == OtherMul1) {
1307 // Matched: sqrt((x * x) * z)
1308 RepeatOp = OtherMul0;
1314 // Fast math flags for any created instructions should match the sqrt
1316 // FIXME: We're not checking the sqrt because it doesn't have
1317 // fast-math-flags (see earlier comment).
1318 IRBuilder<>::FastMathFlagGuard Guard(B);
1319 B.SetFastMathFlags(I->getFastMathFlags());
1320 // If we found a repeated factor, hoist it out of the square root and
1321 // replace it with the fabs of that factor.
1322 Module *M = Callee->getParent();
1323 Type *ArgType = Op->getType();
1324 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1325 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1327 // If we found a non-repeated factor, we still need to get its square
1328 // root. We then multiply that by the value that was simplified out
1329 // of the square root calculation.
1330 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1331 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1332 return B.CreateFMul(FabsCall, SqrtCall);
1341 static bool isTrigLibCall(CallInst *CI);
1342 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1343 bool UseFloat, Value *&Sin, Value *&Cos,
1346 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1348 // Make sure the prototype is as expected, otherwise the rest of the
1349 // function is probably invalid and likely to abort.
1350 if (!isTrigLibCall(CI))
1353 Value *Arg = CI->getArgOperand(0);
1354 SmallVector<CallInst *, 1> SinCalls;
1355 SmallVector<CallInst *, 1> CosCalls;
1356 SmallVector<CallInst *, 1> SinCosCalls;
1358 bool IsFloat = Arg->getType()->isFloatTy();
1360 // Look for all compatible sinpi, cospi and sincospi calls with the same
1361 // argument. If there are enough (in some sense) we can make the
1363 for (User *U : Arg->users())
1364 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1367 // It's only worthwhile if both sinpi and cospi are actually used.
1368 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1371 Value *Sin, *Cos, *SinCos;
1372 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1374 replaceTrigInsts(SinCalls, Sin);
1375 replaceTrigInsts(CosCalls, Cos);
1376 replaceTrigInsts(SinCosCalls, SinCos);
1381 static bool isTrigLibCall(CallInst *CI) {
1382 Function *Callee = CI->getCalledFunction();
1383 FunctionType *FT = Callee->getFunctionType();
1385 // We can only hope to do anything useful if we can ignore things like errno
1386 // and floating-point exceptions.
1387 bool AttributesSafe =
1388 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1390 // Other than that we need float(float) or double(double)
1391 return AttributesSafe && FT->getNumParams() == 1 &&
1392 FT->getReturnType() == FT->getParamType(0) &&
1393 (FT->getParamType(0)->isFloatTy() ||
1394 FT->getParamType(0)->isDoubleTy());
1398 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1399 SmallVectorImpl<CallInst *> &SinCalls,
1400 SmallVectorImpl<CallInst *> &CosCalls,
1401 SmallVectorImpl<CallInst *> &SinCosCalls) {
1402 CallInst *CI = dyn_cast<CallInst>(Val);
1407 Function *Callee = CI->getCalledFunction();
1408 StringRef FuncName = Callee->getName();
1410 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1414 if (Func == LibFunc::sinpif)
1415 SinCalls.push_back(CI);
1416 else if (Func == LibFunc::cospif)
1417 CosCalls.push_back(CI);
1418 else if (Func == LibFunc::sincospif_stret)
1419 SinCosCalls.push_back(CI);
1421 if (Func == LibFunc::sinpi)
1422 SinCalls.push_back(CI);
1423 else if (Func == LibFunc::cospi)
1424 CosCalls.push_back(CI);
1425 else if (Func == LibFunc::sincospi_stret)
1426 SinCosCalls.push_back(CI);
1430 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1432 for (CallInst *C : Calls)
1433 replaceAllUsesWith(C, Res);
1436 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1437 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1438 Type *ArgTy = Arg->getType();
1442 Triple T(OrigCallee->getParent()->getTargetTriple());
1444 Name = "__sincospif_stret";
1446 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1447 // x86_64 can't use {float, float} since that would be returned in both
1448 // xmm0 and xmm1, which isn't what a real struct would do.
1449 ResTy = T.getArch() == Triple::x86_64
1450 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1451 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1453 Name = "__sincospi_stret";
1454 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1457 Module *M = OrigCallee->getParent();
1458 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1459 ResTy, ArgTy, nullptr);
1461 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1462 // If the argument is an instruction, it must dominate all uses so put our
1463 // sincos call there.
1464 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1466 // Otherwise (e.g. for a constant) the beginning of the function is as
1467 // good a place as any.
1468 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1469 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1472 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1474 if (SinCos->getType()->isStructTy()) {
1475 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1476 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1478 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1480 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1485 //===----------------------------------------------------------------------===//
1486 // Integer Library Call Optimizations
1487 //===----------------------------------------------------------------------===//
1489 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1490 Function *Callee = CI->getCalledFunction();
1491 FunctionType *FT = Callee->getFunctionType();
1492 // Just make sure this has 2 arguments of the same FP type, which match the
1494 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1495 !FT->getParamType(0)->isIntegerTy())
1498 Value *Op = CI->getArgOperand(0);
1501 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1502 if (CI->isZero()) // ffs(0) -> 0.
1503 return B.getInt32(0);
1504 // ffs(c) -> cttz(c)+1
1505 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1508 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1509 Type *ArgType = Op->getType();
1511 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1512 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1513 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1514 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1516 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1517 return B.CreateSelect(Cond, V, B.getInt32(0));
1520 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1521 Function *Callee = CI->getCalledFunction();
1522 FunctionType *FT = Callee->getFunctionType();
1523 // We require integer(integer) where the types agree.
1524 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1525 FT->getParamType(0) != FT->getReturnType())
1528 // abs(x) -> x >s -1 ? x : -x
1529 Value *Op = CI->getArgOperand(0);
1531 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1532 Value *Neg = B.CreateNeg(Op, "neg");
1533 return B.CreateSelect(Pos, Op, Neg);
1536 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1537 Function *Callee = CI->getCalledFunction();
1538 FunctionType *FT = Callee->getFunctionType();
1539 // We require integer(i32)
1540 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1541 !FT->getParamType(0)->isIntegerTy(32))
1544 // isdigit(c) -> (c-'0') <u 10
1545 Value *Op = CI->getArgOperand(0);
1546 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1547 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1548 return B.CreateZExt(Op, CI->getType());
1551 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1552 Function *Callee = CI->getCalledFunction();
1553 FunctionType *FT = Callee->getFunctionType();
1554 // We require integer(i32)
1555 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1556 !FT->getParamType(0)->isIntegerTy(32))
1559 // isascii(c) -> c <u 128
1560 Value *Op = CI->getArgOperand(0);
1561 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1562 return B.CreateZExt(Op, CI->getType());
1565 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1566 Function *Callee = CI->getCalledFunction();
1567 FunctionType *FT = Callee->getFunctionType();
1568 // We require i32(i32)
1569 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1570 !FT->getParamType(0)->isIntegerTy(32))
1573 // toascii(c) -> c & 0x7f
1574 return B.CreateAnd(CI->getArgOperand(0),
1575 ConstantInt::get(CI->getType(), 0x7F));
1578 //===----------------------------------------------------------------------===//
1579 // Formatting and IO Library Call Optimizations
1580 //===----------------------------------------------------------------------===//
1582 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1584 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1586 // Error reporting calls should be cold, mark them as such.
1587 // This applies even to non-builtin calls: it is only a hint and applies to
1588 // functions that the frontend might not understand as builtins.
1590 // This heuristic was suggested in:
1591 // Improving Static Branch Prediction in a Compiler
1592 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1593 // Proceedings of PACT'98, Oct. 1998, IEEE
1594 Function *Callee = CI->getCalledFunction();
1596 if (!CI->hasFnAttr(Attribute::Cold) &&
1597 isReportingError(Callee, CI, StreamArg)) {
1598 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1604 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1605 if (!ColdErrorCalls)
1608 if (!Callee || !Callee->isDeclaration())
1614 // These functions might be considered cold, but only if their stream
1615 // argument is stderr.
1617 if (StreamArg >= (int)CI->getNumArgOperands())
1619 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1622 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1623 if (!GV || !GV->isDeclaration())
1625 return GV->getName() == "stderr";
1628 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1629 // Check for a fixed format string.
1630 StringRef FormatStr;
1631 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1634 // Empty format string -> noop.
1635 if (FormatStr.empty()) // Tolerate printf's declared void.
1636 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1638 // Do not do any of the following transformations if the printf return value
1639 // is used, in general the printf return value is not compatible with either
1640 // putchar() or puts().
1641 if (!CI->use_empty())
1644 // printf("x") -> putchar('x'), even for '%'.
1645 if (FormatStr.size() == 1) {
1646 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1647 if (CI->use_empty() || !Res)
1649 return B.CreateIntCast(Res, CI->getType(), true);
1652 // printf("foo\n") --> puts("foo")
1653 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1654 FormatStr.find('%') == StringRef::npos) { // No format characters.
1655 // Create a string literal with no \n on it. We expect the constant merge
1656 // pass to be run after this pass, to merge duplicate strings.
1657 FormatStr = FormatStr.drop_back();
1658 Value *GV = B.CreateGlobalString(FormatStr, "str");
1659 Value *NewCI = EmitPutS(GV, B, TLI);
1660 return (CI->use_empty() || !NewCI)
1662 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1665 // Optimize specific format strings.
1666 // printf("%c", chr) --> putchar(chr)
1667 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1668 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1669 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1671 if (CI->use_empty() || !Res)
1673 return B.CreateIntCast(Res, CI->getType(), true);
1676 // printf("%s\n", str) --> puts(str)
1677 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1678 CI->getArgOperand(1)->getType()->isPointerTy()) {
1679 return EmitPutS(CI->getArgOperand(1), B, TLI);
1684 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1686 Function *Callee = CI->getCalledFunction();
1687 // Require one fixed pointer argument and an integer/void result.
1688 FunctionType *FT = Callee->getFunctionType();
1689 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1690 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1693 if (Value *V = optimizePrintFString(CI, B)) {
1697 // printf(format, ...) -> iprintf(format, ...) if no floating point
1699 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1700 Module *M = B.GetInsertBlock()->getParent()->getParent();
1701 Constant *IPrintFFn =
1702 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1703 CallInst *New = cast<CallInst>(CI->clone());
1704 New->setCalledFunction(IPrintFFn);
1711 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1712 // Check for a fixed format string.
1713 StringRef FormatStr;
1714 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1717 // If we just have a format string (nothing else crazy) transform it.
1718 if (CI->getNumArgOperands() == 2) {
1719 // Make sure there's no % in the constant array. We could try to handle
1720 // %% -> % in the future if we cared.
1721 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1722 if (FormatStr[i] == '%')
1723 return nullptr; // we found a format specifier, bail out.
1725 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1726 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1727 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1728 FormatStr.size() + 1),
1729 1); // Copy the null byte.
1730 return ConstantInt::get(CI->getType(), FormatStr.size());
1733 // The remaining optimizations require the format string to be "%s" or "%c"
1734 // and have an extra operand.
1735 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1736 CI->getNumArgOperands() < 3)
1739 // Decode the second character of the format string.
1740 if (FormatStr[1] == 'c') {
1741 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1742 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1744 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1745 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1746 B.CreateStore(V, Ptr);
1747 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1748 B.CreateStore(B.getInt8(0), Ptr);
1750 return ConstantInt::get(CI->getType(), 1);
1753 if (FormatStr[1] == 's') {
1754 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1755 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1758 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1762 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1763 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1765 // The sprintf result is the unincremented number of bytes in the string.
1766 return B.CreateIntCast(Len, CI->getType(), false);
1771 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1772 Function *Callee = CI->getCalledFunction();
1773 // Require two fixed pointer arguments and an integer result.
1774 FunctionType *FT = Callee->getFunctionType();
1775 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1776 !FT->getParamType(1)->isPointerTy() ||
1777 !FT->getReturnType()->isIntegerTy())
1780 if (Value *V = optimizeSPrintFString(CI, B)) {
1784 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1786 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1787 Module *M = B.GetInsertBlock()->getParent()->getParent();
1788 Constant *SIPrintFFn =
1789 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1790 CallInst *New = cast<CallInst>(CI->clone());
1791 New->setCalledFunction(SIPrintFFn);
1798 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1799 optimizeErrorReporting(CI, B, 0);
1801 // All the optimizations depend on the format string.
1802 StringRef FormatStr;
1803 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1806 // Do not do any of the following transformations if the fprintf return
1807 // value is used, in general the fprintf return value is not compatible
1808 // with fwrite(), fputc() or fputs().
1809 if (!CI->use_empty())
1812 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1813 if (CI->getNumArgOperands() == 2) {
1814 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1815 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1816 return nullptr; // We found a format specifier.
1819 CI->getArgOperand(1),
1820 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1821 CI->getArgOperand(0), B, DL, TLI);
1824 // The remaining optimizations require the format string to be "%s" or "%c"
1825 // and have an extra operand.
1826 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1827 CI->getNumArgOperands() < 3)
1830 // Decode the second character of the format string.
1831 if (FormatStr[1] == 'c') {
1832 // fprintf(F, "%c", chr) --> fputc(chr, F)
1833 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1835 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1838 if (FormatStr[1] == 's') {
1839 // fprintf(F, "%s", str) --> fputs(str, F)
1840 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1842 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1847 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1848 Function *Callee = CI->getCalledFunction();
1849 // Require two fixed paramters as pointers and integer result.
1850 FunctionType *FT = Callee->getFunctionType();
1851 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1852 !FT->getParamType(1)->isPointerTy() ||
1853 !FT->getReturnType()->isIntegerTy())
1856 if (Value *V = optimizeFPrintFString(CI, B)) {
1860 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1861 // floating point arguments.
1862 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1863 Module *M = B.GetInsertBlock()->getParent()->getParent();
1864 Constant *FIPrintFFn =
1865 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1866 CallInst *New = cast<CallInst>(CI->clone());
1867 New->setCalledFunction(FIPrintFFn);
1874 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1875 optimizeErrorReporting(CI, B, 3);
1877 Function *Callee = CI->getCalledFunction();
1878 // Require a pointer, an integer, an integer, a pointer, returning integer.
1879 FunctionType *FT = Callee->getFunctionType();
1880 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1881 !FT->getParamType(1)->isIntegerTy() ||
1882 !FT->getParamType(2)->isIntegerTy() ||
1883 !FT->getParamType(3)->isPointerTy() ||
1884 !FT->getReturnType()->isIntegerTy())
1887 // Get the element size and count.
1888 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1889 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1890 if (!SizeC || !CountC)
1892 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1894 // If this is writing zero records, remove the call (it's a noop).
1896 return ConstantInt::get(CI->getType(), 0);
1898 // If this is writing one byte, turn it into fputc.
1899 // This optimisation is only valid, if the return value is unused.
1900 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1901 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1902 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1903 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1909 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1910 optimizeErrorReporting(CI, B, 1);
1912 Function *Callee = CI->getCalledFunction();
1914 // Require two pointers. Also, we can't optimize if return value is used.
1915 FunctionType *FT = Callee->getFunctionType();
1916 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1917 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1920 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1921 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1925 // Known to have no uses (see above).
1927 CI->getArgOperand(0),
1928 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1929 CI->getArgOperand(1), B, DL, TLI);
1932 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1933 Function *Callee = CI->getCalledFunction();
1934 // Require one fixed pointer argument and an integer/void result.
1935 FunctionType *FT = Callee->getFunctionType();
1936 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1937 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1940 // Check for a constant string.
1942 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1945 if (Str.empty() && CI->use_empty()) {
1946 // puts("") -> putchar('\n')
1947 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1948 if (CI->use_empty() || !Res)
1950 return B.CreateIntCast(Res, CI->getType(), true);
1956 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1958 SmallString<20> FloatFuncName = FuncName;
1959 FloatFuncName += 'f';
1960 if (TLI->getLibFunc(FloatFuncName, Func))
1961 return TLI->has(Func);
1965 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1966 IRBuilder<> &Builder) {
1968 Function *Callee = CI->getCalledFunction();
1969 StringRef FuncName = Callee->getName();
1971 // Check for string/memory library functions.
1972 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1973 // Make sure we never change the calling convention.
1974 assert((ignoreCallingConv(Func) ||
1975 CI->getCallingConv() == llvm::CallingConv::C) &&
1976 "Optimizing string/memory libcall would change the calling convention");
1978 case LibFunc::strcat:
1979 return optimizeStrCat(CI, Builder);
1980 case LibFunc::strncat:
1981 return optimizeStrNCat(CI, Builder);
1982 case LibFunc::strchr:
1983 return optimizeStrChr(CI, Builder);
1984 case LibFunc::strrchr:
1985 return optimizeStrRChr(CI, Builder);
1986 case LibFunc::strcmp:
1987 return optimizeStrCmp(CI, Builder);
1988 case LibFunc::strncmp:
1989 return optimizeStrNCmp(CI, Builder);
1990 case LibFunc::strcpy:
1991 return optimizeStrCpy(CI, Builder);
1992 case LibFunc::stpcpy:
1993 return optimizeStpCpy(CI, Builder);
1994 case LibFunc::strncpy:
1995 return optimizeStrNCpy(CI, Builder);
1996 case LibFunc::strlen:
1997 return optimizeStrLen(CI, Builder);
1998 case LibFunc::strpbrk:
1999 return optimizeStrPBrk(CI, Builder);
2000 case LibFunc::strtol:
2001 case LibFunc::strtod:
2002 case LibFunc::strtof:
2003 case LibFunc::strtoul:
2004 case LibFunc::strtoll:
2005 case LibFunc::strtold:
2006 case LibFunc::strtoull:
2007 return optimizeStrTo(CI, Builder);
2008 case LibFunc::strspn:
2009 return optimizeStrSpn(CI, Builder);
2010 case LibFunc::strcspn:
2011 return optimizeStrCSpn(CI, Builder);
2012 case LibFunc::strstr:
2013 return optimizeStrStr(CI, Builder);
2014 case LibFunc::memchr:
2015 return optimizeMemChr(CI, Builder);
2016 case LibFunc::memcmp:
2017 return optimizeMemCmp(CI, Builder);
2018 case LibFunc::memcpy:
2019 return optimizeMemCpy(CI, Builder);
2020 case LibFunc::memmove:
2021 return optimizeMemMove(CI, Builder);
2022 case LibFunc::memset:
2023 return optimizeMemSet(CI, Builder);
2031 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2032 if (CI->isNoBuiltin())
2036 Function *Callee = CI->getCalledFunction();
2037 StringRef FuncName = Callee->getName();
2038 IRBuilder<> Builder(CI);
2039 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2041 // Command-line parameter overrides function attribute.
2042 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2043 UnsafeFPShrink = EnableUnsafeFPShrink;
2044 else if (canUseUnsafeFPMath(Callee))
2045 UnsafeFPShrink = true;
2047 // First, check for intrinsics.
2048 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2049 if (!isCallingConvC)
2051 switch (II->getIntrinsicID()) {
2052 case Intrinsic::pow:
2053 return optimizePow(CI, Builder);
2054 case Intrinsic::exp2:
2055 return optimizeExp2(CI, Builder);
2056 case Intrinsic::fabs:
2057 return optimizeFabs(CI, Builder);
2058 case Intrinsic::sqrt:
2059 return optimizeSqrt(CI, Builder);
2065 // Also try to simplify calls to fortified library functions.
2066 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2067 // Try to further simplify the result.
2068 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2069 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2070 // Use an IR Builder from SimplifiedCI if available instead of CI
2071 // to guarantee we reach all uses we might replace later on.
2072 IRBuilder<> TmpBuilder(SimplifiedCI);
2073 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2074 // If we were able to further simplify, remove the now redundant call.
2075 SimplifiedCI->replaceAllUsesWith(V);
2076 SimplifiedCI->eraseFromParent();
2080 return SimplifiedFortifiedCI;
2083 // Then check for known library functions.
2084 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2085 // We never change the calling convention.
2086 if (!ignoreCallingConv(Func) && !isCallingConvC)
2088 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2094 return optimizeCos(CI, Builder);
2095 case LibFunc::sinpif:
2096 case LibFunc::sinpi:
2097 case LibFunc::cospif:
2098 case LibFunc::cospi:
2099 return optimizeSinCosPi(CI, Builder);
2103 return optimizePow(CI, Builder);
2104 case LibFunc::exp2l:
2106 case LibFunc::exp2f:
2107 return optimizeExp2(CI, Builder);
2108 case LibFunc::fabsf:
2110 case LibFunc::fabsl:
2111 return optimizeFabs(CI, Builder);
2112 case LibFunc::sqrtf:
2114 case LibFunc::sqrtl:
2115 return optimizeSqrt(CI, Builder);
2118 case LibFunc::ffsll:
2119 return optimizeFFS(CI, Builder);
2122 case LibFunc::llabs:
2123 return optimizeAbs(CI, Builder);
2124 case LibFunc::isdigit:
2125 return optimizeIsDigit(CI, Builder);
2126 case LibFunc::isascii:
2127 return optimizeIsAscii(CI, Builder);
2128 case LibFunc::toascii:
2129 return optimizeToAscii(CI, Builder);
2130 case LibFunc::printf:
2131 return optimizePrintF(CI, Builder);
2132 case LibFunc::sprintf:
2133 return optimizeSPrintF(CI, Builder);
2134 case LibFunc::fprintf:
2135 return optimizeFPrintF(CI, Builder);
2136 case LibFunc::fwrite:
2137 return optimizeFWrite(CI, Builder);
2138 case LibFunc::fputs:
2139 return optimizeFPuts(CI, Builder);
2141 return optimizePuts(CI, Builder);
2142 case LibFunc::perror:
2143 return optimizeErrorReporting(CI, Builder);
2144 case LibFunc::vfprintf:
2145 case LibFunc::fiprintf:
2146 return optimizeErrorReporting(CI, Builder, 0);
2147 case LibFunc::fputc:
2148 return optimizeErrorReporting(CI, Builder, 1);
2150 case LibFunc::floor:
2152 case LibFunc::round:
2153 case LibFunc::nearbyint:
2154 case LibFunc::trunc:
2155 if (hasFloatVersion(FuncName))
2156 return optimizeUnaryDoubleFP(CI, Builder, false);
2159 case LibFunc::acosh:
2161 case LibFunc::asinh:
2163 case LibFunc::atanh:
2167 case LibFunc::exp10:
2168 case LibFunc::expm1:
2170 case LibFunc::log10:
2171 case LibFunc::log1p:
2178 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2179 return optimizeUnaryDoubleFP(CI, Builder, true);
2181 case LibFunc::copysign:
2182 if (hasFloatVersion(FuncName))
2183 return optimizeBinaryDoubleFP(CI, Builder);
2185 case LibFunc::fminf:
2187 case LibFunc::fminl:
2188 case LibFunc::fmaxf:
2190 case LibFunc::fmaxl:
2191 return optimizeFMinFMax(CI, Builder);
2199 LibCallSimplifier::LibCallSimplifier(
2200 const DataLayout &DL, const TargetLibraryInfo *TLI,
2201 function_ref<void(Instruction *, Value *)> Replacer)
2202 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2203 Replacer(Replacer) {}
2205 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2206 // Indirect through the replacer used in this instance.
2210 /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2212 I->replaceAllUsesWith(With);
2213 I->eraseFromParent();
2217 // Additional cases that we need to add to this file:
2220 // * cbrt(expN(X)) -> expN(x/3)
2221 // * cbrt(sqrt(x)) -> pow(x,1/6)
2222 // * cbrt(cbrt(x)) -> pow(x,1/9)
2225 // * exp(log(x)) -> x
2228 // * log(exp(x)) -> x
2229 // * log(x**y) -> y*log(x)
2230 // * log(exp(y)) -> y*log(e)
2231 // * log(exp2(y)) -> y*log(2)
2232 // * log(exp10(y)) -> y*log(10)
2233 // * log(sqrt(x)) -> 0.5*log(x)
2234 // * log(pow(x,y)) -> y*log(x)
2236 // lround, lroundf, lroundl:
2237 // * lround(cnst) -> cnst'
2240 // * pow(exp(x),y) -> exp(x*y)
2241 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2242 // * pow(pow(x,y),z)-> pow(x,y*z)
2244 // round, roundf, roundl:
2245 // * round(cnst) -> cnst'
2248 // * signbit(cnst) -> cnst'
2249 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2251 // sqrt, sqrtf, sqrtl:
2252 // * sqrt(expN(x)) -> expN(x*0.5)
2253 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2254 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2257 // * tan(atan(x)) -> x
2259 // trunc, truncf, truncl:
2260 // * trunc(cnst) -> cnst'
2264 //===----------------------------------------------------------------------===//
2265 // Fortified Library Call Optimizations
2266 //===----------------------------------------------------------------------===//
2268 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2272 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2274 if (ConstantInt *ObjSizeCI =
2275 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2276 if (ObjSizeCI->isAllOnesValue())
2278 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2279 if (OnlyLowerUnknownSize)
2282 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2283 // If the length is 0 we don't know how long it is and so we can't
2284 // remove the check.
2287 return ObjSizeCI->getZExtValue() >= Len;
2289 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2290 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2295 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2296 Function *Callee = CI->getCalledFunction();
2298 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2301 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2302 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2303 CI->getArgOperand(2), 1);
2304 return CI->getArgOperand(0);
2309 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2310 Function *Callee = CI->getCalledFunction();
2312 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2315 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2316 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2317 CI->getArgOperand(2), 1);
2318 return CI->getArgOperand(0);
2323 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2324 Function *Callee = CI->getCalledFunction();
2326 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2329 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2330 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2331 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2332 return CI->getArgOperand(0);
2337 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2339 LibFunc::Func Func) {
2340 Function *Callee = CI->getCalledFunction();
2341 StringRef Name = Callee->getName();
2342 const DataLayout &DL = CI->getModule()->getDataLayout();
2344 if (!checkStringCopyLibFuncSignature(Callee, Func))
2347 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2348 *ObjSize = CI->getArgOperand(2);
2350 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2351 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2352 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2353 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2356 // If a) we don't have any length information, or b) we know this will
2357 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2358 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2359 // TODO: It might be nice to get a maximum length out of the possible
2360 // string lengths for varying.
2361 if (isFortifiedCallFoldable(CI, 2, 1, true))
2362 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2364 if (OnlyLowerUnknownSize)
2367 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2368 uint64_t Len = GetStringLength(Src);
2372 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2373 Value *LenV = ConstantInt::get(SizeTTy, Len);
2374 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2375 // If the function was an __stpcpy_chk, and we were able to fold it into
2376 // a __memcpy_chk, we still need to return the correct end pointer.
2377 if (Ret && Func == LibFunc::stpcpy_chk)
2378 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2382 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2384 LibFunc::Func Func) {
2385 Function *Callee = CI->getCalledFunction();
2386 StringRef Name = Callee->getName();
2388 if (!checkStringCopyLibFuncSignature(Callee, Func))
2390 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2391 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2392 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2398 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2399 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2400 // Some clang users checked for _chk libcall availability using:
2401 // __has_builtin(__builtin___memcpy_chk)
2402 // When compiling with -fno-builtin, this is always true.
2403 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2404 // end up with fortified libcalls, which isn't acceptable in a freestanding
2405 // environment which only provides their non-fortified counterparts.
2407 // Until we change clang and/or teach external users to check for availability
2408 // differently, disregard the "nobuiltin" attribute and TLI::has.
2413 Function *Callee = CI->getCalledFunction();
2414 StringRef FuncName = Callee->getName();
2415 IRBuilder<> Builder(CI);
2416 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2418 // First, check that this is a known library functions.
2419 if (!TLI->getLibFunc(FuncName, Func))
2422 // We never change the calling convention.
2423 if (!ignoreCallingConv(Func) && !isCallingConvC)
2427 case LibFunc::memcpy_chk:
2428 return optimizeMemCpyChk(CI, Builder);
2429 case LibFunc::memmove_chk:
2430 return optimizeMemMoveChk(CI, Builder);
2431 case LibFunc::memset_chk:
2432 return optimizeMemSetChk(CI, Builder);
2433 case LibFunc::stpcpy_chk:
2434 case LibFunc::strcpy_chk:
2435 return optimizeStrpCpyChk(CI, Builder, Func);
2436 case LibFunc::stpncpy_chk:
2437 case LibFunc::strncpy_chk:
2438 return optimizeStrpNCpyChk(CI, Builder, Func);
2445 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2446 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2447 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}