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