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