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/StringExtras.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/AttributeMask.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/IRBuilder.h" 27 #include "llvm/IR/IntrinsicInst.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/PatternMatch.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/KnownBits.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/TargetParser/Triple.h" 36 #include "llvm/Transforms/Utils/BuildLibCalls.h" 37 #include "llvm/Transforms/Utils/Local.h" 38 #include "llvm/Transforms/Utils/SizeOpts.h" 39 40 #include <cmath> 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 // Enable conversion of operator new calls with a MemProf hot or cold hint 52 // to an operator new call that takes a hot/cold hint. Off by default since 53 // not all allocators currently support this extension. 54 static cl::opt<bool> 55 OptimizeHotColdNew("optimize-hot-cold-new", cl::Hidden, cl::init(false), 56 cl::desc("Enable hot/cold operator new library calls")); 57 static cl::opt<bool> OptimizeExistingHotColdNew( 58 "optimize-existing-hot-cold-new", cl::Hidden, cl::init(false), 59 cl::desc( 60 "Enable optimization of existing hot/cold operator new library calls")); 61 62 namespace { 63 64 // Specialized parser to ensure the hint is an 8 bit value (we can't specify 65 // uint8_t to opt<> as that is interpreted to mean that we are passing a char 66 // option with a specific set of values. 67 struct HotColdHintParser : public cl::parser<unsigned> { 68 HotColdHintParser(cl::Option &O) : cl::parser<unsigned>(O) {} 69 70 bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) { 71 if (Arg.getAsInteger(0, Value)) 72 return O.error("'" + Arg + "' value invalid for uint argument!"); 73 74 if (Value > 255) 75 return O.error("'" + Arg + "' value must be in the range [0, 255]!"); 76 77 return false; 78 } 79 }; 80 81 } // end anonymous namespace 82 83 // Hot/cold operator new takes an 8 bit hotness hint, where 0 is the coldest 84 // and 255 is the hottest. Default to 1 value away from the coldest and hottest 85 // hints, so that the compiler hinted allocations are slightly less strong than 86 // manually inserted hints at the two extremes. 87 static cl::opt<unsigned, false, HotColdHintParser> ColdNewHintValue( 88 "cold-new-hint-value", cl::Hidden, cl::init(1), 89 cl::desc("Value to pass to hot/cold operator new for cold allocation")); 90 static cl::opt<unsigned, false, HotColdHintParser> 91 NotColdNewHintValue("notcold-new-hint-value", cl::Hidden, cl::init(128), 92 cl::desc("Value to pass to hot/cold operator new for " 93 "notcold (warm) allocation")); 94 static cl::opt<unsigned, false, HotColdHintParser> HotNewHintValue( 95 "hot-new-hint-value", cl::Hidden, cl::init(254), 96 cl::desc("Value to pass to hot/cold operator new for hot allocation")); 97 98 //===----------------------------------------------------------------------===// 99 // Helper Functions 100 //===----------------------------------------------------------------------===// 101 102 static bool ignoreCallingConv(LibFunc Func) { 103 return Func == LibFunc_abs || Func == LibFunc_labs || 104 Func == LibFunc_llabs || Func == LibFunc_strlen; 105 } 106 107 /// Return true if it is only used in equality comparisons with With. 108 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 109 for (User *U : V->users()) { 110 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 111 if (IC->isEquality() && IC->getOperand(1) == With) 112 continue; 113 // Unknown instruction. 114 return false; 115 } 116 return true; 117 } 118 119 static bool callHasFloatingPointArgument(const CallInst *CI) { 120 return any_of(CI->operands(), [](const Use &OI) { 121 return OI->getType()->isFloatingPointTy(); 122 }); 123 } 124 125 static bool callHasFP128Argument(const CallInst *CI) { 126 return any_of(CI->operands(), [](const Use &OI) { 127 return OI->getType()->isFP128Ty(); 128 }); 129 } 130 131 // Convert the entire string Str representing an integer in Base, up to 132 // the terminating nul if present, to a constant according to the rules 133 // of strtoul[l] or, when AsSigned is set, of strtol[l]. On success 134 // return the result, otherwise null. 135 // The function assumes the string is encoded in ASCII and carefully 136 // avoids converting sequences (including "") that the corresponding 137 // library call might fail and set errno for. 138 static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr, 139 uint64_t Base, bool AsSigned, IRBuilderBase &B) { 140 if (Base < 2 || Base > 36) 141 if (Base != 0) 142 // Fail for an invalid base (required by POSIX). 143 return nullptr; 144 145 // Current offset into the original string to reflect in EndPtr. 146 size_t Offset = 0; 147 // Strip leading whitespace. 148 for ( ; Offset != Str.size(); ++Offset) 149 if (!isSpace((unsigned char)Str[Offset])) { 150 Str = Str.substr(Offset); 151 break; 152 } 153 154 if (Str.empty()) 155 // Fail for empty subject sequences (POSIX allows but doesn't require 156 // strtol[l]/strtoul[l] to fail with EINVAL). 157 return nullptr; 158 159 // Strip but remember the sign. 160 bool Negate = Str[0] == '-'; 161 if (Str[0] == '-' || Str[0] == '+') { 162 Str = Str.drop_front(); 163 if (Str.empty()) 164 // Fail for a sign with nothing after it. 165 return nullptr; 166 ++Offset; 167 } 168 169 // Set Max to the absolute value of the minimum (for signed), or 170 // to the maximum (for unsigned) value representable in the type. 171 Type *RetTy = CI->getType(); 172 unsigned NBits = RetTy->getPrimitiveSizeInBits(); 173 uint64_t Max = AsSigned && Negate ? 1 : 0; 174 Max += AsSigned ? maxIntN(NBits) : maxUIntN(NBits); 175 176 // Autodetect Base if it's zero and consume the "0x" prefix. 177 if (Str.size() > 1) { 178 if (Str[0] == '0') { 179 if (toUpper((unsigned char)Str[1]) == 'X') { 180 if (Str.size() == 2 || (Base && Base != 16)) 181 // Fail if Base doesn't allow the "0x" prefix or for the prefix 182 // alone that implementations like BSD set errno to EINVAL for. 183 return nullptr; 184 185 Str = Str.drop_front(2); 186 Offset += 2; 187 Base = 16; 188 } 189 else if (Base == 0) 190 Base = 8; 191 } else if (Base == 0) 192 Base = 10; 193 } 194 else if (Base == 0) 195 Base = 10; 196 197 // Convert the rest of the subject sequence, not including the sign, 198 // to its uint64_t representation (this assumes the source character 199 // set is ASCII). 200 uint64_t Result = 0; 201 for (unsigned i = 0; i != Str.size(); ++i) { 202 unsigned char DigVal = Str[i]; 203 if (isDigit(DigVal)) 204 DigVal = DigVal - '0'; 205 else { 206 DigVal = toUpper(DigVal); 207 if (isAlpha(DigVal)) 208 DigVal = DigVal - 'A' + 10; 209 else 210 return nullptr; 211 } 212 213 if (DigVal >= Base) 214 // Fail if the digit is not valid in the Base. 215 return nullptr; 216 217 // Add the digit and fail if the result is not representable in 218 // the (unsigned form of the) destination type. 219 bool VFlow; 220 Result = SaturatingMultiplyAdd(Result, Base, (uint64_t)DigVal, &VFlow); 221 if (VFlow || Result > Max) 222 return nullptr; 223 } 224 225 if (EndPtr) { 226 // Store the pointer to the end. 227 Value *Off = B.getInt64(Offset + Str.size()); 228 Value *StrBeg = CI->getArgOperand(0); 229 Value *StrEnd = B.CreateInBoundsGEP(B.getInt8Ty(), StrBeg, Off, "endptr"); 230 B.CreateStore(StrEnd, EndPtr); 231 } 232 233 if (Negate) 234 // Unsigned negation doesn't overflow. 235 Result = -Result; 236 237 return ConstantInt::get(RetTy, Result); 238 } 239 240 static bool isOnlyUsedInComparisonWithZero(Value *V) { 241 for (User *U : V->users()) { 242 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 243 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 244 if (C->isNullValue()) 245 continue; 246 // Unknown instruction. 247 return false; 248 } 249 return true; 250 } 251 252 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, 253 const DataLayout &DL) { 254 if (!isOnlyUsedInComparisonWithZero(CI)) 255 return false; 256 257 if (!isDereferenceableAndAlignedPointer(Str, Align(1), APInt(64, Len), DL)) 258 return false; 259 260 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory)) 261 return false; 262 263 return true; 264 } 265 266 static void annotateDereferenceableBytes(CallInst *CI, 267 ArrayRef<unsigned> ArgNos, 268 uint64_t DereferenceableBytes) { 269 const Function *F = CI->getCaller(); 270 if (!F) 271 return; 272 for (unsigned ArgNo : ArgNos) { 273 uint64_t DerefBytes = DereferenceableBytes; 274 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 275 if (!llvm::NullPointerIsDefined(F, AS) || 276 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 277 DerefBytes = std::max(CI->getParamDereferenceableOrNullBytes(ArgNo), 278 DereferenceableBytes); 279 280 if (CI->getParamDereferenceableBytes(ArgNo) < DerefBytes) { 281 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable); 282 if (!llvm::NullPointerIsDefined(F, AS) || 283 CI->paramHasAttr(ArgNo, Attribute::NonNull)) 284 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull); 285 CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes( 286 CI->getContext(), DerefBytes)); 287 } 288 } 289 } 290 291 static void annotateNonNullNoUndefBasedOnAccess(CallInst *CI, 292 ArrayRef<unsigned> ArgNos) { 293 Function *F = CI->getCaller(); 294 if (!F) 295 return; 296 297 for (unsigned ArgNo : ArgNos) { 298 if (!CI->paramHasAttr(ArgNo, Attribute::NoUndef)) 299 CI->addParamAttr(ArgNo, Attribute::NoUndef); 300 301 if (!CI->paramHasAttr(ArgNo, Attribute::NonNull)) { 302 unsigned AS = 303 CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace(); 304 if (llvm::NullPointerIsDefined(F, AS)) 305 continue; 306 CI->addParamAttr(ArgNo, Attribute::NonNull); 307 } 308 309 annotateDereferenceableBytes(CI, ArgNo, 1); 310 } 311 } 312 313 static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos, 314 Value *Size, const DataLayout &DL) { 315 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) { 316 annotateNonNullNoUndefBasedOnAccess(CI, ArgNos); 317 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue()); 318 } else if (isKnownNonZero(Size, DL)) { 319 annotateNonNullNoUndefBasedOnAccess(CI, ArgNos); 320 const APInt *X, *Y; 321 uint64_t DerefMin = 1; 322 if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) { 323 DerefMin = std::min(X->getZExtValue(), Y->getZExtValue()); 324 annotateDereferenceableBytes(CI, ArgNos, DerefMin); 325 } 326 } 327 } 328 329 // Copy CallInst "flags" like musttail, notail, and tail. Return New param for 330 // easier chaining. Calls to emit* and B.createCall should probably be wrapped 331 // in this function when New is created to replace Old. Callers should take 332 // care to check Old.isMustTailCall() if they aren't replacing Old directly 333 // with New. 334 static Value *copyFlags(const CallInst &Old, Value *New) { 335 assert(!Old.isMustTailCall() && "do not copy musttail call flags"); 336 assert(!Old.isNoTailCall() && "do not copy notail call flags"); 337 if (auto *NewCI = dyn_cast_or_null<CallInst>(New)) 338 NewCI->setTailCallKind(Old.getTailCallKind()); 339 return New; 340 } 341 342 static Value *mergeAttributesAndFlags(CallInst *NewCI, const CallInst &Old) { 343 NewCI->setAttributes(AttributeList::get( 344 NewCI->getContext(), {NewCI->getAttributes(), Old.getAttributes()})); 345 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType())); 346 return copyFlags(Old, NewCI); 347 } 348 349 // Helper to avoid truncating the length if size_t is 32-bits. 350 static StringRef substr(StringRef Str, uint64_t Len) { 351 return Len >= Str.size() ? Str : Str.substr(0, Len); 352 } 353 354 //===----------------------------------------------------------------------===// 355 // String and Memory Library Call Optimizations 356 //===----------------------------------------------------------------------===// 357 358 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) { 359 // Extract some information from the instruction 360 Value *Dst = CI->getArgOperand(0); 361 Value *Src = CI->getArgOperand(1); 362 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 363 364 // See if we can get the length of the input string. 365 uint64_t Len = GetStringLength(Src); 366 if (Len) 367 annotateDereferenceableBytes(CI, 1, Len); 368 else 369 return nullptr; 370 --Len; // Unbias length. 371 372 // Handle the simple, do-nothing case: strcat(x, "") -> x 373 if (Len == 0) 374 return Dst; 375 376 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, Len, B)); 377 } 378 379 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 380 IRBuilderBase &B) { 381 // We need to find the end of the destination string. That's where the 382 // memory is to be moved to. We just generate a call to strlen. 383 Value *DstLen = emitStrLen(Dst, B, DL, TLI); 384 if (!DstLen) 385 return nullptr; 386 387 // Now that we have the destination's length, we must index into the 388 // destination's pointer to get the actual memcpy destination (end of 389 // the string .. we're concatenating). 390 Value *CpyDst = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, DstLen, "endptr"); 391 392 // We have enough information to now generate the memcpy call to do the 393 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 394 B.CreateMemCpy( 395 CpyDst, Align(1), Src, Align(1), 396 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1)); 397 return Dst; 398 } 399 400 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) { 401 // Extract some information from the instruction. 402 Value *Dst = CI->getArgOperand(0); 403 Value *Src = CI->getArgOperand(1); 404 Value *Size = CI->getArgOperand(2); 405 uint64_t Len; 406 annotateNonNullNoUndefBasedOnAccess(CI, 0); 407 if (isKnownNonZero(Size, DL)) 408 annotateNonNullNoUndefBasedOnAccess(CI, 1); 409 410 // We don't do anything if length is not constant. 411 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size); 412 if (LengthArg) { 413 Len = LengthArg->getZExtValue(); 414 // strncat(x, c, 0) -> x 415 if (!Len) 416 return Dst; 417 } else { 418 return nullptr; 419 } 420 421 // See if we can get the length of the input string. 422 uint64_t SrcLen = GetStringLength(Src); 423 if (SrcLen) { 424 annotateDereferenceableBytes(CI, 1, SrcLen); 425 --SrcLen; // Unbias length. 426 } else { 427 return nullptr; 428 } 429 430 // strncat(x, "", c) -> x 431 if (SrcLen == 0) 432 return Dst; 433 434 // We don't optimize this case. 435 if (Len < SrcLen) 436 return nullptr; 437 438 // strncat(x, s, c) -> strcat(x, s) 439 // s is constant so the strcat can be optimized further. 440 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, SrcLen, B)); 441 } 442 443 // Helper to transform memchr(S, C, N) == S to N && *S == C and, when 444 // NBytes is null, strchr(S, C) to *S == C. A precondition of the function 445 // is that either S is dereferenceable or the value of N is nonzero. 446 static Value* memChrToCharCompare(CallInst *CI, Value *NBytes, 447 IRBuilderBase &B, const DataLayout &DL) 448 { 449 Value *Src = CI->getArgOperand(0); 450 Value *CharVal = CI->getArgOperand(1); 451 452 // Fold memchr(A, C, N) == A to N && *A == C. 453 Type *CharTy = B.getInt8Ty(); 454 Value *Char0 = B.CreateLoad(CharTy, Src); 455 CharVal = B.CreateTrunc(CharVal, CharTy); 456 Value *Cmp = B.CreateICmpEQ(Char0, CharVal, "char0cmp"); 457 458 if (NBytes) { 459 Value *Zero = ConstantInt::get(NBytes->getType(), 0); 460 Value *And = B.CreateICmpNE(NBytes, Zero); 461 Cmp = B.CreateLogicalAnd(And, Cmp); 462 } 463 464 Value *NullPtr = Constant::getNullValue(CI->getType()); 465 return B.CreateSelect(Cmp, Src, NullPtr); 466 } 467 468 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) { 469 Value *SrcStr = CI->getArgOperand(0); 470 Value *CharVal = CI->getArgOperand(1); 471 annotateNonNullNoUndefBasedOnAccess(CI, 0); 472 473 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 474 return memChrToCharCompare(CI, nullptr, B, DL); 475 476 // If the second operand is non-constant, see if we can compute the length 477 // of the input string and turn this into memchr. 478 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 479 if (!CharC) { 480 uint64_t Len = GetStringLength(SrcStr); 481 if (Len) 482 annotateDereferenceableBytes(CI, 0, Len); 483 else 484 return nullptr; 485 486 Function *Callee = CI->getCalledFunction(); 487 FunctionType *FT = Callee->getFunctionType(); 488 unsigned IntBits = TLI->getIntSize(); 489 if (!FT->getParamType(1)->isIntegerTy(IntBits)) // memchr needs 'int'. 490 return nullptr; 491 492 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 493 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 494 return copyFlags(*CI, 495 emitMemChr(SrcStr, CharVal, // include nul. 496 ConstantInt::get(SizeTTy, Len), B, 497 DL, TLI)); 498 } 499 500 if (CharC->isZero()) { 501 Value *NullPtr = Constant::getNullValue(CI->getType()); 502 if (isOnlyUsedInEqualityComparison(CI, NullPtr)) 503 // Pre-empt the transformation to strlen below and fold 504 // strchr(A, '\0') == null to false. 505 return B.CreateIntToPtr(B.getTrue(), CI->getType()); 506 } 507 508 // Otherwise, the character is a constant, see if the first argument is 509 // a string literal. If so, we can constant fold. 510 StringRef Str; 511 if (!getConstantStringInfo(SrcStr, Str)) { 512 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) 513 if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI)) 514 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr"); 515 return nullptr; 516 } 517 518 // Compute the offset, make sure to handle the case when we're searching for 519 // zero (a weird way to spell strlen). 520 size_t I = (0xFF & CharC->getSExtValue()) == 0 521 ? Str.size() 522 : Str.find(CharC->getSExtValue()); 523 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 524 return Constant::getNullValue(CI->getType()); 525 526 // strchr(s+n,c) -> gep(s+n+i,c) 527 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr"); 528 } 529 530 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) { 531 Value *SrcStr = CI->getArgOperand(0); 532 Value *CharVal = CI->getArgOperand(1); 533 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 534 annotateNonNullNoUndefBasedOnAccess(CI, 0); 535 536 StringRef Str; 537 if (!getConstantStringInfo(SrcStr, Str)) { 538 // strrchr(s, 0) -> strchr(s, 0) 539 if (CharC && CharC->isZero()) 540 return copyFlags(*CI, emitStrChr(SrcStr, '\0', B, TLI)); 541 return nullptr; 542 } 543 544 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 545 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 546 547 // Try to expand strrchr to the memrchr nonstandard extension if it's 548 // available, or simply fail otherwise. 549 uint64_t NBytes = Str.size() + 1; // Include the terminating nul. 550 Value *Size = ConstantInt::get(SizeTTy, NBytes); 551 return copyFlags(*CI, emitMemRChr(SrcStr, CharVal, Size, B, DL, TLI)); 552 } 553 554 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) { 555 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 556 if (Str1P == Str2P) // strcmp(x,x) -> 0 557 return ConstantInt::get(CI->getType(), 0); 558 559 StringRef Str1, Str2; 560 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 561 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 562 563 // strcmp(x, y) -> cnst (if both x and y are constant strings) 564 if (HasStr1 && HasStr2) 565 return ConstantInt::get(CI->getType(), 566 std::clamp(Str1.compare(Str2), -1, 1)); 567 568 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 569 return B.CreateNeg(B.CreateZExt( 570 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 571 572 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 573 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 574 CI->getType()); 575 576 // strcmp(P, "x") -> memcmp(P, "x", 2) 577 uint64_t Len1 = GetStringLength(Str1P); 578 if (Len1) 579 annotateDereferenceableBytes(CI, 0, Len1); 580 uint64_t Len2 = GetStringLength(Str2P); 581 if (Len2) 582 annotateDereferenceableBytes(CI, 1, Len2); 583 584 if (Len1 && Len2) { 585 return copyFlags( 586 *CI, emitMemCmp(Str1P, Str2P, 587 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 588 std::min(Len1, Len2)), 589 B, DL, TLI)); 590 } 591 592 // strcmp to memcmp 593 if (!HasStr1 && HasStr2) { 594 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 595 return copyFlags( 596 *CI, 597 emitMemCmp(Str1P, Str2P, 598 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), 599 B, DL, TLI)); 600 } else if (HasStr1 && !HasStr2) { 601 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 602 return copyFlags( 603 *CI, 604 emitMemCmp(Str1P, Str2P, 605 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), 606 B, DL, TLI)); 607 } 608 609 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 610 return nullptr; 611 } 612 613 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant 614 // arrays LHS and RHS and nonconstant Size. 615 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, 616 Value *Size, bool StrNCmp, 617 IRBuilderBase &B, const DataLayout &DL); 618 619 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) { 620 Value *Str1P = CI->getArgOperand(0); 621 Value *Str2P = CI->getArgOperand(1); 622 Value *Size = CI->getArgOperand(2); 623 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 624 return ConstantInt::get(CI->getType(), 0); 625 626 if (isKnownNonZero(Size, DL)) 627 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 628 // Get the length argument if it is constant. 629 uint64_t Length; 630 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size)) 631 Length = LengthArg->getZExtValue(); 632 else 633 return optimizeMemCmpVarSize(CI, Str1P, Str2P, Size, true, B, DL); 634 635 if (Length == 0) // strncmp(x,y,0) -> 0 636 return ConstantInt::get(CI->getType(), 0); 637 638 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 639 return copyFlags(*CI, emitMemCmp(Str1P, Str2P, Size, B, DL, TLI)); 640 641 StringRef Str1, Str2; 642 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 643 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 644 645 // strncmp(x, y) -> cnst (if both x and y are constant strings) 646 if (HasStr1 && HasStr2) { 647 // Avoid truncating the 64-bit Length to 32 bits in ILP32. 648 StringRef SubStr1 = substr(Str1, Length); 649 StringRef SubStr2 = substr(Str2, Length); 650 return ConstantInt::get(CI->getType(), 651 std::clamp(SubStr1.compare(SubStr2), -1, 1)); 652 } 653 654 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 655 return B.CreateNeg(B.CreateZExt( 656 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType())); 657 658 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 659 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"), 660 CI->getType()); 661 662 uint64_t Len1 = GetStringLength(Str1P); 663 if (Len1) 664 annotateDereferenceableBytes(CI, 0, Len1); 665 uint64_t Len2 = GetStringLength(Str2P); 666 if (Len2) 667 annotateDereferenceableBytes(CI, 1, Len2); 668 669 // strncmp to memcmp 670 if (!HasStr1 && HasStr2) { 671 Len2 = std::min(Len2, Length); 672 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 673 return copyFlags( 674 *CI, 675 emitMemCmp(Str1P, Str2P, 676 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), 677 B, DL, TLI)); 678 } else if (HasStr1 && !HasStr2) { 679 Len1 = std::min(Len1, Length); 680 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 681 return copyFlags( 682 *CI, 683 emitMemCmp(Str1P, Str2P, 684 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), 685 B, DL, TLI)); 686 } 687 688 return nullptr; 689 } 690 691 Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) { 692 Value *Src = CI->getArgOperand(0); 693 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 694 uint64_t SrcLen = GetStringLength(Src); 695 if (SrcLen && Size) { 696 annotateDereferenceableBytes(CI, 0, SrcLen); 697 if (SrcLen <= Size->getZExtValue() + 1) 698 return copyFlags(*CI, emitStrDup(Src, B, TLI)); 699 } 700 701 return nullptr; 702 } 703 704 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) { 705 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 706 if (Dst == Src) // strcpy(x,x) -> x 707 return Src; 708 709 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 710 // See if we can get the length of the input string. 711 uint64_t Len = GetStringLength(Src); 712 if (Len) 713 annotateDereferenceableBytes(CI, 1, Len); 714 else 715 return nullptr; 716 717 // We have enough information to now generate the memcpy call to do the 718 // copy for us. Make a memcpy to copy the nul byte with align = 1. 719 CallInst *NewCI = 720 B.CreateMemCpy(Dst, Align(1), Src, Align(1), 721 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len)); 722 mergeAttributesAndFlags(NewCI, *CI); 723 return Dst; 724 } 725 726 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) { 727 Function *Callee = CI->getCalledFunction(); 728 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 729 730 // stpcpy(d,s) -> strcpy(d,s) if the result is not used. 731 if (CI->use_empty()) 732 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI)); 733 734 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 735 Value *StrLen = emitStrLen(Src, B, DL, TLI); 736 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 737 } 738 739 // See if we can get the length of the input string. 740 uint64_t Len = GetStringLength(Src); 741 if (Len) 742 annotateDereferenceableBytes(CI, 1, Len); 743 else 744 return nullptr; 745 746 Type *PT = Callee->getFunctionType()->getParamType(0); 747 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len); 748 Value *DstEnd = B.CreateInBoundsGEP( 749 B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1)); 750 751 // We have enough information to now generate the memcpy call to do the 752 // copy for us. Make a memcpy to copy the nul byte with align = 1. 753 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV); 754 mergeAttributesAndFlags(NewCI, *CI); 755 return DstEnd; 756 } 757 758 // Optimize a call to size_t strlcpy(char*, const char*, size_t). 759 760 Value *LibCallSimplifier::optimizeStrLCpy(CallInst *CI, IRBuilderBase &B) { 761 Value *Size = CI->getArgOperand(2); 762 if (isKnownNonZero(Size, DL)) 763 // Like snprintf, the function stores into the destination only when 764 // the size argument is nonzero. 765 annotateNonNullNoUndefBasedOnAccess(CI, 0); 766 // The function reads the source argument regardless of Size (it returns 767 // its length). 768 annotateNonNullNoUndefBasedOnAccess(CI, 1); 769 770 uint64_t NBytes; 771 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size)) 772 NBytes = SizeC->getZExtValue(); 773 else 774 return nullptr; 775 776 Value *Dst = CI->getArgOperand(0); 777 Value *Src = CI->getArgOperand(1); 778 if (NBytes <= 1) { 779 if (NBytes == 1) 780 // For a call to strlcpy(D, S, 1) first store a nul in *D. 781 B.CreateStore(B.getInt8(0), Dst); 782 783 // Transform strlcpy(D, S, 0) to a call to strlen(S). 784 return copyFlags(*CI, emitStrLen(Src, B, DL, TLI)); 785 } 786 787 // Try to determine the length of the source, substituting its size 788 // when it's not nul-terminated (as it's required to be) to avoid 789 // reading past its end. 790 StringRef Str; 791 if (!getConstantStringInfo(Src, Str, /*TrimAtNul=*/false)) 792 return nullptr; 793 794 uint64_t SrcLen = Str.find('\0'); 795 // Set if the terminating nul should be copied by the call to memcpy 796 // below. 797 bool NulTerm = SrcLen < NBytes; 798 799 if (NulTerm) 800 // Overwrite NBytes with the number of bytes to copy, including 801 // the terminating nul. 802 NBytes = SrcLen + 1; 803 else { 804 // Set the length of the source for the function to return to its 805 // size, and cap NBytes at the same. 806 SrcLen = std::min(SrcLen, uint64_t(Str.size())); 807 NBytes = std::min(NBytes - 1, SrcLen); 808 } 809 810 if (SrcLen == 0) { 811 // Transform strlcpy(D, "", N) to (*D = '\0, 0). 812 B.CreateStore(B.getInt8(0), Dst); 813 return ConstantInt::get(CI->getType(), 0); 814 } 815 816 Function *Callee = CI->getCalledFunction(); 817 Type *PT = Callee->getFunctionType()->getParamType(0); 818 // Transform strlcpy(D, S, N) to memcpy(D, S, N') where N' is the lower 819 // bound on strlen(S) + 1 and N, optionally followed by a nul store to 820 // D[N' - 1] if necessary. 821 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), 822 ConstantInt::get(DL.getIntPtrType(PT), NBytes)); 823 mergeAttributesAndFlags(NewCI, *CI); 824 825 if (!NulTerm) { 826 Value *EndOff = ConstantInt::get(CI->getType(), NBytes); 827 Value *EndPtr = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, EndOff); 828 B.CreateStore(B.getInt8(0), EndPtr); 829 } 830 831 // Like snprintf, strlcpy returns the number of nonzero bytes that would 832 // have been copied if the bound had been sufficiently big (which in this 833 // case is strlen(Src)). 834 return ConstantInt::get(CI->getType(), SrcLen); 835 } 836 837 // Optimize a call CI to either stpncpy when RetEnd is true, or to strncpy 838 // otherwise. 839 Value *LibCallSimplifier::optimizeStringNCpy(CallInst *CI, bool RetEnd, 840 IRBuilderBase &B) { 841 Function *Callee = CI->getCalledFunction(); 842 Value *Dst = CI->getArgOperand(0); 843 Value *Src = CI->getArgOperand(1); 844 Value *Size = CI->getArgOperand(2); 845 846 if (isKnownNonZero(Size, DL)) { 847 // Both st{p,r}ncpy(D, S, N) access the source and destination arrays 848 // only when N is nonzero. 849 annotateNonNullNoUndefBasedOnAccess(CI, 0); 850 annotateNonNullNoUndefBasedOnAccess(CI, 1); 851 } 852 853 // If the "bound" argument is known set N to it. Otherwise set it to 854 // UINT64_MAX and handle it later. 855 uint64_t N = UINT64_MAX; 856 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size)) 857 N = SizeC->getZExtValue(); 858 859 if (N == 0) 860 // Fold st{p,r}ncpy(D, S, 0) to D. 861 return Dst; 862 863 if (N == 1) { 864 Type *CharTy = B.getInt8Ty(); 865 Value *CharVal = B.CreateLoad(CharTy, Src, "stxncpy.char0"); 866 B.CreateStore(CharVal, Dst); 867 if (!RetEnd) 868 // Transform strncpy(D, S, 1) to return (*D = *S), D. 869 return Dst; 870 871 // Transform stpncpy(D, S, 1) to return (*D = *S) ? D + 1 : D. 872 Value *ZeroChar = ConstantInt::get(CharTy, 0); 873 Value *Cmp = B.CreateICmpEQ(CharVal, ZeroChar, "stpncpy.char0cmp"); 874 875 Value *Off1 = B.getInt32(1); 876 Value *EndPtr = B.CreateInBoundsGEP(CharTy, Dst, Off1, "stpncpy.end"); 877 return B.CreateSelect(Cmp, Dst, EndPtr, "stpncpy.sel"); 878 } 879 880 // If the length of the input string is known set SrcLen to it. 881 uint64_t SrcLen = GetStringLength(Src); 882 if (SrcLen) 883 annotateDereferenceableBytes(CI, 1, SrcLen); 884 else 885 return nullptr; 886 887 --SrcLen; // Unbias length. 888 889 if (SrcLen == 0) { 890 // Transform st{p,r}ncpy(D, "", N) to memset(D, '\0', N) for any N. 891 Align MemSetAlign = 892 CI->getAttributes().getParamAttrs(0).getAlignment().valueOrOne(); 893 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, MemSetAlign); 894 AttrBuilder ArgAttrs(CI->getContext(), CI->getAttributes().getParamAttrs(0)); 895 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes( 896 CI->getContext(), 0, ArgAttrs)); 897 copyFlags(*CI, NewCI); 898 return Dst; 899 } 900 901 if (N > SrcLen + 1) { 902 if (N > 128) 903 // Bail if N is large or unknown. 904 return nullptr; 905 906 // st{p,r}ncpy(D, "a", N) -> memcpy(D, "a\0\0\0", N) for N <= 128. 907 StringRef Str; 908 if (!getConstantStringInfo(Src, Str)) 909 return nullptr; 910 std::string SrcStr = Str.str(); 911 // Create a bigger, nul-padded array with the same length, SrcLen, 912 // as the original string. 913 SrcStr.resize(N, '\0'); 914 Src = B.CreateGlobalString(SrcStr, "str", /*AddressSpace=*/0, 915 /*M=*/nullptr, /*AddNull=*/false); 916 } 917 918 Type *PT = Callee->getFunctionType()->getParamType(0); 919 // st{p,r}ncpy(D, S, N) -> memcpy(align 1 D, align 1 S, N) when both 920 // S and N are constant. 921 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), 922 ConstantInt::get(DL.getIntPtrType(PT), N)); 923 mergeAttributesAndFlags(NewCI, *CI); 924 if (!RetEnd) 925 return Dst; 926 927 // stpncpy(D, S, N) returns the address of the first null in D if it writes 928 // one, otherwise D + N. 929 Value *Off = B.getInt64(std::min(SrcLen, N)); 930 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, Off, "endptr"); 931 } 932 933 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B, 934 unsigned CharSize, 935 Value *Bound) { 936 Value *Src = CI->getArgOperand(0); 937 Type *CharTy = B.getIntNTy(CharSize); 938 939 if (isOnlyUsedInZeroEqualityComparison(CI) && 940 (!Bound || isKnownNonZero(Bound, DL))) { 941 // Fold strlen: 942 // strlen(x) != 0 --> *x != 0 943 // strlen(x) == 0 --> *x == 0 944 // and likewise strnlen with constant N > 0: 945 // strnlen(x, N) != 0 --> *x != 0 946 // strnlen(x, N) == 0 --> *x == 0 947 return B.CreateZExt(B.CreateLoad(CharTy, Src, "char0"), 948 CI->getType()); 949 } 950 951 if (Bound) { 952 if (ConstantInt *BoundCst = dyn_cast<ConstantInt>(Bound)) { 953 if (BoundCst->isZero()) 954 // Fold strnlen(s, 0) -> 0 for any s, constant or otherwise. 955 return ConstantInt::get(CI->getType(), 0); 956 957 if (BoundCst->isOne()) { 958 // Fold strnlen(s, 1) -> *s ? 1 : 0 for any s. 959 Value *CharVal = B.CreateLoad(CharTy, Src, "strnlen.char0"); 960 Value *ZeroChar = ConstantInt::get(CharTy, 0); 961 Value *Cmp = B.CreateICmpNE(CharVal, ZeroChar, "strnlen.char0cmp"); 962 return B.CreateZExt(Cmp, CI->getType()); 963 } 964 } 965 } 966 967 if (uint64_t Len = GetStringLength(Src, CharSize)) { 968 Value *LenC = ConstantInt::get(CI->getType(), Len - 1); 969 // Fold strlen("xyz") -> 3 and strnlen("xyz", 2) -> 2 970 // and strnlen("xyz", Bound) -> min(3, Bound) for nonconstant Bound. 971 if (Bound) 972 return B.CreateBinaryIntrinsic(Intrinsic::umin, LenC, Bound); 973 return LenC; 974 } 975 976 if (Bound) 977 // Punt for strnlen for now. 978 return nullptr; 979 980 // If s is a constant pointer pointing to a string literal, we can fold 981 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 982 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 983 // We only try to simplify strlen when the pointer s points to an array 984 // of CharSize elements. Otherwise, we would need to scale the offset x before 985 // doing the subtraction. This will make the optimization more complex, and 986 // it's not very useful because calling strlen for a pointer of other types is 987 // very uncommon. 988 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 989 // TODO: Handle subobjects. 990 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 991 return nullptr; 992 993 ConstantDataArraySlice Slice; 994 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 995 uint64_t NullTermIdx; 996 if (Slice.Array == nullptr) { 997 NullTermIdx = 0; 998 } else { 999 NullTermIdx = ~((uint64_t)0); 1000 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 1001 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 1002 NullTermIdx = I; 1003 break; 1004 } 1005 } 1006 // If the string does not have '\0', leave it to strlen to compute 1007 // its length. 1008 if (NullTermIdx == ~((uint64_t)0)) 1009 return nullptr; 1010 } 1011 1012 Value *Offset = GEP->getOperand(2); 1013 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 1014 uint64_t ArrSize = 1015 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 1016 1017 // If Offset is not provably in the range [0, NullTermIdx], we can still 1018 // optimize if we can prove that the program has undefined behavior when 1019 // Offset is outside that range. That is the case when GEP->getOperand(0) 1020 // is a pointer to an object whose memory extent is NullTermIdx+1. 1021 if ((Known.isNonNegative() && Known.getMaxValue().ule(NullTermIdx)) || 1022 (isa<GlobalVariable>(GEP->getOperand(0)) && 1023 NullTermIdx == ArrSize - 1)) { 1024 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 1025 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 1026 Offset); 1027 } 1028 } 1029 } 1030 1031 // strlen(x?"foo":"bars") --> x ? 3 : 4 1032 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 1033 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 1034 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 1035 if (LenTrue && LenFalse) { 1036 ORE.emit([&]() { 1037 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 1038 << "folded strlen(select) to select of constants"; 1039 }); 1040 return B.CreateSelect(SI->getCondition(), 1041 ConstantInt::get(CI->getType(), LenTrue - 1), 1042 ConstantInt::get(CI->getType(), LenFalse - 1)); 1043 } 1044 } 1045 1046 return nullptr; 1047 } 1048 1049 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) { 1050 if (Value *V = optimizeStringLength(CI, B, 8)) 1051 return V; 1052 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1053 return nullptr; 1054 } 1055 1056 Value *LibCallSimplifier::optimizeStrNLen(CallInst *CI, IRBuilderBase &B) { 1057 Value *Bound = CI->getArgOperand(1); 1058 if (Value *V = optimizeStringLength(CI, B, 8, Bound)) 1059 return V; 1060 1061 if (isKnownNonZero(Bound, DL)) 1062 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1063 return nullptr; 1064 } 1065 1066 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) { 1067 Module &M = *CI->getModule(); 1068 unsigned WCharSize = TLI->getWCharSize(M) * 8; 1069 // We cannot perform this optimization without wchar_size metadata. 1070 if (WCharSize == 0) 1071 return nullptr; 1072 1073 return optimizeStringLength(CI, B, WCharSize); 1074 } 1075 1076 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) { 1077 StringRef S1, S2; 1078 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1079 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1080 1081 // strpbrk(s, "") -> nullptr 1082 // strpbrk("", s) -> nullptr 1083 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 1084 return Constant::getNullValue(CI->getType()); 1085 1086 // Constant folding. 1087 if (HasS1 && HasS2) { 1088 size_t I = S1.find_first_of(S2); 1089 if (I == StringRef::npos) // No match. 1090 return Constant::getNullValue(CI->getType()); 1091 1092 return B.CreateInBoundsGEP(B.getInt8Ty(), CI->getArgOperand(0), 1093 B.getInt64(I), "strpbrk"); 1094 } 1095 1096 // strpbrk(s, "a") -> strchr(s, 'a') 1097 if (HasS2 && S2.size() == 1) 1098 return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI)); 1099 1100 return nullptr; 1101 } 1102 1103 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) { 1104 Value *EndPtr = CI->getArgOperand(1); 1105 if (isa<ConstantPointerNull>(EndPtr)) { 1106 // With a null EndPtr, this function won't capture the main argument. 1107 // It would be readonly too, except that it still may write to errno. 1108 CI->addParamAttr(0, Attribute::NoCapture); 1109 } 1110 1111 return nullptr; 1112 } 1113 1114 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) { 1115 StringRef S1, S2; 1116 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1117 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1118 1119 // strspn(s, "") -> 0 1120 // strspn("", s) -> 0 1121 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 1122 return Constant::getNullValue(CI->getType()); 1123 1124 // Constant folding. 1125 if (HasS1 && HasS2) { 1126 size_t Pos = S1.find_first_not_of(S2); 1127 if (Pos == StringRef::npos) 1128 Pos = S1.size(); 1129 return ConstantInt::get(CI->getType(), Pos); 1130 } 1131 1132 return nullptr; 1133 } 1134 1135 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) { 1136 StringRef S1, S2; 1137 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 1138 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 1139 1140 // strcspn("", s) -> 0 1141 if (HasS1 && S1.empty()) 1142 return Constant::getNullValue(CI->getType()); 1143 1144 // Constant folding. 1145 if (HasS1 && HasS2) { 1146 size_t Pos = S1.find_first_of(S2); 1147 if (Pos == StringRef::npos) 1148 Pos = S1.size(); 1149 return ConstantInt::get(CI->getType(), Pos); 1150 } 1151 1152 // strcspn(s, "") -> strlen(s) 1153 if (HasS2 && S2.empty()) 1154 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI)); 1155 1156 return nullptr; 1157 } 1158 1159 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) { 1160 // fold strstr(x, x) -> x. 1161 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 1162 return CI->getArgOperand(0); 1163 1164 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 1165 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 1166 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 1167 if (!StrLen) 1168 return nullptr; 1169 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 1170 StrLen, B, DL, TLI); 1171 if (!StrNCmp) 1172 return nullptr; 1173 for (User *U : llvm::make_early_inc_range(CI->users())) { 1174 ICmpInst *Old = cast<ICmpInst>(U); 1175 Value *Cmp = 1176 B.CreateICmp(Old->getPredicate(), StrNCmp, 1177 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 1178 replaceAllUsesWith(Old, Cmp); 1179 } 1180 return CI; 1181 } 1182 1183 // See if either input string is a constant string. 1184 StringRef SearchStr, ToFindStr; 1185 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 1186 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 1187 1188 // fold strstr(x, "") -> x. 1189 if (HasStr2 && ToFindStr.empty()) 1190 return CI->getArgOperand(0); 1191 1192 // If both strings are known, constant fold it. 1193 if (HasStr1 && HasStr2) { 1194 size_t Offset = SearchStr.find(ToFindStr); 1195 1196 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 1197 return Constant::getNullValue(CI->getType()); 1198 1199 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 1200 return B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), CI->getArgOperand(0), 1201 Offset, "strstr"); 1202 } 1203 1204 // fold strstr(x, "y") -> strchr(x, 'y'). 1205 if (HasStr2 && ToFindStr.size() == 1) { 1206 return emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 1207 } 1208 1209 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 1210 return nullptr; 1211 } 1212 1213 Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) { 1214 Value *SrcStr = CI->getArgOperand(0); 1215 Value *Size = CI->getArgOperand(2); 1216 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1217 Value *CharVal = CI->getArgOperand(1); 1218 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1219 Value *NullPtr = Constant::getNullValue(CI->getType()); 1220 1221 if (LenC) { 1222 if (LenC->isZero()) 1223 // Fold memrchr(x, y, 0) --> null. 1224 return NullPtr; 1225 1226 if (LenC->isOne()) { 1227 // Fold memrchr(x, y, 1) --> *x == y ? x : null for any x and y, 1228 // constant or otherwise. 1229 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memrchr.char0"); 1230 // Slice off the character's high end bits. 1231 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1232 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memrchr.char0cmp"); 1233 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memrchr.sel"); 1234 } 1235 } 1236 1237 StringRef Str; 1238 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false)) 1239 return nullptr; 1240 1241 if (Str.size() == 0) 1242 // If the array is empty fold memrchr(A, C, N) to null for any value 1243 // of C and N on the basis that the only valid value of N is zero 1244 // (otherwise the call is undefined). 1245 return NullPtr; 1246 1247 uint64_t EndOff = UINT64_MAX; 1248 if (LenC) { 1249 EndOff = LenC->getZExtValue(); 1250 if (Str.size() < EndOff) 1251 // Punt out-of-bounds accesses to sanitizers and/or libc. 1252 return nullptr; 1253 } 1254 1255 if (ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal)) { 1256 // Fold memrchr(S, C, N) for a constant C. 1257 size_t Pos = Str.rfind(CharC->getZExtValue(), EndOff); 1258 if (Pos == StringRef::npos) 1259 // When the character is not in the source array fold the result 1260 // to null regardless of Size. 1261 return NullPtr; 1262 1263 if (LenC) 1264 // Fold memrchr(s, c, N) --> s + Pos for constant N > Pos. 1265 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos)); 1266 1267 if (Str.find(Str[Pos]) == Pos) { 1268 // When there is just a single occurrence of C in S, i.e., the one 1269 // in Str[Pos], fold 1270 // memrchr(s, c, N) --> N <= Pos ? null : s + Pos 1271 // for nonconstant N. 1272 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1273 "memrchr.cmp"); 1274 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, 1275 B.getInt64(Pos), "memrchr.ptr_plus"); 1276 return B.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel"); 1277 } 1278 } 1279 1280 // Truncate the string to search at most EndOff characters. 1281 Str = Str.substr(0, EndOff); 1282 if (Str.find_first_not_of(Str[0]) != StringRef::npos) 1283 return nullptr; 1284 1285 // If the source array consists of all equal characters, then for any 1286 // C and N (whether in bounds or not), fold memrchr(S, C, N) to 1287 // N != 0 && *S == C ? S + N - 1 : null 1288 Type *SizeTy = Size->getType(); 1289 Type *Int8Ty = B.getInt8Ty(); 1290 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1291 // Slice off the sought character's high end bits. 1292 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1293 Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal); 1294 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0); 1295 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1)); 1296 Value *SrcPlus = 1297 B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus"); 1298 return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel"); 1299 } 1300 1301 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) { 1302 Value *SrcStr = CI->getArgOperand(0); 1303 Value *Size = CI->getArgOperand(2); 1304 1305 if (isKnownNonZero(Size, DL)) { 1306 annotateNonNullNoUndefBasedOnAccess(CI, 0); 1307 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 1308 return memChrToCharCompare(CI, Size, B, DL); 1309 } 1310 1311 Value *CharVal = CI->getArgOperand(1); 1312 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal); 1313 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1314 Value *NullPtr = Constant::getNullValue(CI->getType()); 1315 1316 // memchr(x, y, 0) -> null 1317 if (LenC) { 1318 if (LenC->isZero()) 1319 return NullPtr; 1320 1321 if (LenC->isOne()) { 1322 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y, 1323 // constant or otherwise. 1324 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0"); 1325 // Slice off the character's high end bits. 1326 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty()); 1327 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp"); 1328 return B.CreateSelect(Cmp, SrcStr, NullPtr, "memchr.sel"); 1329 } 1330 } 1331 1332 StringRef Str; 1333 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false)) 1334 return nullptr; 1335 1336 if (CharC) { 1337 size_t Pos = Str.find(CharC->getZExtValue()); 1338 if (Pos == StringRef::npos) 1339 // When the character is not in the source array fold the result 1340 // to null regardless of Size. 1341 return NullPtr; 1342 1343 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos 1344 // When the constant Size is less than or equal to the character 1345 // position also fold the result to null. 1346 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos), 1347 "memchr.cmp"); 1348 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos), 1349 "memchr.ptr"); 1350 return B.CreateSelect(Cmp, NullPtr, SrcPlus); 1351 } 1352 1353 if (Str.size() == 0) 1354 // If the array is empty fold memchr(A, C, N) to null for any value 1355 // of C and N on the basis that the only valid value of N is zero 1356 // (otherwise the call is undefined). 1357 return NullPtr; 1358 1359 if (LenC) 1360 Str = substr(Str, LenC->getZExtValue()); 1361 1362 size_t Pos = Str.find_first_not_of(Str[0]); 1363 if (Pos == StringRef::npos 1364 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) { 1365 // If the source array consists of at most two consecutive sequences 1366 // of the same characters, then for any C and N (whether in bounds or 1367 // not), fold memchr(S, C, N) to 1368 // N != 0 && *S == C ? S : null 1369 // or for the two sequences to: 1370 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null) 1371 // ^Sel2 ^Sel1 are denoted above. 1372 // The latter makes it also possible to fold strchr() calls with strings 1373 // of the same characters. 1374 Type *SizeTy = Size->getType(); 1375 Type *Int8Ty = B.getInt8Ty(); 1376 1377 // Slice off the sought character's high end bits. 1378 CharVal = B.CreateTrunc(CharVal, Int8Ty); 1379 1380 Value *Sel1 = NullPtr; 1381 if (Pos != StringRef::npos) { 1382 // Handle two consecutive sequences of the same characters. 1383 Value *PosVal = ConstantInt::get(SizeTy, Pos); 1384 Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]); 1385 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos); 1386 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal); 1387 Value *And = B.CreateAnd(CEqSPos, NGtPos); 1388 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal); 1389 Sel1 = B.CreateSelect(And, SrcPlus, NullPtr, "memchr.sel1"); 1390 } 1391 1392 Value *Str0 = ConstantInt::get(Int8Ty, Str[0]); 1393 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal); 1394 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0)); 1395 Value *And = B.CreateAnd(NNeZ, CEqS0); 1396 return B.CreateSelect(And, SrcStr, Sel1, "memchr.sel2"); 1397 } 1398 1399 if (!LenC) { 1400 if (isOnlyUsedInEqualityComparison(CI, SrcStr)) 1401 // S is dereferenceable so it's safe to load from it and fold 1402 // memchr(S, C, N) == S to N && *S == C for any C and N. 1403 // TODO: This is safe even for nonconstant S. 1404 return memChrToCharCompare(CI, Size, B, DL); 1405 1406 // From now on we need a constant length and constant array. 1407 return nullptr; 1408 } 1409 1410 bool OptForSize = CI->getFunction()->hasOptSize() || 1411 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 1412 PGSOQueryType::IRPass); 1413 1414 // If the char is variable but the input str and length are not we can turn 1415 // this memchr call into a simple bit field test. Of course this only works 1416 // when the return value is only checked against null. 1417 // 1418 // It would be really nice to reuse switch lowering here but we can't change 1419 // the CFG at this point. 1420 // 1421 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n'))) 1422 // != 0 1423 // after bounds check. 1424 if (OptForSize || Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI)) 1425 return nullptr; 1426 1427 unsigned char Max = 1428 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 1429 reinterpret_cast<const unsigned char *>(Str.end())); 1430 1431 // Make sure the bit field we're about to create fits in a register on the 1432 // target. 1433 // FIXME: On a 64 bit architecture this prevents us from using the 1434 // interesting range of alpha ascii chars. We could do better by emitting 1435 // two bitfields or shifting the range by 64 if no lower chars are used. 1436 if (!DL.fitsInLegalInteger(Max + 1)) { 1437 // Build chain of ORs 1438 // Transform: 1439 // memchr("abcd", C, 4) != nullptr 1440 // to: 1441 // (C == 'a' || C == 'b' || C == 'c' || C == 'd') != 0 1442 std::string SortedStr = Str.str(); 1443 llvm::sort(SortedStr); 1444 // Compute the number of of non-contiguous ranges. 1445 unsigned NonContRanges = 1; 1446 for (size_t i = 1; i < SortedStr.size(); ++i) { 1447 if (SortedStr[i] > SortedStr[i - 1] + 1) { 1448 NonContRanges++; 1449 } 1450 } 1451 1452 // Restrict this optimization to profitable cases with one or two range 1453 // checks. 1454 if (NonContRanges > 2) 1455 return nullptr; 1456 1457 SmallVector<Value *> CharCompares; 1458 for (unsigned char C : SortedStr) 1459 CharCompares.push_back( 1460 B.CreateICmpEQ(CharVal, ConstantInt::get(CharVal->getType(), C))); 1461 1462 return B.CreateIntToPtr(B.CreateOr(CharCompares), CI->getType()); 1463 } 1464 1465 // For the bit field use a power-of-2 type with at least 8 bits to avoid 1466 // creating unnecessary illegal types. 1467 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 1468 1469 // Now build the bit field. 1470 APInt Bitfield(Width, 0); 1471 for (char C : Str) 1472 Bitfield.setBit((unsigned char)C); 1473 Value *BitfieldC = B.getInt(Bitfield); 1474 1475 // Adjust width of "C" to the bitfield width, then mask off the high bits. 1476 Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType()); 1477 C = B.CreateAnd(C, B.getIntN(Width, 0xFF)); 1478 1479 // First check that the bit field access is within bounds. 1480 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 1481 "memchr.bounds"); 1482 1483 // Create code that checks if the given bit is set in the field. 1484 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 1485 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 1486 1487 // Finally merge both checks and cast to pointer type. The inttoptr 1488 // implicitly zexts the i1 to intptr type. 1489 return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"), 1490 CI->getType()); 1491 } 1492 1493 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant 1494 // arrays LHS and RHS and nonconstant Size. 1495 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, 1496 Value *Size, bool StrNCmp, 1497 IRBuilderBase &B, const DataLayout &DL) { 1498 if (LHS == RHS) // memcmp(s,s,x) -> 0 1499 return Constant::getNullValue(CI->getType()); 1500 1501 StringRef LStr, RStr; 1502 if (!getConstantStringInfo(LHS, LStr, /*TrimAtNul=*/false) || 1503 !getConstantStringInfo(RHS, RStr, /*TrimAtNul=*/false)) 1504 return nullptr; 1505 1506 // If the contents of both constant arrays are known, fold a call to 1507 // memcmp(A, B, N) to 1508 // N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0) 1509 // where Pos is the first mismatch between A and B, determined below. 1510 1511 uint64_t Pos = 0; 1512 Value *Zero = ConstantInt::get(CI->getType(), 0); 1513 for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) { 1514 if (Pos == MinSize || 1515 (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) { 1516 // One array is a leading part of the other of equal or greater 1517 // size, or for strncmp, the arrays are equal strings. 1518 // Fold the result to zero. Size is assumed to be in bounds, since 1519 // otherwise the call would be undefined. 1520 return Zero; 1521 } 1522 1523 if (LStr[Pos] != RStr[Pos]) 1524 break; 1525 } 1526 1527 // Normalize the result. 1528 typedef unsigned char UChar; 1529 int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1; 1530 Value *MaxSize = ConstantInt::get(Size->getType(), Pos); 1531 Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize); 1532 Value *Res = ConstantInt::get(CI->getType(), IRes); 1533 return B.CreateSelect(Cmp, Zero, Res); 1534 } 1535 1536 // Optimize a memcmp call CI with constant size Len. 1537 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, 1538 uint64_t Len, IRBuilderBase &B, 1539 const DataLayout &DL) { 1540 if (Len == 0) // memcmp(s1,s2,0) -> 0 1541 return Constant::getNullValue(CI->getType()); 1542 1543 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 1544 if (Len == 1) { 1545 Value *LHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), LHS, "lhsc"), 1546 CI->getType(), "lhsv"); 1547 Value *RHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), RHS, "rhsc"), 1548 CI->getType(), "rhsv"); 1549 return B.CreateSub(LHSV, RHSV, "chardiff"); 1550 } 1551 1552 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 1553 // TODO: The case where both inputs are constants does not need to be limited 1554 // to legal integers or equality comparison. See block below this. 1555 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 1556 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 1557 Align PrefAlignment = DL.getPrefTypeAlign(IntType); 1558 1559 // First, see if we can fold either argument to a constant. 1560 Value *LHSV = nullptr; 1561 if (auto *LHSC = dyn_cast<Constant>(LHS)) 1562 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 1563 1564 Value *RHSV = nullptr; 1565 if (auto *RHSC = dyn_cast<Constant>(RHS)) 1566 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 1567 1568 // Don't generate unaligned loads. If either source is constant data, 1569 // alignment doesn't matter for that source because there is no load. 1570 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 1571 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 1572 if (!LHSV) 1573 LHSV = B.CreateLoad(IntType, LHS, "lhsv"); 1574 if (!RHSV) 1575 RHSV = B.CreateLoad(IntType, RHS, "rhsv"); 1576 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 1577 } 1578 } 1579 1580 return nullptr; 1581 } 1582 1583 // Most simplifications for memcmp also apply to bcmp. 1584 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI, 1585 IRBuilderBase &B) { 1586 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 1587 Value *Size = CI->getArgOperand(2); 1588 1589 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1590 1591 if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL)) 1592 return Res; 1593 1594 // Handle constant Size. 1595 ConstantInt *LenC = dyn_cast<ConstantInt>(Size); 1596 if (!LenC) 1597 return nullptr; 1598 1599 return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL); 1600 } 1601 1602 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) { 1603 Module *M = CI->getModule(); 1604 if (Value *V = optimizeMemCmpBCmpCommon(CI, B)) 1605 return V; 1606 1607 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0 1608 // bcmp can be more efficient than memcmp because it only has to know that 1609 // there is a difference, not how different one is to the other. 1610 if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) && 1611 isOnlyUsedInZeroEqualityComparison(CI)) { 1612 Value *LHS = CI->getArgOperand(0); 1613 Value *RHS = CI->getArgOperand(1); 1614 Value *Size = CI->getArgOperand(2); 1615 return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI)); 1616 } 1617 1618 return nullptr; 1619 } 1620 1621 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) { 1622 return optimizeMemCmpBCmpCommon(CI, B); 1623 } 1624 1625 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) { 1626 Value *Size = CI->getArgOperand(2); 1627 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1628 if (isa<IntrinsicInst>(CI)) 1629 return nullptr; 1630 1631 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n) 1632 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1), 1633 CI->getArgOperand(1), Align(1), Size); 1634 mergeAttributesAndFlags(NewCI, *CI); 1635 return CI->getArgOperand(0); 1636 } 1637 1638 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) { 1639 Value *Dst = CI->getArgOperand(0); 1640 Value *Src = CI->getArgOperand(1); 1641 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 1642 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3)); 1643 StringRef SrcStr; 1644 if (CI->use_empty() && Dst == Src) 1645 return Dst; 1646 // memccpy(d, s, c, 0) -> nullptr 1647 if (N) { 1648 if (N->isNullValue()) 1649 return Constant::getNullValue(CI->getType()); 1650 if (!getConstantStringInfo(Src, SrcStr, /*TrimAtNul=*/false) || 1651 // TODO: Handle zeroinitializer. 1652 !StopChar) 1653 return nullptr; 1654 } else { 1655 return nullptr; 1656 } 1657 1658 // Wrap arg 'c' of type int to char 1659 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF); 1660 if (Pos == StringRef::npos) { 1661 if (N->getZExtValue() <= SrcStr.size()) { 1662 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), 1663 CI->getArgOperand(3))); 1664 return Constant::getNullValue(CI->getType()); 1665 } 1666 return nullptr; 1667 } 1668 1669 Value *NewN = 1670 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue())); 1671 // memccpy -> llvm.memcpy 1672 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN)); 1673 return Pos + 1 <= N->getZExtValue() 1674 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN) 1675 : Constant::getNullValue(CI->getType()); 1676 } 1677 1678 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) { 1679 Value *Dst = CI->getArgOperand(0); 1680 Value *N = CI->getArgOperand(2); 1681 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n 1682 CallInst *NewCI = 1683 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N); 1684 // Propagate attributes, but memcpy has no return value, so make sure that 1685 // any return attributes are compliant. 1686 // TODO: Attach return value attributes to the 1st operand to preserve them? 1687 mergeAttributesAndFlags(NewCI, *CI); 1688 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N); 1689 } 1690 1691 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) { 1692 Value *Size = CI->getArgOperand(2); 1693 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL); 1694 if (isa<IntrinsicInst>(CI)) 1695 return nullptr; 1696 1697 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n) 1698 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1), 1699 CI->getArgOperand(1), Align(1), Size); 1700 mergeAttributesAndFlags(NewCI, *CI); 1701 return CI->getArgOperand(0); 1702 } 1703 1704 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) { 1705 Value *Size = CI->getArgOperand(2); 1706 annotateNonNullAndDereferenceable(CI, 0, Size, DL); 1707 if (isa<IntrinsicInst>(CI)) 1708 return nullptr; 1709 1710 // memset(p, v, n) -> llvm.memset(align 1 p, v, n) 1711 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 1712 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1)); 1713 mergeAttributesAndFlags(NewCI, *CI); 1714 return CI->getArgOperand(0); 1715 } 1716 1717 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) { 1718 if (isa<ConstantPointerNull>(CI->getArgOperand(0))) 1719 return copyFlags(*CI, emitMalloc(CI->getArgOperand(1), B, DL, TLI)); 1720 1721 return nullptr; 1722 } 1723 1724 // When enabled, replace operator new() calls marked with a hot or cold memprof 1725 // attribute with an operator new() call that takes a __hot_cold_t parameter. 1726 // Currently this is supported by the open source version of tcmalloc, see: 1727 // https://github.com/google/tcmalloc/blob/master/tcmalloc/new_extension.h 1728 Value *LibCallSimplifier::optimizeNew(CallInst *CI, IRBuilderBase &B, 1729 LibFunc &Func) { 1730 if (!OptimizeHotColdNew) 1731 return nullptr; 1732 1733 uint8_t HotCold; 1734 if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "cold") 1735 HotCold = ColdNewHintValue; 1736 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == 1737 "notcold") 1738 HotCold = NotColdNewHintValue; 1739 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "hot") 1740 HotCold = HotNewHintValue; 1741 else 1742 return nullptr; 1743 1744 // For calls that already pass a hot/cold hint, only update the hint if 1745 // directed by OptimizeExistingHotColdNew. For other calls to new, add a hint 1746 // if cold or hot, and leave as-is for default handling if "notcold" aka warm. 1747 // Note that in cases where we decide it is "notcold", it might be slightly 1748 // better to replace the hinted call with a non hinted call, to avoid the 1749 // extra parameter and the if condition check of the hint value in the 1750 // allocator. This can be considered in the future. 1751 switch (Func) { 1752 case LibFunc_Znwm12__hot_cold_t: 1753 if (OptimizeExistingHotColdNew) 1754 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1755 LibFunc_Znwm12__hot_cold_t, HotCold); 1756 break; 1757 case LibFunc_Znwm: 1758 if (HotCold != NotColdNewHintValue) 1759 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1760 LibFunc_Znwm12__hot_cold_t, HotCold); 1761 break; 1762 case LibFunc_Znam12__hot_cold_t: 1763 if (OptimizeExistingHotColdNew) 1764 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1765 LibFunc_Znam12__hot_cold_t, HotCold); 1766 break; 1767 case LibFunc_Znam: 1768 if (HotCold != NotColdNewHintValue) 1769 return emitHotColdNew(CI->getArgOperand(0), B, TLI, 1770 LibFunc_Znam12__hot_cold_t, HotCold); 1771 break; 1772 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t: 1773 if (OptimizeExistingHotColdNew) 1774 return emitHotColdNewNoThrow( 1775 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1776 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold); 1777 break; 1778 case LibFunc_ZnwmRKSt9nothrow_t: 1779 if (HotCold != NotColdNewHintValue) 1780 return emitHotColdNewNoThrow( 1781 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1782 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotCold); 1783 break; 1784 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t: 1785 if (OptimizeExistingHotColdNew) 1786 return emitHotColdNewNoThrow( 1787 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1788 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold); 1789 break; 1790 case LibFunc_ZnamRKSt9nothrow_t: 1791 if (HotCold != NotColdNewHintValue) 1792 return emitHotColdNewNoThrow( 1793 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1794 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotCold); 1795 break; 1796 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t: 1797 if (OptimizeExistingHotColdNew) 1798 return emitHotColdNewAligned( 1799 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1800 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold); 1801 break; 1802 case LibFunc_ZnwmSt11align_val_t: 1803 if (HotCold != NotColdNewHintValue) 1804 return emitHotColdNewAligned( 1805 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1806 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotCold); 1807 break; 1808 case LibFunc_ZnamSt11align_val_t12__hot_cold_t: 1809 if (OptimizeExistingHotColdNew) 1810 return emitHotColdNewAligned( 1811 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1812 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold); 1813 break; 1814 case LibFunc_ZnamSt11align_val_t: 1815 if (HotCold != NotColdNewHintValue) 1816 return emitHotColdNewAligned( 1817 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1818 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotCold); 1819 break; 1820 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 1821 if (OptimizeExistingHotColdNew) 1822 return emitHotColdNewAlignedNoThrow( 1823 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1824 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1825 HotCold); 1826 break; 1827 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: 1828 if (HotCold != NotColdNewHintValue) 1829 return emitHotColdNewAlignedNoThrow( 1830 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1831 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1832 HotCold); 1833 break; 1834 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 1835 if (OptimizeExistingHotColdNew) 1836 return emitHotColdNewAlignedNoThrow( 1837 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1838 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1839 HotCold); 1840 break; 1841 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: 1842 if (HotCold != NotColdNewHintValue) 1843 return emitHotColdNewAlignedNoThrow( 1844 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B, 1845 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t, 1846 HotCold); 1847 break; 1848 case LibFunc_size_returning_new: 1849 if (HotCold != NotColdNewHintValue) 1850 return emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI, 1851 LibFunc_size_returning_new_hot_cold, 1852 HotCold); 1853 break; 1854 case LibFunc_size_returning_new_hot_cold: 1855 if (OptimizeExistingHotColdNew) 1856 return emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI, 1857 LibFunc_size_returning_new_hot_cold, 1858 HotCold); 1859 break; 1860 case LibFunc_size_returning_new_aligned: 1861 if (HotCold != NotColdNewHintValue) 1862 return emitHotColdSizeReturningNewAligned( 1863 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1864 LibFunc_size_returning_new_aligned_hot_cold, HotCold); 1865 break; 1866 case LibFunc_size_returning_new_aligned_hot_cold: 1867 if (OptimizeExistingHotColdNew) 1868 return emitHotColdSizeReturningNewAligned( 1869 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI, 1870 LibFunc_size_returning_new_aligned_hot_cold, HotCold); 1871 break; 1872 default: 1873 return nullptr; 1874 } 1875 return nullptr; 1876 } 1877 1878 //===----------------------------------------------------------------------===// 1879 // Math Library Optimizations 1880 //===----------------------------------------------------------------------===// 1881 1882 // Replace a libcall \p CI with a call to intrinsic \p IID 1883 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B, 1884 Intrinsic::ID IID) { 1885 CallInst *NewCall = B.CreateUnaryIntrinsic(IID, CI->getArgOperand(0), CI); 1886 NewCall->takeName(CI); 1887 return copyFlags(*CI, NewCall); 1888 } 1889 1890 /// Return a variant of Val with float type. 1891 /// Currently this works in two cases: If Val is an FPExtension of a float 1892 /// value to something bigger, simply return the operand. 1893 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1894 /// loss of precision do so. 1895 static Value *valueHasFloatPrecision(Value *Val) { 1896 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1897 Value *Op = Cast->getOperand(0); 1898 if (Op->getType()->isFloatTy()) 1899 return Op; 1900 } 1901 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1902 APFloat F = Const->getValueAPF(); 1903 bool losesInfo; 1904 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1905 &losesInfo); 1906 if (!losesInfo) 1907 return ConstantFP::get(Const->getContext(), F); 1908 } 1909 return nullptr; 1910 } 1911 1912 /// Shrink double -> float functions. 1913 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, 1914 bool isBinary, const TargetLibraryInfo *TLI, 1915 bool isPrecise = false) { 1916 Function *CalleeFn = CI->getCalledFunction(); 1917 if (!CI->getType()->isDoubleTy() || !CalleeFn) 1918 return nullptr; 1919 1920 // If not all the uses of the function are converted to float, then bail out. 1921 // This matters if the precision of the result is more important than the 1922 // precision of the arguments. 1923 if (isPrecise) 1924 for (User *U : CI->users()) { 1925 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1926 if (!Cast || !Cast->getType()->isFloatTy()) 1927 return nullptr; 1928 } 1929 1930 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1931 Value *V[2]; 1932 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1933 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1934 if (!V[0] || (isBinary && !V[1])) 1935 return nullptr; 1936 1937 // If call isn't an intrinsic, check that it isn't within a function with the 1938 // same name as the float version of this call, otherwise the result is an 1939 // infinite loop. For example, from MinGW-w64: 1940 // 1941 // float expf(float val) { return (float) exp((double) val); } 1942 StringRef CalleeName = CalleeFn->getName(); 1943 bool IsIntrinsic = CalleeFn->isIntrinsic(); 1944 if (!IsIntrinsic) { 1945 StringRef CallerName = CI->getFunction()->getName(); 1946 if (!CallerName.empty() && CallerName.back() == 'f' && 1947 CallerName.size() == (CalleeName.size() + 1) && 1948 CallerName.starts_with(CalleeName)) 1949 return nullptr; 1950 } 1951 1952 // Propagate the math semantics from the current function to the new function. 1953 IRBuilderBase::FastMathFlagGuard Guard(B); 1954 B.setFastMathFlags(CI->getFastMathFlags()); 1955 1956 // g((double) float) -> (double) gf(float) 1957 Value *R; 1958 if (IsIntrinsic) { 1959 Module *M = CI->getModule(); 1960 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1961 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 1962 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]); 1963 } else { 1964 AttributeList CalleeAttrs = CalleeFn->getAttributes(); 1965 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B, 1966 CalleeAttrs) 1967 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CalleeAttrs); 1968 } 1969 return B.CreateFPExt(R, B.getDoubleTy()); 1970 } 1971 1972 /// Shrink double -> float for unary functions. 1973 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1974 const TargetLibraryInfo *TLI, 1975 bool isPrecise = false) { 1976 return optimizeDoubleFP(CI, B, false, TLI, isPrecise); 1977 } 1978 1979 /// Shrink double -> float for binary functions. 1980 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, 1981 const TargetLibraryInfo *TLI, 1982 bool isPrecise = false) { 1983 return optimizeDoubleFP(CI, B, true, TLI, isPrecise); 1984 } 1985 1986 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1987 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) { 1988 Value *Real, *Imag; 1989 1990 if (CI->arg_size() == 1) { 1991 1992 if (!CI->isFast()) 1993 return nullptr; 1994 1995 Value *Op = CI->getArgOperand(0); 1996 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 1997 1998 Real = B.CreateExtractValue(Op, 0, "real"); 1999 Imag = B.CreateExtractValue(Op, 1, "imag"); 2000 2001 } else { 2002 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!"); 2003 2004 Real = CI->getArgOperand(0); 2005 Imag = CI->getArgOperand(1); 2006 2007 // if real or imaginary part is zero, simplify to abs(cimag(z)) 2008 // or abs(creal(z)) 2009 Value *AbsOp = nullptr; 2010 if (ConstantFP *ConstReal = dyn_cast<ConstantFP>(Real)) { 2011 if (ConstReal->isZero()) 2012 AbsOp = Imag; 2013 2014 } else if (ConstantFP *ConstImag = dyn_cast<ConstantFP>(Imag)) { 2015 if (ConstImag->isZero()) 2016 AbsOp = Real; 2017 } 2018 2019 if (AbsOp) { 2020 IRBuilderBase::FastMathFlagGuard Guard(B); 2021 B.setFastMathFlags(CI->getFastMathFlags()); 2022 2023 return copyFlags( 2024 *CI, B.CreateUnaryIntrinsic(Intrinsic::fabs, AbsOp, nullptr, "cabs")); 2025 } 2026 2027 if (!CI->isFast()) 2028 return nullptr; 2029 } 2030 2031 // Propagate fast-math flags from the existing call to new instructions. 2032 IRBuilderBase::FastMathFlagGuard Guard(B); 2033 B.setFastMathFlags(CI->getFastMathFlags()); 2034 2035 Value *RealReal = B.CreateFMul(Real, Real); 2036 Value *ImagImag = B.CreateFMul(Imag, Imag); 2037 2038 return copyFlags(*CI, B.CreateUnaryIntrinsic(Intrinsic::sqrt, 2039 B.CreateFAdd(RealReal, ImagImag), 2040 nullptr, "cabs")); 2041 } 2042 2043 // Return a properly extended integer (DstWidth bits wide) if the operation is 2044 // an itofp. 2045 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) { 2046 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) { 2047 Value *Op = cast<Instruction>(I2F)->getOperand(0); 2048 // Make sure that the exponent fits inside an "int" of size DstWidth, 2049 // thus avoiding any range issues that FP has not. 2050 unsigned BitWidth = Op->getType()->getScalarSizeInBits(); 2051 if (BitWidth < DstWidth || (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) { 2052 Type *IntTy = Op->getType()->getWithNewBitWidth(DstWidth); 2053 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, IntTy) 2054 : B.CreateZExt(Op, IntTy); 2055 } 2056 } 2057 2058 return nullptr; 2059 } 2060 2061 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 2062 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x); 2063 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x). 2064 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) { 2065 Module *M = Pow->getModule(); 2066 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 2067 Type *Ty = Pow->getType(); 2068 bool Ignored; 2069 2070 // Evaluate special cases related to a nested function as the base. 2071 2072 // pow(exp(x), y) -> exp(x * y) 2073 // pow(exp2(x), y) -> exp2(x * y) 2074 // If exp{,2}() is used only once, it is better to fold two transcendental 2075 // math functions into one. If used again, exp{,2}() would still have to be 2076 // called with the original argument, then keep both original transcendental 2077 // functions. However, this transformation is only safe with fully relaxed 2078 // math semantics, since, besides rounding differences, it changes overflow 2079 // and underflow behavior quite dramatically. For example: 2080 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 2081 // Whereas: 2082 // exp(1000 * 0.001) = exp(1) 2083 // TODO: Loosen the requirement for fully relaxed math semantics. 2084 // TODO: Handle exp10() when more targets have it available. 2085 CallInst *BaseFn = dyn_cast<CallInst>(Base); 2086 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 2087 LibFunc LibFn; 2088 2089 Function *CalleeFn = BaseFn->getCalledFunction(); 2090 if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) && 2091 isLibFuncEmittable(M, TLI, LibFn)) { 2092 StringRef ExpName; 2093 Intrinsic::ID ID; 2094 Value *ExpFn; 2095 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble; 2096 2097 switch (LibFn) { 2098 default: 2099 return nullptr; 2100 case LibFunc_expf: 2101 case LibFunc_exp: 2102 case LibFunc_expl: 2103 ExpName = TLI->getName(LibFunc_exp); 2104 ID = Intrinsic::exp; 2105 LibFnFloat = LibFunc_expf; 2106 LibFnDouble = LibFunc_exp; 2107 LibFnLongDouble = LibFunc_expl; 2108 break; 2109 case LibFunc_exp2f: 2110 case LibFunc_exp2: 2111 case LibFunc_exp2l: 2112 ExpName = TLI->getName(LibFunc_exp2); 2113 ID = Intrinsic::exp2; 2114 LibFnFloat = LibFunc_exp2f; 2115 LibFnDouble = LibFunc_exp2; 2116 LibFnLongDouble = LibFunc_exp2l; 2117 break; 2118 } 2119 2120 // Create new exp{,2}() with the product as its argument. 2121 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 2122 ExpFn = BaseFn->doesNotAccessMemory() 2123 ? B.CreateUnaryIntrinsic(ID, FMul, nullptr, ExpName) 2124 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat, 2125 LibFnLongDouble, B, 2126 BaseFn->getAttributes()); 2127 2128 // Since the new exp{,2}() is different from the original one, dead code 2129 // elimination cannot be trusted to remove it, since it may have side 2130 // effects (e.g., errno). When the only consumer for the original 2131 // exp{,2}() is pow(), then it has to be explicitly erased. 2132 substituteInParent(BaseFn, ExpFn); 2133 return ExpFn; 2134 } 2135 } 2136 2137 // Evaluate special cases related to a constant base. 2138 2139 const APFloat *BaseF; 2140 if (!match(Base, m_APFloat(BaseF))) 2141 return nullptr; 2142 2143 AttributeList NoAttrs; // Attributes are only meaningful on the original call 2144 2145 const bool UseIntrinsic = Pow->doesNotAccessMemory(); 2146 2147 // pow(2.0, itofp(x)) -> ldexp(1.0, x) 2148 if ((UseIntrinsic || !Ty->isVectorTy()) && BaseF->isExactlyValue(2.0) && 2149 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) && 2150 (UseIntrinsic || 2151 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) { 2152 2153 // TODO: Shouldn't really need to depend on getIntToFPVal for intrinsic. Can 2154 // just directly use the original integer type. 2155 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) { 2156 Constant *One = ConstantFP::get(Ty, 1.0); 2157 2158 if (UseIntrinsic) { 2159 return copyFlags(*Pow, B.CreateIntrinsic(Intrinsic::ldexp, 2160 {Ty, ExpoI->getType()}, 2161 {One, ExpoI}, Pow, "exp2")); 2162 } 2163 2164 return copyFlags(*Pow, emitBinaryFloatFnCall( 2165 One, ExpoI, TLI, LibFunc_ldexp, LibFunc_ldexpf, 2166 LibFunc_ldexpl, B, NoAttrs)); 2167 } 2168 } 2169 2170 // pow(2.0 ** n, x) -> exp2(n * x) 2171 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) { 2172 APFloat BaseR = APFloat(1.0); 2173 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored); 2174 BaseR = BaseR / *BaseF; 2175 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger(); 2176 const APFloat *NF = IsReciprocal ? &BaseR : BaseF; 2177 APSInt NI(64, false); 2178 if ((IsInteger || IsReciprocal) && 2179 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) == 2180 APFloat::opOK && 2181 NI > 1 && NI.isPowerOf2()) { 2182 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0); 2183 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul"); 2184 if (Pow->doesNotAccessMemory()) 2185 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul, 2186 nullptr, "exp2")); 2187 else 2188 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 2189 LibFunc_exp2f, 2190 LibFunc_exp2l, B, NoAttrs)); 2191 } 2192 } 2193 2194 // pow(10.0, x) -> exp10(x) 2195 if (BaseF->isExactlyValue(10.0) && 2196 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) { 2197 2198 if (Pow->doesNotAccessMemory()) { 2199 CallInst *NewExp10 = 2200 B.CreateIntrinsic(Intrinsic::exp10, {Ty}, {Expo}, Pow, "exp10"); 2201 return copyFlags(*Pow, NewExp10); 2202 } 2203 2204 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, 2205 LibFunc_exp10f, LibFunc_exp10l, 2206 B, NoAttrs)); 2207 } 2208 2209 // pow(x, y) -> exp2(log2(x) * y) 2210 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() && 2211 !BaseF->isNegative()) { 2212 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN. 2213 // Luckily optimizePow has already handled the x == 1 case. 2214 assert(!match(Base, m_FPOne()) && 2215 "pow(1.0, y) should have been simplified earlier!"); 2216 2217 Value *Log = nullptr; 2218 if (Ty->isFloatTy()) 2219 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 2220 else if (Ty->isDoubleTy()) 2221 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 2222 2223 if (Log) { 2224 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 2225 if (Pow->doesNotAccessMemory()) 2226 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul, 2227 nullptr, "exp2")); 2228 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, 2229 LibFunc_exp2l)) 2230 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, 2231 LibFunc_exp2f, 2232 LibFunc_exp2l, B, NoAttrs)); 2233 } 2234 } 2235 2236 return nullptr; 2237 } 2238 2239 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 2240 Module *M, IRBuilderBase &B, 2241 const TargetLibraryInfo *TLI) { 2242 // If errno is never set, then use the intrinsic for sqrt(). 2243 if (NoErrno) 2244 return B.CreateUnaryIntrinsic(Intrinsic::sqrt, V, nullptr, "sqrt"); 2245 2246 // Otherwise, use the libcall for sqrt(). 2247 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, 2248 LibFunc_sqrtl)) 2249 // TODO: We also should check that the target can in fact lower the sqrt() 2250 // libcall. We currently have no way to ask this question, so we ask if 2251 // the target has a sqrt() libcall, which is not exactly the same. 2252 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 2253 LibFunc_sqrtl, B, Attrs); 2254 2255 return nullptr; 2256 } 2257 2258 /// Use square root in place of pow(x, +/-0.5). 2259 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) { 2260 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 2261 Module *Mod = Pow->getModule(); 2262 Type *Ty = Pow->getType(); 2263 2264 const APFloat *ExpoF; 2265 if (!match(Expo, m_APFloat(ExpoF)) || 2266 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 2267 return nullptr; 2268 2269 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step, 2270 // so that requires fast-math-flags (afn or reassoc). 2271 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc())) 2272 return nullptr; 2273 2274 // If we have a pow() library call (accesses memory) and we can't guarantee 2275 // that the base is not an infinity, give up: 2276 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting 2277 // errno), but sqrt(-Inf) is required by various standards to set errno. 2278 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() && 2279 !isKnownNeverInfinity(Base, 0, 2280 SimplifyQuery(DL, TLI, /*DT=*/nullptr, AC, Pow))) 2281 return nullptr; 2282 2283 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), Mod, B, 2284 TLI); 2285 if (!Sqrt) 2286 return nullptr; 2287 2288 // Handle signed zero base by expanding to fabs(sqrt(x)). 2289 if (!Pow->hasNoSignedZeros()) 2290 Sqrt = B.CreateUnaryIntrinsic(Intrinsic::fabs, Sqrt, nullptr, "abs"); 2291 2292 Sqrt = copyFlags(*Pow, Sqrt); 2293 2294 // Handle non finite base by expanding to 2295 // (x == -infinity ? +infinity : sqrt(x)). 2296 if (!Pow->hasNoInfs()) { 2297 Value *PosInf = ConstantFP::getInfinity(Ty), 2298 *NegInf = ConstantFP::getInfinity(Ty, true); 2299 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 2300 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 2301 } 2302 2303 // If the exponent is negative, then get the reciprocal. 2304 if (ExpoF->isNegative()) 2305 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 2306 2307 return Sqrt; 2308 } 2309 2310 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 2311 IRBuilderBase &B) { 2312 Value *Args[] = {Base, Expo}; 2313 Type *Types[] = {Base->getType(), Expo->getType()}; 2314 return B.CreateIntrinsic(Intrinsic::powi, Types, Args); 2315 } 2316 2317 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) { 2318 Value *Base = Pow->getArgOperand(0); 2319 Value *Expo = Pow->getArgOperand(1); 2320 Function *Callee = Pow->getCalledFunction(); 2321 StringRef Name = Callee->getName(); 2322 Type *Ty = Pow->getType(); 2323 Module *M = Pow->getModule(); 2324 bool AllowApprox = Pow->hasApproxFunc(); 2325 bool Ignored; 2326 2327 // Propagate the math semantics from the call to any created instructions. 2328 IRBuilderBase::FastMathFlagGuard Guard(B); 2329 B.setFastMathFlags(Pow->getFastMathFlags()); 2330 // Evaluate special cases related to the base. 2331 2332 // pow(1.0, x) -> 1.0 2333 if (match(Base, m_FPOne())) 2334 return Base; 2335 2336 if (Value *Exp = replacePowWithExp(Pow, B)) 2337 return Exp; 2338 2339 // Evaluate special cases related to the exponent. 2340 2341 // pow(x, -1.0) -> 1.0 / x 2342 if (match(Expo, m_SpecificFP(-1.0))) 2343 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 2344 2345 // pow(x, +/-0.0) -> 1.0 2346 if (match(Expo, m_AnyZeroFP())) 2347 return ConstantFP::get(Ty, 1.0); 2348 2349 // pow(x, 1.0) -> x 2350 if (match(Expo, m_FPOne())) 2351 return Base; 2352 2353 // pow(x, 2.0) -> x * x 2354 if (match(Expo, m_SpecificFP(2.0))) 2355 return B.CreateFMul(Base, Base, "square"); 2356 2357 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 2358 return Sqrt; 2359 2360 // If we can approximate pow: 2361 // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction 2362 // pow(x, n) -> powi(x, n) if n is a constant signed integer value 2363 const APFloat *ExpoF; 2364 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) && 2365 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) { 2366 APFloat ExpoA(abs(*ExpoF)); 2367 APFloat ExpoI(*ExpoF); 2368 Value *Sqrt = nullptr; 2369 if (!ExpoA.isInteger()) { 2370 APFloat Expo2 = ExpoA; 2371 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 2372 // is no floating point exception and the result is an integer, then 2373 // ExpoA == integer + 0.5 2374 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 2375 return nullptr; 2376 2377 if (!Expo2.isInteger()) 2378 return nullptr; 2379 2380 if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) != 2381 APFloat::opInexact) 2382 return nullptr; 2383 if (!ExpoI.isInteger()) 2384 return nullptr; 2385 ExpoF = &ExpoI; 2386 2387 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), M, 2388 B, TLI); 2389 if (!Sqrt) 2390 return nullptr; 2391 } 2392 2393 // 0.5 fraction is now optionally handled. 2394 // Do pow -> powi for remaining integer exponent 2395 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false); 2396 if (ExpoF->isInteger() && 2397 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 2398 APFloat::opOK) { 2399 Value *PowI = copyFlags( 2400 *Pow, 2401 createPowWithIntegerExponent( 2402 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo), 2403 M, B)); 2404 2405 if (PowI && Sqrt) 2406 return B.CreateFMul(PowI, Sqrt); 2407 2408 return PowI; 2409 } 2410 } 2411 2412 // powf(x, itofp(y)) -> powi(x, y) 2413 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 2414 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) 2415 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B)); 2416 } 2417 2418 // Shrink pow() to powf() if the arguments are single precision, 2419 // unless the result is expected to be double precision. 2420 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 2421 hasFloatVersion(M, Name)) { 2422 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true)) 2423 return Shrunk; 2424 } 2425 2426 return nullptr; 2427 } 2428 2429 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) { 2430 Module *M = CI->getModule(); 2431 Function *Callee = CI->getCalledFunction(); 2432 StringRef Name = Callee->getName(); 2433 Value *Ret = nullptr; 2434 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) && 2435 hasFloatVersion(M, Name)) 2436 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2437 2438 // If we have an llvm.exp2 intrinsic, emit the llvm.ldexp intrinsic. If we 2439 // have the libcall, emit the libcall. 2440 // 2441 // TODO: In principle we should be able to just always use the intrinsic for 2442 // any doesNotAccessMemory callsite. 2443 2444 const bool UseIntrinsic = Callee->isIntrinsic(); 2445 // Bail out for vectors because the code below only expects scalars. 2446 Type *Ty = CI->getType(); 2447 if (!UseIntrinsic && Ty->isVectorTy()) 2448 return Ret; 2449 2450 // exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize 2451 // exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize 2452 Value *Op = CI->getArgOperand(0); 2453 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) && 2454 (UseIntrinsic || 2455 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) { 2456 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) { 2457 Constant *One = ConstantFP::get(Ty, 1.0); 2458 2459 if (UseIntrinsic) { 2460 return copyFlags(*CI, B.CreateIntrinsic(Intrinsic::ldexp, 2461 {Ty, Exp->getType()}, 2462 {One, Exp}, CI)); 2463 } 2464 2465 IRBuilderBase::FastMathFlagGuard Guard(B); 2466 B.setFastMathFlags(CI->getFastMathFlags()); 2467 return copyFlags(*CI, emitBinaryFloatFnCall( 2468 One, Exp, TLI, LibFunc_ldexp, LibFunc_ldexpf, 2469 LibFunc_ldexpl, B, AttributeList())); 2470 } 2471 } 2472 2473 return Ret; 2474 } 2475 2476 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) { 2477 Module *M = CI->getModule(); 2478 2479 // If we can shrink the call to a float function rather than a double 2480 // function, do that first. 2481 Function *Callee = CI->getCalledFunction(); 2482 StringRef Name = Callee->getName(); 2483 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name)) 2484 if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI)) 2485 return Ret; 2486 2487 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to 2488 // the intrinsics for improved optimization (for example, vectorization). 2489 // No-signed-zeros is implied by the definitions of fmax/fmin themselves. 2490 // From the C standard draft WG14/N1256: 2491 // "Ideally, fmax would be sensitive to the sign of zero, for example 2492 // fmax(-0.0, +0.0) would return +0; however, implementation in software 2493 // might be impractical." 2494 IRBuilderBase::FastMathFlagGuard Guard(B); 2495 FastMathFlags FMF = CI->getFastMathFlags(); 2496 FMF.setNoSignedZeros(); 2497 B.setFastMathFlags(FMF); 2498 2499 Intrinsic::ID IID = Callee->getName().starts_with("fmin") ? Intrinsic::minnum 2500 : Intrinsic::maxnum; 2501 return copyFlags(*CI, B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0), 2502 CI->getArgOperand(1))); 2503 } 2504 2505 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) { 2506 Function *LogFn = Log->getCalledFunction(); 2507 StringRef LogNm = LogFn->getName(); 2508 Intrinsic::ID LogID = LogFn->getIntrinsicID(); 2509 Module *Mod = Log->getModule(); 2510 Type *Ty = Log->getType(); 2511 Value *Ret = nullptr; 2512 2513 if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm)) 2514 Ret = optimizeUnaryDoubleFP(Log, B, TLI, true); 2515 2516 // The earlier call must also be 'fast' in order to do these transforms. 2517 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0)); 2518 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse()) 2519 return Ret; 2520 2521 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb; 2522 2523 // This is only applicable to log(), log2(), log10(). 2524 if (TLI->getLibFunc(LogNm, LogLb)) 2525 switch (LogLb) { 2526 case LibFunc_logf: 2527 LogID = Intrinsic::log; 2528 ExpLb = LibFunc_expf; 2529 Exp2Lb = LibFunc_exp2f; 2530 Exp10Lb = LibFunc_exp10f; 2531 PowLb = LibFunc_powf; 2532 break; 2533 case LibFunc_log: 2534 LogID = Intrinsic::log; 2535 ExpLb = LibFunc_exp; 2536 Exp2Lb = LibFunc_exp2; 2537 Exp10Lb = LibFunc_exp10; 2538 PowLb = LibFunc_pow; 2539 break; 2540 case LibFunc_logl: 2541 LogID = Intrinsic::log; 2542 ExpLb = LibFunc_expl; 2543 Exp2Lb = LibFunc_exp2l; 2544 Exp10Lb = LibFunc_exp10l; 2545 PowLb = LibFunc_powl; 2546 break; 2547 case LibFunc_log2f: 2548 LogID = Intrinsic::log2; 2549 ExpLb = LibFunc_expf; 2550 Exp2Lb = LibFunc_exp2f; 2551 Exp10Lb = LibFunc_exp10f; 2552 PowLb = LibFunc_powf; 2553 break; 2554 case LibFunc_log2: 2555 LogID = Intrinsic::log2; 2556 ExpLb = LibFunc_exp; 2557 Exp2Lb = LibFunc_exp2; 2558 Exp10Lb = LibFunc_exp10; 2559 PowLb = LibFunc_pow; 2560 break; 2561 case LibFunc_log2l: 2562 LogID = Intrinsic::log2; 2563 ExpLb = LibFunc_expl; 2564 Exp2Lb = LibFunc_exp2l; 2565 Exp10Lb = LibFunc_exp10l; 2566 PowLb = LibFunc_powl; 2567 break; 2568 case LibFunc_log10f: 2569 LogID = Intrinsic::log10; 2570 ExpLb = LibFunc_expf; 2571 Exp2Lb = LibFunc_exp2f; 2572 Exp10Lb = LibFunc_exp10f; 2573 PowLb = LibFunc_powf; 2574 break; 2575 case LibFunc_log10: 2576 LogID = Intrinsic::log10; 2577 ExpLb = LibFunc_exp; 2578 Exp2Lb = LibFunc_exp2; 2579 Exp10Lb = LibFunc_exp10; 2580 PowLb = LibFunc_pow; 2581 break; 2582 case LibFunc_log10l: 2583 LogID = Intrinsic::log10; 2584 ExpLb = LibFunc_expl; 2585 Exp2Lb = LibFunc_exp2l; 2586 Exp10Lb = LibFunc_exp10l; 2587 PowLb = LibFunc_powl; 2588 break; 2589 default: 2590 return Ret; 2591 } 2592 else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 || 2593 LogID == Intrinsic::log10) { 2594 if (Ty->getScalarType()->isFloatTy()) { 2595 ExpLb = LibFunc_expf; 2596 Exp2Lb = LibFunc_exp2f; 2597 Exp10Lb = LibFunc_exp10f; 2598 PowLb = LibFunc_powf; 2599 } else if (Ty->getScalarType()->isDoubleTy()) { 2600 ExpLb = LibFunc_exp; 2601 Exp2Lb = LibFunc_exp2; 2602 Exp10Lb = LibFunc_exp10; 2603 PowLb = LibFunc_pow; 2604 } else 2605 return Ret; 2606 } else 2607 return Ret; 2608 2609 IRBuilderBase::FastMathFlagGuard Guard(B); 2610 B.setFastMathFlags(FastMathFlags::getFast()); 2611 2612 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2613 LibFunc ArgLb = NotLibFunc; 2614 TLI->getLibFunc(*Arg, ArgLb); 2615 2616 // log(pow(x,y)) -> y*log(x) 2617 AttributeList NoAttrs; 2618 if (ArgLb == PowLb || ArgID == Intrinsic::pow || ArgID == Intrinsic::powi) { 2619 Value *LogX = 2620 Log->doesNotAccessMemory() 2621 ? B.CreateUnaryIntrinsic(LogID, Arg->getOperand(0), nullptr, "log") 2622 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, NoAttrs); 2623 Value *Y = Arg->getArgOperand(1); 2624 // Cast exponent to FP if integer. 2625 if (ArgID == Intrinsic::powi) 2626 Y = B.CreateSIToFP(Y, Ty, "cast"); 2627 Value *MulY = B.CreateFMul(Y, LogX, "mul"); 2628 // Since pow() may have side effects, e.g. errno, 2629 // dead code elimination may not be trusted to remove it. 2630 substituteInParent(Arg, MulY); 2631 return MulY; 2632 } 2633 2634 // log(exp{,2,10}(y)) -> y*log({e,2,10}) 2635 // TODO: There is no exp10() intrinsic yet. 2636 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb || 2637 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) { 2638 Constant *Eul; 2639 if (ArgLb == ExpLb || ArgID == Intrinsic::exp) 2640 // FIXME: Add more precise value of e for long double. 2641 Eul = ConstantFP::get(Log->getType(), numbers::e); 2642 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2) 2643 Eul = ConstantFP::get(Log->getType(), 2.0); 2644 else 2645 Eul = ConstantFP::get(Log->getType(), 10.0); 2646 Value *LogE = Log->doesNotAccessMemory() 2647 ? B.CreateUnaryIntrinsic(LogID, Eul, nullptr, "log") 2648 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, NoAttrs); 2649 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul"); 2650 // Since exp() may have side effects, e.g. errno, 2651 // dead code elimination may not be trusted to remove it. 2652 substituteInParent(Arg, MulY); 2653 return MulY; 2654 } 2655 2656 return Ret; 2657 } 2658 2659 // sqrt(exp(X)) -> exp(X * 0.5) 2660 Value *LibCallSimplifier::mergeSqrtToExp(CallInst *CI, IRBuilderBase &B) { 2661 if (!CI->hasAllowReassoc()) 2662 return nullptr; 2663 2664 Function *SqrtFn = CI->getCalledFunction(); 2665 CallInst *Arg = dyn_cast<CallInst>(CI->getArgOperand(0)); 2666 if (!Arg || !Arg->hasAllowReassoc() || !Arg->hasOneUse()) 2667 return nullptr; 2668 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 2669 LibFunc ArgLb = NotLibFunc; 2670 TLI->getLibFunc(*Arg, ArgLb); 2671 2672 LibFunc SqrtLb, ExpLb, Exp2Lb, Exp10Lb; 2673 2674 if (TLI->getLibFunc(SqrtFn->getName(), SqrtLb)) 2675 switch (SqrtLb) { 2676 case LibFunc_sqrtf: 2677 ExpLb = LibFunc_expf; 2678 Exp2Lb = LibFunc_exp2f; 2679 Exp10Lb = LibFunc_exp10f; 2680 break; 2681 case LibFunc_sqrt: 2682 ExpLb = LibFunc_exp; 2683 Exp2Lb = LibFunc_exp2; 2684 Exp10Lb = LibFunc_exp10; 2685 break; 2686 case LibFunc_sqrtl: 2687 ExpLb = LibFunc_expl; 2688 Exp2Lb = LibFunc_exp2l; 2689 Exp10Lb = LibFunc_exp10l; 2690 break; 2691 default: 2692 return nullptr; 2693 } 2694 else if (SqrtFn->getIntrinsicID() == Intrinsic::sqrt) { 2695 if (CI->getType()->getScalarType()->isFloatTy()) { 2696 ExpLb = LibFunc_expf; 2697 Exp2Lb = LibFunc_exp2f; 2698 Exp10Lb = LibFunc_exp10f; 2699 } else if (CI->getType()->getScalarType()->isDoubleTy()) { 2700 ExpLb = LibFunc_exp; 2701 Exp2Lb = LibFunc_exp2; 2702 Exp10Lb = LibFunc_exp10; 2703 } else 2704 return nullptr; 2705 } else 2706 return nullptr; 2707 2708 if (ArgLb != ExpLb && ArgLb != Exp2Lb && ArgLb != Exp10Lb && 2709 ArgID != Intrinsic::exp && ArgID != Intrinsic::exp2) 2710 return nullptr; 2711 2712 IRBuilderBase::InsertPointGuard Guard(B); 2713 B.SetInsertPoint(Arg); 2714 auto *ExpOperand = Arg->getOperand(0); 2715 auto *FMul = 2716 B.CreateFMulFMF(ExpOperand, ConstantFP::get(ExpOperand->getType(), 0.5), 2717 CI, "merged.sqrt"); 2718 2719 Arg->setOperand(0, FMul); 2720 return Arg; 2721 } 2722 2723 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) { 2724 Module *M = CI->getModule(); 2725 Function *Callee = CI->getCalledFunction(); 2726 Value *Ret = nullptr; 2727 // TODO: Once we have a way (other than checking for the existince of the 2728 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 2729 // condition below. 2730 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) && 2731 (Callee->getName() == "sqrt" || 2732 Callee->getIntrinsicID() == Intrinsic::sqrt)) 2733 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2734 2735 if (Value *Opt = mergeSqrtToExp(CI, B)) 2736 return Opt; 2737 2738 if (!CI->isFast()) 2739 return Ret; 2740 2741 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 2742 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 2743 return Ret; 2744 2745 // We're looking for a repeated factor in a multiplication tree, 2746 // so we can do this fold: sqrt(x * x) -> fabs(x); 2747 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 2748 Value *Op0 = I->getOperand(0); 2749 Value *Op1 = I->getOperand(1); 2750 Value *RepeatOp = nullptr; 2751 Value *OtherOp = nullptr; 2752 if (Op0 == Op1) { 2753 // Simple match: the operands of the multiply are identical. 2754 RepeatOp = Op0; 2755 } else { 2756 // Look for a more complicated pattern: one of the operands is itself 2757 // a multiply, so search for a common factor in that multiply. 2758 // Note: We don't bother looking any deeper than this first level or for 2759 // variations of this pattern because instcombine's visitFMUL and/or the 2760 // reassociation pass should give us this form. 2761 Value *OtherMul0, *OtherMul1; 2762 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 2763 // Pattern: sqrt((x * y) * z) 2764 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) { 2765 // Matched: sqrt((x * x) * z) 2766 RepeatOp = OtherMul0; 2767 OtherOp = Op1; 2768 } 2769 } 2770 } 2771 if (!RepeatOp) 2772 return Ret; 2773 2774 // Fast math flags for any created instructions should match the sqrt 2775 // and multiply. 2776 IRBuilderBase::FastMathFlagGuard Guard(B); 2777 B.setFastMathFlags(I->getFastMathFlags()); 2778 2779 // If we found a repeated factor, hoist it out of the square root and 2780 // replace it with the fabs of that factor. 2781 Value *FabsCall = 2782 B.CreateUnaryIntrinsic(Intrinsic::fabs, RepeatOp, nullptr, "fabs"); 2783 if (OtherOp) { 2784 // If we found a non-repeated factor, we still need to get its square 2785 // root. We then multiply that by the value that was simplified out 2786 // of the square root calculation. 2787 Value *SqrtCall = 2788 B.CreateUnaryIntrinsic(Intrinsic::sqrt, OtherOp, nullptr, "sqrt"); 2789 return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall)); 2790 } 2791 return copyFlags(*CI, FabsCall); 2792 } 2793 2794 Value *LibCallSimplifier::optimizeTrigInversionPairs(CallInst *CI, 2795 IRBuilderBase &B) { 2796 Module *M = CI->getModule(); 2797 Function *Callee = CI->getCalledFunction(); 2798 Value *Ret = nullptr; 2799 StringRef Name = Callee->getName(); 2800 if (UnsafeFPShrink && 2801 (Name == "tan" || Name == "atanh" || Name == "sinh" || Name == "cosh" || 2802 Name == "asinh") && 2803 hasFloatVersion(M, Name)) 2804 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true); 2805 2806 Value *Op1 = CI->getArgOperand(0); 2807 auto *OpC = dyn_cast<CallInst>(Op1); 2808 if (!OpC) 2809 return Ret; 2810 2811 // Both calls must be 'fast' in order to remove them. 2812 if (!CI->isFast() || !OpC->isFast()) 2813 return Ret; 2814 2815 // tan(atan(x)) -> x 2816 // atanh(tanh(x)) -> x 2817 // sinh(asinh(x)) -> x 2818 // asinh(sinh(x)) -> x 2819 // cosh(acosh(x)) -> x 2820 LibFunc Func; 2821 Function *F = OpC->getCalledFunction(); 2822 if (F && TLI->getLibFunc(F->getName(), Func) && 2823 isLibFuncEmittable(M, TLI, Func)) { 2824 LibFunc inverseFunc = llvm::StringSwitch<LibFunc>(Callee->getName()) 2825 .Case("tan", LibFunc_atan) 2826 .Case("atanh", LibFunc_tanh) 2827 .Case("sinh", LibFunc_asinh) 2828 .Case("cosh", LibFunc_acosh) 2829 .Case("tanf", LibFunc_atanf) 2830 .Case("atanhf", LibFunc_tanhf) 2831 .Case("sinhf", LibFunc_asinhf) 2832 .Case("coshf", LibFunc_acoshf) 2833 .Case("tanl", LibFunc_atanl) 2834 .Case("atanhl", LibFunc_tanhl) 2835 .Case("sinhl", LibFunc_asinhl) 2836 .Case("coshl", LibFunc_acoshl) 2837 .Case("asinh", LibFunc_sinh) 2838 .Case("asinhf", LibFunc_sinhf) 2839 .Case("asinhl", LibFunc_sinhl) 2840 .Default(NumLibFuncs); // Used as error value 2841 if (Func == inverseFunc) 2842 Ret = OpC->getArgOperand(0); 2843 } 2844 return Ret; 2845 } 2846 2847 static bool isTrigLibCall(CallInst *CI) { 2848 // We can only hope to do anything useful if we can ignore things like errno 2849 // and floating-point exceptions. 2850 // We already checked the prototype. 2851 return CI->doesNotThrow() && CI->doesNotAccessMemory(); 2852 } 2853 2854 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, 2855 bool UseFloat, Value *&Sin, Value *&Cos, 2856 Value *&SinCos, const TargetLibraryInfo *TLI) { 2857 Module *M = OrigCallee->getParent(); 2858 Type *ArgTy = Arg->getType(); 2859 Type *ResTy; 2860 StringRef Name; 2861 2862 Triple T(OrigCallee->getParent()->getTargetTriple()); 2863 if (UseFloat) { 2864 Name = "__sincospif_stret"; 2865 2866 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 2867 // x86_64 can't use {float, float} since that would be returned in both 2868 // xmm0 and xmm1, which isn't what a real struct would do. 2869 ResTy = T.getArch() == Triple::x86_64 2870 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2)) 2871 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 2872 } else { 2873 Name = "__sincospi_stret"; 2874 ResTy = StructType::get(ArgTy, ArgTy); 2875 } 2876 2877 if (!isLibFuncEmittable(M, TLI, Name)) 2878 return false; 2879 LibFunc TheLibFunc; 2880 TLI->getLibFunc(Name, TheLibFunc); 2881 FunctionCallee Callee = getOrInsertLibFunc( 2882 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy); 2883 2884 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 2885 // If the argument is an instruction, it must dominate all uses so put our 2886 // sincos call there. 2887 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 2888 } else { 2889 // Otherwise (e.g. for a constant) the beginning of the function is as 2890 // good a place as any. 2891 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 2892 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 2893 } 2894 2895 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 2896 2897 if (SinCos->getType()->isStructTy()) { 2898 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 2899 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 2900 } else { 2901 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 2902 "sinpi"); 2903 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 2904 "cospi"); 2905 } 2906 2907 return true; 2908 } 2909 2910 static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven, 2911 IRBuilderBase &B) { 2912 Value *X; 2913 Value *Src = CI->getArgOperand(0); 2914 2915 if (match(Src, m_OneUse(m_FNeg(m_Value(X))))) { 2916 IRBuilderBase::FastMathFlagGuard Guard(B); 2917 B.setFastMathFlags(CI->getFastMathFlags()); 2918 2919 auto *CallInst = copyFlags(*CI, B.CreateCall(CI->getCalledFunction(), {X})); 2920 if (IsEven) { 2921 // Even function: f(-x) = f(x) 2922 return CallInst; 2923 } 2924 // Odd function: f(-x) = -f(x) 2925 return B.CreateFNeg(CallInst); 2926 } 2927 2928 // Even function: f(abs(x)) = f(x), f(copysign(x, y)) = f(x) 2929 if (IsEven && (match(Src, m_FAbs(m_Value(X))) || 2930 match(Src, m_CopySign(m_Value(X), m_Value())))) { 2931 IRBuilderBase::FastMathFlagGuard Guard(B); 2932 B.setFastMathFlags(CI->getFastMathFlags()); 2933 2934 auto *CallInst = copyFlags(*CI, B.CreateCall(CI->getCalledFunction(), {X})); 2935 return CallInst; 2936 } 2937 2938 return nullptr; 2939 } 2940 2941 Value *LibCallSimplifier::optimizeSymmetric(CallInst *CI, LibFunc Func, 2942 IRBuilderBase &B) { 2943 switch (Func) { 2944 case LibFunc_cos: 2945 case LibFunc_cosf: 2946 case LibFunc_cosl: 2947 return optimizeSymmetricCall(CI, /*IsEven*/ true, B); 2948 2949 case LibFunc_sin: 2950 case LibFunc_sinf: 2951 case LibFunc_sinl: 2952 2953 case LibFunc_tan: 2954 case LibFunc_tanf: 2955 case LibFunc_tanl: 2956 2957 case LibFunc_erf: 2958 case LibFunc_erff: 2959 case LibFunc_erfl: 2960 return optimizeSymmetricCall(CI, /*IsEven*/ false, B); 2961 2962 default: 2963 return nullptr; 2964 } 2965 } 2966 2967 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, bool IsSin, IRBuilderBase &B) { 2968 // Make sure the prototype is as expected, otherwise the rest of the 2969 // function is probably invalid and likely to abort. 2970 if (!isTrigLibCall(CI)) 2971 return nullptr; 2972 2973 Value *Arg = CI->getArgOperand(0); 2974 SmallVector<CallInst *, 1> SinCalls; 2975 SmallVector<CallInst *, 1> CosCalls; 2976 SmallVector<CallInst *, 1> SinCosCalls; 2977 2978 bool IsFloat = Arg->getType()->isFloatTy(); 2979 2980 // Look for all compatible sinpi, cospi and sincospi calls with the same 2981 // argument. If there are enough (in some sense) we can make the 2982 // substitution. 2983 Function *F = CI->getFunction(); 2984 for (User *U : Arg->users()) 2985 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 2986 2987 // It's only worthwhile if both sinpi and cospi are actually used. 2988 if (SinCalls.empty() || CosCalls.empty()) 2989 return nullptr; 2990 2991 Value *Sin, *Cos, *SinCos; 2992 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, 2993 SinCos, TLI)) 2994 return nullptr; 2995 2996 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 2997 Value *Res) { 2998 for (CallInst *C : Calls) 2999 replaceAllUsesWith(C, Res); 3000 }; 3001 3002 replaceTrigInsts(SinCalls, Sin); 3003 replaceTrigInsts(CosCalls, Cos); 3004 replaceTrigInsts(SinCosCalls, SinCos); 3005 3006 return IsSin ? Sin : Cos; 3007 } 3008 3009 void LibCallSimplifier::classifyArgUse( 3010 Value *Val, Function *F, bool IsFloat, 3011 SmallVectorImpl<CallInst *> &SinCalls, 3012 SmallVectorImpl<CallInst *> &CosCalls, 3013 SmallVectorImpl<CallInst *> &SinCosCalls) { 3014 auto *CI = dyn_cast<CallInst>(Val); 3015 if (!CI || CI->use_empty()) 3016 return; 3017 3018 // Don't consider calls in other functions. 3019 if (CI->getFunction() != F) 3020 return; 3021 3022 Module *M = CI->getModule(); 3023 Function *Callee = CI->getCalledFunction(); 3024 LibFunc Func; 3025 if (!Callee || !TLI->getLibFunc(*Callee, Func) || 3026 !isLibFuncEmittable(M, TLI, Func) || 3027 !isTrigLibCall(CI)) 3028 return; 3029 3030 if (IsFloat) { 3031 if (Func == LibFunc_sinpif) 3032 SinCalls.push_back(CI); 3033 else if (Func == LibFunc_cospif) 3034 CosCalls.push_back(CI); 3035 else if (Func == LibFunc_sincospif_stret) 3036 SinCosCalls.push_back(CI); 3037 } else { 3038 if (Func == LibFunc_sinpi) 3039 SinCalls.push_back(CI); 3040 else if (Func == LibFunc_cospi) 3041 CosCalls.push_back(CI); 3042 else if (Func == LibFunc_sincospi_stret) 3043 SinCosCalls.push_back(CI); 3044 } 3045 } 3046 3047 /// Constant folds remquo 3048 Value *LibCallSimplifier::optimizeRemquo(CallInst *CI, IRBuilderBase &B) { 3049 const APFloat *X, *Y; 3050 if (!match(CI->getArgOperand(0), m_APFloat(X)) || 3051 !match(CI->getArgOperand(1), m_APFloat(Y))) 3052 return nullptr; 3053 3054 APFloat::opStatus Status; 3055 APFloat Quot = *X; 3056 Status = Quot.divide(*Y, APFloat::rmNearestTiesToEven); 3057 if (Status != APFloat::opOK && Status != APFloat::opInexact) 3058 return nullptr; 3059 APFloat Rem = *X; 3060 if (Rem.remainder(*Y) != APFloat::opOK) 3061 return nullptr; 3062 3063 // TODO: We can only keep at least the three of the last bits of x/y 3064 unsigned IntBW = TLI->getIntSize(); 3065 APSInt QuotInt(IntBW, /*isUnsigned=*/false); 3066 bool IsExact; 3067 Status = 3068 Quot.convertToInteger(QuotInt, APFloat::rmNearestTiesToEven, &IsExact); 3069 if (Status != APFloat::opOK && Status != APFloat::opInexact) 3070 return nullptr; 3071 3072 B.CreateAlignedStore( 3073 ConstantInt::get(B.getIntNTy(IntBW), QuotInt.getExtValue()), 3074 CI->getArgOperand(2), CI->getParamAlign(2)); 3075 return ConstantFP::get(CI->getType(), Rem); 3076 } 3077 3078 //===----------------------------------------------------------------------===// 3079 // Integer Library Call Optimizations 3080 //===----------------------------------------------------------------------===// 3081 3082 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) { 3083 // All variants of ffs return int which need not be 32 bits wide. 3084 // ffs{,l,ll}(x) -> x != 0 ? (int)llvm.cttz(x)+1 : 0 3085 Type *RetType = CI->getType(); 3086 Value *Op = CI->getArgOperand(0); 3087 Type *ArgType = Op->getType(); 3088 Value *V = B.CreateIntrinsic(Intrinsic::cttz, {ArgType}, {Op, B.getTrue()}, 3089 nullptr, "cttz"); 3090 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 3091 V = B.CreateIntCast(V, RetType, false); 3092 3093 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 3094 return B.CreateSelect(Cond, V, ConstantInt::get(RetType, 0)); 3095 } 3096 3097 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) { 3098 // All variants of fls return int which need not be 32 bits wide. 3099 // fls{,l,ll}(x) -> (int)(sizeInBits(x) - llvm.ctlz(x, false)) 3100 Value *Op = CI->getArgOperand(0); 3101 Type *ArgType = Op->getType(); 3102 Value *V = B.CreateIntrinsic(Intrinsic::ctlz, {ArgType}, {Op, B.getFalse()}, 3103 nullptr, "ctlz"); 3104 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 3105 V); 3106 return B.CreateIntCast(V, CI->getType(), false); 3107 } 3108 3109 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) { 3110 // abs(x) -> x <s 0 ? -x : x 3111 // The negation has 'nsw' because abs of INT_MIN is undefined. 3112 Value *X = CI->getArgOperand(0); 3113 Value *IsNeg = B.CreateIsNeg(X); 3114 Value *NegX = B.CreateNSWNeg(X, "neg"); 3115 return B.CreateSelect(IsNeg, NegX, X); 3116 } 3117 3118 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) { 3119 // isdigit(c) -> (c-'0') <u 10 3120 Value *Op = CI->getArgOperand(0); 3121 Type *ArgType = Op->getType(); 3122 Op = B.CreateSub(Op, ConstantInt::get(ArgType, '0'), "isdigittmp"); 3123 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 10), "isdigit"); 3124 return B.CreateZExt(Op, CI->getType()); 3125 } 3126 3127 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) { 3128 // isascii(c) -> c <u 128 3129 Value *Op = CI->getArgOperand(0); 3130 Type *ArgType = Op->getType(); 3131 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 128), "isascii"); 3132 return B.CreateZExt(Op, CI->getType()); 3133 } 3134 3135 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) { 3136 // toascii(c) -> c & 0x7f 3137 return B.CreateAnd(CI->getArgOperand(0), 3138 ConstantInt::get(CI->getType(), 0x7F)); 3139 } 3140 3141 // Fold calls to atoi, atol, and atoll. 3142 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) { 3143 CI->addParamAttr(0, Attribute::NoCapture); 3144 3145 StringRef Str; 3146 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 3147 return nullptr; 3148 3149 return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B); 3150 } 3151 3152 // Fold calls to strtol, strtoll, strtoul, and strtoull. 3153 Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B, 3154 bool AsSigned) { 3155 Value *EndPtr = CI->getArgOperand(1); 3156 if (isa<ConstantPointerNull>(EndPtr)) { 3157 // With a null EndPtr, this function won't capture the main argument. 3158 // It would be readonly too, except that it still may write to errno. 3159 CI->addParamAttr(0, Attribute::NoCapture); 3160 EndPtr = nullptr; 3161 } else if (!isKnownNonZero(EndPtr, DL)) 3162 return nullptr; 3163 3164 StringRef Str; 3165 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 3166 return nullptr; 3167 3168 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 3169 return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B); 3170 } 3171 3172 return nullptr; 3173 } 3174 3175 //===----------------------------------------------------------------------===// 3176 // Formatting and IO Library Call Optimizations 3177 //===----------------------------------------------------------------------===// 3178 3179 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 3180 3181 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B, 3182 int StreamArg) { 3183 Function *Callee = CI->getCalledFunction(); 3184 // Error reporting calls should be cold, mark them as such. 3185 // This applies even to non-builtin calls: it is only a hint and applies to 3186 // functions that the frontend might not understand as builtins. 3187 3188 // This heuristic was suggested in: 3189 // Improving Static Branch Prediction in a Compiler 3190 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 3191 // Proceedings of PACT'98, Oct. 1998, IEEE 3192 if (!CI->hasFnAttr(Attribute::Cold) && 3193 isReportingError(Callee, CI, StreamArg)) { 3194 CI->addFnAttr(Attribute::Cold); 3195 } 3196 3197 return nullptr; 3198 } 3199 3200 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 3201 if (!Callee || !Callee->isDeclaration()) 3202 return false; 3203 3204 if (StreamArg < 0) 3205 return true; 3206 3207 // These functions might be considered cold, but only if their stream 3208 // argument is stderr. 3209 3210 if (StreamArg >= (int)CI->arg_size()) 3211 return false; 3212 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 3213 if (!LI) 3214 return false; 3215 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 3216 if (!GV || !GV->isDeclaration()) 3217 return false; 3218 return GV->getName() == "stderr"; 3219 } 3220 3221 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) { 3222 // Check for a fixed format string. 3223 StringRef FormatStr; 3224 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 3225 return nullptr; 3226 3227 // Empty format string -> noop. 3228 if (FormatStr.empty()) // Tolerate printf's declared void. 3229 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 3230 3231 // Do not do any of the following transformations if the printf return value 3232 // is used, in general the printf return value is not compatible with either 3233 // putchar() or puts(). 3234 if (!CI->use_empty()) 3235 return nullptr; 3236 3237 Type *IntTy = CI->getType(); 3238 // printf("x") -> putchar('x'), even for "%" and "%%". 3239 if (FormatStr.size() == 1 || FormatStr == "%%") { 3240 // Convert the character to unsigned char before passing it to putchar 3241 // to avoid host-specific sign extension in the IR. Putchar converts 3242 // it to unsigned char regardless. 3243 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)FormatStr[0]); 3244 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3245 } 3246 3247 // Try to remove call or emit putchar/puts. 3248 if (FormatStr == "%s" && CI->arg_size() > 1) { 3249 StringRef OperandStr; 3250 if (!getConstantStringInfo(CI->getOperand(1), OperandStr)) 3251 return nullptr; 3252 // printf("%s", "") --> NOP 3253 if (OperandStr.empty()) 3254 return (Value *)CI; 3255 // printf("%s", "a") --> putchar('a') 3256 if (OperandStr.size() == 1) { 3257 // Convert the character to unsigned char before passing it to putchar 3258 // to avoid host-specific sign extension in the IR. Putchar converts 3259 // it to unsigned char regardless. 3260 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)OperandStr[0]); 3261 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3262 } 3263 // printf("%s", str"\n") --> puts(str) 3264 if (OperandStr.back() == '\n') { 3265 OperandStr = OperandStr.drop_back(); 3266 Value *GV = B.CreateGlobalString(OperandStr, "str"); 3267 return copyFlags(*CI, emitPutS(GV, B, TLI)); 3268 } 3269 return nullptr; 3270 } 3271 3272 // printf("foo\n") --> puts("foo") 3273 if (FormatStr.back() == '\n' && 3274 !FormatStr.contains('%')) { // No format characters. 3275 // Create a string literal with no \n on it. We expect the constant merge 3276 // pass to be run after this pass, to merge duplicate strings. 3277 FormatStr = FormatStr.drop_back(); 3278 Value *GV = B.CreateGlobalString(FormatStr, "str"); 3279 return copyFlags(*CI, emitPutS(GV, B, TLI)); 3280 } 3281 3282 // Optimize specific format strings. 3283 // printf("%c", chr) --> putchar(chr) 3284 if (FormatStr == "%c" && CI->arg_size() > 1 && 3285 CI->getArgOperand(1)->getType()->isIntegerTy()) { 3286 // Convert the argument to the type expected by putchar, i.e., int, which 3287 // need not be 32 bits wide but which is the same as printf's return type. 3288 Value *IntChar = B.CreateIntCast(CI->getArgOperand(1), IntTy, false); 3289 return copyFlags(*CI, emitPutChar(IntChar, B, TLI)); 3290 } 3291 3292 // printf("%s\n", str) --> puts(str) 3293 if (FormatStr == "%s\n" && CI->arg_size() > 1 && 3294 CI->getArgOperand(1)->getType()->isPointerTy()) 3295 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI)); 3296 return nullptr; 3297 } 3298 3299 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) { 3300 3301 Module *M = CI->getModule(); 3302 Function *Callee = CI->getCalledFunction(); 3303 FunctionType *FT = Callee->getFunctionType(); 3304 if (Value *V = optimizePrintFString(CI, B)) { 3305 return V; 3306 } 3307 3308 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3309 3310 // printf(format, ...) -> iprintf(format, ...) if no floating point 3311 // arguments. 3312 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) && 3313 !callHasFloatingPointArgument(CI)) { 3314 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT, 3315 Callee->getAttributes()); 3316 CallInst *New = cast<CallInst>(CI->clone()); 3317 New->setCalledFunction(IPrintFFn); 3318 B.Insert(New); 3319 return New; 3320 } 3321 3322 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point 3323 // arguments. 3324 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) && 3325 !callHasFP128Argument(CI)) { 3326 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT, 3327 Callee->getAttributes()); 3328 CallInst *New = cast<CallInst>(CI->clone()); 3329 New->setCalledFunction(SmallPrintFFn); 3330 B.Insert(New); 3331 return New; 3332 } 3333 3334 return nullptr; 3335 } 3336 3337 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, 3338 IRBuilderBase &B) { 3339 // Check for a fixed format string. 3340 StringRef FormatStr; 3341 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 3342 return nullptr; 3343 3344 // If we just have a format string (nothing else crazy) transform it. 3345 Value *Dest = CI->getArgOperand(0); 3346 if (CI->arg_size() == 2) { 3347 // Make sure there's no % in the constant array. We could try to handle 3348 // %% -> % in the future if we cared. 3349 if (FormatStr.contains('%')) 3350 return nullptr; // we found a format specifier, bail out. 3351 3352 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 3353 B.CreateMemCpy( 3354 Dest, Align(1), CI->getArgOperand(1), Align(1), 3355 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 3356 FormatStr.size() + 1)); // Copy the null byte. 3357 return ConstantInt::get(CI->getType(), FormatStr.size()); 3358 } 3359 3360 // The remaining optimizations require the format string to be "%s" or "%c" 3361 // and have an extra operand. 3362 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 3363 return nullptr; 3364 3365 // Decode the second character of the format string. 3366 if (FormatStr[1] == 'c') { 3367 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 3368 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 3369 return nullptr; 3370 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 3371 Value *Ptr = Dest; 3372 B.CreateStore(V, Ptr); 3373 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 3374 B.CreateStore(B.getInt8(0), Ptr); 3375 3376 return ConstantInt::get(CI->getType(), 1); 3377 } 3378 3379 if (FormatStr[1] == 's') { 3380 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str, 3381 // strlen(str)+1) 3382 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 3383 return nullptr; 3384 3385 if (CI->use_empty()) 3386 // sprintf(dest, "%s", str) -> strcpy(dest, str) 3387 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI)); 3388 3389 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2)); 3390 if (SrcLen) { 3391 B.CreateMemCpy( 3392 Dest, Align(1), CI->getArgOperand(2), Align(1), 3393 ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen)); 3394 // Returns total number of characters written without null-character. 3395 return ConstantInt::get(CI->getType(), SrcLen - 1); 3396 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) { 3397 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest 3398 Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest); 3399 return B.CreateIntCast(PtrDiff, CI->getType(), false); 3400 } 3401 3402 bool OptForSize = CI->getFunction()->hasOptSize() || 3403 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3404 PGSOQueryType::IRPass); 3405 if (OptForSize) 3406 return nullptr; 3407 3408 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 3409 if (!Len) 3410 return nullptr; 3411 Value *IncLen = 3412 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 3413 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen); 3414 3415 // The sprintf result is the unincremented number of bytes in the string. 3416 return B.CreateIntCast(Len, CI->getType(), false); 3417 } 3418 return nullptr; 3419 } 3420 3421 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) { 3422 Module *M = CI->getModule(); 3423 Function *Callee = CI->getCalledFunction(); 3424 FunctionType *FT = Callee->getFunctionType(); 3425 if (Value *V = optimizeSPrintFString(CI, B)) { 3426 return V; 3427 } 3428 3429 annotateNonNullNoUndefBasedOnAccess(CI, {0, 1}); 3430 3431 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 3432 // point arguments. 3433 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) && 3434 !callHasFloatingPointArgument(CI)) { 3435 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf, 3436 FT, Callee->getAttributes()); 3437 CallInst *New = cast<CallInst>(CI->clone()); 3438 New->setCalledFunction(SIPrintFFn); 3439 B.Insert(New); 3440 return New; 3441 } 3442 3443 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit 3444 // floating point arguments. 3445 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) && 3446 !callHasFP128Argument(CI)) { 3447 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT, 3448 Callee->getAttributes()); 3449 CallInst *New = cast<CallInst>(CI->clone()); 3450 New->setCalledFunction(SmallSPrintFFn); 3451 B.Insert(New); 3452 return New; 3453 } 3454 3455 return nullptr; 3456 } 3457 3458 // Transform an snprintf call CI with the bound N to format the string Str 3459 // either to a call to memcpy, or to single character a store, or to nothing, 3460 // and fold the result to a constant. A nonnull StrArg refers to the string 3461 // argument being formatted. Otherwise the call is one with N < 2 and 3462 // the "%c" directive to format a single character. 3463 Value *LibCallSimplifier::emitSnPrintfMemCpy(CallInst *CI, Value *StrArg, 3464 StringRef Str, uint64_t N, 3465 IRBuilderBase &B) { 3466 assert(StrArg || (N < 2 && Str.size() == 1)); 3467 3468 unsigned IntBits = TLI->getIntSize(); 3469 uint64_t IntMax = maxIntN(IntBits); 3470 if (Str.size() > IntMax) 3471 // Bail if the string is longer than INT_MAX. POSIX requires 3472 // implementations to set errno to EOVERFLOW in this case, in 3473 // addition to when N is larger than that (checked by the caller). 3474 return nullptr; 3475 3476 Value *StrLen = ConstantInt::get(CI->getType(), Str.size()); 3477 if (N == 0) 3478 return StrLen; 3479 3480 // Set to the number of bytes to copy fron StrArg which is also 3481 // the offset of the terinating nul. 3482 uint64_t NCopy; 3483 if (N > Str.size()) 3484 // Copy the full string, including the terminating nul (which must 3485 // be present regardless of the bound). 3486 NCopy = Str.size() + 1; 3487 else 3488 NCopy = N - 1; 3489 3490 Value *DstArg = CI->getArgOperand(0); 3491 if (NCopy && StrArg) 3492 // Transform the call to lvm.memcpy(dst, fmt, N). 3493 copyFlags( 3494 *CI, 3495 B.CreateMemCpy( 3496 DstArg, Align(1), StrArg, Align(1), 3497 ConstantInt::get(DL.getIntPtrType(CI->getContext()), NCopy))); 3498 3499 if (N > Str.size()) 3500 // Return early when the whole format string, including the final nul, 3501 // has been copied. 3502 return StrLen; 3503 3504 // Otherwise, when truncating the string append a terminating nul. 3505 Type *Int8Ty = B.getInt8Ty(); 3506 Value *NulOff = B.getIntN(IntBits, NCopy); 3507 Value *DstEnd = B.CreateInBoundsGEP(Int8Ty, DstArg, NulOff, "endptr"); 3508 B.CreateStore(ConstantInt::get(Int8Ty, 0), DstEnd); 3509 return StrLen; 3510 } 3511 3512 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, 3513 IRBuilderBase &B) { 3514 // Check for size 3515 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 3516 if (!Size) 3517 return nullptr; 3518 3519 uint64_t N = Size->getZExtValue(); 3520 uint64_t IntMax = maxIntN(TLI->getIntSize()); 3521 if (N > IntMax) 3522 // Bail if the bound exceeds INT_MAX. POSIX requires implementations 3523 // to set errno to EOVERFLOW in this case. 3524 return nullptr; 3525 3526 Value *DstArg = CI->getArgOperand(0); 3527 Value *FmtArg = CI->getArgOperand(2); 3528 3529 // Check for a fixed format string. 3530 StringRef FormatStr; 3531 if (!getConstantStringInfo(FmtArg, FormatStr)) 3532 return nullptr; 3533 3534 // If we just have a format string (nothing else crazy) transform it. 3535 if (CI->arg_size() == 3) { 3536 if (FormatStr.contains('%')) 3537 // Bail if the format string contains a directive and there are 3538 // no arguments. We could handle "%%" in the future. 3539 return nullptr; 3540 3541 return emitSnPrintfMemCpy(CI, FmtArg, FormatStr, N, B); 3542 } 3543 3544 // The remaining optimizations require the format string to be "%s" or "%c" 3545 // and have an extra operand. 3546 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() != 4) 3547 return nullptr; 3548 3549 // Decode the second character of the format string. 3550 if (FormatStr[1] == 'c') { 3551 if (N <= 1) { 3552 // Use an arbitary string of length 1 to transform the call into 3553 // either a nul store (N == 1) or a no-op (N == 0) and fold it 3554 // to one. 3555 StringRef CharStr("*"); 3556 return emitSnPrintfMemCpy(CI, nullptr, CharStr, N, B); 3557 } 3558 3559 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 3560 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 3561 return nullptr; 3562 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 3563 Value *Ptr = DstArg; 3564 B.CreateStore(V, Ptr); 3565 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 3566 B.CreateStore(B.getInt8(0), Ptr); 3567 return ConstantInt::get(CI->getType(), 1); 3568 } 3569 3570 if (FormatStr[1] != 's') 3571 return nullptr; 3572 3573 Value *StrArg = CI->getArgOperand(3); 3574 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 3575 StringRef Str; 3576 if (!getConstantStringInfo(StrArg, Str)) 3577 return nullptr; 3578 3579 return emitSnPrintfMemCpy(CI, StrArg, Str, N, B); 3580 } 3581 3582 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) { 3583 if (Value *V = optimizeSnPrintFString(CI, B)) { 3584 return V; 3585 } 3586 3587 if (isKnownNonZero(CI->getOperand(1), DL)) 3588 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3589 return nullptr; 3590 } 3591 3592 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, 3593 IRBuilderBase &B) { 3594 optimizeErrorReporting(CI, B, 0); 3595 3596 // All the optimizations depend on the format string. 3597 StringRef FormatStr; 3598 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 3599 return nullptr; 3600 3601 // Do not do any of the following transformations if the fprintf return 3602 // value is used, in general the fprintf return value is not compatible 3603 // with fwrite(), fputc() or fputs(). 3604 if (!CI->use_empty()) 3605 return nullptr; 3606 3607 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 3608 if (CI->arg_size() == 2) { 3609 // Could handle %% -> % if we cared. 3610 if (FormatStr.contains('%')) 3611 return nullptr; // We found a format specifier. 3612 3613 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 3614 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 3615 return copyFlags( 3616 *CI, emitFWrite(CI->getArgOperand(1), 3617 ConstantInt::get(SizeTTy, FormatStr.size()), 3618 CI->getArgOperand(0), B, DL, TLI)); 3619 } 3620 3621 // The remaining optimizations require the format string to be "%s" or "%c" 3622 // and have an extra operand. 3623 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3) 3624 return nullptr; 3625 3626 // Decode the second character of the format string. 3627 if (FormatStr[1] == 'c') { 3628 // fprintf(F, "%c", chr) --> fputc((int)chr, F) 3629 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 3630 return nullptr; 3631 Type *IntTy = B.getIntNTy(TLI->getIntSize()); 3632 Value *V = B.CreateIntCast(CI->getArgOperand(2), IntTy, /*isSigned*/ true, 3633 "chari"); 3634 return copyFlags(*CI, emitFPutC(V, CI->getArgOperand(0), B, TLI)); 3635 } 3636 3637 if (FormatStr[1] == 's') { 3638 // fprintf(F, "%s", str) --> fputs(str, F) 3639 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 3640 return nullptr; 3641 return copyFlags( 3642 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI)); 3643 } 3644 return nullptr; 3645 } 3646 3647 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) { 3648 Module *M = CI->getModule(); 3649 Function *Callee = CI->getCalledFunction(); 3650 FunctionType *FT = Callee->getFunctionType(); 3651 if (Value *V = optimizeFPrintFString(CI, B)) { 3652 return V; 3653 } 3654 3655 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 3656 // floating point arguments. 3657 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) && 3658 !callHasFloatingPointArgument(CI)) { 3659 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf, 3660 FT, Callee->getAttributes()); 3661 CallInst *New = cast<CallInst>(CI->clone()); 3662 New->setCalledFunction(FIPrintFFn); 3663 B.Insert(New); 3664 return New; 3665 } 3666 3667 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no 3668 // 128-bit floating point arguments. 3669 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) && 3670 !callHasFP128Argument(CI)) { 3671 auto SmallFPrintFFn = 3672 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT, 3673 Callee->getAttributes()); 3674 CallInst *New = cast<CallInst>(CI->clone()); 3675 New->setCalledFunction(SmallFPrintFFn); 3676 B.Insert(New); 3677 return New; 3678 } 3679 3680 return nullptr; 3681 } 3682 3683 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) { 3684 optimizeErrorReporting(CI, B, 3); 3685 3686 // Get the element size and count. 3687 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 3688 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 3689 if (SizeC && CountC) { 3690 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 3691 3692 // If this is writing zero records, remove the call (it's a noop). 3693 if (Bytes == 0) 3694 return ConstantInt::get(CI->getType(), 0); 3695 3696 // If this is writing one byte, turn it into fputc. 3697 // This optimisation is only valid, if the return value is unused. 3698 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 3699 Value *Char = B.CreateLoad(B.getInt8Ty(), CI->getArgOperand(0), "char"); 3700 Type *IntTy = B.getIntNTy(TLI->getIntSize()); 3701 Value *Cast = B.CreateIntCast(Char, IntTy, /*isSigned*/ true, "chari"); 3702 Value *NewCI = emitFPutC(Cast, CI->getArgOperand(3), B, TLI); 3703 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 3704 } 3705 } 3706 3707 return nullptr; 3708 } 3709 3710 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) { 3711 optimizeErrorReporting(CI, B, 1); 3712 3713 // Don't rewrite fputs to fwrite when optimising for size because fwrite 3714 // requires more arguments and thus extra MOVs are required. 3715 bool OptForSize = CI->getFunction()->hasOptSize() || 3716 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 3717 PGSOQueryType::IRPass); 3718 if (OptForSize) 3719 return nullptr; 3720 3721 // We can't optimize if return value is used. 3722 if (!CI->use_empty()) 3723 return nullptr; 3724 3725 // fputs(s,F) --> fwrite(s,strlen(s),1,F) 3726 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 3727 if (!Len) 3728 return nullptr; 3729 3730 // Known to have no uses (see above). 3731 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 3732 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 3733 return copyFlags( 3734 *CI, 3735 emitFWrite(CI->getArgOperand(0), 3736 ConstantInt::get(SizeTTy, Len - 1), 3737 CI->getArgOperand(1), B, DL, TLI)); 3738 } 3739 3740 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) { 3741 annotateNonNullNoUndefBasedOnAccess(CI, 0); 3742 if (!CI->use_empty()) 3743 return nullptr; 3744 3745 // Check for a constant string. 3746 // puts("") -> putchar('\n') 3747 StringRef Str; 3748 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) { 3749 // putchar takes an argument of the same type as puts returns, i.e., 3750 // int, which need not be 32 bits wide. 3751 Type *IntTy = CI->getType(); 3752 return copyFlags(*CI, emitPutChar(ConstantInt::get(IntTy, '\n'), B, TLI)); 3753 } 3754 3755 return nullptr; 3756 } 3757 3758 Value *LibCallSimplifier::optimizeExit(CallInst *CI) { 3759 3760 // Mark 'exit' as cold if its not exit(0) (success). 3761 const APInt *C; 3762 if (!CI->hasFnAttr(Attribute::Cold) && 3763 match(CI->getArgOperand(0), m_APInt(C)) && !C->isZero()) { 3764 CI->addFnAttr(Attribute::Cold); 3765 } 3766 return nullptr; 3767 } 3768 3769 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) { 3770 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) 3771 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1), 3772 CI->getArgOperand(0), Align(1), 3773 CI->getArgOperand(2))); 3774 } 3775 3776 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) { 3777 SmallString<20> FloatFuncName = FuncName; 3778 FloatFuncName += 'f'; 3779 return isLibFuncEmittable(M, TLI, FloatFuncName); 3780 } 3781 3782 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 3783 IRBuilderBase &Builder) { 3784 Module *M = CI->getModule(); 3785 LibFunc Func; 3786 Function *Callee = CI->getCalledFunction(); 3787 3788 // Check for string/memory library functions. 3789 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 3790 // Make sure we never change the calling convention. 3791 assert( 3792 (ignoreCallingConv(Func) || 3793 TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) && 3794 "Optimizing string/memory libcall would change the calling convention"); 3795 switch (Func) { 3796 case LibFunc_strcat: 3797 return optimizeStrCat(CI, Builder); 3798 case LibFunc_strncat: 3799 return optimizeStrNCat(CI, Builder); 3800 case LibFunc_strchr: 3801 return optimizeStrChr(CI, Builder); 3802 case LibFunc_strrchr: 3803 return optimizeStrRChr(CI, Builder); 3804 case LibFunc_strcmp: 3805 return optimizeStrCmp(CI, Builder); 3806 case LibFunc_strncmp: 3807 return optimizeStrNCmp(CI, Builder); 3808 case LibFunc_strcpy: 3809 return optimizeStrCpy(CI, Builder); 3810 case LibFunc_stpcpy: 3811 return optimizeStpCpy(CI, Builder); 3812 case LibFunc_strlcpy: 3813 return optimizeStrLCpy(CI, Builder); 3814 case LibFunc_stpncpy: 3815 return optimizeStringNCpy(CI, /*RetEnd=*/true, Builder); 3816 case LibFunc_strncpy: 3817 return optimizeStringNCpy(CI, /*RetEnd=*/false, Builder); 3818 case LibFunc_strlen: 3819 return optimizeStrLen(CI, Builder); 3820 case LibFunc_strnlen: 3821 return optimizeStrNLen(CI, Builder); 3822 case LibFunc_strpbrk: 3823 return optimizeStrPBrk(CI, Builder); 3824 case LibFunc_strndup: 3825 return optimizeStrNDup(CI, Builder); 3826 case LibFunc_strtol: 3827 case LibFunc_strtod: 3828 case LibFunc_strtof: 3829 case LibFunc_strtoul: 3830 case LibFunc_strtoll: 3831 case LibFunc_strtold: 3832 case LibFunc_strtoull: 3833 return optimizeStrTo(CI, Builder); 3834 case LibFunc_strspn: 3835 return optimizeStrSpn(CI, Builder); 3836 case LibFunc_strcspn: 3837 return optimizeStrCSpn(CI, Builder); 3838 case LibFunc_strstr: 3839 return optimizeStrStr(CI, Builder); 3840 case LibFunc_memchr: 3841 return optimizeMemChr(CI, Builder); 3842 case LibFunc_memrchr: 3843 return optimizeMemRChr(CI, Builder); 3844 case LibFunc_bcmp: 3845 return optimizeBCmp(CI, Builder); 3846 case LibFunc_memcmp: 3847 return optimizeMemCmp(CI, Builder); 3848 case LibFunc_memcpy: 3849 return optimizeMemCpy(CI, Builder); 3850 case LibFunc_memccpy: 3851 return optimizeMemCCpy(CI, Builder); 3852 case LibFunc_mempcpy: 3853 return optimizeMemPCpy(CI, Builder); 3854 case LibFunc_memmove: 3855 return optimizeMemMove(CI, Builder); 3856 case LibFunc_memset: 3857 return optimizeMemSet(CI, Builder); 3858 case LibFunc_realloc: 3859 return optimizeRealloc(CI, Builder); 3860 case LibFunc_wcslen: 3861 return optimizeWcslen(CI, Builder); 3862 case LibFunc_bcopy: 3863 return optimizeBCopy(CI, Builder); 3864 case LibFunc_Znwm: 3865 case LibFunc_ZnwmRKSt9nothrow_t: 3866 case LibFunc_ZnwmSt11align_val_t: 3867 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t: 3868 case LibFunc_Znam: 3869 case LibFunc_ZnamRKSt9nothrow_t: 3870 case LibFunc_ZnamSt11align_val_t: 3871 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t: 3872 case LibFunc_Znwm12__hot_cold_t: 3873 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t: 3874 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t: 3875 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 3876 case LibFunc_Znam12__hot_cold_t: 3877 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t: 3878 case LibFunc_ZnamSt11align_val_t12__hot_cold_t: 3879 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t: 3880 case LibFunc_size_returning_new: 3881 case LibFunc_size_returning_new_hot_cold: 3882 case LibFunc_size_returning_new_aligned: 3883 case LibFunc_size_returning_new_aligned_hot_cold: 3884 return optimizeNew(CI, Builder, Func); 3885 default: 3886 break; 3887 } 3888 } 3889 return nullptr; 3890 } 3891 3892 /// Constant folding nan/nanf/nanl. 3893 static Value *optimizeNaN(CallInst *CI) { 3894 StringRef CharSeq; 3895 if (!getConstantStringInfo(CI->getArgOperand(0), CharSeq)) 3896 return nullptr; 3897 3898 APInt Fill; 3899 // Treat empty strings as if they were zero. 3900 if (CharSeq.empty()) 3901 Fill = APInt(32, 0); 3902 else if (CharSeq.getAsInteger(0, Fill)) 3903 return nullptr; 3904 3905 return ConstantFP::getQNaN(CI->getType(), /*Negative=*/false, &Fill); 3906 } 3907 3908 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 3909 LibFunc Func, 3910 IRBuilderBase &Builder) { 3911 const Module *M = CI->getModule(); 3912 3913 // Don't optimize calls that require strict floating point semantics. 3914 if (CI->isStrictFP()) 3915 return nullptr; 3916 3917 if (Value *V = optimizeSymmetric(CI, Func, Builder)) 3918 return V; 3919 3920 switch (Func) { 3921 case LibFunc_sinpif: 3922 case LibFunc_sinpi: 3923 return optimizeSinCosPi(CI, /*IsSin*/true, Builder); 3924 case LibFunc_cospif: 3925 case LibFunc_cospi: 3926 return optimizeSinCosPi(CI, /*IsSin*/false, Builder); 3927 case LibFunc_powf: 3928 case LibFunc_pow: 3929 case LibFunc_powl: 3930 return optimizePow(CI, Builder); 3931 case LibFunc_exp2l: 3932 case LibFunc_exp2: 3933 case LibFunc_exp2f: 3934 return optimizeExp2(CI, Builder); 3935 case LibFunc_fabsf: 3936 case LibFunc_fabs: 3937 case LibFunc_fabsl: 3938 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 3939 case LibFunc_sqrtf: 3940 case LibFunc_sqrt: 3941 case LibFunc_sqrtl: 3942 return optimizeSqrt(CI, Builder); 3943 case LibFunc_logf: 3944 case LibFunc_log: 3945 case LibFunc_logl: 3946 case LibFunc_log10f: 3947 case LibFunc_log10: 3948 case LibFunc_log10l: 3949 case LibFunc_log1pf: 3950 case LibFunc_log1p: 3951 case LibFunc_log1pl: 3952 case LibFunc_log2f: 3953 case LibFunc_log2: 3954 case LibFunc_log2l: 3955 case LibFunc_logbf: 3956 case LibFunc_logb: 3957 case LibFunc_logbl: 3958 return optimizeLog(CI, Builder); 3959 case LibFunc_tan: 3960 case LibFunc_tanf: 3961 case LibFunc_tanl: 3962 case LibFunc_sinh: 3963 case LibFunc_sinhf: 3964 case LibFunc_sinhl: 3965 case LibFunc_asinh: 3966 case LibFunc_asinhf: 3967 case LibFunc_asinhl: 3968 case LibFunc_cosh: 3969 case LibFunc_coshf: 3970 case LibFunc_coshl: 3971 case LibFunc_atanh: 3972 case LibFunc_atanhf: 3973 case LibFunc_atanhl: 3974 return optimizeTrigInversionPairs(CI, Builder); 3975 case LibFunc_ceil: 3976 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 3977 case LibFunc_floor: 3978 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 3979 case LibFunc_round: 3980 return replaceUnaryCall(CI, Builder, Intrinsic::round); 3981 case LibFunc_roundeven: 3982 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven); 3983 case LibFunc_nearbyint: 3984 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 3985 case LibFunc_rint: 3986 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 3987 case LibFunc_trunc: 3988 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 3989 case LibFunc_acos: 3990 case LibFunc_acosh: 3991 case LibFunc_asin: 3992 case LibFunc_atan: 3993 case LibFunc_cbrt: 3994 case LibFunc_exp: 3995 case LibFunc_exp10: 3996 case LibFunc_expm1: 3997 case LibFunc_cos: 3998 case LibFunc_sin: 3999 case LibFunc_tanh: 4000 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName())) 4001 return optimizeUnaryDoubleFP(CI, Builder, TLI, true); 4002 return nullptr; 4003 case LibFunc_copysign: 4004 if (hasFloatVersion(M, CI->getCalledFunction()->getName())) 4005 return optimizeBinaryDoubleFP(CI, Builder, TLI); 4006 return nullptr; 4007 case LibFunc_fminf: 4008 case LibFunc_fmin: 4009 case LibFunc_fminl: 4010 case LibFunc_fmaxf: 4011 case LibFunc_fmax: 4012 case LibFunc_fmaxl: 4013 return optimizeFMinFMax(CI, Builder); 4014 case LibFunc_cabs: 4015 case LibFunc_cabsf: 4016 case LibFunc_cabsl: 4017 return optimizeCAbs(CI, Builder); 4018 case LibFunc_remquo: 4019 case LibFunc_remquof: 4020 case LibFunc_remquol: 4021 return optimizeRemquo(CI, Builder); 4022 case LibFunc_nan: 4023 case LibFunc_nanf: 4024 case LibFunc_nanl: 4025 return optimizeNaN(CI); 4026 default: 4027 return nullptr; 4028 } 4029 } 4030 4031 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) { 4032 Module *M = CI->getModule(); 4033 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe."); 4034 4035 // TODO: Split out the code below that operates on FP calls so that 4036 // we can all non-FP calls with the StrictFP attribute to be 4037 // optimized. 4038 if (CI->isNoBuiltin()) 4039 return nullptr; 4040 4041 LibFunc Func; 4042 Function *Callee = CI->getCalledFunction(); 4043 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 4044 4045 SmallVector<OperandBundleDef, 2> OpBundles; 4046 CI->getOperandBundlesAsDefs(OpBundles); 4047 4048 IRBuilderBase::OperandBundlesGuard Guard(Builder); 4049 Builder.setDefaultOperandBundles(OpBundles); 4050 4051 // Command-line parameter overrides instruction attribute. 4052 // This can't be moved to optimizeFloatingPointLibCall() because it may be 4053 // used by the intrinsic optimizations. 4054 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 4055 UnsafeFPShrink = EnableUnsafeFPShrink; 4056 else if (isa<FPMathOperator>(CI) && CI->isFast()) 4057 UnsafeFPShrink = true; 4058 4059 // First, check for intrinsics. 4060 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 4061 if (!IsCallingConvC) 4062 return nullptr; 4063 // The FP intrinsics have corresponding constrained versions so we don't 4064 // need to check for the StrictFP attribute here. 4065 switch (II->getIntrinsicID()) { 4066 case Intrinsic::pow: 4067 return optimizePow(CI, Builder); 4068 case Intrinsic::exp2: 4069 return optimizeExp2(CI, Builder); 4070 case Intrinsic::log: 4071 case Intrinsic::log2: 4072 case Intrinsic::log10: 4073 return optimizeLog(CI, Builder); 4074 case Intrinsic::sqrt: 4075 return optimizeSqrt(CI, Builder); 4076 case Intrinsic::memset: 4077 return optimizeMemSet(CI, Builder); 4078 case Intrinsic::memcpy: 4079 return optimizeMemCpy(CI, Builder); 4080 case Intrinsic::memmove: 4081 return optimizeMemMove(CI, Builder); 4082 default: 4083 return nullptr; 4084 } 4085 } 4086 4087 // Also try to simplify calls to fortified library functions. 4088 if (Value *SimplifiedFortifiedCI = 4089 FortifiedSimplifier.optimizeCall(CI, Builder)) 4090 return SimplifiedFortifiedCI; 4091 4092 // Then check for known library functions. 4093 if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) { 4094 // We never change the calling convention. 4095 if (!ignoreCallingConv(Func) && !IsCallingConvC) 4096 return nullptr; 4097 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 4098 return V; 4099 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 4100 return V; 4101 switch (Func) { 4102 case LibFunc_ffs: 4103 case LibFunc_ffsl: 4104 case LibFunc_ffsll: 4105 return optimizeFFS(CI, Builder); 4106 case LibFunc_fls: 4107 case LibFunc_flsl: 4108 case LibFunc_flsll: 4109 return optimizeFls(CI, Builder); 4110 case LibFunc_abs: 4111 case LibFunc_labs: 4112 case LibFunc_llabs: 4113 return optimizeAbs(CI, Builder); 4114 case LibFunc_isdigit: 4115 return optimizeIsDigit(CI, Builder); 4116 case LibFunc_isascii: 4117 return optimizeIsAscii(CI, Builder); 4118 case LibFunc_toascii: 4119 return optimizeToAscii(CI, Builder); 4120 case LibFunc_atoi: 4121 case LibFunc_atol: 4122 case LibFunc_atoll: 4123 return optimizeAtoi(CI, Builder); 4124 case LibFunc_strtol: 4125 case LibFunc_strtoll: 4126 return optimizeStrToInt(CI, Builder, /*AsSigned=*/true); 4127 case LibFunc_strtoul: 4128 case LibFunc_strtoull: 4129 return optimizeStrToInt(CI, Builder, /*AsSigned=*/false); 4130 case LibFunc_printf: 4131 return optimizePrintF(CI, Builder); 4132 case LibFunc_sprintf: 4133 return optimizeSPrintF(CI, Builder); 4134 case LibFunc_snprintf: 4135 return optimizeSnPrintF(CI, Builder); 4136 case LibFunc_fprintf: 4137 return optimizeFPrintF(CI, Builder); 4138 case LibFunc_fwrite: 4139 return optimizeFWrite(CI, Builder); 4140 case LibFunc_fputs: 4141 return optimizeFPuts(CI, Builder); 4142 case LibFunc_puts: 4143 return optimizePuts(CI, Builder); 4144 case LibFunc_perror: 4145 return optimizeErrorReporting(CI, Builder); 4146 case LibFunc_vfprintf: 4147 case LibFunc_fiprintf: 4148 return optimizeErrorReporting(CI, Builder, 0); 4149 case LibFunc_exit: 4150 case LibFunc_Exit: 4151 return optimizeExit(CI); 4152 default: 4153 return nullptr; 4154 } 4155 } 4156 return nullptr; 4157 } 4158 4159 LibCallSimplifier::LibCallSimplifier( 4160 const DataLayout &DL, const TargetLibraryInfo *TLI, AssumptionCache *AC, 4161 OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 4162 ProfileSummaryInfo *PSI, 4163 function_ref<void(Instruction *, Value *)> Replacer, 4164 function_ref<void(Instruction *)> Eraser) 4165 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), AC(AC), ORE(ORE), BFI(BFI), 4166 PSI(PSI), Replacer(Replacer), Eraser(Eraser) {} 4167 4168 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 4169 // Indirect through the replacer used in this instance. 4170 Replacer(I, With); 4171 } 4172 4173 void LibCallSimplifier::eraseFromParent(Instruction *I) { 4174 Eraser(I); 4175 } 4176 4177 // TODO: 4178 // Additional cases that we need to add to this file: 4179 // 4180 // cbrt: 4181 // * cbrt(expN(X)) -> expN(x/3) 4182 // * cbrt(sqrt(x)) -> pow(x,1/6) 4183 // * cbrt(cbrt(x)) -> pow(x,1/9) 4184 // 4185 // exp, expf, expl: 4186 // * exp(log(x)) -> x 4187 // 4188 // log, logf, logl: 4189 // * log(exp(x)) -> x 4190 // * log(exp(y)) -> y*log(e) 4191 // * log(exp10(y)) -> y*log(10) 4192 // * log(sqrt(x)) -> 0.5*log(x) 4193 // 4194 // pow, powf, powl: 4195 // * pow(sqrt(x),y) -> pow(x,y*0.5) 4196 // * pow(pow(x,y),z)-> pow(x,y*z) 4197 // 4198 // signbit: 4199 // * signbit(cnst) -> cnst' 4200 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 4201 // 4202 // sqrt, sqrtf, sqrtl: 4203 // * sqrt(expN(x)) -> expN(x*0.5) 4204 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 4205 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 4206 // 4207 4208 //===----------------------------------------------------------------------===// 4209 // Fortified Library Call Optimizations 4210 //===----------------------------------------------------------------------===// 4211 4212 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable( 4213 CallInst *CI, unsigned ObjSizeOp, std::optional<unsigned> SizeOp, 4214 std::optional<unsigned> StrOp, std::optional<unsigned> FlagOp) { 4215 // If this function takes a flag argument, the implementation may use it to 4216 // perform extra checks. Don't fold into the non-checking variant. 4217 if (FlagOp) { 4218 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 4219 if (!Flag || !Flag->isZero()) 4220 return false; 4221 } 4222 4223 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 4224 return true; 4225 4226 if (ConstantInt *ObjSizeCI = 4227 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 4228 if (ObjSizeCI->isMinusOne()) 4229 return true; 4230 // If the object size wasn't -1 (unknown), bail out if we were asked to. 4231 if (OnlyLowerUnknownSize) 4232 return false; 4233 if (StrOp) { 4234 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 4235 // If the length is 0 we don't know how long it is and so we can't 4236 // remove the check. 4237 if (Len) 4238 annotateDereferenceableBytes(CI, *StrOp, Len); 4239 else 4240 return false; 4241 return ObjSizeCI->getZExtValue() >= Len; 4242 } 4243 4244 if (SizeOp) { 4245 if (ConstantInt *SizeCI = 4246 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 4247 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 4248 } 4249 } 4250 return false; 4251 } 4252 4253 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 4254 IRBuilderBase &B) { 4255 if (isFortifiedCallFoldable(CI, 3, 2)) { 4256 CallInst *NewCI = 4257 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 4258 Align(1), CI->getArgOperand(2)); 4259 mergeAttributesAndFlags(NewCI, *CI); 4260 return CI->getArgOperand(0); 4261 } 4262 return nullptr; 4263 } 4264 4265 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 4266 IRBuilderBase &B) { 4267 if (isFortifiedCallFoldable(CI, 3, 2)) { 4268 CallInst *NewCI = 4269 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 4270 Align(1), CI->getArgOperand(2)); 4271 mergeAttributesAndFlags(NewCI, *CI); 4272 return CI->getArgOperand(0); 4273 } 4274 return nullptr; 4275 } 4276 4277 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 4278 IRBuilderBase &B) { 4279 if (isFortifiedCallFoldable(CI, 3, 2)) { 4280 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 4281 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 4282 CI->getArgOperand(2), Align(1)); 4283 mergeAttributesAndFlags(NewCI, *CI); 4284 return CI->getArgOperand(0); 4285 } 4286 return nullptr; 4287 } 4288 4289 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI, 4290 IRBuilderBase &B) { 4291 const DataLayout &DL = CI->getDataLayout(); 4292 if (isFortifiedCallFoldable(CI, 3, 2)) 4293 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4294 CI->getArgOperand(2), B, DL, TLI)) { 4295 return mergeAttributesAndFlags(cast<CallInst>(Call), *CI); 4296 } 4297 return nullptr; 4298 } 4299 4300 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 4301 IRBuilderBase &B, 4302 LibFunc Func) { 4303 const DataLayout &DL = CI->getDataLayout(); 4304 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 4305 *ObjSize = CI->getArgOperand(2); 4306 4307 // __stpcpy_chk(x,x,...) -> x+strlen(x) 4308 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 4309 Value *StrLen = emitStrLen(Src, B, DL, TLI); 4310 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 4311 } 4312 4313 // If a) we don't have any length information, or b) we know this will 4314 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 4315 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 4316 // TODO: It might be nice to get a maximum length out of the possible 4317 // string lengths for varying. 4318 if (isFortifiedCallFoldable(CI, 2, std::nullopt, 1)) { 4319 if (Func == LibFunc_strcpy_chk) 4320 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI)); 4321 else 4322 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI)); 4323 } 4324 4325 if (OnlyLowerUnknownSize) 4326 return nullptr; 4327 4328 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 4329 uint64_t Len = GetStringLength(Src); 4330 if (Len) 4331 annotateDereferenceableBytes(CI, 1, Len); 4332 else 4333 return nullptr; 4334 4335 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule()); 4336 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits); 4337 Value *LenV = ConstantInt::get(SizeTTy, Len); 4338 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 4339 // If the function was an __stpcpy_chk, and we were able to fold it into 4340 // a __memcpy_chk, we still need to return the correct end pointer. 4341 if (Ret && Func == LibFunc_stpcpy_chk) 4342 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, 4343 ConstantInt::get(SizeTTy, Len - 1)); 4344 return copyFlags(*CI, cast<CallInst>(Ret)); 4345 } 4346 4347 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI, 4348 IRBuilderBase &B) { 4349 if (isFortifiedCallFoldable(CI, 1, std::nullopt, 0)) 4350 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, 4351 CI->getDataLayout(), TLI)); 4352 return nullptr; 4353 } 4354 4355 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 4356 IRBuilderBase &B, 4357 LibFunc Func) { 4358 if (isFortifiedCallFoldable(CI, 3, 2)) { 4359 if (Func == LibFunc_strncpy_chk) 4360 return copyFlags(*CI, 4361 emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4362 CI->getArgOperand(2), B, TLI)); 4363 else 4364 return copyFlags(*CI, 4365 emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4366 CI->getArgOperand(2), B, TLI)); 4367 } 4368 4369 return nullptr; 4370 } 4371 4372 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 4373 IRBuilderBase &B) { 4374 if (isFortifiedCallFoldable(CI, 4, 3)) 4375 return copyFlags( 4376 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4377 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI)); 4378 4379 return nullptr; 4380 } 4381 4382 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 4383 IRBuilderBase &B) { 4384 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) { 4385 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5)); 4386 return copyFlags(*CI, 4387 emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 4388 CI->getArgOperand(4), VariadicArgs, B, TLI)); 4389 } 4390 4391 return nullptr; 4392 } 4393 4394 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 4395 IRBuilderBase &B) { 4396 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) { 4397 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4)); 4398 return copyFlags(*CI, 4399 emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 4400 VariadicArgs, B, TLI)); 4401 } 4402 4403 return nullptr; 4404 } 4405 4406 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 4407 IRBuilderBase &B) { 4408 if (isFortifiedCallFoldable(CI, 2)) 4409 return copyFlags( 4410 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI)); 4411 4412 return nullptr; 4413 } 4414 4415 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 4416 IRBuilderBase &B) { 4417 if (isFortifiedCallFoldable(CI, 3)) 4418 return copyFlags(*CI, 4419 emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 4420 CI->getArgOperand(2), B, TLI)); 4421 4422 return nullptr; 4423 } 4424 4425 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 4426 IRBuilderBase &B) { 4427 if (isFortifiedCallFoldable(CI, 3)) 4428 return copyFlags(*CI, 4429 emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 4430 CI->getArgOperand(2), B, TLI)); 4431 4432 return nullptr; 4433 } 4434 4435 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 4436 IRBuilderBase &B) { 4437 if (isFortifiedCallFoldable(CI, 3)) 4438 return copyFlags(*CI, 4439 emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 4440 CI->getArgOperand(2), B, TLI)); 4441 4442 return nullptr; 4443 } 4444 4445 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 4446 IRBuilderBase &B) { 4447 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) 4448 return copyFlags( 4449 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 4450 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI)); 4451 4452 return nullptr; 4453 } 4454 4455 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 4456 IRBuilderBase &B) { 4457 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) 4458 return copyFlags(*CI, 4459 emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 4460 CI->getArgOperand(4), B, TLI)); 4461 4462 return nullptr; 4463 } 4464 4465 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI, 4466 IRBuilderBase &Builder) { 4467 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 4468 // Some clang users checked for _chk libcall availability using: 4469 // __has_builtin(__builtin___memcpy_chk) 4470 // When compiling with -fno-builtin, this is always true. 4471 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 4472 // end up with fortified libcalls, which isn't acceptable in a freestanding 4473 // environment which only provides their non-fortified counterparts. 4474 // 4475 // Until we change clang and/or teach external users to check for availability 4476 // differently, disregard the "nobuiltin" attribute and TLI::has. 4477 // 4478 // PR23093. 4479 4480 LibFunc Func; 4481 Function *Callee = CI->getCalledFunction(); 4482 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI); 4483 4484 SmallVector<OperandBundleDef, 2> OpBundles; 4485 CI->getOperandBundlesAsDefs(OpBundles); 4486 4487 IRBuilderBase::OperandBundlesGuard Guard(Builder); 4488 Builder.setDefaultOperandBundles(OpBundles); 4489 4490 // First, check that this is a known library functions and that the prototype 4491 // is correct. 4492 if (!TLI->getLibFunc(*Callee, Func)) 4493 return nullptr; 4494 4495 // We never change the calling convention. 4496 if (!ignoreCallingConv(Func) && !IsCallingConvC) 4497 return nullptr; 4498 4499 switch (Func) { 4500 case LibFunc_memcpy_chk: 4501 return optimizeMemCpyChk(CI, Builder); 4502 case LibFunc_mempcpy_chk: 4503 return optimizeMemPCpyChk(CI, Builder); 4504 case LibFunc_memmove_chk: 4505 return optimizeMemMoveChk(CI, Builder); 4506 case LibFunc_memset_chk: 4507 return optimizeMemSetChk(CI, Builder); 4508 case LibFunc_stpcpy_chk: 4509 case LibFunc_strcpy_chk: 4510 return optimizeStrpCpyChk(CI, Builder, Func); 4511 case LibFunc_strlen_chk: 4512 return optimizeStrLenChk(CI, Builder); 4513 case LibFunc_stpncpy_chk: 4514 case LibFunc_strncpy_chk: 4515 return optimizeStrpNCpyChk(CI, Builder, Func); 4516 case LibFunc_memccpy_chk: 4517 return optimizeMemCCpyChk(CI, Builder); 4518 case LibFunc_snprintf_chk: 4519 return optimizeSNPrintfChk(CI, Builder); 4520 case LibFunc_sprintf_chk: 4521 return optimizeSPrintfChk(CI, Builder); 4522 case LibFunc_strcat_chk: 4523 return optimizeStrCatChk(CI, Builder); 4524 case LibFunc_strlcat_chk: 4525 return optimizeStrLCat(CI, Builder); 4526 case LibFunc_strncat_chk: 4527 return optimizeStrNCatChk(CI, Builder); 4528 case LibFunc_strlcpy_chk: 4529 return optimizeStrLCpyChk(CI, Builder); 4530 case LibFunc_vsnprintf_chk: 4531 return optimizeVSNPrintfChk(CI, Builder); 4532 case LibFunc_vsprintf_chk: 4533 return optimizeVSPrintfChk(CI, Builder); 4534 default: 4535 break; 4536 } 4537 return nullptr; 4538 } 4539 4540 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 4541 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 4542 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 4543