1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 14 // 15 //===----------------------------------------------------------------------===// 16 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/ConstantFolding.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/ValueTracking.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/KnownBits.h" 35 #include "llvm/Transforms/Utils/BuildLibCalls.h" 36 #include "llvm/Transforms/Utils/Local.h" 37 38 using namespace llvm; 39 using namespace PatternMatch; 40 41 static cl::opt<bool> 42 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, 43 cl::init(false), 44 cl::desc("Enable unsafe double to float " 45 "shrinking for math lib calls")); 46 47 48 //===----------------------------------------------------------------------===// 49 // Helper Functions 50 //===----------------------------------------------------------------------===// 51 52 static bool ignoreCallingConv(LibFunc Func) { 53 return Func == LibFunc_abs || Func == LibFunc_labs || 54 Func == LibFunc_llabs || Func == LibFunc_strlen; 55 } 56 57 static bool isCallingConvCCompatible(CallInst *CI) { 58 switch(CI->getCallingConv()) { 59 default: 60 return false; 61 case llvm::CallingConv::C: 62 return true; 63 case llvm::CallingConv::ARM_APCS: 64 case llvm::CallingConv::ARM_AAPCS: 65 case llvm::CallingConv::ARM_AAPCS_VFP: { 66 67 // The iOS ABI diverges from the standard in some cases, so for now don't 68 // try to simplify those calls. 69 if (Triple(CI->getModule()->getTargetTriple()).isiOS()) 70 return false; 71 72 auto *FuncTy = CI->getFunctionType(); 73 74 if (!FuncTy->getReturnType()->isPointerTy() && 75 !FuncTy->getReturnType()->isIntegerTy() && 76 !FuncTy->getReturnType()->isVoidTy()) 77 return false; 78 79 for (auto Param : FuncTy->params()) { 80 if (!Param->isPointerTy() && !Param->isIntegerTy()) 81 return false; 82 } 83 return true; 84 } 85 } 86 return false; 87 } 88 89 /// Return true if it is only used in equality comparisons with With. 90 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 91 for (User *U : V->users()) { 92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 93 if (IC->isEquality() && IC->getOperand(1) == With) 94 continue; 95 // Unknown instruction. 96 return false; 97 } 98 return true; 99 } 100 101 static bool callHasFloatingPointArgument(const CallInst *CI) { 102 return any_of(CI->operands(), [](const Use &OI) { 103 return OI->getType()->isFloatingPointTy(); 104 }); 105 } 106 107 //===----------------------------------------------------------------------===// 108 // String and Memory Library Call Optimizations 109 //===----------------------------------------------------------------------===// 110 111 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) { 112 // Extract some information from the instruction 113 Value *Dst = CI->getArgOperand(0); 114 Value *Src = CI->getArgOperand(1); 115 116 // See if we can get the length of the input string. 117 uint64_t Len = GetStringLength(Src); 118 if (Len == 0) 119 return nullptr; 120 --Len; // Unbias length. 121 122 // Handle the simple, do-nothing case: strcat(x, "") -> x 123 if (Len == 0) 124 return Dst; 125 126 return emitStrLenMemCpy(Src, Dst, Len, B); 127 } 128 129 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 130 IRBuilder<> &B) { 131 // We need to find the end of the destination string. That's where the 132 // memory is to be moved to. We just generate a call to strlen. 133 Value *DstLen = emitStrLen(Dst, B, DL, TLI); 134 if (!DstLen) 135 return nullptr; 136 137 // Now that we have the destination's length, we must index into the 138 // destination's pointer to get the actual memcpy destination (end of 139 // the string .. we're concatenating). 140 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr"); 141 142 // We have enough information to now generate the memcpy call to do the 143 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 144 B.CreateMemCpy(CpyDst, Src, 145 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1), 146 1); 147 return Dst; 148 } 149 150 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) { 151 // Extract some information from the instruction. 152 Value *Dst = CI->getArgOperand(0); 153 Value *Src = CI->getArgOperand(1); 154 uint64_t Len; 155 156 // We don't do anything if length is not constant. 157 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2))) 158 Len = LengthArg->getZExtValue(); 159 else 160 return nullptr; 161 162 // See if we can get the length of the input string. 163 uint64_t SrcLen = GetStringLength(Src); 164 if (SrcLen == 0) 165 return nullptr; 166 --SrcLen; // Unbias length. 167 168 // Handle the simple, do-nothing cases: 169 // strncat(x, "", c) -> x 170 // strncat(x, c, 0) -> x 171 if (SrcLen == 0 || Len == 0) 172 return Dst; 173 174 // We don't optimize this case. 175 if (Len < SrcLen) 176 return nullptr; 177 178 // strncat(x, s, c) -> strcat(x, s) 179 // s is constant so the strcat can be optimized further. 180 return emitStrLenMemCpy(Src, Dst, SrcLen, B); 181 } 182 183 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) { 184 Function *Callee = CI->getCalledFunction(); 185 FunctionType *FT = Callee->getFunctionType(); 186 Value *SrcStr = CI->getArgOperand(0); 187 188 // If the second operand is non-constant, see if we can compute the length 189 // of the input string and turn this into memchr. 190 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 191 if (!CharC) { 192 uint64_t Len = GetStringLength(SrcStr); 193 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32. 194 return nullptr; 195 196 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul. 197 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 198 B, DL, TLI); 199 } 200 201 // Otherwise, the character is a constant, see if the first argument is 202 // a string literal. If so, we can constant fold. 203 StringRef Str; 204 if (!getConstantStringInfo(SrcStr, Str)) { 205 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) 206 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI), 207 "strchr"); 208 return nullptr; 209 } 210 211 // Compute the offset, make sure to handle the case when we're searching for 212 // zero (a weird way to spell strlen). 213 size_t I = (0xFF & CharC->getSExtValue()) == 0 214 ? Str.size() 215 : Str.find(CharC->getSExtValue()); 216 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 217 return Constant::getNullValue(CI->getType()); 218 219 // strchr(s+n,c) -> gep(s+n+i,c) 220 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr"); 221 } 222 223 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) { 224 Value *SrcStr = CI->getArgOperand(0); 225 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 226 227 // Cannot fold anything if we're not looking for a constant. 228 if (!CharC) 229 return nullptr; 230 231 StringRef Str; 232 if (!getConstantStringInfo(SrcStr, Str)) { 233 // strrchr(s, 0) -> strchr(s, 0) 234 if (CharC->isZero()) 235 return emitStrChr(SrcStr, '\0', B, TLI); 236 return nullptr; 237 } 238 239 // Compute the offset. 240 size_t I = (0xFF & CharC->getSExtValue()) == 0 241 ? Str.size() 242 : Str.rfind(CharC->getSExtValue()); 243 if (I == StringRef::npos) // Didn't find the char. Return null. 244 return Constant::getNullValue(CI->getType()); 245 246 // strrchr(s+n,c) -> gep(s+n+i,c) 247 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr"); 248 } 249 250 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) { 251 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 252 if (Str1P == Str2P) // strcmp(x,x) -> 0 253 return ConstantInt::get(CI->getType(), 0); 254 255 StringRef Str1, Str2; 256 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 257 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 258 259 // strcmp(x, y) -> cnst (if both x and y are constant strings) 260 if (HasStr1 && HasStr2) 261 return ConstantInt::get(CI->getType(), Str1.compare(Str2)); 262 263 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 264 return B.CreateNeg( 265 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType())); 266 267 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 268 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 269 270 // strcmp(P, "x") -> memcmp(P, "x", 2) 271 uint64_t Len1 = GetStringLength(Str1P); 272 uint64_t Len2 = GetStringLength(Str2P); 273 if (Len1 && Len2) { 274 return emitMemCmp(Str1P, Str2P, 275 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 276 std::min(Len1, Len2)), 277 B, DL, TLI); 278 } 279 280 return nullptr; 281 } 282 283 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) { 284 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 285 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 286 return ConstantInt::get(CI->getType(), 0); 287 288 // Get the length argument if it is constant. 289 uint64_t Length; 290 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2))) 291 Length = LengthArg->getZExtValue(); 292 else 293 return nullptr; 294 295 if (Length == 0) // strncmp(x,y,0) -> 0 296 return ConstantInt::get(CI->getType(), 0); 297 298 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 299 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI); 300 301 StringRef Str1, Str2; 302 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 303 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 304 305 // strncmp(x, y) -> cnst (if both x and y are constant strings) 306 if (HasStr1 && HasStr2) { 307 StringRef SubStr1 = Str1.substr(0, Length); 308 StringRef SubStr2 = Str2.substr(0, Length); 309 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2)); 310 } 311 312 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 313 return B.CreateNeg( 314 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType())); 315 316 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 317 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 318 319 return nullptr; 320 } 321 322 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) { 323 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 324 if (Dst == Src) // strcpy(x,x) -> x 325 return Src; 326 327 // See if we can get the length of the input string. 328 uint64_t Len = GetStringLength(Src); 329 if (Len == 0) 330 return nullptr; 331 332 // We have enough information to now generate the memcpy call to do the 333 // copy for us. Make a memcpy to copy the nul byte with align = 1. 334 B.CreateMemCpy(Dst, Src, 335 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1); 336 return Dst; 337 } 338 339 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) { 340 Function *Callee = CI->getCalledFunction(); 341 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 342 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 343 Value *StrLen = emitStrLen(Src, B, DL, TLI); 344 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 345 } 346 347 // See if we can get the length of the input string. 348 uint64_t Len = GetStringLength(Src); 349 if (Len == 0) 350 return nullptr; 351 352 Type *PT = Callee->getFunctionType()->getParamType(0); 353 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len); 354 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst, 355 ConstantInt::get(DL.getIntPtrType(PT), Len - 1)); 356 357 // We have enough information to now generate the memcpy call to do the 358 // copy for us. Make a memcpy to copy the nul byte with align = 1. 359 B.CreateMemCpy(Dst, Src, LenV, 1); 360 return DstEnd; 361 } 362 363 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) { 364 Function *Callee = CI->getCalledFunction(); 365 Value *Dst = CI->getArgOperand(0); 366 Value *Src = CI->getArgOperand(1); 367 Value *LenOp = CI->getArgOperand(2); 368 369 // See if we can get the length of the input string. 370 uint64_t SrcLen = GetStringLength(Src); 371 if (SrcLen == 0) 372 return nullptr; 373 --SrcLen; 374 375 if (SrcLen == 0) { 376 // strncpy(x, "", y) -> memset(x, '\0', y, 1) 377 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1); 378 return Dst; 379 } 380 381 uint64_t Len; 382 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp)) 383 Len = LengthArg->getZExtValue(); 384 else 385 return nullptr; 386 387 if (Len == 0) 388 return Dst; // strncpy(x, y, 0) -> x 389 390 // Let strncpy handle the zero padding 391 if (Len > SrcLen + 1) 392 return nullptr; 393 394 Type *PT = Callee->getFunctionType()->getParamType(0); 395 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant] 396 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1); 397 398 return Dst; 399 } 400 401 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B, 402 unsigned CharSize) { 403 Value *Src = CI->getArgOperand(0); 404 405 // Constant folding: strlen("xyz") -> 3 406 if (uint64_t Len = GetStringLength(Src, CharSize)) 407 return ConstantInt::get(CI->getType(), Len - 1); 408 409 // If s is a constant pointer pointing to a string literal, we can fold 410 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 411 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 412 // We only try to simplify strlen when the pointer s points to an array 413 // of i8. Otherwise, we would need to scale the offset x before doing the 414 // subtraction. This will make the optimization more complex, and it's not 415 // very useful because calling strlen for a pointer of other types is 416 // very uncommon. 417 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 418 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 419 return nullptr; 420 421 ConstantDataArraySlice Slice; 422 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 423 uint64_t NullTermIdx; 424 if (Slice.Array == nullptr) { 425 NullTermIdx = 0; 426 } else { 427 NullTermIdx = ~((uint64_t)0); 428 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 429 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 430 NullTermIdx = I; 431 break; 432 } 433 } 434 // If the string does not have '\0', leave it to strlen to compute 435 // its length. 436 if (NullTermIdx == ~((uint64_t)0)) 437 return nullptr; 438 } 439 440 Value *Offset = GEP->getOperand(2); 441 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 442 Known.Zero.flipAllBits(); 443 uint64_t ArrSize = 444 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 445 446 // KnownZero's bits are flipped, so zeros in KnownZero now represent 447 // bits known to be zeros in Offset, and ones in KnowZero represent 448 // bits unknown in Offset. Therefore, Offset is known to be in range 449 // [0, NullTermIdx] when the flipped KnownZero is non-negative and 450 // unsigned-less-than NullTermIdx. 451 // 452 // If Offset is not provably in the range [0, NullTermIdx], we can still 453 // optimize if we can prove that the program has undefined behavior when 454 // Offset is outside that range. That is the case when GEP->getOperand(0) 455 // is a pointer to an object whose memory extent is NullTermIdx+1. 456 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) || 457 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) && 458 NullTermIdx == ArrSize - 1)) { 459 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 460 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 461 Offset); 462 } 463 } 464 465 return nullptr; 466 } 467 468 // strlen(x?"foo":"bars") --> x ? 3 : 4 469 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 470 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 471 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 472 if (LenTrue && LenFalse) { 473 ORE.emit([&]() { 474 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 475 << "folded strlen(select) to select of constants"; 476 }); 477 return B.CreateSelect(SI->getCondition(), 478 ConstantInt::get(CI->getType(), LenTrue - 1), 479 ConstantInt::get(CI->getType(), LenFalse - 1)); 480 } 481 } 482 483 // strlen(x) != 0 --> *x != 0 484 // strlen(x) == 0 --> *x == 0 485 if (isOnlyUsedInZeroEqualityComparison(CI)) 486 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType()); 487 488 return nullptr; 489 } 490 491 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) { 492 return optimizeStringLength(CI, B, 8); 493 } 494 495 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) { 496 Module &M = *CI->getParent()->getParent()->getParent(); 497 unsigned WCharSize = TLI->getWCharSize(M) * 8; 498 // We cannot perform this optimization without wchar_size metadata. 499 if (WCharSize == 0) 500 return nullptr; 501 502 return optimizeStringLength(CI, B, WCharSize); 503 } 504 505 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) { 506 StringRef S1, S2; 507 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 508 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 509 510 // strpbrk(s, "") -> nullptr 511 // strpbrk("", s) -> nullptr 512 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 513 return Constant::getNullValue(CI->getType()); 514 515 // Constant folding. 516 if (HasS1 && HasS2) { 517 size_t I = S1.find_first_of(S2); 518 if (I == StringRef::npos) // No match. 519 return Constant::getNullValue(CI->getType()); 520 521 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), 522 "strpbrk"); 523 } 524 525 // strpbrk(s, "a") -> strchr(s, 'a') 526 if (HasS2 && S2.size() == 1) 527 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI); 528 529 return nullptr; 530 } 531 532 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) { 533 Value *EndPtr = CI->getArgOperand(1); 534 if (isa<ConstantPointerNull>(EndPtr)) { 535 // With a null EndPtr, this function won't capture the main argument. 536 // It would be readonly too, except that it still may write to errno. 537 CI->addParamAttr(0, Attribute::NoCapture); 538 } 539 540 return nullptr; 541 } 542 543 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) { 544 StringRef S1, S2; 545 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 546 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 547 548 // strspn(s, "") -> 0 549 // strspn("", s) -> 0 550 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 551 return Constant::getNullValue(CI->getType()); 552 553 // Constant folding. 554 if (HasS1 && HasS2) { 555 size_t Pos = S1.find_first_not_of(S2); 556 if (Pos == StringRef::npos) 557 Pos = S1.size(); 558 return ConstantInt::get(CI->getType(), Pos); 559 } 560 561 return nullptr; 562 } 563 564 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) { 565 StringRef S1, S2; 566 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 567 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 568 569 // strcspn("", s) -> 0 570 if (HasS1 && S1.empty()) 571 return Constant::getNullValue(CI->getType()); 572 573 // Constant folding. 574 if (HasS1 && HasS2) { 575 size_t Pos = S1.find_first_of(S2); 576 if (Pos == StringRef::npos) 577 Pos = S1.size(); 578 return ConstantInt::get(CI->getType(), Pos); 579 } 580 581 // strcspn(s, "") -> strlen(s) 582 if (HasS2 && S2.empty()) 583 return emitStrLen(CI->getArgOperand(0), B, DL, TLI); 584 585 return nullptr; 586 } 587 588 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) { 589 // fold strstr(x, x) -> x. 590 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 591 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 592 593 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 594 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 595 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 596 if (!StrLen) 597 return nullptr; 598 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 599 StrLen, B, DL, TLI); 600 if (!StrNCmp) 601 return nullptr; 602 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) { 603 ICmpInst *Old = cast<ICmpInst>(*UI++); 604 Value *Cmp = 605 B.CreateICmp(Old->getPredicate(), StrNCmp, 606 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 607 replaceAllUsesWith(Old, Cmp); 608 } 609 return CI; 610 } 611 612 // See if either input string is a constant string. 613 StringRef SearchStr, ToFindStr; 614 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 615 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 616 617 // fold strstr(x, "") -> x. 618 if (HasStr2 && ToFindStr.empty()) 619 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 620 621 // If both strings are known, constant fold it. 622 if (HasStr1 && HasStr2) { 623 size_t Offset = SearchStr.find(ToFindStr); 624 625 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 626 return Constant::getNullValue(CI->getType()); 627 628 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 629 Value *Result = castToCStr(CI->getArgOperand(0), B); 630 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr"); 631 return B.CreateBitCast(Result, CI->getType()); 632 } 633 634 // fold strstr(x, "y") -> strchr(x, 'y'). 635 if (HasStr2 && ToFindStr.size() == 1) { 636 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 637 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr; 638 } 639 return nullptr; 640 } 641 642 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) { 643 Value *SrcStr = CI->getArgOperand(0); 644 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 645 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 646 647 // memchr(x, y, 0) -> null 648 if (LenC && LenC->isZero()) 649 return Constant::getNullValue(CI->getType()); 650 651 // From now on we need at least constant length and string. 652 StringRef Str; 653 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false)) 654 return nullptr; 655 656 // Truncate the string to LenC. If Str is smaller than LenC we will still only 657 // scan the string, as reading past the end of it is undefined and we can just 658 // return null if we don't find the char. 659 Str = Str.substr(0, LenC->getZExtValue()); 660 661 // If the char is variable but the input str and length are not we can turn 662 // this memchr call into a simple bit field test. Of course this only works 663 // when the return value is only checked against null. 664 // 665 // It would be really nice to reuse switch lowering here but we can't change 666 // the CFG at this point. 667 // 668 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0 669 // after bounds check. 670 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) { 671 unsigned char Max = 672 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 673 reinterpret_cast<const unsigned char *>(Str.end())); 674 675 // Make sure the bit field we're about to create fits in a register on the 676 // target. 677 // FIXME: On a 64 bit architecture this prevents us from using the 678 // interesting range of alpha ascii chars. We could do better by emitting 679 // two bitfields or shifting the range by 64 if no lower chars are used. 680 if (!DL.fitsInLegalInteger(Max + 1)) 681 return nullptr; 682 683 // For the bit field use a power-of-2 type with at least 8 bits to avoid 684 // creating unnecessary illegal types. 685 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 686 687 // Now build the bit field. 688 APInt Bitfield(Width, 0); 689 for (char C : Str) 690 Bitfield.setBit((unsigned char)C); 691 Value *BitfieldC = B.getInt(Bitfield); 692 693 // First check that the bit field access is within bounds. 694 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType()); 695 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 696 "memchr.bounds"); 697 698 // Create code that checks if the given bit is set in the field. 699 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 700 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 701 702 // Finally merge both checks and cast to pointer type. The inttoptr 703 // implicitly zexts the i1 to intptr type. 704 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType()); 705 } 706 707 // Check if all arguments are constants. If so, we can constant fold. 708 if (!CharC) 709 return nullptr; 710 711 // Compute the offset. 712 size_t I = Str.find(CharC->getSExtValue() & 0xFF); 713 if (I == StringRef::npos) // Didn't find the char. memchr returns null. 714 return Constant::getNullValue(CI->getType()); 715 716 // memchr(s+n,c,l) -> gep(s+n+i,c) 717 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr"); 718 } 719 720 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) { 721 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 722 723 if (LHS == RHS) // memcmp(s,s,x) -> 0 724 return Constant::getNullValue(CI->getType()); 725 726 // Make sure we have a constant length. 727 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 728 if (!LenC) 729 return nullptr; 730 731 uint64_t Len = LenC->getZExtValue(); 732 if (Len == 0) // memcmp(s1,s2,0) -> 0 733 return Constant::getNullValue(CI->getType()); 734 735 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 736 if (Len == 1) { 737 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"), 738 CI->getType(), "lhsv"); 739 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"), 740 CI->getType(), "rhsv"); 741 return B.CreateSub(LHSV, RHSV, "chardiff"); 742 } 743 744 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 745 // TODO: The case where both inputs are constants does not need to be limited 746 // to legal integers or equality comparison. See block below this. 747 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 748 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 749 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType); 750 751 // First, see if we can fold either argument to a constant. 752 Value *LHSV = nullptr; 753 if (auto *LHSC = dyn_cast<Constant>(LHS)) { 754 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo()); 755 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 756 } 757 Value *RHSV = nullptr; 758 if (auto *RHSC = dyn_cast<Constant>(RHS)) { 759 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo()); 760 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 761 } 762 763 // Don't generate unaligned loads. If either source is constant data, 764 // alignment doesn't matter for that source because there is no load. 765 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 766 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 767 if (!LHSV) { 768 Type *LHSPtrTy = 769 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace()); 770 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv"); 771 } 772 if (!RHSV) { 773 Type *RHSPtrTy = 774 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace()); 775 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv"); 776 } 777 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 778 } 779 } 780 781 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const). 782 // TODO: This is limited to i8 arrays. 783 StringRef LHSStr, RHSStr; 784 if (getConstantStringInfo(LHS, LHSStr) && 785 getConstantStringInfo(RHS, RHSStr)) { 786 // Make sure we're not reading out-of-bounds memory. 787 if (Len > LHSStr.size() || Len > RHSStr.size()) 788 return nullptr; 789 // Fold the memcmp and normalize the result. This way we get consistent 790 // results across multiple platforms. 791 uint64_t Ret = 0; 792 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len); 793 if (Cmp < 0) 794 Ret = -1; 795 else if (Cmp > 0) 796 Ret = 1; 797 return ConstantInt::get(CI->getType(), Ret); 798 } 799 800 return nullptr; 801 } 802 803 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) { 804 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1) 805 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 806 CI->getArgOperand(2), 1); 807 return CI->getArgOperand(0); 808 } 809 810 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) { 811 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1) 812 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1), 813 CI->getArgOperand(2), 1); 814 return CI->getArgOperand(0); 815 } 816 817 // TODO: Does this belong in BuildLibCalls or should all of those similar 818 // functions be moved here? 819 static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs, 820 IRBuilder<> &B, const TargetLibraryInfo &TLI) { 821 LibFunc Func; 822 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func)) 823 return nullptr; 824 825 Module *M = B.GetInsertBlock()->getModule(); 826 const DataLayout &DL = M->getDataLayout(); 827 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext())); 828 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(), 829 PtrType, PtrType); 830 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc"); 831 832 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts())) 833 CI->setCallingConv(F->getCallingConv()); 834 835 return CI; 836 } 837 838 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n). 839 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B, 840 const TargetLibraryInfo &TLI) { 841 // This has to be a memset of zeros (bzero). 842 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1)); 843 if (!FillValue || FillValue->getZExtValue() != 0) 844 return nullptr; 845 846 // TODO: We should handle the case where the malloc has more than one use. 847 // This is necessary to optimize common patterns such as when the result of 848 // the malloc is checked against null or when a memset intrinsic is used in 849 // place of a memset library call. 850 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0)); 851 if (!Malloc || !Malloc->hasOneUse()) 852 return nullptr; 853 854 // Is the inner call really malloc()? 855 Function *InnerCallee = Malloc->getCalledFunction(); 856 if (!InnerCallee) 857 return nullptr; 858 859 LibFunc Func; 860 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) || 861 Func != LibFunc_malloc) 862 return nullptr; 863 864 // The memset must cover the same number of bytes that are malloc'd. 865 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0)) 866 return nullptr; 867 868 // Replace the malloc with a calloc. We need the data layout to know what the 869 // actual size of a 'size_t' parameter is. 870 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator()); 871 const DataLayout &DL = Malloc->getModule()->getDataLayout(); 872 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext()); 873 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1), 874 Malloc->getArgOperand(0), Malloc->getAttributes(), 875 B, TLI); 876 if (!Calloc) 877 return nullptr; 878 879 Malloc->replaceAllUsesWith(Calloc); 880 Malloc->eraseFromParent(); 881 882 return Calloc; 883 } 884 885 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) { 886 if (auto *Calloc = foldMallocMemset(CI, B, *TLI)) 887 return Calloc; 888 889 // memset(p, v, n) -> llvm.memset(p, v, n, 1) 890 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 891 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 892 return CI->getArgOperand(0); 893 } 894 895 //===----------------------------------------------------------------------===// 896 // Math Library Optimizations 897 //===----------------------------------------------------------------------===// 898 899 /// Return a variant of Val with float type. 900 /// Currently this works in two cases: If Val is an FPExtension of a float 901 /// value to something bigger, simply return the operand. 902 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 903 /// loss of precision do so. 904 static Value *valueHasFloatPrecision(Value *Val) { 905 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 906 Value *Op = Cast->getOperand(0); 907 if (Op->getType()->isFloatTy()) 908 return Op; 909 } 910 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 911 APFloat F = Const->getValueAPF(); 912 bool losesInfo; 913 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 914 &losesInfo); 915 if (!losesInfo) 916 return ConstantFP::get(Const->getContext(), F); 917 } 918 return nullptr; 919 } 920 921 /// Shrink double -> float for unary functions like 'floor'. 922 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B, 923 bool CheckRetType) { 924 Function *Callee = CI->getCalledFunction(); 925 // We know this libcall has a valid prototype, but we don't know which. 926 if (!CI->getType()->isDoubleTy()) 927 return nullptr; 928 929 if (CheckRetType) { 930 // Check if all the uses for function like 'sin' are converted to float. 931 for (User *U : CI->users()) { 932 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 933 if (!Cast || !Cast->getType()->isFloatTy()) 934 return nullptr; 935 } 936 } 937 938 // If this is something like 'floor((double)floatval)', convert to floorf. 939 Value *V = valueHasFloatPrecision(CI->getArgOperand(0)); 940 if (V == nullptr) 941 return nullptr; 942 943 // If call isn't an intrinsic, check that it isn't within a function with the 944 // same name as the float version of this call. 945 // 946 // e.g. inline float expf(float val) { return (float) exp((double) val); } 947 // 948 // A similar such definition exists in the MinGW-w64 math.h header file which 949 // when compiled with -O2 -ffast-math causes the generation of infinite loops 950 // where expf is called. 951 if (!Callee->isIntrinsic()) { 952 const Function *F = CI->getFunction(); 953 StringRef FName = F->getName(); 954 StringRef CalleeName = Callee->getName(); 955 if ((FName.size() == (CalleeName.size() + 1)) && 956 (FName.back() == 'f') && 957 FName.startswith(CalleeName)) 958 return nullptr; 959 } 960 961 // Propagate fast-math flags from the existing call to the new call. 962 IRBuilder<>::FastMathFlagGuard Guard(B); 963 B.setFastMathFlags(CI->getFastMathFlags()); 964 965 // floor((double)floatval) -> (double)floorf(floatval) 966 if (Callee->isIntrinsic()) { 967 Module *M = CI->getModule(); 968 Intrinsic::ID IID = Callee->getIntrinsicID(); 969 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 970 V = B.CreateCall(F, V); 971 } else { 972 // The call is a library call rather than an intrinsic. 973 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes()); 974 } 975 976 return B.CreateFPExt(V, B.getDoubleTy()); 977 } 978 979 // Replace a libcall \p CI with a call to intrinsic \p IID 980 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) { 981 // Propagate fast-math flags from the existing call to the new call. 982 IRBuilder<>::FastMathFlagGuard Guard(B); 983 B.setFastMathFlags(CI->getFastMathFlags()); 984 985 Module *M = CI->getModule(); 986 Value *V = CI->getArgOperand(0); 987 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType()); 988 CallInst *NewCall = B.CreateCall(F, V); 989 NewCall->takeName(CI); 990 return NewCall; 991 } 992 993 /// Shrink double -> float for binary functions like 'fmin/fmax'. 994 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) { 995 Function *Callee = CI->getCalledFunction(); 996 // We know this libcall has a valid prototype, but we don't know which. 997 if (!CI->getType()->isDoubleTy()) 998 return nullptr; 999 1000 // If this is something like 'fmin((double)floatval1, (double)floatval2)', 1001 // or fmin(1.0, (double)floatval), then we convert it to fminf. 1002 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0)); 1003 if (V1 == nullptr) 1004 return nullptr; 1005 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1)); 1006 if (V2 == nullptr) 1007 return nullptr; 1008 1009 // Propagate fast-math flags from the existing call to the new call. 1010 IRBuilder<>::FastMathFlagGuard Guard(B); 1011 B.setFastMathFlags(CI->getFastMathFlags()); 1012 1013 // fmin((double)floatval1, (double)floatval2) 1014 // -> (double)fminf(floatval1, floatval2) 1015 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP(). 1016 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B, 1017 Callee->getAttributes()); 1018 return B.CreateFPExt(V, B.getDoubleTy()); 1019 } 1020 1021 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1022 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) { 1023 if (!CI->isFast()) 1024 return nullptr; 1025 1026 // Propagate fast-math flags from the existing call to new instructions. 1027 IRBuilder<>::FastMathFlagGuard Guard(B); 1028 B.setFastMathFlags(CI->getFastMathFlags()); 1029 1030 Value *Real, *Imag; 1031 if (CI->getNumArgOperands() == 1) { 1032 Value *Op = CI->getArgOperand(0); 1033 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 1034 Real = B.CreateExtractValue(Op, 0, "real"); 1035 Imag = B.CreateExtractValue(Op, 1, "imag"); 1036 } else { 1037 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!"); 1038 Real = CI->getArgOperand(0); 1039 Imag = CI->getArgOperand(1); 1040 } 1041 1042 Value *RealReal = B.CreateFMul(Real, Real); 1043 Value *ImagImag = B.CreateFMul(Imag, Imag); 1044 1045 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt, 1046 CI->getType()); 1047 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"); 1048 } 1049 1050 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) { 1051 Function *Callee = CI->getCalledFunction(); 1052 Value *Ret = nullptr; 1053 StringRef Name = Callee->getName(); 1054 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name)) 1055 Ret = optimizeUnaryDoubleFP(CI, B, true); 1056 1057 // cos(-x) -> cos(x) 1058 Value *Op1 = CI->getArgOperand(0); 1059 if (BinaryOperator::isFNeg(Op1)) { 1060 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1); 1061 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos"); 1062 } 1063 return Ret; 1064 } 1065 1066 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) { 1067 // Multiplications calculated using Addition Chains. 1068 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html 1069 1070 assert(Exp != 0 && "Incorrect exponent 0 not handled"); 1071 1072 if (InnerChain[Exp]) 1073 return InnerChain[Exp]; 1074 1075 static const unsigned AddChain[33][2] = { 1076 {0, 0}, // Unused. 1077 {0, 0}, // Unused (base case = pow1). 1078 {1, 1}, // Unused (pre-computed). 1079 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4}, 1080 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7}, 1081 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10}, 1082 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13}, 1083 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16}, 1084 }; 1085 1086 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B), 1087 getPow(InnerChain, AddChain[Exp][1], B)); 1088 return InnerChain[Exp]; 1089 } 1090 1091 /// Use square root in place of pow(x, +/-0.5). 1092 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) { 1093 // TODO: There is some subset of 'fast' under which these transforms should 1094 // be allowed. 1095 if (!Pow->isFast()) 1096 return nullptr; 1097 1098 const APFloat *Arg1C; 1099 if (!match(Pow->getArgOperand(1), m_APFloat(Arg1C))) 1100 return nullptr; 1101 if (!Arg1C->isExactlyValue(0.5) && !Arg1C->isExactlyValue(-0.5)) 1102 return nullptr; 1103 1104 // Fast-math flags from the pow() are propagated to all replacement ops. 1105 IRBuilder<>::FastMathFlagGuard Guard(B); 1106 B.setFastMathFlags(Pow->getFastMathFlags()); 1107 Type *Ty = Pow->getType(); 1108 Value *Sqrt; 1109 if (Pow->hasFnAttr(Attribute::ReadNone)) { 1110 // We know that errno is never set, so replace with an intrinsic: 1111 // pow(x, 0.5) --> llvm.sqrt(x) 1112 // llvm.pow(x, 0.5) --> llvm.sqrt(x) 1113 auto *F = Intrinsic::getDeclaration(Pow->getModule(), Intrinsic::sqrt, Ty); 1114 Sqrt = B.CreateCall(F, Pow->getArgOperand(0)); 1115 } else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, 1116 LibFunc_sqrtl)) { 1117 // Errno could be set, so we must use a sqrt libcall. 1118 // TODO: We also should check that the target can in fact lower the sqrt 1119 // libcall. We currently have no way to ask this question, so we ask 1120 // whether the target has a sqrt libcall which is not exactly the same. 1121 Sqrt = emitUnaryFloatFnCall(Pow->getArgOperand(0), 1122 TLI->getName(LibFunc_sqrt), B, 1123 Pow->getCalledFunction()->getAttributes()); 1124 } else { 1125 // We can't replace with an intrinsic or a libcall. 1126 return nullptr; 1127 } 1128 1129 // If this is pow(x, -0.5), get the reciprocal. 1130 if (Arg1C->isExactlyValue(-0.5)) 1131 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt); 1132 1133 return Sqrt; 1134 } 1135 1136 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) { 1137 Function *Callee = CI->getCalledFunction(); 1138 Value *Ret = nullptr; 1139 StringRef Name = Callee->getName(); 1140 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name)) 1141 Ret = optimizeUnaryDoubleFP(CI, B, true); 1142 1143 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1); 1144 1145 // pow(1.0, x) -> 1.0 1146 if (match(Op1, m_SpecificFP(1.0))) 1147 return Op1; 1148 // pow(2.0, x) -> llvm.exp2(x) 1149 if (match(Op1, m_SpecificFP(2.0))) { 1150 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2, 1151 CI->getType()); 1152 return B.CreateCall(Exp2, Op2, "exp2"); 1153 } 1154 1155 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will 1156 // be one. 1157 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 1158 // pow(10.0, x) -> exp10(x) 1159 if (Op1C->isExactlyValue(10.0) && 1160 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f, 1161 LibFunc_exp10l)) 1162 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B, 1163 Callee->getAttributes()); 1164 } 1165 1166 // pow(exp(x), y) -> exp(x * y) 1167 // pow(exp2(x), y) -> exp2(x * y) 1168 // We enable these only with fast-math. Besides rounding differences, the 1169 // transformation changes overflow and underflow behavior quite dramatically. 1170 // Example: x = 1000, y = 0.001. 1171 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1). 1172 auto *OpC = dyn_cast<CallInst>(Op1); 1173 if (OpC && OpC->isFast() && CI->isFast()) { 1174 LibFunc Func; 1175 Function *OpCCallee = OpC->getCalledFunction(); 1176 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) && 1177 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) { 1178 IRBuilder<>::FastMathFlagGuard Guard(B); 1179 B.setFastMathFlags(CI->getFastMathFlags()); 1180 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"); 1181 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B, 1182 OpCCallee->getAttributes()); 1183 } 1184 } 1185 1186 if (Value *Sqrt = replacePowWithSqrt(CI, B)) 1187 return Sqrt; 1188 1189 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2); 1190 if (!Op2C) 1191 return Ret; 1192 1193 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0 1194 return ConstantFP::get(CI->getType(), 1.0); 1195 1196 // FIXME: Correct the transforms and pull this into replacePowWithSqrt(). 1197 if (Op2C->isExactlyValue(0.5) && 1198 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf, 1199 LibFunc_sqrtl)) { 1200 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))). 1201 // This is faster than calling pow, and still handles negative zero 1202 // and negative infinity correctly. 1203 // TODO: In finite-only mode, this could be just fabs(sqrt(x)). 1204 Value *Inf = ConstantFP::getInfinity(CI->getType()); 1205 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true); 1206 1207 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an 1208 // intrinsic, to match errno semantics. 1209 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes()); 1210 1211 Module *M = Callee->getParent(); 1212 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs, 1213 CI->getType()); 1214 Value *FAbs = B.CreateCall(FabsF, Sqrt); 1215 1216 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf); 1217 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs); 1218 return Sel; 1219 } 1220 1221 // Propagate fast-math-flags from the call to any created instructions. 1222 IRBuilder<>::FastMathFlagGuard Guard(B); 1223 B.setFastMathFlags(CI->getFastMathFlags()); 1224 // pow(x, 1.0) --> x 1225 if (Op2C->isExactlyValue(1.0)) 1226 return Op1; 1227 // pow(x, 2.0) --> x * x 1228 if (Op2C->isExactlyValue(2.0)) 1229 return B.CreateFMul(Op1, Op1, "pow2"); 1230 // pow(x, -1.0) --> 1.0 / x 1231 if (Op2C->isExactlyValue(-1.0)) 1232 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip"); 1233 1234 // In -ffast-math, generate repeated fmul instead of generating pow(x, n). 1235 if (CI->isFast()) { 1236 APFloat V = abs(Op2C->getValueAPF()); 1237 // We limit to a max of 7 fmul(s). Thus max exponent is 32. 1238 // This transformation applies to integer exponents only. 1239 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan || 1240 !V.isInteger()) 1241 return nullptr; 1242 1243 // We will memoize intermediate products of the Addition Chain. 1244 Value *InnerChain[33] = {nullptr}; 1245 InnerChain[1] = Op1; 1246 InnerChain[2] = B.CreateFMul(Op1, Op1); 1247 1248 // We cannot readily convert a non-double type (like float) to a double. 1249 // So we first convert V to something which could be converted to double. 1250 bool Ignored; 1251 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored); 1252 1253 Value *FMul = getPow(InnerChain, V.convertToDouble(), B); 1254 // For negative exponents simply compute the reciprocal. 1255 if (Op2C->isNegative()) 1256 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul); 1257 return FMul; 1258 } 1259 1260 return nullptr; 1261 } 1262 1263 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) { 1264 Function *Callee = CI->getCalledFunction(); 1265 Value *Ret = nullptr; 1266 StringRef Name = Callee->getName(); 1267 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name)) 1268 Ret = optimizeUnaryDoubleFP(CI, B, true); 1269 1270 Value *Op = CI->getArgOperand(0); 1271 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32 1272 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32 1273 LibFunc LdExp = LibFunc_ldexpl; 1274 if (Op->getType()->isFloatTy()) 1275 LdExp = LibFunc_ldexpf; 1276 else if (Op->getType()->isDoubleTy()) 1277 LdExp = LibFunc_ldexp; 1278 1279 if (TLI->has(LdExp)) { 1280 Value *LdExpArg = nullptr; 1281 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) { 1282 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32) 1283 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty()); 1284 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) { 1285 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32) 1286 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty()); 1287 } 1288 1289 if (LdExpArg) { 1290 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f)); 1291 if (!Op->getType()->isFloatTy()) 1292 One = ConstantExpr::getFPExtend(One, Op->getType()); 1293 1294 Module *M = CI->getModule(); 1295 Value *NewCallee = 1296 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(), 1297 Op->getType(), B.getInt32Ty()); 1298 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg}); 1299 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) 1300 CI->setCallingConv(F->getCallingConv()); 1301 1302 return CI; 1303 } 1304 } 1305 return Ret; 1306 } 1307 1308 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) { 1309 Function *Callee = CI->getCalledFunction(); 1310 // If we can shrink the call to a float function rather than a double 1311 // function, do that first. 1312 StringRef Name = Callee->getName(); 1313 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name)) 1314 if (Value *Ret = optimizeBinaryDoubleFP(CI, B)) 1315 return Ret; 1316 1317 IRBuilder<>::FastMathFlagGuard Guard(B); 1318 FastMathFlags FMF; 1319 if (CI->isFast()) { 1320 // If the call is 'fast', then anything we create here will also be 'fast'. 1321 FMF.setFast(); 1322 } else { 1323 // At a minimum, no-nans-fp-math must be true. 1324 if (!CI->hasNoNaNs()) 1325 return nullptr; 1326 // No-signed-zeros is implied by the definitions of fmax/fmin themselves: 1327 // "Ideally, fmax would be sensitive to the sign of zero, for example 1328 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software 1329 // might be impractical." 1330 FMF.setNoSignedZeros(); 1331 FMF.setNoNaNs(); 1332 } 1333 B.setFastMathFlags(FMF); 1334 1335 // We have a relaxed floating-point environment. We can ignore NaN-handling 1336 // and transform to a compare and select. We do not have to consider errno or 1337 // exceptions, because fmin/fmax do not have those. 1338 Value *Op0 = CI->getArgOperand(0); 1339 Value *Op1 = CI->getArgOperand(1); 1340 Value *Cmp = Callee->getName().startswith("fmin") ? 1341 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1); 1342 return B.CreateSelect(Cmp, Op0, Op1); 1343 } 1344 1345 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) { 1346 Function *Callee = CI->getCalledFunction(); 1347 Value *Ret = nullptr; 1348 StringRef Name = Callee->getName(); 1349 if (UnsafeFPShrink && hasFloatVersion(Name)) 1350 Ret = optimizeUnaryDoubleFP(CI, B, true); 1351 1352 if (!CI->isFast()) 1353 return Ret; 1354 Value *Op1 = CI->getArgOperand(0); 1355 auto *OpC = dyn_cast<CallInst>(Op1); 1356 1357 // The earlier call must also be 'fast' in order to do these transforms. 1358 if (!OpC || !OpC->isFast()) 1359 return Ret; 1360 1361 // log(pow(x,y)) -> y*log(x) 1362 // This is only applicable to log, log2, log10. 1363 if (Name != "log" && Name != "log2" && Name != "log10") 1364 return Ret; 1365 1366 IRBuilder<>::FastMathFlagGuard Guard(B); 1367 FastMathFlags FMF; 1368 FMF.setFast(); 1369 B.setFastMathFlags(FMF); 1370 1371 LibFunc Func; 1372 Function *F = OpC->getCalledFunction(); 1373 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 1374 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow)) 1375 return B.CreateFMul(OpC->getArgOperand(1), 1376 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B, 1377 Callee->getAttributes()), "mul"); 1378 1379 // log(exp2(y)) -> y*log(2) 1380 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) && 1381 TLI->has(Func) && Func == LibFunc_exp2) 1382 return B.CreateFMul( 1383 OpC->getArgOperand(0), 1384 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0), 1385 Callee->getName(), B, Callee->getAttributes()), 1386 "logmul"); 1387 return Ret; 1388 } 1389 1390 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) { 1391 Function *Callee = CI->getCalledFunction(); 1392 Value *Ret = nullptr; 1393 // TODO: Once we have a way (other than checking for the existince of the 1394 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 1395 // condition below. 1396 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" || 1397 Callee->getIntrinsicID() == Intrinsic::sqrt)) 1398 Ret = optimizeUnaryDoubleFP(CI, B, true); 1399 1400 if (!CI->isFast()) 1401 return Ret; 1402 1403 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 1404 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 1405 return Ret; 1406 1407 // We're looking for a repeated factor in a multiplication tree, 1408 // so we can do this fold: sqrt(x * x) -> fabs(x); 1409 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 1410 Value *Op0 = I->getOperand(0); 1411 Value *Op1 = I->getOperand(1); 1412 Value *RepeatOp = nullptr; 1413 Value *OtherOp = nullptr; 1414 if (Op0 == Op1) { 1415 // Simple match: the operands of the multiply are identical. 1416 RepeatOp = Op0; 1417 } else { 1418 // Look for a more complicated pattern: one of the operands is itself 1419 // a multiply, so search for a common factor in that multiply. 1420 // Note: We don't bother looking any deeper than this first level or for 1421 // variations of this pattern because instcombine's visitFMUL and/or the 1422 // reassociation pass should give us this form. 1423 Value *OtherMul0, *OtherMul1; 1424 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 1425 // Pattern: sqrt((x * y) * z) 1426 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) { 1427 // Matched: sqrt((x * x) * z) 1428 RepeatOp = OtherMul0; 1429 OtherOp = Op1; 1430 } 1431 } 1432 } 1433 if (!RepeatOp) 1434 return Ret; 1435 1436 // Fast math flags for any created instructions should match the sqrt 1437 // and multiply. 1438 IRBuilder<>::FastMathFlagGuard Guard(B); 1439 B.setFastMathFlags(I->getFastMathFlags()); 1440 1441 // If we found a repeated factor, hoist it out of the square root and 1442 // replace it with the fabs of that factor. 1443 Module *M = Callee->getParent(); 1444 Type *ArgType = I->getType(); 1445 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType); 1446 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs"); 1447 if (OtherOp) { 1448 // If we found a non-repeated factor, we still need to get its square 1449 // root. We then multiply that by the value that was simplified out 1450 // of the square root calculation. 1451 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType); 1452 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt"); 1453 return B.CreateFMul(FabsCall, SqrtCall); 1454 } 1455 return FabsCall; 1456 } 1457 1458 // TODO: Generalize to handle any trig function and its inverse. 1459 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) { 1460 Function *Callee = CI->getCalledFunction(); 1461 Value *Ret = nullptr; 1462 StringRef Name = Callee->getName(); 1463 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name)) 1464 Ret = optimizeUnaryDoubleFP(CI, B, true); 1465 1466 Value *Op1 = CI->getArgOperand(0); 1467 auto *OpC = dyn_cast<CallInst>(Op1); 1468 if (!OpC) 1469 return Ret; 1470 1471 // Both calls must be 'fast' in order to remove them. 1472 if (!CI->isFast() || !OpC->isFast()) 1473 return Ret; 1474 1475 // tan(atan(x)) -> x 1476 // tanf(atanf(x)) -> x 1477 // tanl(atanl(x)) -> x 1478 LibFunc Func; 1479 Function *F = OpC->getCalledFunction(); 1480 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 1481 ((Func == LibFunc_atan && Callee->getName() == "tan") || 1482 (Func == LibFunc_atanf && Callee->getName() == "tanf") || 1483 (Func == LibFunc_atanl && Callee->getName() == "tanl"))) 1484 Ret = OpC->getArgOperand(0); 1485 return Ret; 1486 } 1487 1488 static bool isTrigLibCall(CallInst *CI) { 1489 // We can only hope to do anything useful if we can ignore things like errno 1490 // and floating-point exceptions. 1491 // We already checked the prototype. 1492 return CI->hasFnAttr(Attribute::NoUnwind) && 1493 CI->hasFnAttr(Attribute::ReadNone); 1494 } 1495 1496 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, 1497 bool UseFloat, Value *&Sin, Value *&Cos, 1498 Value *&SinCos) { 1499 Type *ArgTy = Arg->getType(); 1500 Type *ResTy; 1501 StringRef Name; 1502 1503 Triple T(OrigCallee->getParent()->getTargetTriple()); 1504 if (UseFloat) { 1505 Name = "__sincospif_stret"; 1506 1507 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 1508 // x86_64 can't use {float, float} since that would be returned in both 1509 // xmm0 and xmm1, which isn't what a real struct would do. 1510 ResTy = T.getArch() == Triple::x86_64 1511 ? static_cast<Type *>(VectorType::get(ArgTy, 2)) 1512 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 1513 } else { 1514 Name = "__sincospi_stret"; 1515 ResTy = StructType::get(ArgTy, ArgTy); 1516 } 1517 1518 Module *M = OrigCallee->getParent(); 1519 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(), 1520 ResTy, ArgTy); 1521 1522 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 1523 // If the argument is an instruction, it must dominate all uses so put our 1524 // sincos call there. 1525 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 1526 } else { 1527 // Otherwise (e.g. for a constant) the beginning of the function is as 1528 // good a place as any. 1529 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 1530 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 1531 } 1532 1533 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 1534 1535 if (SinCos->getType()->isStructTy()) { 1536 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 1537 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 1538 } else { 1539 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 1540 "sinpi"); 1541 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 1542 "cospi"); 1543 } 1544 } 1545 1546 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) { 1547 // Make sure the prototype is as expected, otherwise the rest of the 1548 // function is probably invalid and likely to abort. 1549 if (!isTrigLibCall(CI)) 1550 return nullptr; 1551 1552 Value *Arg = CI->getArgOperand(0); 1553 SmallVector<CallInst *, 1> SinCalls; 1554 SmallVector<CallInst *, 1> CosCalls; 1555 SmallVector<CallInst *, 1> SinCosCalls; 1556 1557 bool IsFloat = Arg->getType()->isFloatTy(); 1558 1559 // Look for all compatible sinpi, cospi and sincospi calls with the same 1560 // argument. If there are enough (in some sense) we can make the 1561 // substitution. 1562 Function *F = CI->getFunction(); 1563 for (User *U : Arg->users()) 1564 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 1565 1566 // It's only worthwhile if both sinpi and cospi are actually used. 1567 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty())) 1568 return nullptr; 1569 1570 Value *Sin, *Cos, *SinCos; 1571 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos); 1572 1573 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 1574 Value *Res) { 1575 for (CallInst *C : Calls) 1576 replaceAllUsesWith(C, Res); 1577 }; 1578 1579 replaceTrigInsts(SinCalls, Sin); 1580 replaceTrigInsts(CosCalls, Cos); 1581 replaceTrigInsts(SinCosCalls, SinCos); 1582 1583 return nullptr; 1584 } 1585 1586 void LibCallSimplifier::classifyArgUse( 1587 Value *Val, Function *F, bool IsFloat, 1588 SmallVectorImpl<CallInst *> &SinCalls, 1589 SmallVectorImpl<CallInst *> &CosCalls, 1590 SmallVectorImpl<CallInst *> &SinCosCalls) { 1591 CallInst *CI = dyn_cast<CallInst>(Val); 1592 1593 if (!CI) 1594 return; 1595 1596 // Don't consider calls in other functions. 1597 if (CI->getFunction() != F) 1598 return; 1599 1600 Function *Callee = CI->getCalledFunction(); 1601 LibFunc Func; 1602 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) || 1603 !isTrigLibCall(CI)) 1604 return; 1605 1606 if (IsFloat) { 1607 if (Func == LibFunc_sinpif) 1608 SinCalls.push_back(CI); 1609 else if (Func == LibFunc_cospif) 1610 CosCalls.push_back(CI); 1611 else if (Func == LibFunc_sincospif_stret) 1612 SinCosCalls.push_back(CI); 1613 } else { 1614 if (Func == LibFunc_sinpi) 1615 SinCalls.push_back(CI); 1616 else if (Func == LibFunc_cospi) 1617 CosCalls.push_back(CI); 1618 else if (Func == LibFunc_sincospi_stret) 1619 SinCosCalls.push_back(CI); 1620 } 1621 } 1622 1623 //===----------------------------------------------------------------------===// 1624 // Integer Library Call Optimizations 1625 //===----------------------------------------------------------------------===// 1626 1627 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) { 1628 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 1629 Value *Op = CI->getArgOperand(0); 1630 Type *ArgType = Op->getType(); 1631 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 1632 Intrinsic::cttz, ArgType); 1633 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz"); 1634 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 1635 V = B.CreateIntCast(V, B.getInt32Ty(), false); 1636 1637 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 1638 return B.CreateSelect(Cond, V, B.getInt32(0)); 1639 } 1640 1641 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) { 1642 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false)) 1643 Value *Op = CI->getArgOperand(0); 1644 Type *ArgType = Op->getType(); 1645 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 1646 Intrinsic::ctlz, ArgType); 1647 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz"); 1648 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 1649 V); 1650 return B.CreateIntCast(V, CI->getType(), false); 1651 } 1652 1653 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) { 1654 // abs(x) -> x >s -1 ? x : -x 1655 Value *Op = CI->getArgOperand(0); 1656 Value *Pos = 1657 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos"); 1658 Value *Neg = B.CreateNeg(Op, "neg"); 1659 return B.CreateSelect(Pos, Op, Neg); 1660 } 1661 1662 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) { 1663 // isdigit(c) -> (c-'0') <u 10 1664 Value *Op = CI->getArgOperand(0); 1665 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 1666 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 1667 return B.CreateZExt(Op, CI->getType()); 1668 } 1669 1670 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) { 1671 // isascii(c) -> c <u 128 1672 Value *Op = CI->getArgOperand(0); 1673 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 1674 return B.CreateZExt(Op, CI->getType()); 1675 } 1676 1677 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) { 1678 // toascii(c) -> c & 0x7f 1679 return B.CreateAnd(CI->getArgOperand(0), 1680 ConstantInt::get(CI->getType(), 0x7F)); 1681 } 1682 1683 //===----------------------------------------------------------------------===// 1684 // Formatting and IO Library Call Optimizations 1685 //===----------------------------------------------------------------------===// 1686 1687 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 1688 1689 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B, 1690 int StreamArg) { 1691 Function *Callee = CI->getCalledFunction(); 1692 // Error reporting calls should be cold, mark them as such. 1693 // This applies even to non-builtin calls: it is only a hint and applies to 1694 // functions that the frontend might not understand as builtins. 1695 1696 // This heuristic was suggested in: 1697 // Improving Static Branch Prediction in a Compiler 1698 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 1699 // Proceedings of PACT'98, Oct. 1998, IEEE 1700 if (!CI->hasFnAttr(Attribute::Cold) && 1701 isReportingError(Callee, CI, StreamArg)) { 1702 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold); 1703 } 1704 1705 return nullptr; 1706 } 1707 1708 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 1709 if (!Callee || !Callee->isDeclaration()) 1710 return false; 1711 1712 if (StreamArg < 0) 1713 return true; 1714 1715 // These functions might be considered cold, but only if their stream 1716 // argument is stderr. 1717 1718 if (StreamArg >= (int)CI->getNumArgOperands()) 1719 return false; 1720 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 1721 if (!LI) 1722 return false; 1723 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 1724 if (!GV || !GV->isDeclaration()) 1725 return false; 1726 return GV->getName() == "stderr"; 1727 } 1728 1729 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) { 1730 // Check for a fixed format string. 1731 StringRef FormatStr; 1732 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 1733 return nullptr; 1734 1735 // Empty format string -> noop. 1736 if (FormatStr.empty()) // Tolerate printf's declared void. 1737 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 1738 1739 // Do not do any of the following transformations if the printf return value 1740 // is used, in general the printf return value is not compatible with either 1741 // putchar() or puts(). 1742 if (!CI->use_empty()) 1743 return nullptr; 1744 1745 // printf("x") -> putchar('x'), even for "%" and "%%". 1746 if (FormatStr.size() == 1 || FormatStr == "%%") 1747 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI); 1748 1749 // printf("%s", "a") --> putchar('a') 1750 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) { 1751 StringRef ChrStr; 1752 if (!getConstantStringInfo(CI->getOperand(1), ChrStr)) 1753 return nullptr; 1754 if (ChrStr.size() != 1) 1755 return nullptr; 1756 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI); 1757 } 1758 1759 // printf("foo\n") --> puts("foo") 1760 if (FormatStr[FormatStr.size() - 1] == '\n' && 1761 FormatStr.find('%') == StringRef::npos) { // No format characters. 1762 // Create a string literal with no \n on it. We expect the constant merge 1763 // pass to be run after this pass, to merge duplicate strings. 1764 FormatStr = FormatStr.drop_back(); 1765 Value *GV = B.CreateGlobalString(FormatStr, "str"); 1766 return emitPutS(GV, B, TLI); 1767 } 1768 1769 // Optimize specific format strings. 1770 // printf("%c", chr) --> putchar(chr) 1771 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 && 1772 CI->getArgOperand(1)->getType()->isIntegerTy()) 1773 return emitPutChar(CI->getArgOperand(1), B, TLI); 1774 1775 // printf("%s\n", str) --> puts(str) 1776 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 && 1777 CI->getArgOperand(1)->getType()->isPointerTy()) 1778 return emitPutS(CI->getArgOperand(1), B, TLI); 1779 return nullptr; 1780 } 1781 1782 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) { 1783 1784 Function *Callee = CI->getCalledFunction(); 1785 FunctionType *FT = Callee->getFunctionType(); 1786 if (Value *V = optimizePrintFString(CI, B)) { 1787 return V; 1788 } 1789 1790 // printf(format, ...) -> iprintf(format, ...) if no floating point 1791 // arguments. 1792 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) { 1793 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1794 Constant *IPrintFFn = 1795 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes()); 1796 CallInst *New = cast<CallInst>(CI->clone()); 1797 New->setCalledFunction(IPrintFFn); 1798 B.Insert(New); 1799 return New; 1800 } 1801 return nullptr; 1802 } 1803 1804 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) { 1805 // Check for a fixed format string. 1806 StringRef FormatStr; 1807 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1808 return nullptr; 1809 1810 // If we just have a format string (nothing else crazy) transform it. 1811 if (CI->getNumArgOperands() == 2) { 1812 // Make sure there's no % in the constant array. We could try to handle 1813 // %% -> % in the future if we cared. 1814 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 1815 if (FormatStr[i] == '%') 1816 return nullptr; // we found a format specifier, bail out. 1817 1818 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1) 1819 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 1820 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 1821 FormatStr.size() + 1), 1822 1); // Copy the null byte. 1823 return ConstantInt::get(CI->getType(), FormatStr.size()); 1824 } 1825 1826 // The remaining optimizations require the format string to be "%s" or "%c" 1827 // and have an extra operand. 1828 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1829 CI->getNumArgOperands() < 3) 1830 return nullptr; 1831 1832 // Decode the second character of the format string. 1833 if (FormatStr[1] == 'c') { 1834 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 1835 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 1836 return nullptr; 1837 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 1838 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 1839 B.CreateStore(V, Ptr); 1840 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 1841 B.CreateStore(B.getInt8(0), Ptr); 1842 1843 return ConstantInt::get(CI->getType(), 1); 1844 } 1845 1846 if (FormatStr[1] == 's') { 1847 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1) 1848 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 1849 return nullptr; 1850 1851 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 1852 if (!Len) 1853 return nullptr; 1854 Value *IncLen = 1855 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 1856 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1); 1857 1858 // The sprintf result is the unincremented number of bytes in the string. 1859 return B.CreateIntCast(Len, CI->getType(), false); 1860 } 1861 return nullptr; 1862 } 1863 1864 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) { 1865 Function *Callee = CI->getCalledFunction(); 1866 FunctionType *FT = Callee->getFunctionType(); 1867 if (Value *V = optimizeSPrintFString(CI, B)) { 1868 return V; 1869 } 1870 1871 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 1872 // point arguments. 1873 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) { 1874 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1875 Constant *SIPrintFFn = 1876 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes()); 1877 CallInst *New = cast<CallInst>(CI->clone()); 1878 New->setCalledFunction(SIPrintFFn); 1879 B.Insert(New); 1880 return New; 1881 } 1882 return nullptr; 1883 } 1884 1885 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) { 1886 optimizeErrorReporting(CI, B, 0); 1887 1888 // All the optimizations depend on the format string. 1889 StringRef FormatStr; 1890 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1891 return nullptr; 1892 1893 // Do not do any of the following transformations if the fprintf return 1894 // value is used, in general the fprintf return value is not compatible 1895 // with fwrite(), fputc() or fputs(). 1896 if (!CI->use_empty()) 1897 return nullptr; 1898 1899 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 1900 if (CI->getNumArgOperands() == 2) { 1901 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i) 1902 if (FormatStr[i] == '%') // Could handle %% -> % if we cared. 1903 return nullptr; // We found a format specifier. 1904 1905 return emitFWrite( 1906 CI->getArgOperand(1), 1907 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()), 1908 CI->getArgOperand(0), B, DL, TLI); 1909 } 1910 1911 // The remaining optimizations require the format string to be "%s" or "%c" 1912 // and have an extra operand. 1913 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1914 CI->getNumArgOperands() < 3) 1915 return nullptr; 1916 1917 // Decode the second character of the format string. 1918 if (FormatStr[1] == 'c') { 1919 // fprintf(F, "%c", chr) --> fputc(chr, F) 1920 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 1921 return nullptr; 1922 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 1923 } 1924 1925 if (FormatStr[1] == 's') { 1926 // fprintf(F, "%s", str) --> fputs(str, F) 1927 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 1928 return nullptr; 1929 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 1930 } 1931 return nullptr; 1932 } 1933 1934 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) { 1935 Function *Callee = CI->getCalledFunction(); 1936 FunctionType *FT = Callee->getFunctionType(); 1937 if (Value *V = optimizeFPrintFString(CI, B)) { 1938 return V; 1939 } 1940 1941 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 1942 // floating point arguments. 1943 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) { 1944 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1945 Constant *FIPrintFFn = 1946 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes()); 1947 CallInst *New = cast<CallInst>(CI->clone()); 1948 New->setCalledFunction(FIPrintFFn); 1949 B.Insert(New); 1950 return New; 1951 } 1952 return nullptr; 1953 } 1954 1955 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) { 1956 optimizeErrorReporting(CI, B, 3); 1957 1958 // Get the element size and count. 1959 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 1960 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1961 if (!SizeC || !CountC) 1962 return nullptr; 1963 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 1964 1965 // If this is writing zero records, remove the call (it's a noop). 1966 if (Bytes == 0) 1967 return ConstantInt::get(CI->getType(), 0); 1968 1969 // If this is writing one byte, turn it into fputc. 1970 // This optimisation is only valid, if the return value is unused. 1971 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 1972 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char"); 1973 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI); 1974 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 1975 } 1976 1977 return nullptr; 1978 } 1979 1980 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) { 1981 optimizeErrorReporting(CI, B, 1); 1982 1983 // Don't rewrite fputs to fwrite when optimising for size because fwrite 1984 // requires more arguments and thus extra MOVs are required. 1985 if (CI->getParent()->getParent()->optForSize()) 1986 return nullptr; 1987 1988 // We can't optimize if return value is used. 1989 if (!CI->use_empty()) 1990 return nullptr; 1991 1992 // fputs(s,F) --> fwrite(s,1,strlen(s),F) 1993 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 1994 if (!Len) 1995 return nullptr; 1996 1997 // Known to have no uses (see above). 1998 return emitFWrite( 1999 CI->getArgOperand(0), 2000 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1), 2001 CI->getArgOperand(1), B, DL, TLI); 2002 } 2003 2004 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) { 2005 // Check for a constant string. 2006 StringRef Str; 2007 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2008 return nullptr; 2009 2010 if (Str.empty() && CI->use_empty()) { 2011 // puts("") -> putchar('\n') 2012 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI); 2013 if (CI->use_empty() || !Res) 2014 return Res; 2015 return B.CreateIntCast(Res, CI->getType(), true); 2016 } 2017 2018 return nullptr; 2019 } 2020 2021 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) { 2022 LibFunc Func; 2023 SmallString<20> FloatFuncName = FuncName; 2024 FloatFuncName += 'f'; 2025 if (TLI->getLibFunc(FloatFuncName, Func)) 2026 return TLI->has(Func); 2027 return false; 2028 } 2029 2030 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 2031 IRBuilder<> &Builder) { 2032 LibFunc Func; 2033 Function *Callee = CI->getCalledFunction(); 2034 // Check for string/memory library functions. 2035 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 2036 // Make sure we never change the calling convention. 2037 assert((ignoreCallingConv(Func) || 2038 isCallingConvCCompatible(CI)) && 2039 "Optimizing string/memory libcall would change the calling convention"); 2040 switch (Func) { 2041 case LibFunc_strcat: 2042 return optimizeStrCat(CI, Builder); 2043 case LibFunc_strncat: 2044 return optimizeStrNCat(CI, Builder); 2045 case LibFunc_strchr: 2046 return optimizeStrChr(CI, Builder); 2047 case LibFunc_strrchr: 2048 return optimizeStrRChr(CI, Builder); 2049 case LibFunc_strcmp: 2050 return optimizeStrCmp(CI, Builder); 2051 case LibFunc_strncmp: 2052 return optimizeStrNCmp(CI, Builder); 2053 case LibFunc_strcpy: 2054 return optimizeStrCpy(CI, Builder); 2055 case LibFunc_stpcpy: 2056 return optimizeStpCpy(CI, Builder); 2057 case LibFunc_strncpy: 2058 return optimizeStrNCpy(CI, Builder); 2059 case LibFunc_strlen: 2060 return optimizeStrLen(CI, Builder); 2061 case LibFunc_strpbrk: 2062 return optimizeStrPBrk(CI, Builder); 2063 case LibFunc_strtol: 2064 case LibFunc_strtod: 2065 case LibFunc_strtof: 2066 case LibFunc_strtoul: 2067 case LibFunc_strtoll: 2068 case LibFunc_strtold: 2069 case LibFunc_strtoull: 2070 return optimizeStrTo(CI, Builder); 2071 case LibFunc_strspn: 2072 return optimizeStrSpn(CI, Builder); 2073 case LibFunc_strcspn: 2074 return optimizeStrCSpn(CI, Builder); 2075 case LibFunc_strstr: 2076 return optimizeStrStr(CI, Builder); 2077 case LibFunc_memchr: 2078 return optimizeMemChr(CI, Builder); 2079 case LibFunc_memcmp: 2080 return optimizeMemCmp(CI, Builder); 2081 case LibFunc_memcpy: 2082 return optimizeMemCpy(CI, Builder); 2083 case LibFunc_memmove: 2084 return optimizeMemMove(CI, Builder); 2085 case LibFunc_memset: 2086 return optimizeMemSet(CI, Builder); 2087 case LibFunc_wcslen: 2088 return optimizeWcslen(CI, Builder); 2089 default: 2090 break; 2091 } 2092 } 2093 return nullptr; 2094 } 2095 2096 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 2097 LibFunc Func, 2098 IRBuilder<> &Builder) { 2099 // Don't optimize calls that require strict floating point semantics. 2100 if (CI->isStrictFP()) 2101 return nullptr; 2102 2103 switch (Func) { 2104 case LibFunc_cosf: 2105 case LibFunc_cos: 2106 case LibFunc_cosl: 2107 return optimizeCos(CI, Builder); 2108 case LibFunc_sinpif: 2109 case LibFunc_sinpi: 2110 case LibFunc_cospif: 2111 case LibFunc_cospi: 2112 return optimizeSinCosPi(CI, Builder); 2113 case LibFunc_powf: 2114 case LibFunc_pow: 2115 case LibFunc_powl: 2116 return optimizePow(CI, Builder); 2117 case LibFunc_exp2l: 2118 case LibFunc_exp2: 2119 case LibFunc_exp2f: 2120 return optimizeExp2(CI, Builder); 2121 case LibFunc_fabsf: 2122 case LibFunc_fabs: 2123 case LibFunc_fabsl: 2124 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 2125 case LibFunc_sqrtf: 2126 case LibFunc_sqrt: 2127 case LibFunc_sqrtl: 2128 return optimizeSqrt(CI, Builder); 2129 case LibFunc_log: 2130 case LibFunc_log10: 2131 case LibFunc_log1p: 2132 case LibFunc_log2: 2133 case LibFunc_logb: 2134 return optimizeLog(CI, Builder); 2135 case LibFunc_tan: 2136 case LibFunc_tanf: 2137 case LibFunc_tanl: 2138 return optimizeTan(CI, Builder); 2139 case LibFunc_ceil: 2140 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 2141 case LibFunc_floor: 2142 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 2143 case LibFunc_round: 2144 return replaceUnaryCall(CI, Builder, Intrinsic::round); 2145 case LibFunc_nearbyint: 2146 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 2147 case LibFunc_rint: 2148 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 2149 case LibFunc_trunc: 2150 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 2151 case LibFunc_acos: 2152 case LibFunc_acosh: 2153 case LibFunc_asin: 2154 case LibFunc_asinh: 2155 case LibFunc_atan: 2156 case LibFunc_atanh: 2157 case LibFunc_cbrt: 2158 case LibFunc_cosh: 2159 case LibFunc_exp: 2160 case LibFunc_exp10: 2161 case LibFunc_expm1: 2162 case LibFunc_sin: 2163 case LibFunc_sinh: 2164 case LibFunc_tanh: 2165 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName())) 2166 return optimizeUnaryDoubleFP(CI, Builder, true); 2167 return nullptr; 2168 case LibFunc_copysign: 2169 if (hasFloatVersion(CI->getCalledFunction()->getName())) 2170 return optimizeBinaryDoubleFP(CI, Builder); 2171 return nullptr; 2172 case LibFunc_fminf: 2173 case LibFunc_fmin: 2174 case LibFunc_fminl: 2175 case LibFunc_fmaxf: 2176 case LibFunc_fmax: 2177 case LibFunc_fmaxl: 2178 return optimizeFMinFMax(CI, Builder); 2179 case LibFunc_cabs: 2180 case LibFunc_cabsf: 2181 case LibFunc_cabsl: 2182 return optimizeCAbs(CI, Builder); 2183 default: 2184 return nullptr; 2185 } 2186 } 2187 2188 Value *LibCallSimplifier::optimizeCall(CallInst *CI) { 2189 // TODO: Split out the code below that operates on FP calls so that 2190 // we can all non-FP calls with the StrictFP attribute to be 2191 // optimized. 2192 if (CI->isNoBuiltin()) 2193 return nullptr; 2194 2195 LibFunc Func; 2196 Function *Callee = CI->getCalledFunction(); 2197 2198 SmallVector<OperandBundleDef, 2> OpBundles; 2199 CI->getOperandBundlesAsDefs(OpBundles); 2200 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 2201 bool isCallingConvC = isCallingConvCCompatible(CI); 2202 2203 // Command-line parameter overrides instruction attribute. 2204 // This can't be moved to optimizeFloatingPointLibCall() because it may be 2205 // used by the intrinsic optimizations. 2206 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 2207 UnsafeFPShrink = EnableUnsafeFPShrink; 2208 else if (isa<FPMathOperator>(CI) && CI->isFast()) 2209 UnsafeFPShrink = true; 2210 2211 // First, check for intrinsics. 2212 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 2213 if (!isCallingConvC) 2214 return nullptr; 2215 // The FP intrinsics have corresponding constrained versions so we don't 2216 // need to check for the StrictFP attribute here. 2217 switch (II->getIntrinsicID()) { 2218 case Intrinsic::pow: 2219 return optimizePow(CI, Builder); 2220 case Intrinsic::exp2: 2221 return optimizeExp2(CI, Builder); 2222 case Intrinsic::log: 2223 return optimizeLog(CI, Builder); 2224 case Intrinsic::sqrt: 2225 return optimizeSqrt(CI, Builder); 2226 // TODO: Use foldMallocMemset() with memset intrinsic. 2227 default: 2228 return nullptr; 2229 } 2230 } 2231 2232 // Also try to simplify calls to fortified library functions. 2233 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) { 2234 // Try to further simplify the result. 2235 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 2236 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 2237 // Use an IR Builder from SimplifiedCI if available instead of CI 2238 // to guarantee we reach all uses we might replace later on. 2239 IRBuilder<> TmpBuilder(SimplifiedCI); 2240 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) { 2241 // If we were able to further simplify, remove the now redundant call. 2242 SimplifiedCI->replaceAllUsesWith(V); 2243 SimplifiedCI->eraseFromParent(); 2244 return V; 2245 } 2246 } 2247 return SimplifiedFortifiedCI; 2248 } 2249 2250 // Then check for known library functions. 2251 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 2252 // We never change the calling convention. 2253 if (!ignoreCallingConv(Func) && !isCallingConvC) 2254 return nullptr; 2255 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 2256 return V; 2257 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 2258 return V; 2259 switch (Func) { 2260 case LibFunc_ffs: 2261 case LibFunc_ffsl: 2262 case LibFunc_ffsll: 2263 return optimizeFFS(CI, Builder); 2264 case LibFunc_fls: 2265 case LibFunc_flsl: 2266 case LibFunc_flsll: 2267 return optimizeFls(CI, Builder); 2268 case LibFunc_abs: 2269 case LibFunc_labs: 2270 case LibFunc_llabs: 2271 return optimizeAbs(CI, Builder); 2272 case LibFunc_isdigit: 2273 return optimizeIsDigit(CI, Builder); 2274 case LibFunc_isascii: 2275 return optimizeIsAscii(CI, Builder); 2276 case LibFunc_toascii: 2277 return optimizeToAscii(CI, Builder); 2278 case LibFunc_printf: 2279 return optimizePrintF(CI, Builder); 2280 case LibFunc_sprintf: 2281 return optimizeSPrintF(CI, Builder); 2282 case LibFunc_fprintf: 2283 return optimizeFPrintF(CI, Builder); 2284 case LibFunc_fwrite: 2285 return optimizeFWrite(CI, Builder); 2286 case LibFunc_fputs: 2287 return optimizeFPuts(CI, Builder); 2288 case LibFunc_puts: 2289 return optimizePuts(CI, Builder); 2290 case LibFunc_perror: 2291 return optimizeErrorReporting(CI, Builder); 2292 case LibFunc_vfprintf: 2293 case LibFunc_fiprintf: 2294 return optimizeErrorReporting(CI, Builder, 0); 2295 case LibFunc_fputc: 2296 return optimizeErrorReporting(CI, Builder, 1); 2297 default: 2298 return nullptr; 2299 } 2300 } 2301 return nullptr; 2302 } 2303 2304 LibCallSimplifier::LibCallSimplifier( 2305 const DataLayout &DL, const TargetLibraryInfo *TLI, 2306 OptimizationRemarkEmitter &ORE, 2307 function_ref<void(Instruction *, Value *)> Replacer) 2308 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), 2309 UnsafeFPShrink(false), Replacer(Replacer) {} 2310 2311 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 2312 // Indirect through the replacer used in this instance. 2313 Replacer(I, With); 2314 } 2315 2316 // TODO: 2317 // Additional cases that we need to add to this file: 2318 // 2319 // cbrt: 2320 // * cbrt(expN(X)) -> expN(x/3) 2321 // * cbrt(sqrt(x)) -> pow(x,1/6) 2322 // * cbrt(cbrt(x)) -> pow(x,1/9) 2323 // 2324 // exp, expf, expl: 2325 // * exp(log(x)) -> x 2326 // 2327 // log, logf, logl: 2328 // * log(exp(x)) -> x 2329 // * log(exp(y)) -> y*log(e) 2330 // * log(exp10(y)) -> y*log(10) 2331 // * log(sqrt(x)) -> 0.5*log(x) 2332 // 2333 // pow, powf, powl: 2334 // * pow(sqrt(x),y) -> pow(x,y*0.5) 2335 // * pow(pow(x,y),z)-> pow(x,y*z) 2336 // 2337 // signbit: 2338 // * signbit(cnst) -> cnst' 2339 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 2340 // 2341 // sqrt, sqrtf, sqrtl: 2342 // * sqrt(expN(x)) -> expN(x*0.5) 2343 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 2344 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 2345 // 2346 2347 //===----------------------------------------------------------------------===// 2348 // Fortified Library Call Optimizations 2349 //===----------------------------------------------------------------------===// 2350 2351 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 2352 unsigned ObjSizeOp, 2353 unsigned SizeOp, 2354 bool isString) { 2355 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp)) 2356 return true; 2357 if (ConstantInt *ObjSizeCI = 2358 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 2359 if (ObjSizeCI->isMinusOne()) 2360 return true; 2361 // If the object size wasn't -1 (unknown), bail out if we were asked to. 2362 if (OnlyLowerUnknownSize) 2363 return false; 2364 if (isString) { 2365 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp)); 2366 // If the length is 0 we don't know how long it is and so we can't 2367 // remove the check. 2368 if (Len == 0) 2369 return false; 2370 return ObjSizeCI->getZExtValue() >= Len; 2371 } 2372 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp))) 2373 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 2374 } 2375 return false; 2376 } 2377 2378 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 2379 IRBuilder<> &B) { 2380 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2381 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), 2382 CI->getArgOperand(2), 1); 2383 return CI->getArgOperand(0); 2384 } 2385 return nullptr; 2386 } 2387 2388 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 2389 IRBuilder<> &B) { 2390 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2391 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1), 2392 CI->getArgOperand(2), 1); 2393 return CI->getArgOperand(0); 2394 } 2395 return nullptr; 2396 } 2397 2398 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 2399 IRBuilder<> &B) { 2400 // TODO: Try foldMallocMemset() here. 2401 2402 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2403 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 2404 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 2405 return CI->getArgOperand(0); 2406 } 2407 return nullptr; 2408 } 2409 2410 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 2411 IRBuilder<> &B, 2412 LibFunc Func) { 2413 Function *Callee = CI->getCalledFunction(); 2414 StringRef Name = Callee->getName(); 2415 const DataLayout &DL = CI->getModule()->getDataLayout(); 2416 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 2417 *ObjSize = CI->getArgOperand(2); 2418 2419 // __stpcpy_chk(x,x,...) -> x+strlen(x) 2420 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 2421 Value *StrLen = emitStrLen(Src, B, DL, TLI); 2422 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 2423 } 2424 2425 // If a) we don't have any length information, or b) we know this will 2426 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 2427 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 2428 // TODO: It might be nice to get a maximum length out of the possible 2429 // string lengths for varying. 2430 if (isFortifiedCallFoldable(CI, 2, 1, true)) 2431 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6)); 2432 2433 if (OnlyLowerUnknownSize) 2434 return nullptr; 2435 2436 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 2437 uint64_t Len = GetStringLength(Src); 2438 if (Len == 0) 2439 return nullptr; 2440 2441 Type *SizeTTy = DL.getIntPtrType(CI->getContext()); 2442 Value *LenV = ConstantInt::get(SizeTTy, Len); 2443 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 2444 // If the function was an __stpcpy_chk, and we were able to fold it into 2445 // a __memcpy_chk, we still need to return the correct end pointer. 2446 if (Ret && Func == LibFunc_stpcpy_chk) 2447 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 2448 return Ret; 2449 } 2450 2451 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 2452 IRBuilder<> &B, 2453 LibFunc Func) { 2454 Function *Callee = CI->getCalledFunction(); 2455 StringRef Name = Callee->getName(); 2456 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2457 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 2458 CI->getArgOperand(2), B, TLI, Name.substr(2, 7)); 2459 return Ret; 2460 } 2461 return nullptr; 2462 } 2463 2464 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) { 2465 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 2466 // Some clang users checked for _chk libcall availability using: 2467 // __has_builtin(__builtin___memcpy_chk) 2468 // When compiling with -fno-builtin, this is always true. 2469 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 2470 // end up with fortified libcalls, which isn't acceptable in a freestanding 2471 // environment which only provides their non-fortified counterparts. 2472 // 2473 // Until we change clang and/or teach external users to check for availability 2474 // differently, disregard the "nobuiltin" attribute and TLI::has. 2475 // 2476 // PR23093. 2477 2478 LibFunc Func; 2479 Function *Callee = CI->getCalledFunction(); 2480 2481 SmallVector<OperandBundleDef, 2> OpBundles; 2482 CI->getOperandBundlesAsDefs(OpBundles); 2483 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 2484 bool isCallingConvC = isCallingConvCCompatible(CI); 2485 2486 // First, check that this is a known library functions and that the prototype 2487 // is correct. 2488 if (!TLI->getLibFunc(*Callee, Func)) 2489 return nullptr; 2490 2491 // We never change the calling convention. 2492 if (!ignoreCallingConv(Func) && !isCallingConvC) 2493 return nullptr; 2494 2495 switch (Func) { 2496 case LibFunc_memcpy_chk: 2497 return optimizeMemCpyChk(CI, Builder); 2498 case LibFunc_memmove_chk: 2499 return optimizeMemMoveChk(CI, Builder); 2500 case LibFunc_memset_chk: 2501 return optimizeMemSetChk(CI, Builder); 2502 case LibFunc_stpcpy_chk: 2503 case LibFunc_strcpy_chk: 2504 return optimizeStrpCpyChk(CI, Builder, Func); 2505 case LibFunc_stpncpy_chk: 2506 case LibFunc_strncpy_chk: 2507 return optimizeStrpNCpyChk(CI, Builder, Func); 2508 default: 2509 break; 2510 } 2511 return nullptr; 2512 } 2513 2514 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 2515 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 2516 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 2517