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