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