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