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/CommandLine.h"
33 #include "llvm/Support/KnownBits.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/Transforms/Utils/Local.h"
38 using namespace PatternMatch;
41 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::desc("Enable unsafe double to float "
44 "shrinking for math lib calls"));
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static bool ignoreCallingConv(LibFunc Func) {
52 return Func == LibFunc_abs || Func == LibFunc_labs ||
53 Func == LibFunc_llabs || Func == LibFunc_strlen;
56 static bool isCallingConvCCompatible(CallInst *CI) {
57 switch(CI->getCallingConv()) {
60 case llvm::CallingConv::C:
62 case llvm::CallingConv::ARM_APCS:
63 case llvm::CallingConv::ARM_AAPCS:
64 case llvm::CallingConv::ARM_AAPCS_VFP: {
66 // The iOS ABI diverges from the standard in some cases, so for now don't
67 // try to simplify those calls.
68 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
71 auto *FuncTy = CI->getFunctionType();
73 if (!FuncTy->getReturnType()->isPointerTy() &&
74 !FuncTy->getReturnType()->isIntegerTy() &&
75 !FuncTy->getReturnType()->isVoidTy())
78 for (auto Param : FuncTy->params()) {
79 if (!Param->isPointerTy() && !Param->isIntegerTy())
88 /// Return true if it is only used in equality comparisons with With.
89 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
90 for (User *U : V->users()) {
91 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
92 if (IC->isEquality() && IC->getOperand(1) == With)
94 // Unknown instruction.
100 static bool callHasFloatingPointArgument(const CallInst *CI) {
101 return any_of(CI->operands(), [](const Use &OI) {
102 return OI->getType()->isFloatingPointTy();
106 /// \brief Check whether the overloaded unary floating point function
107 /// corresponding to \a Ty is available.
108 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
109 LibFunc DoubleFn, LibFunc FloatFn,
110 LibFunc LongDoubleFn) {
111 switch (Ty->getTypeID()) {
112 case Type::FloatTyID:
113 return TLI->has(FloatFn);
114 case Type::DoubleTyID:
115 return TLI->has(DoubleFn);
117 return TLI->has(LongDoubleFn);
121 //===----------------------------------------------------------------------===//
122 // String and Memory Library Call Optimizations
123 //===----------------------------------------------------------------------===//
125 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
126 // Extract some information from the instruction
127 Value *Dst = CI->getArgOperand(0);
128 Value *Src = CI->getArgOperand(1);
130 // See if we can get the length of the input string.
131 uint64_t Len = GetStringLength(Src);
134 --Len; // Unbias length.
136 // Handle the simple, do-nothing case: strcat(x, "") -> x
140 return emitStrLenMemCpy(Src, Dst, Len, B);
143 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
145 // We need to find the end of the destination string. That's where the
146 // memory is to be moved to. We just generate a call to strlen.
147 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
151 // Now that we have the destination's length, we must index into the
152 // destination's pointer to get the actual memcpy destination (end of
153 // the string .. we're concatenating).
154 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
156 // We have enough information to now generate the memcpy call to do the
157 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
158 B.CreateMemCpy(CpyDst, Src,
159 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
164 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
165 // Extract some information from the instruction.
166 Value *Dst = CI->getArgOperand(0);
167 Value *Src = CI->getArgOperand(1);
170 // We don't do anything if length is not constant.
171 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
172 Len = LengthArg->getZExtValue();
176 // See if we can get the length of the input string.
177 uint64_t SrcLen = GetStringLength(Src);
180 --SrcLen; // Unbias length.
182 // Handle the simple, do-nothing cases:
183 // strncat(x, "", c) -> x
184 // strncat(x, c, 0) -> x
185 if (SrcLen == 0 || Len == 0)
188 // We don't optimize this case.
192 // strncat(x, s, c) -> strcat(x, s)
193 // s is constant so the strcat can be optimized further.
194 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
197 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
198 Function *Callee = CI->getCalledFunction();
199 FunctionType *FT = Callee->getFunctionType();
200 Value *SrcStr = CI->getArgOperand(0);
202 // If the second operand is non-constant, see if we can compute the length
203 // of the input string and turn this into memchr.
204 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
206 uint64_t Len = GetStringLength(SrcStr);
207 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
210 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
211 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
215 // Otherwise, the character is a constant, see if the first argument is
216 // a string literal. If so, we can constant fold.
218 if (!getConstantStringInfo(SrcStr, Str)) {
219 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
220 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
225 // Compute the offset, make sure to handle the case when we're searching for
226 // zero (a weird way to spell strlen).
227 size_t I = (0xFF & CharC->getSExtValue()) == 0
229 : Str.find(CharC->getSExtValue());
230 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
231 return Constant::getNullValue(CI->getType());
233 // strchr(s+n,c) -> gep(s+n+i,c)
234 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
237 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
238 Value *SrcStr = CI->getArgOperand(0);
239 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
241 // Cannot fold anything if we're not looking for a constant.
246 if (!getConstantStringInfo(SrcStr, Str)) {
247 // strrchr(s, 0) -> strchr(s, 0)
249 return emitStrChr(SrcStr, '\0', B, TLI);
253 // Compute the offset.
254 size_t I = (0xFF & CharC->getSExtValue()) == 0
256 : Str.rfind(CharC->getSExtValue());
257 if (I == StringRef::npos) // Didn't find the char. Return null.
258 return Constant::getNullValue(CI->getType());
260 // strrchr(s+n,c) -> gep(s+n+i,c)
261 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
264 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
265 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
266 if (Str1P == Str2P) // strcmp(x,x) -> 0
267 return ConstantInt::get(CI->getType(), 0);
269 StringRef Str1, Str2;
270 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
271 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
273 // strcmp(x, y) -> cnst (if both x and y are constant strings)
274 if (HasStr1 && HasStr2)
275 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
277 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
279 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
281 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
282 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
284 // strcmp(P, "x") -> memcmp(P, "x", 2)
285 uint64_t Len1 = GetStringLength(Str1P);
286 uint64_t Len2 = GetStringLength(Str2P);
288 return emitMemCmp(Str1P, Str2P,
289 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
290 std::min(Len1, Len2)),
297 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
298 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
299 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
300 return ConstantInt::get(CI->getType(), 0);
302 // Get the length argument if it is constant.
304 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
305 Length = LengthArg->getZExtValue();
309 if (Length == 0) // strncmp(x,y,0) -> 0
310 return ConstantInt::get(CI->getType(), 0);
312 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
313 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
315 StringRef Str1, Str2;
316 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
317 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
319 // strncmp(x, y) -> cnst (if both x and y are constant strings)
320 if (HasStr1 && HasStr2) {
321 StringRef SubStr1 = Str1.substr(0, Length);
322 StringRef SubStr2 = Str2.substr(0, Length);
323 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
326 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
328 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
330 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
331 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
336 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
337 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
338 if (Dst == Src) // strcpy(x,x) -> x
341 // See if we can get the length of the input string.
342 uint64_t Len = GetStringLength(Src);
346 // We have enough information to now generate the memcpy call to do the
347 // copy for us. Make a memcpy to copy the nul byte with align = 1.
348 B.CreateMemCpy(Dst, Src,
349 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
353 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
354 Function *Callee = CI->getCalledFunction();
355 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
356 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
357 Value *StrLen = emitStrLen(Src, B, DL, TLI);
358 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
361 // See if we can get the length of the input string.
362 uint64_t Len = GetStringLength(Src);
366 Type *PT = Callee->getFunctionType()->getParamType(0);
367 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
368 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
369 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
371 // We have enough information to now generate the memcpy call to do the
372 // copy for us. Make a memcpy to copy the nul byte with align = 1.
373 B.CreateMemCpy(Dst, Src, LenV, 1);
377 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
378 Function *Callee = CI->getCalledFunction();
379 Value *Dst = CI->getArgOperand(0);
380 Value *Src = CI->getArgOperand(1);
381 Value *LenOp = CI->getArgOperand(2);
383 // See if we can get the length of the input string.
384 uint64_t SrcLen = GetStringLength(Src);
390 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
391 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
396 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
397 Len = LengthArg->getZExtValue();
402 return Dst; // strncpy(x, y, 0) -> x
404 // Let strncpy handle the zero padding
405 if (Len > SrcLen + 1)
408 Type *PT = Callee->getFunctionType()->getParamType(0);
409 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
410 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
415 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
417 Value *Src = CI->getArgOperand(0);
419 // Constant folding: strlen("xyz") -> 3
420 if (uint64_t Len = GetStringLength(Src, CharSize))
421 return ConstantInt::get(CI->getType(), Len - 1);
423 // If s is a constant pointer pointing to a string literal, we can fold
424 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
425 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
426 // We only try to simplify strlen when the pointer s points to an array
427 // of i8. Otherwise, we would need to scale the offset x before doing the
428 // subtraction. This will make the optimization more complex, and it's not
429 // very useful because calling strlen for a pointer of other types is
431 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
432 if (!isGEPBasedOnPointerToString(GEP, CharSize))
435 ConstantDataArraySlice Slice;
436 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
437 uint64_t NullTermIdx;
438 if (Slice.Array == nullptr) {
441 NullTermIdx = ~((uint64_t)0);
442 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
443 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
448 // If the string does not have '\0', leave it to strlen to compute
450 if (NullTermIdx == ~((uint64_t)0))
454 Value *Offset = GEP->getOperand(2);
455 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
456 Known.Zero.flipAllBits();
458 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
460 // KnownZero's bits are flipped, so zeros in KnownZero now represent
461 // bits known to be zeros in Offset, and ones in KnowZero represent
462 // bits unknown in Offset. Therefore, Offset is known to be in range
463 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
464 // unsigned-less-than NullTermIdx.
466 // If Offset is not provably in the range [0, NullTermIdx], we can still
467 // optimize if we can prove that the program has undefined behavior when
468 // Offset is outside that range. That is the case when GEP->getOperand(0)
469 // is a pointer to an object whose memory extent is NullTermIdx+1.
470 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
471 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
472 NullTermIdx == ArrSize - 1)) {
473 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
474 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
482 // strlen(x?"foo":"bars") --> x ? 3 : 4
483 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
484 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
485 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
486 if (LenTrue && LenFalse) {
487 Function *Caller = CI->getParent()->getParent();
488 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
490 "folded strlen(select) to select of constants");
491 return B.CreateSelect(SI->getCondition(),
492 ConstantInt::get(CI->getType(), LenTrue - 1),
493 ConstantInt::get(CI->getType(), LenFalse - 1));
497 // strlen(x) != 0 --> *x != 0
498 // strlen(x) == 0 --> *x == 0
499 if (isOnlyUsedInZeroEqualityComparison(CI))
500 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
505 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
506 return optimizeStringLength(CI, B, 8);
509 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
510 Module &M = *CI->getParent()->getParent()->getParent();
511 unsigned WCharSize = TLI->getWCharSize(M) * 8;
513 return optimizeStringLength(CI, B, WCharSize);
516 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
518 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
519 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
521 // strpbrk(s, "") -> nullptr
522 // strpbrk("", s) -> nullptr
523 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
524 return Constant::getNullValue(CI->getType());
527 if (HasS1 && HasS2) {
528 size_t I = S1.find_first_of(S2);
529 if (I == StringRef::npos) // No match.
530 return Constant::getNullValue(CI->getType());
532 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
536 // strpbrk(s, "a") -> strchr(s, 'a')
537 if (HasS2 && S2.size() == 1)
538 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
543 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
544 Value *EndPtr = CI->getArgOperand(1);
545 if (isa<ConstantPointerNull>(EndPtr)) {
546 // With a null EndPtr, this function won't capture the main argument.
547 // It would be readonly too, except that it still may write to errno.
548 CI->addParamAttr(0, Attribute::NoCapture);
554 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
556 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
557 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
559 // strspn(s, "") -> 0
560 // strspn("", s) -> 0
561 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
562 return Constant::getNullValue(CI->getType());
565 if (HasS1 && HasS2) {
566 size_t Pos = S1.find_first_not_of(S2);
567 if (Pos == StringRef::npos)
569 return ConstantInt::get(CI->getType(), Pos);
575 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
577 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
578 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
580 // strcspn("", s) -> 0
581 if (HasS1 && S1.empty())
582 return Constant::getNullValue(CI->getType());
585 if (HasS1 && HasS2) {
586 size_t Pos = S1.find_first_of(S2);
587 if (Pos == StringRef::npos)
589 return ConstantInt::get(CI->getType(), Pos);
592 // strcspn(s, "") -> strlen(s)
593 if (HasS2 && S2.empty())
594 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
599 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
600 // fold strstr(x, x) -> x.
601 if (CI->getArgOperand(0) == CI->getArgOperand(1))
602 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
604 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
605 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
606 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
609 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
613 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
614 ICmpInst *Old = cast<ICmpInst>(*UI++);
616 B.CreateICmp(Old->getPredicate(), StrNCmp,
617 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
618 replaceAllUsesWith(Old, Cmp);
623 // See if either input string is a constant string.
624 StringRef SearchStr, ToFindStr;
625 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
626 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
628 // fold strstr(x, "") -> x.
629 if (HasStr2 && ToFindStr.empty())
630 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
632 // If both strings are known, constant fold it.
633 if (HasStr1 && HasStr2) {
634 size_t Offset = SearchStr.find(ToFindStr);
636 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
637 return Constant::getNullValue(CI->getType());
639 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
640 Value *Result = castToCStr(CI->getArgOperand(0), B);
641 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
642 return B.CreateBitCast(Result, CI->getType());
645 // fold strstr(x, "y") -> strchr(x, 'y').
646 if (HasStr2 && ToFindStr.size() == 1) {
647 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
648 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
653 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
654 Value *SrcStr = CI->getArgOperand(0);
655 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
656 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
658 // memchr(x, y, 0) -> null
659 if (LenC && LenC->isZero())
660 return Constant::getNullValue(CI->getType());
662 // From now on we need at least constant length and string.
664 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
667 // Truncate the string to LenC. If Str is smaller than LenC we will still only
668 // scan the string, as reading past the end of it is undefined and we can just
669 // return null if we don't find the char.
670 Str = Str.substr(0, LenC->getZExtValue());
672 // If the char is variable but the input str and length are not we can turn
673 // this memchr call into a simple bit field test. Of course this only works
674 // when the return value is only checked against null.
676 // It would be really nice to reuse switch lowering here but we can't change
677 // the CFG at this point.
679 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
680 // after bounds check.
681 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
683 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
684 reinterpret_cast<const unsigned char *>(Str.end()));
686 // Make sure the bit field we're about to create fits in a register on the
688 // FIXME: On a 64 bit architecture this prevents us from using the
689 // interesting range of alpha ascii chars. We could do better by emitting
690 // two bitfields or shifting the range by 64 if no lower chars are used.
691 if (!DL.fitsInLegalInteger(Max + 1))
694 // For the bit field use a power-of-2 type with at least 8 bits to avoid
695 // creating unnecessary illegal types.
696 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
698 // Now build the bit field.
699 APInt Bitfield(Width, 0);
701 Bitfield.setBit((unsigned char)C);
702 Value *BitfieldC = B.getInt(Bitfield);
704 // First check that the bit field access is within bounds.
705 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
706 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
709 // Create code that checks if the given bit is set in the field.
710 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
711 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
713 // Finally merge both checks and cast to pointer type. The inttoptr
714 // implicitly zexts the i1 to intptr type.
715 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
718 // Check if all arguments are constants. If so, we can constant fold.
722 // Compute the offset.
723 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
724 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
725 return Constant::getNullValue(CI->getType());
727 // memchr(s+n,c,l) -> gep(s+n+i,c)
728 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
731 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
732 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
734 if (LHS == RHS) // memcmp(s,s,x) -> 0
735 return Constant::getNullValue(CI->getType());
737 // Make sure we have a constant length.
738 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
742 uint64_t Len = LenC->getZExtValue();
743 if (Len == 0) // memcmp(s1,s2,0) -> 0
744 return Constant::getNullValue(CI->getType());
746 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
748 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
749 CI->getType(), "lhsv");
750 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
751 CI->getType(), "rhsv");
752 return B.CreateSub(LHSV, RHSV, "chardiff");
755 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
756 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
758 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
759 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
761 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
762 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
765 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
767 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
770 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
772 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
774 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
778 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
779 StringRef LHSStr, RHSStr;
780 if (getConstantStringInfo(LHS, LHSStr) &&
781 getConstantStringInfo(RHS, RHSStr)) {
782 // Make sure we're not reading out-of-bounds memory.
783 if (Len > LHSStr.size() || Len > RHSStr.size())
785 // Fold the memcmp and normalize the result. This way we get consistent
786 // results across multiple platforms.
788 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
793 return ConstantInt::get(CI->getType(), Ret);
799 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
800 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
801 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
802 CI->getArgOperand(2), 1);
803 return CI->getArgOperand(0);
806 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
807 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
808 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
809 CI->getArgOperand(2), 1);
810 return CI->getArgOperand(0);
813 // TODO: Does this belong in BuildLibCalls or should all of those similar
814 // functions be moved here?
815 static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
816 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
818 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
821 Module *M = B.GetInsertBlock()->getModule();
822 const DataLayout &DL = M->getDataLayout();
823 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
824 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
826 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
828 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
829 CI->setCallingConv(F->getCallingConv());
834 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
835 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
836 const TargetLibraryInfo &TLI) {
837 // This has to be a memset of zeros (bzero).
838 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
839 if (!FillValue || FillValue->getZExtValue() != 0)
842 // TODO: We should handle the case where the malloc has more than one use.
843 // This is necessary to optimize common patterns such as when the result of
844 // the malloc is checked against null or when a memset intrinsic is used in
845 // place of a memset library call.
846 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
847 if (!Malloc || !Malloc->hasOneUse())
850 // Is the inner call really malloc()?
851 Function *InnerCallee = Malloc->getCalledFunction();
856 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
857 Func != LibFunc_malloc)
860 // The memset must cover the same number of bytes that are malloc'd.
861 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
864 // Replace the malloc with a calloc. We need the data layout to know what the
865 // actual size of a 'size_t' parameter is.
866 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
867 const DataLayout &DL = Malloc->getModule()->getDataLayout();
868 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
869 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
870 Malloc->getArgOperand(0), Malloc->getAttributes(),
875 Malloc->replaceAllUsesWith(Calloc);
876 Malloc->eraseFromParent();
881 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
882 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
885 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
886 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
887 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
888 return CI->getArgOperand(0);
891 //===----------------------------------------------------------------------===//
892 // Math Library Optimizations
893 //===----------------------------------------------------------------------===//
895 /// Return a variant of Val with float type.
896 /// Currently this works in two cases: If Val is an FPExtension of a float
897 /// value to something bigger, simply return the operand.
898 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
899 /// loss of precision do so.
900 static Value *valueHasFloatPrecision(Value *Val) {
901 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
902 Value *Op = Cast->getOperand(0);
903 if (Op->getType()->isFloatTy())
906 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
907 APFloat F = Const->getValueAPF();
909 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
912 return ConstantFP::get(Const->getContext(), F);
917 /// Shrink double -> float for unary functions like 'floor'.
918 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
920 Function *Callee = CI->getCalledFunction();
921 // We know this libcall has a valid prototype, but we don't know which.
922 if (!CI->getType()->isDoubleTy())
926 // Check if all the uses for function like 'sin' are converted to float.
927 for (User *U : CI->users()) {
928 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
929 if (!Cast || !Cast->getType()->isFloatTy())
934 // If this is something like 'floor((double)floatval)', convert to floorf.
935 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
939 // If call isn't an intrinsic, check that it isn't within a function with the
940 // same name as the float version of this call.
942 // e.g. inline float expf(float val) { return (float) exp((double) val); }
944 // A similar such definition exists in the MinGW-w64 math.h header file which
945 // when compiled with -O2 -ffast-math causes the generation of infinite loops
946 // where expf is called.
947 if (!Callee->isIntrinsic()) {
948 const Function *F = CI->getFunction();
949 StringRef FName = F->getName();
950 StringRef CalleeName = Callee->getName();
951 if ((FName.size() == (CalleeName.size() + 1)) &&
952 (FName.back() == 'f') &&
953 FName.startswith(CalleeName))
957 // Propagate fast-math flags from the existing call to the new call.
958 IRBuilder<>::FastMathFlagGuard Guard(B);
959 B.setFastMathFlags(CI->getFastMathFlags());
961 // floor((double)floatval) -> (double)floorf(floatval)
962 if (Callee->isIntrinsic()) {
963 Module *M = CI->getModule();
964 Intrinsic::ID IID = Callee->getIntrinsicID();
965 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
966 V = B.CreateCall(F, V);
968 // The call is a library call rather than an intrinsic.
969 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
972 return B.CreateFPExt(V, B.getDoubleTy());
975 // Replace a libcall \p CI with a call to intrinsic \p IID
976 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
977 // Propagate fast-math flags from the existing call to the new call.
978 IRBuilder<>::FastMathFlagGuard Guard(B);
979 B.setFastMathFlags(CI->getFastMathFlags());
981 Module *M = CI->getModule();
982 Value *V = CI->getArgOperand(0);
983 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
984 CallInst *NewCall = B.CreateCall(F, V);
985 NewCall->takeName(CI);
989 /// Shrink double -> float for binary functions like 'fmin/fmax'.
990 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
991 Function *Callee = CI->getCalledFunction();
992 // We know this libcall has a valid prototype, but we don't know which.
993 if (!CI->getType()->isDoubleTy())
996 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
997 // or fmin(1.0, (double)floatval), then we convert it to fminf.
998 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1001 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1005 // Propagate fast-math flags from the existing call to the new call.
1006 IRBuilder<>::FastMathFlagGuard Guard(B);
1007 B.setFastMathFlags(CI->getFastMathFlags());
1009 // fmin((double)floatval1, (double)floatval2)
1010 // -> (double)fminf(floatval1, floatval2)
1011 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1012 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1013 Callee->getAttributes());
1014 return B.CreateFPExt(V, B.getDoubleTy());
1017 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1018 Function *Callee = CI->getCalledFunction();
1019 Value *Ret = nullptr;
1020 StringRef Name = Callee->getName();
1021 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1022 Ret = optimizeUnaryDoubleFP(CI, B, true);
1024 // cos(-x) -> cos(x)
1025 Value *Op1 = CI->getArgOperand(0);
1026 if (BinaryOperator::isFNeg(Op1)) {
1027 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1028 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1033 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1034 // Multiplications calculated using Addition Chains.
1035 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1037 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1039 if (InnerChain[Exp])
1040 return InnerChain[Exp];
1042 static const unsigned AddChain[33][2] = {
1044 {0, 0}, // Unused (base case = pow1).
1045 {1, 1}, // Unused (pre-computed).
1046 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1047 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1048 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1049 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1050 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1053 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1054 getPow(InnerChain, AddChain[Exp][1], B));
1055 return InnerChain[Exp];
1058 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1059 Function *Callee = CI->getCalledFunction();
1060 Value *Ret = nullptr;
1061 StringRef Name = Callee->getName();
1062 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1063 Ret = optimizeUnaryDoubleFP(CI, B, true);
1065 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1067 // pow(1.0, x) -> 1.0
1068 if (match(Op1, m_SpecificFP(1.0)))
1070 // pow(2.0, x) -> llvm.exp2(x)
1071 if (match(Op1, m_SpecificFP(2.0))) {
1072 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1074 return B.CreateCall(Exp2, Op2, "exp2");
1077 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1079 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1080 // pow(10.0, x) -> exp10(x)
1081 if (Op1C->isExactlyValue(10.0) &&
1082 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1084 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
1085 Callee->getAttributes());
1088 // pow(exp(x), y) -> exp(x * y)
1089 // pow(exp2(x), y) -> exp2(x * y)
1090 // We enable these only with fast-math. Besides rounding differences, the
1091 // transformation changes overflow and underflow behavior quite dramatically.
1092 // Example: x = 1000, y = 0.001.
1093 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1094 auto *OpC = dyn_cast<CallInst>(Op1);
1095 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1097 Function *OpCCallee = OpC->getCalledFunction();
1098 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1099 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
1100 IRBuilder<>::FastMathFlagGuard Guard(B);
1101 B.setFastMathFlags(CI->getFastMathFlags());
1102 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1103 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1104 OpCCallee->getAttributes());
1108 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1112 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1113 return ConstantFP::get(CI->getType(), 1.0);
1115 if (Op2C->isExactlyValue(-0.5) &&
1116 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1119 // pow(x, -0.5) -> 1.0 / sqrt(x)
1120 if (CI->hasUnsafeAlgebra()) {
1121 IRBuilder<>::FastMathFlagGuard Guard(B);
1122 B.setFastMathFlags(CI->getFastMathFlags());
1124 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1125 // intrinsic, so we match errno semantics. We also should check that the
1126 // target can in fact lower the sqrt intrinsic -- we currently have no way
1127 // to ask this question other than asking whether the target has a sqrt
1128 // libcall, which is a sufficient but not necessary condition.
1129 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
1130 Callee->getAttributes());
1132 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1136 if (Op2C->isExactlyValue(0.5) &&
1137 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1140 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1141 if (CI->hasUnsafeAlgebra()) {
1142 IRBuilder<>::FastMathFlagGuard Guard(B);
1143 B.setFastMathFlags(CI->getFastMathFlags());
1145 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1146 // intrinsic, to match errno semantics.
1147 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
1148 Callee->getAttributes());
1151 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1152 // This is faster than calling pow, and still handles negative zero
1153 // and negative infinity correctly.
1154 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1155 Value *Inf = ConstantFP::getInfinity(CI->getType());
1156 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1158 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1159 // intrinsic, to match errno semantics.
1160 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1162 Module *M = Callee->getParent();
1163 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1165 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1167 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1168 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1172 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1174 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1175 return B.CreateFMul(Op1, Op1, "pow2");
1176 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1177 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1179 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
1180 if (CI->hasUnsafeAlgebra()) {
1181 APFloat V = abs(Op2C->getValueAPF());
1182 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1183 // This transformation applies to integer exponents only.
1184 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1188 // Propagate fast math flags.
1189 IRBuilder<>::FastMathFlagGuard Guard(B);
1190 B.setFastMathFlags(CI->getFastMathFlags());
1192 // We will memoize intermediate products of the Addition Chain.
1193 Value *InnerChain[33] = {nullptr};
1194 InnerChain[1] = Op1;
1195 InnerChain[2] = B.CreateFMul(Op1, Op1);
1197 // We cannot readily convert a non-double type (like float) to a double.
1198 // So we first convert V to something which could be converted to double.
1200 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
1202 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1203 // For negative exponents simply compute the reciprocal.
1204 if (Op2C->isNegative())
1205 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1212 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1213 Function *Callee = CI->getCalledFunction();
1214 Value *Ret = nullptr;
1215 StringRef Name = Callee->getName();
1216 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1217 Ret = optimizeUnaryDoubleFP(CI, B, true);
1219 Value *Op = CI->getArgOperand(0);
1220 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1221 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1222 LibFunc LdExp = LibFunc_ldexpl;
1223 if (Op->getType()->isFloatTy())
1224 LdExp = LibFunc_ldexpf;
1225 else if (Op->getType()->isDoubleTy())
1226 LdExp = LibFunc_ldexp;
1228 if (TLI->has(LdExp)) {
1229 Value *LdExpArg = nullptr;
1230 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1231 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1232 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1233 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1234 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1235 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1239 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1240 if (!Op->getType()->isFloatTy())
1241 One = ConstantExpr::getFPExtend(One, Op->getType());
1243 Module *M = CI->getModule();
1245 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1246 Op->getType(), B.getInt32Ty());
1247 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1248 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1249 CI->setCallingConv(F->getCallingConv());
1257 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1258 Function *Callee = CI->getCalledFunction();
1259 // If we can shrink the call to a float function rather than a double
1260 // function, do that first.
1261 StringRef Name = Callee->getName();
1262 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1263 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1266 IRBuilder<>::FastMathFlagGuard Guard(B);
1268 if (CI->hasUnsafeAlgebra()) {
1269 // Unsafe algebra sets all fast-math-flags to true.
1270 FMF.setUnsafeAlgebra();
1272 // At a minimum, no-nans-fp-math must be true.
1273 if (!CI->hasNoNaNs())
1275 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1276 // "Ideally, fmax would be sensitive to the sign of zero, for example
1277 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1278 // might be impractical."
1279 FMF.setNoSignedZeros();
1282 B.setFastMathFlags(FMF);
1284 // We have a relaxed floating-point environment. We can ignore NaN-handling
1285 // and transform to a compare and select. We do not have to consider errno or
1286 // exceptions, because fmin/fmax do not have those.
1287 Value *Op0 = CI->getArgOperand(0);
1288 Value *Op1 = CI->getArgOperand(1);
1289 Value *Cmp = Callee->getName().startswith("fmin") ?
1290 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1291 return B.CreateSelect(Cmp, Op0, Op1);
1294 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1295 Function *Callee = CI->getCalledFunction();
1296 Value *Ret = nullptr;
1297 StringRef Name = Callee->getName();
1298 if (UnsafeFPShrink && hasFloatVersion(Name))
1299 Ret = optimizeUnaryDoubleFP(CI, B, true);
1301 if (!CI->hasUnsafeAlgebra())
1303 Value *Op1 = CI->getArgOperand(0);
1304 auto *OpC = dyn_cast<CallInst>(Op1);
1306 // The earlier call must also be unsafe in order to do these transforms.
1307 if (!OpC || !OpC->hasUnsafeAlgebra())
1310 // log(pow(x,y)) -> y*log(x)
1311 // This is only applicable to log, log2, log10.
1312 if (Name != "log" && Name != "log2" && Name != "log10")
1315 IRBuilder<>::FastMathFlagGuard Guard(B);
1317 FMF.setUnsafeAlgebra();
1318 B.setFastMathFlags(FMF);
1321 Function *F = OpC->getCalledFunction();
1322 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1323 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1324 return B.CreateFMul(OpC->getArgOperand(1),
1325 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1326 Callee->getAttributes()), "mul");
1328 // log(exp2(y)) -> y*log(2)
1329 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1330 TLI->has(Func) && Func == LibFunc_exp2)
1331 return B.CreateFMul(
1332 OpC->getArgOperand(0),
1333 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1334 Callee->getName(), B, Callee->getAttributes()),
1339 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1340 Function *Callee = CI->getCalledFunction();
1341 Value *Ret = nullptr;
1342 // TODO: Once we have a way (other than checking for the existince of the
1343 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1345 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1346 Callee->getIntrinsicID() == Intrinsic::sqrt))
1347 Ret = optimizeUnaryDoubleFP(CI, B, true);
1349 if (!CI->hasUnsafeAlgebra())
1352 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1353 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1356 // We're looking for a repeated factor in a multiplication tree,
1357 // so we can do this fold: sqrt(x * x) -> fabs(x);
1358 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1359 Value *Op0 = I->getOperand(0);
1360 Value *Op1 = I->getOperand(1);
1361 Value *RepeatOp = nullptr;
1362 Value *OtherOp = nullptr;
1364 // Simple match: the operands of the multiply are identical.
1367 // Look for a more complicated pattern: one of the operands is itself
1368 // a multiply, so search for a common factor in that multiply.
1369 // Note: We don't bother looking any deeper than this first level or for
1370 // variations of this pattern because instcombine's visitFMUL and/or the
1371 // reassociation pass should give us this form.
1372 Value *OtherMul0, *OtherMul1;
1373 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1374 // Pattern: sqrt((x * y) * z)
1375 if (OtherMul0 == OtherMul1 &&
1376 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
1377 // Matched: sqrt((x * x) * z)
1378 RepeatOp = OtherMul0;
1386 // Fast math flags for any created instructions should match the sqrt
1388 IRBuilder<>::FastMathFlagGuard Guard(B);
1389 B.setFastMathFlags(I->getFastMathFlags());
1391 // If we found a repeated factor, hoist it out of the square root and
1392 // replace it with the fabs of that factor.
1393 Module *M = Callee->getParent();
1394 Type *ArgType = I->getType();
1395 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1396 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1398 // If we found a non-repeated factor, we still need to get its square
1399 // root. We then multiply that by the value that was simplified out
1400 // of the square root calculation.
1401 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1402 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1403 return B.CreateFMul(FabsCall, SqrtCall);
1408 // TODO: Generalize to handle any trig function and its inverse.
1409 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1410 Function *Callee = CI->getCalledFunction();
1411 Value *Ret = nullptr;
1412 StringRef Name = Callee->getName();
1413 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1414 Ret = optimizeUnaryDoubleFP(CI, B, true);
1416 Value *Op1 = CI->getArgOperand(0);
1417 auto *OpC = dyn_cast<CallInst>(Op1);
1421 // Both calls must allow unsafe optimizations in order to remove them.
1422 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1425 // tan(atan(x)) -> x
1426 // tanf(atanf(x)) -> x
1427 // tanl(atanl(x)) -> x
1429 Function *F = OpC->getCalledFunction();
1430 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1431 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1432 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1433 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1434 Ret = OpC->getArgOperand(0);
1438 static bool isTrigLibCall(CallInst *CI) {
1439 // We can only hope to do anything useful if we can ignore things like errno
1440 // and floating-point exceptions.
1441 // We already checked the prototype.
1442 return CI->hasFnAttr(Attribute::NoUnwind) &&
1443 CI->hasFnAttr(Attribute::ReadNone);
1446 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1447 bool UseFloat, Value *&Sin, Value *&Cos,
1449 Type *ArgTy = Arg->getType();
1453 Triple T(OrigCallee->getParent()->getTargetTriple());
1455 Name = "__sincospif_stret";
1457 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1458 // x86_64 can't use {float, float} since that would be returned in both
1459 // xmm0 and xmm1, which isn't what a real struct would do.
1460 ResTy = T.getArch() == Triple::x86_64
1461 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1462 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
1464 Name = "__sincospi_stret";
1465 ResTy = StructType::get(ArgTy, ArgTy);
1468 Module *M = OrigCallee->getParent();
1469 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1472 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1473 // If the argument is an instruction, it must dominate all uses so put our
1474 // sincos call there.
1475 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1477 // Otherwise (e.g. for a constant) the beginning of the function is as
1478 // good a place as any.
1479 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1480 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1483 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1485 if (SinCos->getType()->isStructTy()) {
1486 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1487 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1489 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1491 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1496 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1497 // Make sure the prototype is as expected, otherwise the rest of the
1498 // function is probably invalid and likely to abort.
1499 if (!isTrigLibCall(CI))
1502 Value *Arg = CI->getArgOperand(0);
1503 SmallVector<CallInst *, 1> SinCalls;
1504 SmallVector<CallInst *, 1> CosCalls;
1505 SmallVector<CallInst *, 1> SinCosCalls;
1507 bool IsFloat = Arg->getType()->isFloatTy();
1509 // Look for all compatible sinpi, cospi and sincospi calls with the same
1510 // argument. If there are enough (in some sense) we can make the
1512 Function *F = CI->getFunction();
1513 for (User *U : Arg->users())
1514 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1516 // It's only worthwhile if both sinpi and cospi are actually used.
1517 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1520 Value *Sin, *Cos, *SinCos;
1521 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1523 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1525 for (CallInst *C : Calls)
1526 replaceAllUsesWith(C, Res);
1529 replaceTrigInsts(SinCalls, Sin);
1530 replaceTrigInsts(CosCalls, Cos);
1531 replaceTrigInsts(SinCosCalls, SinCos);
1536 void LibCallSimplifier::classifyArgUse(
1537 Value *Val, Function *F, bool IsFloat,
1538 SmallVectorImpl<CallInst *> &SinCalls,
1539 SmallVectorImpl<CallInst *> &CosCalls,
1540 SmallVectorImpl<CallInst *> &SinCosCalls) {
1541 CallInst *CI = dyn_cast<CallInst>(Val);
1546 // Don't consider calls in other functions.
1547 if (CI->getFunction() != F)
1550 Function *Callee = CI->getCalledFunction();
1552 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1557 if (Func == LibFunc_sinpif)
1558 SinCalls.push_back(CI);
1559 else if (Func == LibFunc_cospif)
1560 CosCalls.push_back(CI);
1561 else if (Func == LibFunc_sincospif_stret)
1562 SinCosCalls.push_back(CI);
1564 if (Func == LibFunc_sinpi)
1565 SinCalls.push_back(CI);
1566 else if (Func == LibFunc_cospi)
1567 CosCalls.push_back(CI);
1568 else if (Func == LibFunc_sincospi_stret)
1569 SinCosCalls.push_back(CI);
1573 //===----------------------------------------------------------------------===//
1574 // Integer Library Call Optimizations
1575 //===----------------------------------------------------------------------===//
1577 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1578 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1579 Value *Op = CI->getArgOperand(0);
1580 Type *ArgType = Op->getType();
1581 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1582 Intrinsic::cttz, ArgType);
1583 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1584 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1585 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1587 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1588 return B.CreateSelect(Cond, V, B.getInt32(0));
1591 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1592 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1593 Value *Op = CI->getArgOperand(0);
1594 Type *ArgType = Op->getType();
1595 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1596 Intrinsic::ctlz, ArgType);
1597 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1598 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1600 return B.CreateIntCast(V, CI->getType(), false);
1603 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1604 // abs(x) -> x >s -1 ? x : -x
1605 Value *Op = CI->getArgOperand(0);
1607 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1608 Value *Neg = B.CreateNeg(Op, "neg");
1609 return B.CreateSelect(Pos, Op, Neg);
1612 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1613 // isdigit(c) -> (c-'0') <u 10
1614 Value *Op = CI->getArgOperand(0);
1615 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1616 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1617 return B.CreateZExt(Op, CI->getType());
1620 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1621 // isascii(c) -> c <u 128
1622 Value *Op = CI->getArgOperand(0);
1623 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1624 return B.CreateZExt(Op, CI->getType());
1627 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1628 // toascii(c) -> c & 0x7f
1629 return B.CreateAnd(CI->getArgOperand(0),
1630 ConstantInt::get(CI->getType(), 0x7F));
1633 //===----------------------------------------------------------------------===//
1634 // Formatting and IO Library Call Optimizations
1635 //===----------------------------------------------------------------------===//
1637 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1639 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1641 Function *Callee = CI->getCalledFunction();
1642 // Error reporting calls should be cold, mark them as such.
1643 // This applies even to non-builtin calls: it is only a hint and applies to
1644 // functions that the frontend might not understand as builtins.
1646 // This heuristic was suggested in:
1647 // Improving Static Branch Prediction in a Compiler
1648 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1649 // Proceedings of PACT'98, Oct. 1998, IEEE
1650 if (!CI->hasFnAttr(Attribute::Cold) &&
1651 isReportingError(Callee, CI, StreamArg)) {
1652 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
1658 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1659 if (!Callee || !Callee->isDeclaration())
1665 // These functions might be considered cold, but only if their stream
1666 // argument is stderr.
1668 if (StreamArg >= (int)CI->getNumArgOperands())
1670 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1673 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1674 if (!GV || !GV->isDeclaration())
1676 return GV->getName() == "stderr";
1679 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1680 // Check for a fixed format string.
1681 StringRef FormatStr;
1682 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1685 // Empty format string -> noop.
1686 if (FormatStr.empty()) // Tolerate printf's declared void.
1687 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1689 // Do not do any of the following transformations if the printf return value
1690 // is used, in general the printf return value is not compatible with either
1691 // putchar() or puts().
1692 if (!CI->use_empty())
1695 // printf("x") -> putchar('x'), even for "%" and "%%".
1696 if (FormatStr.size() == 1 || FormatStr == "%%")
1697 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1699 // printf("%s", "a") --> putchar('a')
1700 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1702 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1704 if (ChrStr.size() != 1)
1706 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1709 // printf("foo\n") --> puts("foo")
1710 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1711 FormatStr.find('%') == StringRef::npos) { // No format characters.
1712 // Create a string literal with no \n on it. We expect the constant merge
1713 // pass to be run after this pass, to merge duplicate strings.
1714 FormatStr = FormatStr.drop_back();
1715 Value *GV = B.CreateGlobalString(FormatStr, "str");
1716 return emitPutS(GV, B, TLI);
1719 // Optimize specific format strings.
1720 // printf("%c", chr) --> putchar(chr)
1721 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1722 CI->getArgOperand(1)->getType()->isIntegerTy())
1723 return emitPutChar(CI->getArgOperand(1), B, TLI);
1725 // printf("%s\n", str) --> puts(str)
1726 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1727 CI->getArgOperand(1)->getType()->isPointerTy())
1728 return emitPutS(CI->getArgOperand(1), B, TLI);
1732 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1734 Function *Callee = CI->getCalledFunction();
1735 FunctionType *FT = Callee->getFunctionType();
1736 if (Value *V = optimizePrintFString(CI, B)) {
1740 // printf(format, ...) -> iprintf(format, ...) if no floating point
1742 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
1743 Module *M = B.GetInsertBlock()->getParent()->getParent();
1744 Constant *IPrintFFn =
1745 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1746 CallInst *New = cast<CallInst>(CI->clone());
1747 New->setCalledFunction(IPrintFFn);
1754 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1755 // Check for a fixed format string.
1756 StringRef FormatStr;
1757 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1760 // If we just have a format string (nothing else crazy) transform it.
1761 if (CI->getNumArgOperands() == 2) {
1762 // Make sure there's no % in the constant array. We could try to handle
1763 // %% -> % in the future if we cared.
1764 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1765 if (FormatStr[i] == '%')
1766 return nullptr; // we found a format specifier, bail out.
1768 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1769 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1770 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1771 FormatStr.size() + 1),
1772 1); // Copy the null byte.
1773 return ConstantInt::get(CI->getType(), FormatStr.size());
1776 // The remaining optimizations require the format string to be "%s" or "%c"
1777 // and have an extra operand.
1778 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1779 CI->getNumArgOperands() < 3)
1782 // Decode the second character of the format string.
1783 if (FormatStr[1] == 'c') {
1784 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1785 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1787 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1788 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1789 B.CreateStore(V, Ptr);
1790 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1791 B.CreateStore(B.getInt8(0), Ptr);
1793 return ConstantInt::get(CI->getType(), 1);
1796 if (FormatStr[1] == 's') {
1797 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1798 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1801 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1805 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1806 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1808 // The sprintf result is the unincremented number of bytes in the string.
1809 return B.CreateIntCast(Len, CI->getType(), false);
1814 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1815 Function *Callee = CI->getCalledFunction();
1816 FunctionType *FT = Callee->getFunctionType();
1817 if (Value *V = optimizeSPrintFString(CI, B)) {
1821 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1823 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
1824 Module *M = B.GetInsertBlock()->getParent()->getParent();
1825 Constant *SIPrintFFn =
1826 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1827 CallInst *New = cast<CallInst>(CI->clone());
1828 New->setCalledFunction(SIPrintFFn);
1835 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1836 optimizeErrorReporting(CI, B, 0);
1838 // All the optimizations depend on the format string.
1839 StringRef FormatStr;
1840 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1843 // Do not do any of the following transformations if the fprintf return
1844 // value is used, in general the fprintf return value is not compatible
1845 // with fwrite(), fputc() or fputs().
1846 if (!CI->use_empty())
1849 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1850 if (CI->getNumArgOperands() == 2) {
1851 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1852 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1853 return nullptr; // We found a format specifier.
1856 CI->getArgOperand(1),
1857 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1858 CI->getArgOperand(0), B, DL, TLI);
1861 // The remaining optimizations require the format string to be "%s" or "%c"
1862 // and have an extra operand.
1863 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1864 CI->getNumArgOperands() < 3)
1867 // Decode the second character of the format string.
1868 if (FormatStr[1] == 'c') {
1869 // fprintf(F, "%c", chr) --> fputc(chr, F)
1870 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1872 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1875 if (FormatStr[1] == 's') {
1876 // fprintf(F, "%s", str) --> fputs(str, F)
1877 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1879 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1884 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1885 Function *Callee = CI->getCalledFunction();
1886 FunctionType *FT = Callee->getFunctionType();
1887 if (Value *V = optimizeFPrintFString(CI, B)) {
1891 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1892 // floating point arguments.
1893 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
1894 Module *M = B.GetInsertBlock()->getParent()->getParent();
1895 Constant *FIPrintFFn =
1896 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1897 CallInst *New = cast<CallInst>(CI->clone());
1898 New->setCalledFunction(FIPrintFFn);
1905 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1906 optimizeErrorReporting(CI, B, 3);
1908 // Get the element size and count.
1909 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1910 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1911 if (!SizeC || !CountC)
1913 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1915 // If this is writing zero records, remove the call (it's a noop).
1917 return ConstantInt::get(CI->getType(), 0);
1919 // If this is writing one byte, turn it into fputc.
1920 // This optimisation is only valid, if the return value is unused.
1921 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1922 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1923 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
1924 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1930 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1931 optimizeErrorReporting(CI, B, 1);
1933 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1934 // requires more arguments and thus extra MOVs are required.
1935 if (CI->getParent()->getParent()->optForSize())
1938 // We can't optimize if return value is used.
1939 if (!CI->use_empty())
1942 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1943 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1947 // Known to have no uses (see above).
1949 CI->getArgOperand(0),
1950 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1951 CI->getArgOperand(1), B, DL, TLI);
1954 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1955 // Check for a constant string.
1957 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1960 if (Str.empty() && CI->use_empty()) {
1961 // puts("") -> putchar('\n')
1962 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
1963 if (CI->use_empty() || !Res)
1965 return B.CreateIntCast(Res, CI->getType(), true);
1971 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1973 SmallString<20> FloatFuncName = FuncName;
1974 FloatFuncName += 'f';
1975 if (TLI->getLibFunc(FloatFuncName, Func))
1976 return TLI->has(Func);
1980 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1981 IRBuilder<> &Builder) {
1983 Function *Callee = CI->getCalledFunction();
1984 // Check for string/memory library functions.
1985 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
1986 // Make sure we never change the calling convention.
1987 assert((ignoreCallingConv(Func) ||
1988 isCallingConvCCompatible(CI)) &&
1989 "Optimizing string/memory libcall would change the calling convention");
1991 case LibFunc_strcat:
1992 return optimizeStrCat(CI, Builder);
1993 case LibFunc_strncat:
1994 return optimizeStrNCat(CI, Builder);
1995 case LibFunc_strchr:
1996 return optimizeStrChr(CI, Builder);
1997 case LibFunc_strrchr:
1998 return optimizeStrRChr(CI, Builder);
1999 case LibFunc_strcmp:
2000 return optimizeStrCmp(CI, Builder);
2001 case LibFunc_strncmp:
2002 return optimizeStrNCmp(CI, Builder);
2003 case LibFunc_strcpy:
2004 return optimizeStrCpy(CI, Builder);
2005 case LibFunc_stpcpy:
2006 return optimizeStpCpy(CI, Builder);
2007 case LibFunc_strncpy:
2008 return optimizeStrNCpy(CI, Builder);
2009 case LibFunc_strlen:
2010 return optimizeStrLen(CI, Builder);
2011 case LibFunc_strpbrk:
2012 return optimizeStrPBrk(CI, Builder);
2013 case LibFunc_strtol:
2014 case LibFunc_strtod:
2015 case LibFunc_strtof:
2016 case LibFunc_strtoul:
2017 case LibFunc_strtoll:
2018 case LibFunc_strtold:
2019 case LibFunc_strtoull:
2020 return optimizeStrTo(CI, Builder);
2021 case LibFunc_strspn:
2022 return optimizeStrSpn(CI, Builder);
2023 case LibFunc_strcspn:
2024 return optimizeStrCSpn(CI, Builder);
2025 case LibFunc_strstr:
2026 return optimizeStrStr(CI, Builder);
2027 case LibFunc_memchr:
2028 return optimizeMemChr(CI, Builder);
2029 case LibFunc_memcmp:
2030 return optimizeMemCmp(CI, Builder);
2031 case LibFunc_memcpy:
2032 return optimizeMemCpy(CI, Builder);
2033 case LibFunc_memmove:
2034 return optimizeMemMove(CI, Builder);
2035 case LibFunc_memset:
2036 return optimizeMemSet(CI, Builder);
2037 case LibFunc_wcslen:
2038 return optimizeWcslen(CI, Builder);
2046 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2047 if (CI->isNoBuiltin())
2051 Function *Callee = CI->getCalledFunction();
2052 StringRef FuncName = Callee->getName();
2054 SmallVector<OperandBundleDef, 2> OpBundles;
2055 CI->getOperandBundlesAsDefs(OpBundles);
2056 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2057 bool isCallingConvC = isCallingConvCCompatible(CI);
2059 // Command-line parameter overrides instruction attribute.
2060 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2061 UnsafeFPShrink = EnableUnsafeFPShrink;
2062 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
2063 UnsafeFPShrink = true;
2065 // First, check for intrinsics.
2066 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2067 if (!isCallingConvC)
2069 switch (II->getIntrinsicID()) {
2070 case Intrinsic::pow:
2071 return optimizePow(CI, Builder);
2072 case Intrinsic::exp2:
2073 return optimizeExp2(CI, Builder);
2074 case Intrinsic::log:
2075 return optimizeLog(CI, Builder);
2076 case Intrinsic::sqrt:
2077 return optimizeSqrt(CI, Builder);
2078 // TODO: Use foldMallocMemset() with memset intrinsic.
2084 // Also try to simplify calls to fortified library functions.
2085 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2086 // Try to further simplify the result.
2087 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2088 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2089 // Use an IR Builder from SimplifiedCI if available instead of CI
2090 // to guarantee we reach all uses we might replace later on.
2091 IRBuilder<> TmpBuilder(SimplifiedCI);
2092 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2093 // If we were able to further simplify, remove the now redundant call.
2094 SimplifiedCI->replaceAllUsesWith(V);
2095 SimplifiedCI->eraseFromParent();
2099 return SimplifiedFortifiedCI;
2102 // Then check for known library functions.
2103 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2104 // We never change the calling convention.
2105 if (!ignoreCallingConv(Func) && !isCallingConvC)
2107 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2113 return optimizeCos(CI, Builder);
2114 case LibFunc_sinpif:
2116 case LibFunc_cospif:
2118 return optimizeSinCosPi(CI, Builder);
2122 return optimizePow(CI, Builder);
2126 return optimizeExp2(CI, Builder);
2130 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2134 return optimizeSqrt(CI, Builder);
2138 return optimizeFFS(CI, Builder);
2142 return optimizeFls(CI, Builder);
2146 return optimizeAbs(CI, Builder);
2147 case LibFunc_isdigit:
2148 return optimizeIsDigit(CI, Builder);
2149 case LibFunc_isascii:
2150 return optimizeIsAscii(CI, Builder);
2151 case LibFunc_toascii:
2152 return optimizeToAscii(CI, Builder);
2153 case LibFunc_printf:
2154 return optimizePrintF(CI, Builder);
2155 case LibFunc_sprintf:
2156 return optimizeSPrintF(CI, Builder);
2157 case LibFunc_fprintf:
2158 return optimizeFPrintF(CI, Builder);
2159 case LibFunc_fwrite:
2160 return optimizeFWrite(CI, Builder);
2162 return optimizeFPuts(CI, Builder);
2168 return optimizeLog(CI, Builder);
2170 return optimizePuts(CI, Builder);
2174 return optimizeTan(CI, Builder);
2175 case LibFunc_perror:
2176 return optimizeErrorReporting(CI, Builder);
2177 case LibFunc_vfprintf:
2178 case LibFunc_fiprintf:
2179 return optimizeErrorReporting(CI, Builder, 0);
2181 return optimizeErrorReporting(CI, Builder, 1);
2183 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2185 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2187 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2188 case LibFunc_nearbyint:
2189 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2191 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2193 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2208 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2209 return optimizeUnaryDoubleFP(CI, Builder, true);
2211 case LibFunc_copysign:
2212 if (hasFloatVersion(FuncName))
2213 return optimizeBinaryDoubleFP(CI, Builder);
2221 return optimizeFMinFMax(CI, Builder);
2229 LibCallSimplifier::LibCallSimplifier(
2230 const DataLayout &DL, const TargetLibraryInfo *TLI,
2231 function_ref<void(Instruction *, Value *)> Replacer)
2232 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2233 Replacer(Replacer) {}
2235 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2236 // Indirect through the replacer used in this instance.
2241 // Additional cases that we need to add to this file:
2244 // * cbrt(expN(X)) -> expN(x/3)
2245 // * cbrt(sqrt(x)) -> pow(x,1/6)
2246 // * cbrt(cbrt(x)) -> pow(x,1/9)
2249 // * exp(log(x)) -> x
2252 // * log(exp(x)) -> x
2253 // * log(exp(y)) -> y*log(e)
2254 // * log(exp10(y)) -> y*log(10)
2255 // * log(sqrt(x)) -> 0.5*log(x)
2258 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2259 // * pow(pow(x,y),z)-> pow(x,y*z)
2262 // * signbit(cnst) -> cnst'
2263 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2265 // sqrt, sqrtf, sqrtl:
2266 // * sqrt(expN(x)) -> expN(x*0.5)
2267 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2268 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2271 //===----------------------------------------------------------------------===//
2272 // Fortified Library Call Optimizations
2273 //===----------------------------------------------------------------------===//
2275 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2279 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2281 if (ConstantInt *ObjSizeCI =
2282 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2283 if (ObjSizeCI->isMinusOne())
2285 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2286 if (OnlyLowerUnknownSize)
2289 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2290 // If the length is 0 we don't know how long it is and so we can't
2291 // remove the check.
2294 return ObjSizeCI->getZExtValue() >= Len;
2296 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2297 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2302 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2305 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2306 CI->getArgOperand(2), 1);
2307 return CI->getArgOperand(0);
2312 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2314 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2315 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2316 CI->getArgOperand(2), 1);
2317 return CI->getArgOperand(0);
2322 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2324 // TODO: Try foldMallocMemset() here.
2326 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2327 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2328 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2329 return CI->getArgOperand(0);
2334 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2337 Function *Callee = CI->getCalledFunction();
2338 StringRef Name = Callee->getName();
2339 const DataLayout &DL = CI->getModule()->getDataLayout();
2340 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2341 *ObjSize = CI->getArgOperand(2);
2343 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2344 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2345 Value *StrLen = emitStrLen(Src, B, DL, TLI);
2346 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2349 // If a) we don't have any length information, or b) we know this will
2350 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2351 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2352 // TODO: It might be nice to get a maximum length out of the possible
2353 // string lengths for varying.
2354 if (isFortifiedCallFoldable(CI, 2, 1, true))
2355 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2357 if (OnlyLowerUnknownSize)
2360 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2361 uint64_t Len = GetStringLength(Src);
2365 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2366 Value *LenV = ConstantInt::get(SizeTTy, Len);
2367 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2368 // If the function was an __stpcpy_chk, and we were able to fold it into
2369 // a __memcpy_chk, we still need to return the correct end pointer.
2370 if (Ret && Func == LibFunc_stpcpy_chk)
2371 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2375 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2378 Function *Callee = CI->getCalledFunction();
2379 StringRef Name = Callee->getName();
2380 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2381 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2382 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2388 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2389 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2390 // Some clang users checked for _chk libcall availability using:
2391 // __has_builtin(__builtin___memcpy_chk)
2392 // When compiling with -fno-builtin, this is always true.
2393 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2394 // end up with fortified libcalls, which isn't acceptable in a freestanding
2395 // environment which only provides their non-fortified counterparts.
2397 // Until we change clang and/or teach external users to check for availability
2398 // differently, disregard the "nobuiltin" attribute and TLI::has.
2403 Function *Callee = CI->getCalledFunction();
2405 SmallVector<OperandBundleDef, 2> OpBundles;
2406 CI->getOperandBundlesAsDefs(OpBundles);
2407 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2408 bool isCallingConvC = isCallingConvCCompatible(CI);
2410 // First, check that this is a known library functions and that the prototype
2412 if (!TLI->getLibFunc(*Callee, Func))
2415 // We never change the calling convention.
2416 if (!ignoreCallingConv(Func) && !isCallingConvC)
2420 case LibFunc_memcpy_chk:
2421 return optimizeMemCpyChk(CI, Builder);
2422 case LibFunc_memmove_chk:
2423 return optimizeMemMoveChk(CI, Builder);
2424 case LibFunc_memset_chk:
2425 return optimizeMemSetChk(CI, Builder);
2426 case LibFunc_stpcpy_chk:
2427 case LibFunc_strcpy_chk:
2428 return optimizeStrpCpyChk(CI, Builder, Func);
2429 case LibFunc_stpncpy_chk:
2430 case LibFunc_strncpy_chk:
2431 return optimizeStrpNCpyChk(CI, Builder, Func);
2438 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2439 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2440 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}