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