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