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