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/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/CommandLine.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) {
56 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
60 /// Return true if it only matters that the value is equal or not-equal to zero.
61 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
62 for (User *U : V->users()) {
63 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
65 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
68 // Unknown instruction.
74 /// Return true if it is only used in equality comparisons with With.
75 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
76 for (User *U : V->users()) {
77 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
78 if (IC->isEquality() && IC->getOperand(1) == With)
80 // Unknown instruction.
86 static bool callHasFloatingPointArgument(const CallInst *CI) {
87 return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
88 return OI->getType()->isFloatingPointTy();
92 /// \brief Check whether the overloaded unary floating point function
93 /// corresponding to \a Ty is available.
94 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
95 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
96 LibFunc::Func LongDoubleFn) {
97 switch (Ty->getTypeID()) {
99 return TLI->has(FloatFn);
100 case Type::DoubleTyID:
101 return TLI->has(DoubleFn);
103 return TLI->has(LongDoubleFn);
107 /// \brief Check whether we can use unsafe floating point math for
108 /// the function passed as input.
109 static bool canUseUnsafeFPMath(Function *F) {
111 // FIXME: For finer-grain optimization, we need intrinsics to have the same
112 // fast-math flag decorations that are applied to FP instructions. For now,
113 // we have to rely on the function-level unsafe-fp-math attribute to do this
114 // optimization because there's no other way to express that the call can be
116 if (F->hasFnAttribute("unsafe-fp-math")) {
117 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
118 if (Attr.getValueAsString() == "true")
124 /// \brief Returns whether \p F matches the signature expected for the
125 /// string/memory copying library function \p Func.
126 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
127 /// Their fortified (_chk) counterparts are also accepted.
128 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
129 const DataLayout &DL = F->getParent()->getDataLayout();
130 FunctionType *FT = F->getFunctionType();
131 LLVMContext &Context = F->getContext();
132 Type *PCharTy = Type::getInt8PtrTy(Context);
133 Type *SizeTTy = DL.getIntPtrType(Context);
134 unsigned NumParams = FT->getNumParams();
136 // All string libfuncs return the same type as the first parameter.
137 if (FT->getReturnType() != FT->getParamType(0))
142 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
143 case LibFunc::stpncpy_chk:
144 case LibFunc::strncpy_chk:
145 --NumParams; // fallthrough
146 case LibFunc::stpncpy:
147 case LibFunc::strncpy: {
148 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
149 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
153 case LibFunc::strcpy_chk:
154 case LibFunc::stpcpy_chk:
155 --NumParams; // fallthrough
156 case LibFunc::stpcpy:
157 case LibFunc::strcpy: {
158 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
159 FT->getParamType(0) != PCharTy)
163 case LibFunc::memmove_chk:
164 case LibFunc::memcpy_chk:
165 --NumParams; // fallthrough
166 case LibFunc::memmove:
167 case LibFunc::memcpy: {
168 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
169 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
173 case LibFunc::memset_chk:
174 --NumParams; // fallthrough
175 case LibFunc::memset: {
176 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
177 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
182 // If this is a fortified libcall, the last parameter is a size_t.
183 if (NumParams == FT->getNumParams() - 1)
184 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
188 //===----------------------------------------------------------------------===//
189 // String and Memory Library Call Optimizations
190 //===----------------------------------------------------------------------===//
192 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
193 Function *Callee = CI->getCalledFunction();
194 // Verify the "strcat" function prototype.
195 FunctionType *FT = Callee->getFunctionType();
196 if (FT->getNumParams() != 2||
197 FT->getReturnType() != B.getInt8PtrTy() ||
198 FT->getParamType(0) != FT->getReturnType() ||
199 FT->getParamType(1) != FT->getReturnType())
202 // Extract some information from the instruction
203 Value *Dst = CI->getArgOperand(0);
204 Value *Src = CI->getArgOperand(1);
206 // See if we can get the length of the input string.
207 uint64_t Len = GetStringLength(Src);
210 --Len; // Unbias length.
212 // Handle the simple, do-nothing case: strcat(x, "") -> x
216 return emitStrLenMemCpy(Src, Dst, Len, B);
219 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
221 // We need to find the end of the destination string. That's where the
222 // memory is to be moved to. We just generate a call to strlen.
223 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
227 // Now that we have the destination's length, we must index into the
228 // destination's pointer to get the actual memcpy destination (end of
229 // the string .. we're concatenating).
230 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
232 // We have enough information to now generate the memcpy call to do the
233 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
234 B.CreateMemCpy(CpyDst, Src,
235 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
240 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
241 Function *Callee = CI->getCalledFunction();
242 // Verify the "strncat" function prototype.
243 FunctionType *FT = Callee->getFunctionType();
244 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
245 FT->getParamType(0) != FT->getReturnType() ||
246 FT->getParamType(1) != FT->getReturnType() ||
247 !FT->getParamType(2)->isIntegerTy())
250 // Extract some information from the instruction.
251 Value *Dst = CI->getArgOperand(0);
252 Value *Src = CI->getArgOperand(1);
255 // We don't do anything if length is not constant.
256 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
257 Len = LengthArg->getZExtValue();
261 // See if we can get the length of the input string.
262 uint64_t SrcLen = GetStringLength(Src);
265 --SrcLen; // Unbias length.
267 // Handle the simple, do-nothing cases:
268 // strncat(x, "", c) -> x
269 // strncat(x, c, 0) -> x
270 if (SrcLen == 0 || Len == 0)
273 // We don't optimize this case.
277 // strncat(x, s, c) -> strcat(x, s)
278 // s is constant so the strcat can be optimized further.
279 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
282 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
283 Function *Callee = CI->getCalledFunction();
284 // Verify the "strchr" function prototype.
285 FunctionType *FT = Callee->getFunctionType();
286 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
287 FT->getParamType(0) != FT->getReturnType() ||
288 !FT->getParamType(1)->isIntegerTy(32))
291 Value *SrcStr = CI->getArgOperand(0);
293 // If the second operand is non-constant, see if we can compute the length
294 // of the input string and turn this into memchr.
295 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
297 uint64_t Len = GetStringLength(SrcStr);
298 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
301 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
302 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
306 // Otherwise, the character is a constant, see if the first argument is
307 // a string literal. If so, we can constant fold.
309 if (!getConstantStringInfo(SrcStr, Str)) {
310 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
311 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI),
316 // Compute the offset, make sure to handle the case when we're searching for
317 // zero (a weird way to spell strlen).
318 size_t I = (0xFF & CharC->getSExtValue()) == 0
320 : Str.find(CharC->getSExtValue());
321 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
322 return Constant::getNullValue(CI->getType());
324 // strchr(s+n,c) -> gep(s+n+i,c)
325 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
328 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
329 Function *Callee = CI->getCalledFunction();
330 // Verify the "strrchr" function prototype.
331 FunctionType *FT = Callee->getFunctionType();
332 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
333 FT->getParamType(0) != FT->getReturnType() ||
334 !FT->getParamType(1)->isIntegerTy(32))
337 Value *SrcStr = CI->getArgOperand(0);
338 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
340 // Cannot fold anything if we're not looking for a constant.
345 if (!getConstantStringInfo(SrcStr, Str)) {
346 // strrchr(s, 0) -> strchr(s, 0)
348 return EmitStrChr(SrcStr, '\0', B, TLI);
352 // Compute the offset.
353 size_t I = (0xFF & CharC->getSExtValue()) == 0
355 : Str.rfind(CharC->getSExtValue());
356 if (I == StringRef::npos) // Didn't find the char. Return null.
357 return Constant::getNullValue(CI->getType());
359 // strrchr(s+n,c) -> gep(s+n+i,c)
360 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
363 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
364 Function *Callee = CI->getCalledFunction();
365 // Verify the "strcmp" function prototype.
366 FunctionType *FT = Callee->getFunctionType();
367 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
368 FT->getParamType(0) != FT->getParamType(1) ||
369 FT->getParamType(0) != B.getInt8PtrTy())
372 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
373 if (Str1P == Str2P) // strcmp(x,x) -> 0
374 return ConstantInt::get(CI->getType(), 0);
376 StringRef Str1, Str2;
377 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
378 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
380 // strcmp(x, y) -> cnst (if both x and y are constant strings)
381 if (HasStr1 && HasStr2)
382 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
384 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
386 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
388 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
389 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
391 // strcmp(P, "x") -> memcmp(P, "x", 2)
392 uint64_t Len1 = GetStringLength(Str1P);
393 uint64_t Len2 = GetStringLength(Str2P);
395 return EmitMemCmp(Str1P, Str2P,
396 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
397 std::min(Len1, Len2)),
404 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
405 Function *Callee = CI->getCalledFunction();
406 // Verify the "strncmp" function prototype.
407 FunctionType *FT = Callee->getFunctionType();
408 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
409 FT->getParamType(0) != FT->getParamType(1) ||
410 FT->getParamType(0) != B.getInt8PtrTy() ||
411 !FT->getParamType(2)->isIntegerTy())
414 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
415 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
416 return ConstantInt::get(CI->getType(), 0);
418 // Get the length argument if it is constant.
420 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
421 Length = LengthArg->getZExtValue();
425 if (Length == 0) // strncmp(x,y,0) -> 0
426 return ConstantInt::get(CI->getType(), 0);
428 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
429 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
431 StringRef Str1, Str2;
432 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
433 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
435 // strncmp(x, y) -> cnst (if both x and y are constant strings)
436 if (HasStr1 && HasStr2) {
437 StringRef SubStr1 = Str1.substr(0, Length);
438 StringRef SubStr2 = Str2.substr(0, Length);
439 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
442 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
444 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
446 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
447 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
452 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
453 Function *Callee = CI->getCalledFunction();
455 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
458 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
459 if (Dst == Src) // strcpy(x,x) -> x
462 // See if we can get the length of the input string.
463 uint64_t Len = GetStringLength(Src);
467 // We have enough information to now generate the memcpy call to do the
468 // copy for us. Make a memcpy to copy the nul byte with align = 1.
469 B.CreateMemCpy(Dst, Src,
470 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
474 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
475 Function *Callee = CI->getCalledFunction();
476 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
479 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
480 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
481 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
482 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
485 // See if we can get the length of the input string.
486 uint64_t Len = GetStringLength(Src);
490 Type *PT = Callee->getFunctionType()->getParamType(0);
491 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
492 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
493 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
495 // We have enough information to now generate the memcpy call to do the
496 // copy for us. Make a memcpy to copy the nul byte with align = 1.
497 B.CreateMemCpy(Dst, Src, LenV, 1);
501 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
502 Function *Callee = CI->getCalledFunction();
503 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
506 Value *Dst = CI->getArgOperand(0);
507 Value *Src = CI->getArgOperand(1);
508 Value *LenOp = CI->getArgOperand(2);
510 // See if we can get the length of the input string.
511 uint64_t SrcLen = GetStringLength(Src);
517 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
518 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
523 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
524 Len = LengthArg->getZExtValue();
529 return Dst; // strncpy(x, y, 0) -> x
531 // Let strncpy handle the zero padding
532 if (Len > SrcLen + 1)
535 Type *PT = Callee->getFunctionType()->getParamType(0);
536 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
537 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
542 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
543 Function *Callee = CI->getCalledFunction();
544 FunctionType *FT = Callee->getFunctionType();
545 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
546 !FT->getReturnType()->isIntegerTy())
549 Value *Src = CI->getArgOperand(0);
551 // Constant folding: strlen("xyz") -> 3
552 if (uint64_t Len = GetStringLength(Src))
553 return ConstantInt::get(CI->getType(), Len - 1);
555 // strlen(x?"foo":"bars") --> x ? 3 : 4
556 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
557 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
558 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
559 if (LenTrue && LenFalse) {
560 Function *Caller = CI->getParent()->getParent();
561 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
563 "folded strlen(select) to select of constants");
564 return B.CreateSelect(SI->getCondition(),
565 ConstantInt::get(CI->getType(), LenTrue - 1),
566 ConstantInt::get(CI->getType(), LenFalse - 1));
570 // strlen(x) != 0 --> *x != 0
571 // strlen(x) == 0 --> *x == 0
572 if (isOnlyUsedInZeroEqualityComparison(CI))
573 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
578 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
579 Function *Callee = CI->getCalledFunction();
580 FunctionType *FT = Callee->getFunctionType();
581 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
582 FT->getParamType(1) != FT->getParamType(0) ||
583 FT->getReturnType() != FT->getParamType(0))
587 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
588 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
590 // strpbrk(s, "") -> nullptr
591 // strpbrk("", s) -> nullptr
592 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
593 return Constant::getNullValue(CI->getType());
596 if (HasS1 && HasS2) {
597 size_t I = S1.find_first_of(S2);
598 if (I == StringRef::npos) // No match.
599 return Constant::getNullValue(CI->getType());
601 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
605 // strpbrk(s, "a") -> strchr(s, 'a')
606 if (HasS2 && S2.size() == 1)
607 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
612 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
613 Function *Callee = CI->getCalledFunction();
614 FunctionType *FT = Callee->getFunctionType();
615 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
616 !FT->getParamType(0)->isPointerTy() ||
617 !FT->getParamType(1)->isPointerTy())
620 Value *EndPtr = CI->getArgOperand(1);
621 if (isa<ConstantPointerNull>(EndPtr)) {
622 // With a null EndPtr, this function won't capture the main argument.
623 // It would be readonly too, except that it still may write to errno.
624 CI->addAttribute(1, Attribute::NoCapture);
630 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
631 Function *Callee = CI->getCalledFunction();
632 FunctionType *FT = Callee->getFunctionType();
633 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
634 FT->getParamType(1) != FT->getParamType(0) ||
635 !FT->getReturnType()->isIntegerTy())
639 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
640 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
642 // strspn(s, "") -> 0
643 // strspn("", s) -> 0
644 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
645 return Constant::getNullValue(CI->getType());
648 if (HasS1 && HasS2) {
649 size_t Pos = S1.find_first_not_of(S2);
650 if (Pos == StringRef::npos)
652 return ConstantInt::get(CI->getType(), Pos);
658 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
659 Function *Callee = CI->getCalledFunction();
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
662 FT->getParamType(1) != FT->getParamType(0) ||
663 !FT->getReturnType()->isIntegerTy())
667 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
668 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
670 // strcspn("", s) -> 0
671 if (HasS1 && S1.empty())
672 return Constant::getNullValue(CI->getType());
675 if (HasS1 && HasS2) {
676 size_t Pos = S1.find_first_of(S2);
677 if (Pos == StringRef::npos)
679 return ConstantInt::get(CI->getType(), Pos);
682 // strcspn(s, "") -> strlen(s)
683 if (HasS2 && S2.empty())
684 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
689 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
690 Function *Callee = CI->getCalledFunction();
691 FunctionType *FT = Callee->getFunctionType();
692 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
693 !FT->getParamType(1)->isPointerTy() ||
694 !FT->getReturnType()->isPointerTy())
697 // fold strstr(x, x) -> x.
698 if (CI->getArgOperand(0) == CI->getArgOperand(1))
699 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
701 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
702 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
703 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
706 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
710 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
711 ICmpInst *Old = cast<ICmpInst>(*UI++);
713 B.CreateICmp(Old->getPredicate(), StrNCmp,
714 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
715 replaceAllUsesWith(Old, Cmp);
720 // See if either input string is a constant string.
721 StringRef SearchStr, ToFindStr;
722 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
723 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
725 // fold strstr(x, "") -> x.
726 if (HasStr2 && ToFindStr.empty())
727 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
729 // If both strings are known, constant fold it.
730 if (HasStr1 && HasStr2) {
731 size_t Offset = SearchStr.find(ToFindStr);
733 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
734 return Constant::getNullValue(CI->getType());
736 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
737 Value *Result = CastToCStr(CI->getArgOperand(0), B);
738 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
739 return B.CreateBitCast(Result, CI->getType());
742 // fold strstr(x, "y") -> strchr(x, 'y').
743 if (HasStr2 && ToFindStr.size() == 1) {
744 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
745 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
750 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
751 Function *Callee = CI->getCalledFunction();
752 FunctionType *FT = Callee->getFunctionType();
753 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
754 !FT->getParamType(1)->isIntegerTy(32) ||
755 !FT->getParamType(2)->isIntegerTy() ||
756 !FT->getReturnType()->isPointerTy())
759 Value *SrcStr = CI->getArgOperand(0);
760 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
761 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
763 // memchr(x, y, 0) -> null
764 if (LenC && LenC->isNullValue())
765 return Constant::getNullValue(CI->getType());
767 // From now on we need at least constant length and string.
769 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
772 // Truncate the string to LenC. If Str is smaller than LenC we will still only
773 // scan the string, as reading past the end of it is undefined and we can just
774 // return null if we don't find the char.
775 Str = Str.substr(0, LenC->getZExtValue());
777 // If the char is variable but the input str and length are not we can turn
778 // this memchr call into a simple bit field test. Of course this only works
779 // when the return value is only checked against null.
781 // It would be really nice to reuse switch lowering here but we can't change
782 // the CFG at this point.
784 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
785 // after bounds check.
786 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
788 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
789 reinterpret_cast<const unsigned char *>(Str.end()));
791 // Make sure the bit field we're about to create fits in a register on the
793 // FIXME: On a 64 bit architecture this prevents us from using the
794 // interesting range of alpha ascii chars. We could do better by emitting
795 // two bitfields or shifting the range by 64 if no lower chars are used.
796 if (!DL.fitsInLegalInteger(Max + 1))
799 // For the bit field use a power-of-2 type with at least 8 bits to avoid
800 // creating unnecessary illegal types.
801 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
803 // Now build the bit field.
804 APInt Bitfield(Width, 0);
806 Bitfield.setBit((unsigned char)C);
807 Value *BitfieldC = B.getInt(Bitfield);
809 // First check that the bit field access is within bounds.
810 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
811 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
814 // Create code that checks if the given bit is set in the field.
815 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
816 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
818 // Finally merge both checks and cast to pointer type. The inttoptr
819 // implicitly zexts the i1 to intptr type.
820 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
823 // Check if all arguments are constants. If so, we can constant fold.
827 // Compute the offset.
828 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
829 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
830 return Constant::getNullValue(CI->getType());
832 // memchr(s+n,c,l) -> gep(s+n+i,c)
833 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
836 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
837 Function *Callee = CI->getCalledFunction();
838 FunctionType *FT = Callee->getFunctionType();
839 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
840 !FT->getParamType(1)->isPointerTy() ||
841 !FT->getReturnType()->isIntegerTy(32))
844 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
846 if (LHS == RHS) // memcmp(s,s,x) -> 0
847 return Constant::getNullValue(CI->getType());
849 // Make sure we have a constant length.
850 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
853 uint64_t Len = LenC->getZExtValue();
855 if (Len == 0) // memcmp(s1,s2,0) -> 0
856 return Constant::getNullValue(CI->getType());
858 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
860 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
861 CI->getType(), "lhsv");
862 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
863 CI->getType(), "rhsv");
864 return B.CreateSub(LHSV, RHSV, "chardiff");
867 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
868 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
870 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
871 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
873 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
874 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
877 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
879 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
882 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
884 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
886 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
890 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
891 StringRef LHSStr, RHSStr;
892 if (getConstantStringInfo(LHS, LHSStr) &&
893 getConstantStringInfo(RHS, RHSStr)) {
894 // Make sure we're not reading out-of-bounds memory.
895 if (Len > LHSStr.size() || Len > RHSStr.size())
897 // Fold the memcmp and normalize the result. This way we get consistent
898 // results across multiple platforms.
900 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
905 return ConstantInt::get(CI->getType(), Ret);
911 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
912 Function *Callee = CI->getCalledFunction();
914 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
917 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
918 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
919 CI->getArgOperand(2), 1);
920 return CI->getArgOperand(0);
923 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
924 Function *Callee = CI->getCalledFunction();
926 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
929 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
930 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
931 CI->getArgOperand(2), 1);
932 return CI->getArgOperand(0);
935 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
936 Function *Callee = CI->getCalledFunction();
938 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
941 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
942 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
943 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
944 return CI->getArgOperand(0);
947 //===----------------------------------------------------------------------===//
948 // Math Library Optimizations
949 //===----------------------------------------------------------------------===//
951 /// Return a variant of Val with float type.
952 /// Currently this works in two cases: If Val is an FPExtension of a float
953 /// value to something bigger, simply return the operand.
954 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
955 /// loss of precision do so.
956 static Value *valueHasFloatPrecision(Value *Val) {
957 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
958 Value *Op = Cast->getOperand(0);
959 if (Op->getType()->isFloatTy())
962 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
963 APFloat F = Const->getValueAPF();
965 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
968 return ConstantFP::get(Const->getContext(), F);
973 /// Any floating-point library function that we're trying to simplify will have
974 /// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
975 /// CheckDoubleTy indicates that 'fptype' must be 'double'.
976 static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
977 bool CheckDoubleTy) {
978 FunctionType *FT = F->getFunctionType();
979 if (FT->getNumParams() != NumParams)
982 // The return type must match what we're looking for.
983 Type *RetTy = FT->getReturnType();
984 if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
987 // Each parameter must match the return type, and therefore, match every other
989 for (const Type *ParamTy : FT->params())
990 if (ParamTy != RetTy)
996 /// Shrink double -> float for unary functions like 'floor'.
997 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
999 Function *Callee = CI->getCalledFunction();
1000 if (!matchesFPLibFunctionSignature(Callee, 1, true))
1004 // Check if all the uses for function like 'sin' are converted to float.
1005 for (User *U : CI->users()) {
1006 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1007 if (!Cast || !Cast->getType()->isFloatTy())
1012 // If this is something like 'floor((double)floatval)', convert to floorf.
1013 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1017 // Propagate fast-math flags from the existing call to the new call.
1018 IRBuilder<>::FastMathFlagGuard Guard(B);
1019 B.setFastMathFlags(CI->getFastMathFlags());
1021 // floor((double)floatval) -> (double)floorf(floatval)
1022 if (Callee->isIntrinsic()) {
1023 Module *M = CI->getModule();
1024 Intrinsic::ID IID = Callee->getIntrinsicID();
1025 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1026 V = B.CreateCall(F, V);
1028 // The call is a library call rather than an intrinsic.
1029 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1032 return B.CreateFPExt(V, B.getDoubleTy());
1035 /// Shrink double -> float for binary functions like 'fmin/fmax'.
1036 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1037 Function *Callee = CI->getCalledFunction();
1038 if (!matchesFPLibFunctionSignature(Callee, 2, true))
1041 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1042 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1043 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1046 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1050 // Propagate fast-math flags from the existing call to the new call.
1051 IRBuilder<>::FastMathFlagGuard Guard(B);
1052 B.setFastMathFlags(CI->getFastMathFlags());
1054 // fmin((double)floatval1, (double)floatval2)
1055 // -> (double)fminf(floatval1, floatval2)
1056 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1057 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1058 Callee->getAttributes());
1059 return B.CreateFPExt(V, B.getDoubleTy());
1062 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1063 Function *Callee = CI->getCalledFunction();
1064 Value *Ret = nullptr;
1065 StringRef Name = Callee->getName();
1066 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1067 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 // cos(-x) -> cos(x)
1077 Value *Op1 = CI->getArgOperand(0);
1078 if (BinaryOperator::isFNeg(Op1)) {
1079 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1080 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1085 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1086 // Multiplications calculated using Addition Chains.
1087 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1089 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1091 if (InnerChain[Exp])
1092 return InnerChain[Exp];
1094 static const unsigned AddChain[33][2] = {
1096 {0, 0}, // Unused (base case = pow1).
1097 {1, 1}, // Unused (pre-computed).
1098 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1099 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1100 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1101 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1102 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1105 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1106 getPow(InnerChain, AddChain[Exp][1], B));
1107 return InnerChain[Exp];
1110 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1111 Function *Callee = CI->getCalledFunction();
1112 Value *Ret = nullptr;
1113 StringRef Name = Callee->getName();
1114 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1115 Ret = optimizeUnaryDoubleFP(CI, B, true);
1117 FunctionType *FT = Callee->getFunctionType();
1118 // Just make sure this has 2 arguments of the same FP type, which match the
1120 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1121 FT->getParamType(0) != FT->getParamType(1) ||
1122 !FT->getParamType(0)->isFloatingPointTy())
1125 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1126 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1127 // pow(1.0, x) -> 1.0
1128 if (Op1C->isExactlyValue(1.0))
1130 // pow(2.0, x) -> exp2(x)
1131 if (Op1C->isExactlyValue(2.0) &&
1132 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1134 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1135 Callee->getAttributes());
1136 // pow(10.0, x) -> exp10(x)
1137 if (Op1C->isExactlyValue(10.0) &&
1138 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1140 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1141 Callee->getAttributes());
1144 // FIXME: Use instruction-level FMF.
1145 bool UnsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1147 // pow(exp(x), y) -> exp(x * y)
1148 // pow(exp2(x), y) -> exp2(x * y)
1149 // We enable these only with fast-math. Besides rounding differences, the
1150 // transformation changes overflow and underflow behavior quite dramatically.
1151 // Example: x = 1000, y = 0.001.
1152 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1153 auto *OpC = dyn_cast<CallInst>(Op1);
1154 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1156 Function *OpCCallee = OpC->getCalledFunction();
1157 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1158 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
1159 IRBuilder<>::FastMathFlagGuard Guard(B);
1160 B.setFastMathFlags(CI->getFastMathFlags());
1161 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1162 return EmitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1163 OpCCallee->getAttributes());
1167 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1171 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1172 return ConstantFP::get(CI->getType(), 1.0);
1174 if (Op2C->isExactlyValue(0.5) &&
1175 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1177 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1180 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1181 if (CI->hasUnsafeAlgebra()) {
1182 IRBuilder<>::FastMathFlagGuard Guard(B);
1183 B.setFastMathFlags(CI->getFastMathFlags());
1184 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1185 Callee->getAttributes());
1188 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1189 // This is faster than calling pow, and still handles negative zero
1190 // and negative infinity correctly.
1191 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1192 Value *Inf = ConstantFP::getInfinity(CI->getType());
1193 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1194 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1196 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1197 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1198 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1202 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1204 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1205 return B.CreateFMul(Op1, Op1, "pow2");
1206 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1207 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1209 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
1211 APFloat V = abs(Op2C->getValueAPF());
1212 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1213 // This transformation applies to integer exponents only.
1214 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1218 // We will memoize intermediate products of the Addition Chain.
1219 Value *InnerChain[33] = {nullptr};
1220 InnerChain[1] = Op1;
1221 InnerChain[2] = B.CreateFMul(Op1, Op1);
1223 // We cannot readily convert a non-double type (like float) to a double.
1224 // So we first convert V to something which could be converted to double.
1226 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
1227 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1228 // For negative exponents simply compute the reciprocal.
1229 if (Op2C->isNegative())
1230 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1237 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1238 Function *Callee = CI->getCalledFunction();
1239 Function *Caller = CI->getParent()->getParent();
1240 Value *Ret = nullptr;
1241 StringRef Name = Callee->getName();
1242 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1243 Ret = optimizeUnaryDoubleFP(CI, B, true);
1245 FunctionType *FT = Callee->getFunctionType();
1246 // Just make sure this has 1 argument of FP type, which matches the
1248 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1249 !FT->getParamType(0)->isFloatingPointTy())
1252 Value *Op = CI->getArgOperand(0);
1253 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1254 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1255 LibFunc::Func LdExp = LibFunc::ldexpl;
1256 if (Op->getType()->isFloatTy())
1257 LdExp = LibFunc::ldexpf;
1258 else if (Op->getType()->isDoubleTy())
1259 LdExp = LibFunc::ldexp;
1261 if (TLI->has(LdExp)) {
1262 Value *LdExpArg = nullptr;
1263 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1264 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1265 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1266 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1267 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1268 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1272 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1273 if (!Op->getType()->isFloatTy())
1274 One = ConstantExpr::getFPExtend(One, Op->getType());
1276 Module *M = Caller->getParent();
1278 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1279 Op->getType(), B.getInt32Ty(), nullptr);
1280 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1281 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1282 CI->setCallingConv(F->getCallingConv());
1290 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1291 Function *Callee = CI->getCalledFunction();
1292 Value *Ret = nullptr;
1293 StringRef Name = Callee->getName();
1294 if (Name == "fabs" && hasFloatVersion(Name))
1295 Ret = optimizeUnaryDoubleFP(CI, B, false);
1297 FunctionType *FT = Callee->getFunctionType();
1298 // Make sure this has 1 argument of FP type which matches the result type.
1299 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1300 !FT->getParamType(0)->isFloatingPointTy())
1303 Value *Op = CI->getArgOperand(0);
1304 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1305 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1306 if (I->getOpcode() == Instruction::FMul)
1307 if (I->getOperand(0) == I->getOperand(1))
1313 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1314 // If we can shrink the call to a float function rather than a double
1315 // function, do that first.
1316 Function *Callee = CI->getCalledFunction();
1317 StringRef Name = Callee->getName();
1318 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1319 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1322 // Make sure this has 2 arguments of FP type which match the result type.
1323 FunctionType *FT = Callee->getFunctionType();
1324 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1325 FT->getParamType(0) != FT->getParamType(1) ||
1326 !FT->getParamType(0)->isFloatingPointTy())
1329 IRBuilder<>::FastMathFlagGuard Guard(B);
1331 if (CI->hasUnsafeAlgebra()) {
1332 // Unsafe algebra sets all fast-math-flags to true.
1333 FMF.setUnsafeAlgebra();
1335 // At a minimum, no-nans-fp-math must be true.
1336 if (!CI->hasNoNaNs())
1338 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1339 // "Ideally, fmax would be sensitive to the sign of zero, for example
1340 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1341 // might be impractical."
1342 FMF.setNoSignedZeros();
1345 B.setFastMathFlags(FMF);
1347 // We have a relaxed floating-point environment. We can ignore NaN-handling
1348 // and transform to a compare and select. We do not have to consider errno or
1349 // exceptions, because fmin/fmax do not have those.
1350 Value *Op0 = CI->getArgOperand(0);
1351 Value *Op1 = CI->getArgOperand(1);
1352 Value *Cmp = Callee->getName().startswith("fmin") ?
1353 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1354 return B.CreateSelect(Cmp, Op0, Op1);
1357 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1358 Function *Callee = CI->getCalledFunction();
1359 Value *Ret = nullptr;
1360 StringRef Name = Callee->getName();
1361 if (UnsafeFPShrink && hasFloatVersion(Name))
1362 Ret = optimizeUnaryDoubleFP(CI, B, true);
1363 FunctionType *FT = Callee->getFunctionType();
1365 // Just make sure this has 1 argument of FP type, which matches the
1367 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1368 !FT->getParamType(0)->isFloatingPointTy())
1371 if (!CI->hasUnsafeAlgebra())
1373 Value *Op1 = CI->getArgOperand(0);
1374 auto *OpC = dyn_cast<CallInst>(Op1);
1376 // The earlier call must also be unsafe in order to do these transforms.
1377 if (!OpC || !OpC->hasUnsafeAlgebra())
1380 // log(pow(x,y)) -> y*log(x)
1381 // This is only applicable to log, log2, log10.
1382 if (Name != "log" && Name != "log2" && Name != "log10")
1385 IRBuilder<>::FastMathFlagGuard Guard(B);
1387 FMF.setUnsafeAlgebra();
1388 B.setFastMathFlags(FMF);
1391 Function *F = OpC->getCalledFunction();
1392 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1393 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
1394 return B.CreateFMul(OpC->getArgOperand(1),
1395 EmitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1396 Callee->getAttributes()), "mul");
1398 // log(exp2(y)) -> y*log(2)
1399 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1400 TLI->has(Func) && Func == LibFunc::exp2)
1401 return B.CreateFMul(
1402 OpC->getArgOperand(0),
1403 EmitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1404 Callee->getName(), B, Callee->getAttributes()),
1409 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1410 Function *Callee = CI->getCalledFunction();
1412 Value *Ret = nullptr;
1413 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1414 Callee->getIntrinsicID() == Intrinsic::sqrt))
1415 Ret = optimizeUnaryDoubleFP(CI, B, true);
1417 // FIXME: Refactor - this check is repeated all over this file and even in the
1418 // preceding call to shrink double -> float.
1420 // Make sure this has 1 argument of FP type, which matches the result type.
1421 FunctionType *FT = Callee->getFunctionType();
1422 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1423 !FT->getParamType(0)->isFloatingPointTy())
1426 if (!CI->hasUnsafeAlgebra())
1429 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1430 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1433 // We're looking for a repeated factor in a multiplication tree,
1434 // so we can do this fold: sqrt(x * x) -> fabs(x);
1435 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1436 Value *Op0 = I->getOperand(0);
1437 Value *Op1 = I->getOperand(1);
1438 Value *RepeatOp = nullptr;
1439 Value *OtherOp = nullptr;
1441 // Simple match: the operands of the multiply are identical.
1444 // Look for a more complicated pattern: one of the operands is itself
1445 // a multiply, so search for a common factor in that multiply.
1446 // Note: We don't bother looking any deeper than this first level or for
1447 // variations of this pattern because instcombine's visitFMUL and/or the
1448 // reassociation pass should give us this form.
1449 Value *OtherMul0, *OtherMul1;
1450 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1451 // Pattern: sqrt((x * y) * z)
1452 if (OtherMul0 == OtherMul1 &&
1453 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
1454 // Matched: sqrt((x * x) * z)
1455 RepeatOp = OtherMul0;
1463 // Fast math flags for any created instructions should match the sqrt
1465 IRBuilder<>::FastMathFlagGuard Guard(B);
1466 B.setFastMathFlags(I->getFastMathFlags());
1468 // If we found a repeated factor, hoist it out of the square root and
1469 // replace it with the fabs of that factor.
1470 Module *M = Callee->getParent();
1471 Type *ArgType = I->getType();
1472 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1473 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1475 // If we found a non-repeated factor, we still need to get its square
1476 // root. We then multiply that by the value that was simplified out
1477 // of the square root calculation.
1478 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1479 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1480 return B.CreateFMul(FabsCall, SqrtCall);
1485 // TODO: Generalize to handle any trig function and its inverse.
1486 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1487 Function *Callee = CI->getCalledFunction();
1488 Value *Ret = nullptr;
1489 StringRef Name = Callee->getName();
1490 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1491 Ret = optimizeUnaryDoubleFP(CI, B, true);
1492 FunctionType *FT = Callee->getFunctionType();
1494 // Just make sure this has 1 argument of FP type, which matches the
1496 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1497 !FT->getParamType(0)->isFloatingPointTy())
1500 Value *Op1 = CI->getArgOperand(0);
1501 auto *OpC = dyn_cast<CallInst>(Op1);
1505 // Both calls must allow unsafe optimizations in order to remove them.
1506 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1509 // tan(atan(x)) -> x
1510 // tanf(atanf(x)) -> x
1511 // tanl(atanl(x)) -> x
1513 Function *F = OpC->getCalledFunction();
1514 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1515 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1516 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1517 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1518 Ret = OpC->getArgOperand(0);
1522 static bool isTrigLibCall(CallInst *CI);
1523 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1524 bool UseFloat, Value *&Sin, Value *&Cos,
1527 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1529 // Make sure the prototype is as expected, otherwise the rest of the
1530 // function is probably invalid and likely to abort.
1531 if (!isTrigLibCall(CI))
1534 Value *Arg = CI->getArgOperand(0);
1535 SmallVector<CallInst *, 1> SinCalls;
1536 SmallVector<CallInst *, 1> CosCalls;
1537 SmallVector<CallInst *, 1> SinCosCalls;
1539 bool IsFloat = Arg->getType()->isFloatTy();
1541 // Look for all compatible sinpi, cospi and sincospi calls with the same
1542 // argument. If there are enough (in some sense) we can make the
1544 for (User *U : Arg->users())
1545 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1548 // It's only worthwhile if both sinpi and cospi are actually used.
1549 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1552 Value *Sin, *Cos, *SinCos;
1553 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1555 replaceTrigInsts(SinCalls, Sin);
1556 replaceTrigInsts(CosCalls, Cos);
1557 replaceTrigInsts(SinCosCalls, SinCos);
1562 static bool isTrigLibCall(CallInst *CI) {
1563 Function *Callee = CI->getCalledFunction();
1564 FunctionType *FT = Callee->getFunctionType();
1566 // We can only hope to do anything useful if we can ignore things like errno
1567 // and floating-point exceptions.
1568 bool AttributesSafe =
1569 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1571 // Other than that we need float(float) or double(double)
1572 return AttributesSafe && FT->getNumParams() == 1 &&
1573 FT->getReturnType() == FT->getParamType(0) &&
1574 (FT->getParamType(0)->isFloatTy() ||
1575 FT->getParamType(0)->isDoubleTy());
1579 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1580 SmallVectorImpl<CallInst *> &SinCalls,
1581 SmallVectorImpl<CallInst *> &CosCalls,
1582 SmallVectorImpl<CallInst *> &SinCosCalls) {
1583 CallInst *CI = dyn_cast<CallInst>(Val);
1588 Function *Callee = CI->getCalledFunction();
1590 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1595 if (Func == LibFunc::sinpif)
1596 SinCalls.push_back(CI);
1597 else if (Func == LibFunc::cospif)
1598 CosCalls.push_back(CI);
1599 else if (Func == LibFunc::sincospif_stret)
1600 SinCosCalls.push_back(CI);
1602 if (Func == LibFunc::sinpi)
1603 SinCalls.push_back(CI);
1604 else if (Func == LibFunc::cospi)
1605 CosCalls.push_back(CI);
1606 else if (Func == LibFunc::sincospi_stret)
1607 SinCosCalls.push_back(CI);
1611 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1613 for (CallInst *C : Calls)
1614 replaceAllUsesWith(C, Res);
1617 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1618 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1619 Type *ArgTy = Arg->getType();
1623 Triple T(OrigCallee->getParent()->getTargetTriple());
1625 Name = "__sincospif_stret";
1627 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1628 // x86_64 can't use {float, float} since that would be returned in both
1629 // xmm0 and xmm1, which isn't what a real struct would do.
1630 ResTy = T.getArch() == Triple::x86_64
1631 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1632 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1634 Name = "__sincospi_stret";
1635 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1638 Module *M = OrigCallee->getParent();
1639 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1640 ResTy, ArgTy, nullptr);
1642 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1643 // If the argument is an instruction, it must dominate all uses so put our
1644 // sincos call there.
1645 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1647 // Otherwise (e.g. for a constant) the beginning of the function is as
1648 // good a place as any.
1649 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1650 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1653 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1655 if (SinCos->getType()->isStructTy()) {
1656 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1657 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1659 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1661 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1666 //===----------------------------------------------------------------------===//
1667 // Integer Library Call Optimizations
1668 //===----------------------------------------------------------------------===//
1670 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1671 FunctionType *FT = Callee->getFunctionType();
1672 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1673 FT->getParamType(0)->isIntegerTy();
1676 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1677 Function *Callee = CI->getCalledFunction();
1678 if (!checkIntUnaryReturnAndParam(Callee))
1680 Value *Op = CI->getArgOperand(0);
1683 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1684 if (CI->isZero()) // ffs(0) -> 0.
1685 return B.getInt32(0);
1686 // ffs(c) -> cttz(c)+1
1687 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1690 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1691 Type *ArgType = Op->getType();
1693 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1694 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1695 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1696 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1698 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1699 return B.CreateSelect(Cond, V, B.getInt32(0));
1702 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1703 Function *Callee = CI->getCalledFunction();
1704 FunctionType *FT = Callee->getFunctionType();
1705 // We require integer(integer) where the types agree.
1706 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1707 FT->getParamType(0) != FT->getReturnType())
1710 // abs(x) -> x >s -1 ? x : -x
1711 Value *Op = CI->getArgOperand(0);
1713 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1714 Value *Neg = B.CreateNeg(Op, "neg");
1715 return B.CreateSelect(Pos, Op, Neg);
1718 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1719 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1722 // isdigit(c) -> (c-'0') <u 10
1723 Value *Op = CI->getArgOperand(0);
1724 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1725 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1726 return B.CreateZExt(Op, CI->getType());
1729 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1730 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1733 // isascii(c) -> c <u 128
1734 Value *Op = CI->getArgOperand(0);
1735 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1736 return B.CreateZExt(Op, CI->getType());
1739 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1740 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1743 // toascii(c) -> c & 0x7f
1744 return B.CreateAnd(CI->getArgOperand(0),
1745 ConstantInt::get(CI->getType(), 0x7F));
1748 //===----------------------------------------------------------------------===//
1749 // Formatting and IO Library Call Optimizations
1750 //===----------------------------------------------------------------------===//
1752 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1754 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1756 // Error reporting calls should be cold, mark them as such.
1757 // This applies even to non-builtin calls: it is only a hint and applies to
1758 // functions that the frontend might not understand as builtins.
1760 // This heuristic was suggested in:
1761 // Improving Static Branch Prediction in a Compiler
1762 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1763 // Proceedings of PACT'98, Oct. 1998, IEEE
1764 Function *Callee = CI->getCalledFunction();
1766 if (!CI->hasFnAttr(Attribute::Cold) &&
1767 isReportingError(Callee, CI, StreamArg)) {
1768 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1774 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1775 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1781 // These functions might be considered cold, but only if their stream
1782 // argument is stderr.
1784 if (StreamArg >= (int)CI->getNumArgOperands())
1786 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1789 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1790 if (!GV || !GV->isDeclaration())
1792 return GV->getName() == "stderr";
1795 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1796 // Check for a fixed format string.
1797 StringRef FormatStr;
1798 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1801 // Empty format string -> noop.
1802 if (FormatStr.empty()) // Tolerate printf's declared void.
1803 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1805 // Do not do any of the following transformations if the printf return value
1806 // is used, in general the printf return value is not compatible with either
1807 // putchar() or puts().
1808 if (!CI->use_empty())
1811 // printf("x") -> putchar('x'), even for '%'.
1812 if (FormatStr.size() == 1) {
1813 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1814 if (CI->use_empty() || !Res)
1816 return B.CreateIntCast(Res, CI->getType(), true);
1819 // printf("foo\n") --> puts("foo")
1820 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1821 FormatStr.find('%') == StringRef::npos) { // No format characters.
1822 // Create a string literal with no \n on it. We expect the constant merge
1823 // pass to be run after this pass, to merge duplicate strings.
1824 FormatStr = FormatStr.drop_back();
1825 Value *GV = B.CreateGlobalString(FormatStr, "str");
1826 Value *NewCI = EmitPutS(GV, B, TLI);
1827 return (CI->use_empty() || !NewCI)
1829 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1832 // Optimize specific format strings.
1833 // printf("%c", chr) --> putchar(chr)
1834 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1835 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1836 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1838 if (CI->use_empty() || !Res)
1840 return B.CreateIntCast(Res, CI->getType(), true);
1843 // printf("%s\n", str) --> puts(str)
1844 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1845 CI->getArgOperand(1)->getType()->isPointerTy()) {
1846 return EmitPutS(CI->getArgOperand(1), B, TLI);
1851 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1853 Function *Callee = CI->getCalledFunction();
1854 // Require one fixed pointer argument and an integer/void result.
1855 FunctionType *FT = Callee->getFunctionType();
1856 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1857 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1860 if (Value *V = optimizePrintFString(CI, B)) {
1864 // printf(format, ...) -> iprintf(format, ...) if no floating point
1866 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1867 Module *M = B.GetInsertBlock()->getParent()->getParent();
1868 Constant *IPrintFFn =
1869 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1870 CallInst *New = cast<CallInst>(CI->clone());
1871 New->setCalledFunction(IPrintFFn);
1878 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1879 // Check for a fixed format string.
1880 StringRef FormatStr;
1881 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1884 // If we just have a format string (nothing else crazy) transform it.
1885 if (CI->getNumArgOperands() == 2) {
1886 // Make sure there's no % in the constant array. We could try to handle
1887 // %% -> % in the future if we cared.
1888 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1889 if (FormatStr[i] == '%')
1890 return nullptr; // we found a format specifier, bail out.
1892 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1893 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1894 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1895 FormatStr.size() + 1),
1896 1); // Copy the null byte.
1897 return ConstantInt::get(CI->getType(), FormatStr.size());
1900 // The remaining optimizations require the format string to be "%s" or "%c"
1901 // and have an extra operand.
1902 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1903 CI->getNumArgOperands() < 3)
1906 // Decode the second character of the format string.
1907 if (FormatStr[1] == 'c') {
1908 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1909 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1911 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1912 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1913 B.CreateStore(V, Ptr);
1914 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1915 B.CreateStore(B.getInt8(0), Ptr);
1917 return ConstantInt::get(CI->getType(), 1);
1920 if (FormatStr[1] == 's') {
1921 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1922 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1925 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1929 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1930 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1932 // The sprintf result is the unincremented number of bytes in the string.
1933 return B.CreateIntCast(Len, CI->getType(), false);
1938 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1939 Function *Callee = CI->getCalledFunction();
1940 // Require two fixed pointer arguments and an integer result.
1941 FunctionType *FT = Callee->getFunctionType();
1942 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1943 !FT->getParamType(1)->isPointerTy() ||
1944 !FT->getReturnType()->isIntegerTy())
1947 if (Value *V = optimizeSPrintFString(CI, B)) {
1951 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1953 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1954 Module *M = B.GetInsertBlock()->getParent()->getParent();
1955 Constant *SIPrintFFn =
1956 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1957 CallInst *New = cast<CallInst>(CI->clone());
1958 New->setCalledFunction(SIPrintFFn);
1965 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1966 optimizeErrorReporting(CI, B, 0);
1968 // All the optimizations depend on the format string.
1969 StringRef FormatStr;
1970 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1973 // Do not do any of the following transformations if the fprintf return
1974 // value is used, in general the fprintf return value is not compatible
1975 // with fwrite(), fputc() or fputs().
1976 if (!CI->use_empty())
1979 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1980 if (CI->getNumArgOperands() == 2) {
1981 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1982 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1983 return nullptr; // We found a format specifier.
1986 CI->getArgOperand(1),
1987 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1988 CI->getArgOperand(0), B, DL, TLI);
1991 // The remaining optimizations require the format string to be "%s" or "%c"
1992 // and have an extra operand.
1993 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1994 CI->getNumArgOperands() < 3)
1997 // Decode the second character of the format string.
1998 if (FormatStr[1] == 'c') {
1999 // fprintf(F, "%c", chr) --> fputc(chr, F)
2000 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2002 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2005 if (FormatStr[1] == 's') {
2006 // fprintf(F, "%s", str) --> fputs(str, F)
2007 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2009 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2014 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2015 Function *Callee = CI->getCalledFunction();
2016 // Require two fixed paramters as pointers and integer result.
2017 FunctionType *FT = Callee->getFunctionType();
2018 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2019 !FT->getParamType(1)->isPointerTy() ||
2020 !FT->getReturnType()->isIntegerTy())
2023 if (Value *V = optimizeFPrintFString(CI, B)) {
2027 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2028 // floating point arguments.
2029 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2030 Module *M = B.GetInsertBlock()->getParent()->getParent();
2031 Constant *FIPrintFFn =
2032 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2033 CallInst *New = cast<CallInst>(CI->clone());
2034 New->setCalledFunction(FIPrintFFn);
2041 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2042 optimizeErrorReporting(CI, B, 3);
2044 Function *Callee = CI->getCalledFunction();
2045 // Require a pointer, an integer, an integer, a pointer, returning integer.
2046 FunctionType *FT = Callee->getFunctionType();
2047 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2048 !FT->getParamType(1)->isIntegerTy() ||
2049 !FT->getParamType(2)->isIntegerTy() ||
2050 !FT->getParamType(3)->isPointerTy() ||
2051 !FT->getReturnType()->isIntegerTy())
2054 // Get the element size and count.
2055 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2056 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2057 if (!SizeC || !CountC)
2059 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2061 // If this is writing zero records, remove the call (it's a noop).
2063 return ConstantInt::get(CI->getType(), 0);
2065 // If this is writing one byte, turn it into fputc.
2066 // This optimisation is only valid, if the return value is unused.
2067 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2068 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
2069 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
2070 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2076 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2077 optimizeErrorReporting(CI, B, 1);
2079 Function *Callee = CI->getCalledFunction();
2081 // Require two pointers. Also, we can't optimize if return value is used.
2082 FunctionType *FT = Callee->getFunctionType();
2083 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2084 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2087 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2088 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2092 // Known to have no uses (see above).
2094 CI->getArgOperand(0),
2095 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2096 CI->getArgOperand(1), B, DL, TLI);
2099 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2100 Function *Callee = CI->getCalledFunction();
2101 // Require one fixed pointer argument and an integer/void result.
2102 FunctionType *FT = Callee->getFunctionType();
2103 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2104 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2107 // Check for a constant string.
2109 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2112 if (Str.empty() && CI->use_empty()) {
2113 // puts("") -> putchar('\n')
2114 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
2115 if (CI->use_empty() || !Res)
2117 return B.CreateIntCast(Res, CI->getType(), true);
2123 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2125 SmallString<20> FloatFuncName = FuncName;
2126 FloatFuncName += 'f';
2127 if (TLI->getLibFunc(FloatFuncName, Func))
2128 return TLI->has(Func);
2132 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2133 IRBuilder<> &Builder) {
2135 Function *Callee = CI->getCalledFunction();
2136 StringRef FuncName = Callee->getName();
2138 // Check for string/memory library functions.
2139 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2140 // Make sure we never change the calling convention.
2141 assert((ignoreCallingConv(Func) ||
2142 CI->getCallingConv() == llvm::CallingConv::C) &&
2143 "Optimizing string/memory libcall would change the calling convention");
2145 case LibFunc::strcat:
2146 return optimizeStrCat(CI, Builder);
2147 case LibFunc::strncat:
2148 return optimizeStrNCat(CI, Builder);
2149 case LibFunc::strchr:
2150 return optimizeStrChr(CI, Builder);
2151 case LibFunc::strrchr:
2152 return optimizeStrRChr(CI, Builder);
2153 case LibFunc::strcmp:
2154 return optimizeStrCmp(CI, Builder);
2155 case LibFunc::strncmp:
2156 return optimizeStrNCmp(CI, Builder);
2157 case LibFunc::strcpy:
2158 return optimizeStrCpy(CI, Builder);
2159 case LibFunc::stpcpy:
2160 return optimizeStpCpy(CI, Builder);
2161 case LibFunc::strncpy:
2162 return optimizeStrNCpy(CI, Builder);
2163 case LibFunc::strlen:
2164 return optimizeStrLen(CI, Builder);
2165 case LibFunc::strpbrk:
2166 return optimizeStrPBrk(CI, Builder);
2167 case LibFunc::strtol:
2168 case LibFunc::strtod:
2169 case LibFunc::strtof:
2170 case LibFunc::strtoul:
2171 case LibFunc::strtoll:
2172 case LibFunc::strtold:
2173 case LibFunc::strtoull:
2174 return optimizeStrTo(CI, Builder);
2175 case LibFunc::strspn:
2176 return optimizeStrSpn(CI, Builder);
2177 case LibFunc::strcspn:
2178 return optimizeStrCSpn(CI, Builder);
2179 case LibFunc::strstr:
2180 return optimizeStrStr(CI, Builder);
2181 case LibFunc::memchr:
2182 return optimizeMemChr(CI, Builder);
2183 case LibFunc::memcmp:
2184 return optimizeMemCmp(CI, Builder);
2185 case LibFunc::memcpy:
2186 return optimizeMemCpy(CI, Builder);
2187 case LibFunc::memmove:
2188 return optimizeMemMove(CI, Builder);
2189 case LibFunc::memset:
2190 return optimizeMemSet(CI, Builder);
2198 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2199 if (CI->isNoBuiltin())
2203 Function *Callee = CI->getCalledFunction();
2204 StringRef FuncName = Callee->getName();
2206 SmallVector<OperandBundleDef, 2> OpBundles;
2207 CI->getOperandBundlesAsDefs(OpBundles);
2208 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2209 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2211 // Command-line parameter overrides function attribute.
2212 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2213 UnsafeFPShrink = EnableUnsafeFPShrink;
2214 else if (canUseUnsafeFPMath(Callee))
2215 UnsafeFPShrink = true;
2217 // First, check for intrinsics.
2218 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2219 if (!isCallingConvC)
2221 switch (II->getIntrinsicID()) {
2222 case Intrinsic::pow:
2223 return optimizePow(CI, Builder);
2224 case Intrinsic::exp2:
2225 return optimizeExp2(CI, Builder);
2226 case Intrinsic::fabs:
2227 return optimizeFabs(CI, Builder);
2228 case Intrinsic::log:
2229 return optimizeLog(CI, Builder);
2230 case Intrinsic::sqrt:
2231 return optimizeSqrt(CI, Builder);
2237 // Also try to simplify calls to fortified library functions.
2238 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2239 // Try to further simplify the result.
2240 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2241 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2242 // Use an IR Builder from SimplifiedCI if available instead of CI
2243 // to guarantee we reach all uses we might replace later on.
2244 IRBuilder<> TmpBuilder(SimplifiedCI);
2245 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2246 // If we were able to further simplify, remove the now redundant call.
2247 SimplifiedCI->replaceAllUsesWith(V);
2248 SimplifiedCI->eraseFromParent();
2252 return SimplifiedFortifiedCI;
2255 // Then check for known library functions.
2256 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2257 // We never change the calling convention.
2258 if (!ignoreCallingConv(Func) && !isCallingConvC)
2260 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2266 return optimizeCos(CI, Builder);
2267 case LibFunc::sinpif:
2268 case LibFunc::sinpi:
2269 case LibFunc::cospif:
2270 case LibFunc::cospi:
2271 return optimizeSinCosPi(CI, Builder);
2275 return optimizePow(CI, Builder);
2276 case LibFunc::exp2l:
2278 case LibFunc::exp2f:
2279 return optimizeExp2(CI, Builder);
2280 case LibFunc::fabsf:
2282 case LibFunc::fabsl:
2283 return optimizeFabs(CI, Builder);
2284 case LibFunc::sqrtf:
2286 case LibFunc::sqrtl:
2287 return optimizeSqrt(CI, Builder);
2290 case LibFunc::ffsll:
2291 return optimizeFFS(CI, Builder);
2294 case LibFunc::llabs:
2295 return optimizeAbs(CI, Builder);
2296 case LibFunc::isdigit:
2297 return optimizeIsDigit(CI, Builder);
2298 case LibFunc::isascii:
2299 return optimizeIsAscii(CI, Builder);
2300 case LibFunc::toascii:
2301 return optimizeToAscii(CI, Builder);
2302 case LibFunc::printf:
2303 return optimizePrintF(CI, Builder);
2304 case LibFunc::sprintf:
2305 return optimizeSPrintF(CI, Builder);
2306 case LibFunc::fprintf:
2307 return optimizeFPrintF(CI, Builder);
2308 case LibFunc::fwrite:
2309 return optimizeFWrite(CI, Builder);
2310 case LibFunc::fputs:
2311 return optimizeFPuts(CI, Builder);
2313 case LibFunc::log10:
2314 case LibFunc::log1p:
2317 return optimizeLog(CI, Builder);
2319 return optimizePuts(CI, Builder);
2323 return optimizeTan(CI, Builder);
2324 case LibFunc::perror:
2325 return optimizeErrorReporting(CI, Builder);
2326 case LibFunc::vfprintf:
2327 case LibFunc::fiprintf:
2328 return optimizeErrorReporting(CI, Builder, 0);
2329 case LibFunc::fputc:
2330 return optimizeErrorReporting(CI, Builder, 1);
2332 case LibFunc::floor:
2334 case LibFunc::round:
2335 case LibFunc::nearbyint:
2336 case LibFunc::trunc:
2337 if (hasFloatVersion(FuncName))
2338 return optimizeUnaryDoubleFP(CI, Builder, false);
2341 case LibFunc::acosh:
2343 case LibFunc::asinh:
2345 case LibFunc::atanh:
2349 case LibFunc::exp10:
2350 case LibFunc::expm1:
2354 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2355 return optimizeUnaryDoubleFP(CI, Builder, true);
2357 case LibFunc::copysign:
2358 if (hasFloatVersion(FuncName))
2359 return optimizeBinaryDoubleFP(CI, Builder);
2361 case LibFunc::fminf:
2363 case LibFunc::fminl:
2364 case LibFunc::fmaxf:
2366 case LibFunc::fmaxl:
2367 return optimizeFMinFMax(CI, Builder);
2375 LibCallSimplifier::LibCallSimplifier(
2376 const DataLayout &DL, const TargetLibraryInfo *TLI,
2377 function_ref<void(Instruction *, Value *)> Replacer)
2378 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2379 Replacer(Replacer) {}
2381 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2382 // Indirect through the replacer used in this instance.
2387 // Additional cases that we need to add to this file:
2390 // * cbrt(expN(X)) -> expN(x/3)
2391 // * cbrt(sqrt(x)) -> pow(x,1/6)
2392 // * cbrt(cbrt(x)) -> pow(x,1/9)
2395 // * exp(log(x)) -> x
2398 // * log(exp(x)) -> x
2399 // * log(exp(y)) -> y*log(e)
2400 // * log(exp10(y)) -> y*log(10)
2401 // * log(sqrt(x)) -> 0.5*log(x)
2403 // lround, lroundf, lroundl:
2404 // * lround(cnst) -> cnst'
2407 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2408 // * pow(pow(x,y),z)-> pow(x,y*z)
2410 // round, roundf, roundl:
2411 // * round(cnst) -> cnst'
2414 // * signbit(cnst) -> cnst'
2415 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2417 // sqrt, sqrtf, sqrtl:
2418 // * sqrt(expN(x)) -> expN(x*0.5)
2419 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2420 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2422 // trunc, truncf, truncl:
2423 // * trunc(cnst) -> cnst'
2427 //===----------------------------------------------------------------------===//
2428 // Fortified Library Call Optimizations
2429 //===----------------------------------------------------------------------===//
2431 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2435 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2437 if (ConstantInt *ObjSizeCI =
2438 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2439 if (ObjSizeCI->isAllOnesValue())
2441 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2442 if (OnlyLowerUnknownSize)
2445 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2446 // If the length is 0 we don't know how long it is and so we can't
2447 // remove the check.
2450 return ObjSizeCI->getZExtValue() >= Len;
2452 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2453 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2458 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2460 Function *Callee = CI->getCalledFunction();
2462 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2465 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2466 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2467 CI->getArgOperand(2), 1);
2468 return CI->getArgOperand(0);
2473 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2475 Function *Callee = CI->getCalledFunction();
2477 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2480 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2481 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2482 CI->getArgOperand(2), 1);
2483 return CI->getArgOperand(0);
2488 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2490 Function *Callee = CI->getCalledFunction();
2492 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2495 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2496 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2497 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2498 return CI->getArgOperand(0);
2503 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2505 LibFunc::Func Func) {
2506 Function *Callee = CI->getCalledFunction();
2507 StringRef Name = Callee->getName();
2508 const DataLayout &DL = CI->getModule()->getDataLayout();
2510 if (!checkStringCopyLibFuncSignature(Callee, Func))
2513 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2514 *ObjSize = CI->getArgOperand(2);
2516 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2517 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2518 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2519 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2522 // If a) we don't have any length information, or b) we know this will
2523 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2524 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2525 // TODO: It might be nice to get a maximum length out of the possible
2526 // string lengths for varying.
2527 if (isFortifiedCallFoldable(CI, 2, 1, true))
2528 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2530 if (OnlyLowerUnknownSize)
2533 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2534 uint64_t Len = GetStringLength(Src);
2538 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2539 Value *LenV = ConstantInt::get(SizeTTy, Len);
2540 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2541 // If the function was an __stpcpy_chk, and we were able to fold it into
2542 // a __memcpy_chk, we still need to return the correct end pointer.
2543 if (Ret && Func == LibFunc::stpcpy_chk)
2544 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2548 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2550 LibFunc::Func Func) {
2551 Function *Callee = CI->getCalledFunction();
2552 StringRef Name = Callee->getName();
2554 if (!checkStringCopyLibFuncSignature(Callee, Func))
2556 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2557 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2558 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2564 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2565 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2566 // Some clang users checked for _chk libcall availability using:
2567 // __has_builtin(__builtin___memcpy_chk)
2568 // When compiling with -fno-builtin, this is always true.
2569 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2570 // end up with fortified libcalls, which isn't acceptable in a freestanding
2571 // environment which only provides their non-fortified counterparts.
2573 // Until we change clang and/or teach external users to check for availability
2574 // differently, disregard the "nobuiltin" attribute and TLI::has.
2579 Function *Callee = CI->getCalledFunction();
2580 StringRef FuncName = Callee->getName();
2582 SmallVector<OperandBundleDef, 2> OpBundles;
2583 CI->getOperandBundlesAsDefs(OpBundles);
2584 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2585 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2587 // First, check that this is a known library functions.
2588 if (!TLI->getLibFunc(FuncName, Func))
2591 // We never change the calling convention.
2592 if (!ignoreCallingConv(Func) && !isCallingConvC)
2596 case LibFunc::memcpy_chk:
2597 return optimizeMemCpyChk(CI, Builder);
2598 case LibFunc::memmove_chk:
2599 return optimizeMemMoveChk(CI, Builder);
2600 case LibFunc::memset_chk:
2601 return optimizeMemSetChk(CI, Builder);
2602 case LibFunc::stpcpy_chk:
2603 case LibFunc::strcpy_chk:
2604 return optimizeStrpCpyChk(CI, Builder, Func);
2605 case LibFunc::stpncpy_chk:
2606 case LibFunc::strncpy_chk:
2607 return optimizeStrpNCpyChk(CI, Builder, Func);
2614 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2615 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2616 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}