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