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