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