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 = Pow->getCalledFunction()->getAttributes(); 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(n, x) -> exp2(log2(n) * x) 1567 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && Pow->hasNoInfs() && 1568 BaseF->isFiniteNonZero() && !BaseF->isNegative()) { 1569 Value *Log = nullptr; 1570 if (Ty->isFloatTy()) 1571 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat())); 1572 else if (Ty->isDoubleTy()) 1573 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble())); 1574 1575 if (Log) { 1576 Value *FMul = B.CreateFMul(Log, Expo, "mul"); 1577 if (Pow->doesNotAccessMemory()) 1578 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty), 1579 FMul, "exp2"); 1580 else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) 1581 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f, 1582 LibFunc_exp2l, B, Attrs); 1583 } 1584 } 1585 1586 return nullptr; 1587 } 1588 1589 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, 1590 Module *M, IRBuilderBase &B, 1591 const TargetLibraryInfo *TLI) { 1592 // If errno is never set, then use the intrinsic for sqrt(). 1593 if (NoErrno) { 1594 Function *SqrtFn = 1595 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType()); 1596 return B.CreateCall(SqrtFn, V, "sqrt"); 1597 } 1598 1599 // Otherwise, use the libcall for sqrt(). 1600 if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) 1601 // TODO: We also should check that the target can in fact lower the sqrt() 1602 // libcall. We currently have no way to ask this question, so we ask if 1603 // the target has a sqrt() libcall, which is not exactly the same. 1604 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf, 1605 LibFunc_sqrtl, B, Attrs); 1606 1607 return nullptr; 1608 } 1609 1610 /// Use square root in place of pow(x, +/-0.5). 1611 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) { 1612 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1613 AttributeList Attrs = Pow->getCalledFunction()->getAttributes(); 1614 Module *Mod = Pow->getModule(); 1615 Type *Ty = Pow->getType(); 1616 1617 const APFloat *ExpoF; 1618 if (!match(Expo, m_APFloat(ExpoF)) || 1619 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 1620 return nullptr; 1621 1622 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step, 1623 // so that requires fast-math-flags (afn or reassoc). 1624 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc())) 1625 return nullptr; 1626 1627 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI); 1628 if (!Sqrt) 1629 return nullptr; 1630 1631 // Handle signed zero base by expanding to fabs(sqrt(x)). 1632 if (!Pow->hasNoSignedZeros()) { 1633 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty); 1634 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs"); 1635 } 1636 1637 // Handle non finite base by expanding to 1638 // (x == -infinity ? +infinity : sqrt(x)). 1639 if (!Pow->hasNoInfs()) { 1640 Value *PosInf = ConstantFP::getInfinity(Ty), 1641 *NegInf = ConstantFP::getInfinity(Ty, true); 1642 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 1643 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 1644 } 1645 1646 // If the exponent is negative, then get the reciprocal. 1647 if (ExpoF->isNegative()) 1648 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 1649 1650 return Sqrt; 1651 } 1652 1653 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, 1654 IRBuilderBase &B) { 1655 Value *Args[] = {Base, Expo}; 1656 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType()); 1657 return B.CreateCall(F, Args); 1658 } 1659 1660 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) { 1661 Value *Base = Pow->getArgOperand(0); 1662 Value *Expo = Pow->getArgOperand(1); 1663 Function *Callee = Pow->getCalledFunction(); 1664 StringRef Name = Callee->getName(); 1665 Type *Ty = Pow->getType(); 1666 Module *M = Pow->getModule(); 1667 Value *Shrunk = nullptr; 1668 bool AllowApprox = Pow->hasApproxFunc(); 1669 bool Ignored; 1670 1671 // Propagate the math semantics from the call to any created instructions. 1672 IRBuilderBase::FastMathFlagGuard Guard(B); 1673 B.setFastMathFlags(Pow->getFastMathFlags()); 1674 1675 // Shrink pow() to powf() if the arguments are single precision, 1676 // unless the result is expected to be double precision. 1677 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) && 1678 hasFloatVersion(Name)) 1679 Shrunk = optimizeBinaryDoubleFP(Pow, B, true); 1680 1681 // Evaluate special cases related to the base. 1682 1683 // pow(1.0, x) -> 1.0 1684 if (match(Base, m_FPOne())) 1685 return Base; 1686 1687 if (Value *Exp = replacePowWithExp(Pow, B)) 1688 return Exp; 1689 1690 // Evaluate special cases related to the exponent. 1691 1692 // pow(x, -1.0) -> 1.0 / x 1693 if (match(Expo, m_SpecificFP(-1.0))) 1694 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 1695 1696 // pow(x, +/-0.0) -> 1.0 1697 if (match(Expo, m_AnyZeroFP())) 1698 return ConstantFP::get(Ty, 1.0); 1699 1700 // pow(x, 1.0) -> x 1701 if (match(Expo, m_FPOne())) 1702 return Base; 1703 1704 // pow(x, 2.0) -> x * x 1705 if (match(Expo, m_SpecificFP(2.0))) 1706 return B.CreateFMul(Base, Base, "square"); 1707 1708 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 1709 return Sqrt; 1710 1711 // pow(x, n) -> x * x * x * ... 1712 const APFloat *ExpoF; 1713 if (AllowApprox && match(Expo, m_APFloat(ExpoF))) { 1714 // We limit to a max of 7 multiplications, thus the maximum exponent is 32. 1715 // If the exponent is an integer+0.5 we generate a call to sqrt and an 1716 // additional fmul. 1717 // TODO: This whole transformation should be backend specific (e.g. some 1718 // backends might prefer libcalls or the limit for the exponent might 1719 // be different) and it should also consider optimizing for size. 1720 APFloat LimF(ExpoF->getSemantics(), 33), 1721 ExpoA(abs(*ExpoF)); 1722 if (ExpoA < LimF) { 1723 // This transformation applies to integer or integer+0.5 exponents only. 1724 // For integer+0.5, we create a sqrt(Base) call. 1725 Value *Sqrt = nullptr; 1726 if (!ExpoA.isInteger()) { 1727 APFloat Expo2 = ExpoA; 1728 // To check if ExpoA is an integer + 0.5, we add it to itself. If there 1729 // is no floating point exception and the result is an integer, then 1730 // ExpoA == integer + 0.5 1731 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK) 1732 return nullptr; 1733 1734 if (!Expo2.isInteger()) 1735 return nullptr; 1736 1737 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(), 1738 Pow->doesNotAccessMemory(), M, B, TLI); 1739 } 1740 1741 // We will memoize intermediate products of the Addition Chain. 1742 Value *InnerChain[33] = {nullptr}; 1743 InnerChain[1] = Base; 1744 InnerChain[2] = B.CreateFMul(Base, Base, "square"); 1745 1746 // We cannot readily convert a non-double type (like float) to a double. 1747 // So we first convert it to something which could be converted to double. 1748 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored); 1749 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B); 1750 1751 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x). 1752 if (Sqrt) 1753 FMul = B.CreateFMul(FMul, Sqrt); 1754 1755 // If the exponent is negative, then get the reciprocal. 1756 if (ExpoF->isNegative()) 1757 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal"); 1758 1759 return FMul; 1760 } 1761 1762 APSInt IntExpo(32, /*isUnsigned=*/false); 1763 // powf(x, n) -> powi(x, n) if n is a constant signed integer value 1764 if (ExpoF->isInteger() && 1765 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) == 1766 APFloat::opOK) { 1767 return createPowWithIntegerExponent( 1768 Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B); 1769 } 1770 } 1771 1772 // powf(x, itofp(y)) -> powi(x, y) 1773 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) { 1774 if (Value *ExpoI = getIntToFPVal(Expo, B)) 1775 return createPowWithIntegerExponent(Base, ExpoI, M, B); 1776 } 1777 1778 return Shrunk; 1779 } 1780 1781 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) { 1782 Function *Callee = CI->getCalledFunction(); 1783 StringRef Name = Callee->getName(); 1784 Value *Ret = nullptr; 1785 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) && 1786 hasFloatVersion(Name)) 1787 Ret = optimizeUnaryDoubleFP(CI, B, true); 1788 1789 Type *Ty = CI->getType(); 1790 Value *Op = CI->getArgOperand(0); 1791 1792 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32 1793 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32 1794 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) && 1795 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) { 1796 if (Value *Exp = getIntToFPVal(Op, B)) 1797 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI, 1798 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl, 1799 B, CI->getCalledFunction()->getAttributes()); 1800 } 1801 1802 return Ret; 1803 } 1804 1805 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) { 1806 // If we can shrink the call to a float function rather than a double 1807 // function, do that first. 1808 Function *Callee = CI->getCalledFunction(); 1809 StringRef Name = Callee->getName(); 1810 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name)) 1811 if (Value *Ret = optimizeBinaryDoubleFP(CI, B)) 1812 return Ret; 1813 1814 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to 1815 // the intrinsics for improved optimization (for example, vectorization). 1816 // No-signed-zeros is implied by the definitions of fmax/fmin themselves. 1817 // From the C standard draft WG14/N1256: 1818 // "Ideally, fmax would be sensitive to the sign of zero, for example 1819 // fmax(-0.0, +0.0) would return +0; however, implementation in software 1820 // might be impractical." 1821 IRBuilderBase::FastMathFlagGuard Guard(B); 1822 FastMathFlags FMF = CI->getFastMathFlags(); 1823 FMF.setNoSignedZeros(); 1824 B.setFastMathFlags(FMF); 1825 1826 Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum 1827 : Intrinsic::maxnum; 1828 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType()); 1829 return B.CreateCall(F, { CI->getArgOperand(0), CI->getArgOperand(1) }); 1830 } 1831 1832 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) { 1833 Function *LogFn = Log->getCalledFunction(); 1834 AttributeList Attrs = LogFn->getAttributes(); 1835 StringRef LogNm = LogFn->getName(); 1836 Intrinsic::ID LogID = LogFn->getIntrinsicID(); 1837 Module *Mod = Log->getModule(); 1838 Type *Ty = Log->getType(); 1839 Value *Ret = nullptr; 1840 1841 if (UnsafeFPShrink && hasFloatVersion(LogNm)) 1842 Ret = optimizeUnaryDoubleFP(Log, B, true); 1843 1844 // The earlier call must also be 'fast' in order to do these transforms. 1845 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0)); 1846 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse()) 1847 return Ret; 1848 1849 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb; 1850 1851 // This is only applicable to log(), log2(), log10(). 1852 if (TLI->getLibFunc(LogNm, LogLb)) 1853 switch (LogLb) { 1854 case LibFunc_logf: 1855 LogID = Intrinsic::log; 1856 ExpLb = LibFunc_expf; 1857 Exp2Lb = LibFunc_exp2f; 1858 Exp10Lb = LibFunc_exp10f; 1859 PowLb = LibFunc_powf; 1860 break; 1861 case LibFunc_log: 1862 LogID = Intrinsic::log; 1863 ExpLb = LibFunc_exp; 1864 Exp2Lb = LibFunc_exp2; 1865 Exp10Lb = LibFunc_exp10; 1866 PowLb = LibFunc_pow; 1867 break; 1868 case LibFunc_logl: 1869 LogID = Intrinsic::log; 1870 ExpLb = LibFunc_expl; 1871 Exp2Lb = LibFunc_exp2l; 1872 Exp10Lb = LibFunc_exp10l; 1873 PowLb = LibFunc_powl; 1874 break; 1875 case LibFunc_log2f: 1876 LogID = Intrinsic::log2; 1877 ExpLb = LibFunc_expf; 1878 Exp2Lb = LibFunc_exp2f; 1879 Exp10Lb = LibFunc_exp10f; 1880 PowLb = LibFunc_powf; 1881 break; 1882 case LibFunc_log2: 1883 LogID = Intrinsic::log2; 1884 ExpLb = LibFunc_exp; 1885 Exp2Lb = LibFunc_exp2; 1886 Exp10Lb = LibFunc_exp10; 1887 PowLb = LibFunc_pow; 1888 break; 1889 case LibFunc_log2l: 1890 LogID = Intrinsic::log2; 1891 ExpLb = LibFunc_expl; 1892 Exp2Lb = LibFunc_exp2l; 1893 Exp10Lb = LibFunc_exp10l; 1894 PowLb = LibFunc_powl; 1895 break; 1896 case LibFunc_log10f: 1897 LogID = Intrinsic::log10; 1898 ExpLb = LibFunc_expf; 1899 Exp2Lb = LibFunc_exp2f; 1900 Exp10Lb = LibFunc_exp10f; 1901 PowLb = LibFunc_powf; 1902 break; 1903 case LibFunc_log10: 1904 LogID = Intrinsic::log10; 1905 ExpLb = LibFunc_exp; 1906 Exp2Lb = LibFunc_exp2; 1907 Exp10Lb = LibFunc_exp10; 1908 PowLb = LibFunc_pow; 1909 break; 1910 case LibFunc_log10l: 1911 LogID = Intrinsic::log10; 1912 ExpLb = LibFunc_expl; 1913 Exp2Lb = LibFunc_exp2l; 1914 Exp10Lb = LibFunc_exp10l; 1915 PowLb = LibFunc_powl; 1916 break; 1917 default: 1918 return Ret; 1919 } 1920 else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 || 1921 LogID == Intrinsic::log10) { 1922 if (Ty->getScalarType()->isFloatTy()) { 1923 ExpLb = LibFunc_expf; 1924 Exp2Lb = LibFunc_exp2f; 1925 Exp10Lb = LibFunc_exp10f; 1926 PowLb = LibFunc_powf; 1927 } else if (Ty->getScalarType()->isDoubleTy()) { 1928 ExpLb = LibFunc_exp; 1929 Exp2Lb = LibFunc_exp2; 1930 Exp10Lb = LibFunc_exp10; 1931 PowLb = LibFunc_pow; 1932 } else 1933 return Ret; 1934 } else 1935 return Ret; 1936 1937 IRBuilderBase::FastMathFlagGuard Guard(B); 1938 B.setFastMathFlags(FastMathFlags::getFast()); 1939 1940 Intrinsic::ID ArgID = Arg->getIntrinsicID(); 1941 LibFunc ArgLb = NotLibFunc; 1942 TLI->getLibFunc(*Arg, ArgLb); 1943 1944 // log(pow(x,y)) -> y*log(x) 1945 if (ArgLb == PowLb || ArgID == Intrinsic::pow) { 1946 Value *LogX = 1947 Log->doesNotAccessMemory() 1948 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty), 1949 Arg->getOperand(0), "log") 1950 : emitUnaryFloatFnCall(Arg->getOperand(0), LogNm, B, Attrs); 1951 Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul"); 1952 // Since pow() may have side effects, e.g. errno, 1953 // dead code elimination may not be trusted to remove it. 1954 substituteInParent(Arg, MulY); 1955 return MulY; 1956 } 1957 1958 // log(exp{,2,10}(y)) -> y*log({e,2,10}) 1959 // TODO: There is no exp10() intrinsic yet. 1960 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb || 1961 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) { 1962 Constant *Eul; 1963 if (ArgLb == ExpLb || ArgID == Intrinsic::exp) 1964 // FIXME: Add more precise value of e for long double. 1965 Eul = ConstantFP::get(Log->getType(), numbers::e); 1966 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2) 1967 Eul = ConstantFP::get(Log->getType(), 2.0); 1968 else 1969 Eul = ConstantFP::get(Log->getType(), 10.0); 1970 Value *LogE = Log->doesNotAccessMemory() 1971 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty), 1972 Eul, "log") 1973 : emitUnaryFloatFnCall(Eul, LogNm, B, Attrs); 1974 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul"); 1975 // Since exp() may have side effects, e.g. errno, 1976 // dead code elimination may not be trusted to remove it. 1977 substituteInParent(Arg, MulY); 1978 return MulY; 1979 } 1980 1981 return Ret; 1982 } 1983 1984 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) { 1985 Function *Callee = CI->getCalledFunction(); 1986 Value *Ret = nullptr; 1987 // TODO: Once we have a way (other than checking for the existince of the 1988 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 1989 // condition below. 1990 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" || 1991 Callee->getIntrinsicID() == Intrinsic::sqrt)) 1992 Ret = optimizeUnaryDoubleFP(CI, B, true); 1993 1994 if (!CI->isFast()) 1995 return Ret; 1996 1997 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 1998 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 1999 return Ret; 2000 2001 // We're looking for a repeated factor in a multiplication tree, 2002 // so we can do this fold: sqrt(x * x) -> fabs(x); 2003 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 2004 Value *Op0 = I->getOperand(0); 2005 Value *Op1 = I->getOperand(1); 2006 Value *RepeatOp = nullptr; 2007 Value *OtherOp = nullptr; 2008 if (Op0 == Op1) { 2009 // Simple match: the operands of the multiply are identical. 2010 RepeatOp = Op0; 2011 } else { 2012 // Look for a more complicated pattern: one of the operands is itself 2013 // a multiply, so search for a common factor in that multiply. 2014 // Note: We don't bother looking any deeper than this first level or for 2015 // variations of this pattern because instcombine's visitFMUL and/or the 2016 // reassociation pass should give us this form. 2017 Value *OtherMul0, *OtherMul1; 2018 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 2019 // Pattern: sqrt((x * y) * z) 2020 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) { 2021 // Matched: sqrt((x * x) * z) 2022 RepeatOp = OtherMul0; 2023 OtherOp = Op1; 2024 } 2025 } 2026 } 2027 if (!RepeatOp) 2028 return Ret; 2029 2030 // Fast math flags for any created instructions should match the sqrt 2031 // and multiply. 2032 IRBuilderBase::FastMathFlagGuard Guard(B); 2033 B.setFastMathFlags(I->getFastMathFlags()); 2034 2035 // If we found a repeated factor, hoist it out of the square root and 2036 // replace it with the fabs of that factor. 2037 Module *M = Callee->getParent(); 2038 Type *ArgType = I->getType(); 2039 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType); 2040 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs"); 2041 if (OtherOp) { 2042 // If we found a non-repeated factor, we still need to get its square 2043 // root. We then multiply that by the value that was simplified out 2044 // of the square root calculation. 2045 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType); 2046 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt"); 2047 return B.CreateFMul(FabsCall, SqrtCall); 2048 } 2049 return FabsCall; 2050 } 2051 2052 // TODO: Generalize to handle any trig function and its inverse. 2053 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilderBase &B) { 2054 Function *Callee = CI->getCalledFunction(); 2055 Value *Ret = nullptr; 2056 StringRef Name = Callee->getName(); 2057 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name)) 2058 Ret = optimizeUnaryDoubleFP(CI, B, true); 2059 2060 Value *Op1 = CI->getArgOperand(0); 2061 auto *OpC = dyn_cast<CallInst>(Op1); 2062 if (!OpC) 2063 return Ret; 2064 2065 // Both calls must be 'fast' in order to remove them. 2066 if (!CI->isFast() || !OpC->isFast()) 2067 return Ret; 2068 2069 // tan(atan(x)) -> x 2070 // tanf(atanf(x)) -> x 2071 // tanl(atanl(x)) -> x 2072 LibFunc Func; 2073 Function *F = OpC->getCalledFunction(); 2074 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 2075 ((Func == LibFunc_atan && Callee->getName() == "tan") || 2076 (Func == LibFunc_atanf && Callee->getName() == "tanf") || 2077 (Func == LibFunc_atanl && Callee->getName() == "tanl"))) 2078 Ret = OpC->getArgOperand(0); 2079 return Ret; 2080 } 2081 2082 static bool isTrigLibCall(CallInst *CI) { 2083 // We can only hope to do anything useful if we can ignore things like errno 2084 // and floating-point exceptions. 2085 // We already checked the prototype. 2086 return CI->hasFnAttr(Attribute::NoUnwind) && 2087 CI->hasFnAttr(Attribute::ReadNone); 2088 } 2089 2090 static void insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, 2091 bool UseFloat, Value *&Sin, Value *&Cos, 2092 Value *&SinCos) { 2093 Type *ArgTy = Arg->getType(); 2094 Type *ResTy; 2095 StringRef Name; 2096 2097 Triple T(OrigCallee->getParent()->getTargetTriple()); 2098 if (UseFloat) { 2099 Name = "__sincospif_stret"; 2100 2101 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 2102 // x86_64 can't use {float, float} since that would be returned in both 2103 // xmm0 and xmm1, which isn't what a real struct would do. 2104 ResTy = T.getArch() == Triple::x86_64 2105 ? static_cast<Type *>(VectorType::get(ArgTy, 2)) 2106 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 2107 } else { 2108 Name = "__sincospi_stret"; 2109 ResTy = StructType::get(ArgTy, ArgTy); 2110 } 2111 2112 Module *M = OrigCallee->getParent(); 2113 FunctionCallee Callee = 2114 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy); 2115 2116 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 2117 // If the argument is an instruction, it must dominate all uses so put our 2118 // sincos call there. 2119 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 2120 } else { 2121 // Otherwise (e.g. for a constant) the beginning of the function is as 2122 // good a place as any. 2123 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 2124 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 2125 } 2126 2127 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 2128 2129 if (SinCos->getType()->isStructTy()) { 2130 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 2131 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 2132 } else { 2133 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 2134 "sinpi"); 2135 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 2136 "cospi"); 2137 } 2138 } 2139 2140 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilderBase &B) { 2141 // Make sure the prototype is as expected, otherwise the rest of the 2142 // function is probably invalid and likely to abort. 2143 if (!isTrigLibCall(CI)) 2144 return nullptr; 2145 2146 Value *Arg = CI->getArgOperand(0); 2147 SmallVector<CallInst *, 1> SinCalls; 2148 SmallVector<CallInst *, 1> CosCalls; 2149 SmallVector<CallInst *, 1> SinCosCalls; 2150 2151 bool IsFloat = Arg->getType()->isFloatTy(); 2152 2153 // Look for all compatible sinpi, cospi and sincospi calls with the same 2154 // argument. If there are enough (in some sense) we can make the 2155 // substitution. 2156 Function *F = CI->getFunction(); 2157 for (User *U : Arg->users()) 2158 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 2159 2160 // It's only worthwhile if both sinpi and cospi are actually used. 2161 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty())) 2162 return nullptr; 2163 2164 Value *Sin, *Cos, *SinCos; 2165 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos); 2166 2167 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 2168 Value *Res) { 2169 for (CallInst *C : Calls) 2170 replaceAllUsesWith(C, Res); 2171 }; 2172 2173 replaceTrigInsts(SinCalls, Sin); 2174 replaceTrigInsts(CosCalls, Cos); 2175 replaceTrigInsts(SinCosCalls, SinCos); 2176 2177 return nullptr; 2178 } 2179 2180 void LibCallSimplifier::classifyArgUse( 2181 Value *Val, Function *F, bool IsFloat, 2182 SmallVectorImpl<CallInst *> &SinCalls, 2183 SmallVectorImpl<CallInst *> &CosCalls, 2184 SmallVectorImpl<CallInst *> &SinCosCalls) { 2185 CallInst *CI = dyn_cast<CallInst>(Val); 2186 2187 if (!CI) 2188 return; 2189 2190 // Don't consider calls in other functions. 2191 if (CI->getFunction() != F) 2192 return; 2193 2194 Function *Callee = CI->getCalledFunction(); 2195 LibFunc Func; 2196 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) || 2197 !isTrigLibCall(CI)) 2198 return; 2199 2200 if (IsFloat) { 2201 if (Func == LibFunc_sinpif) 2202 SinCalls.push_back(CI); 2203 else if (Func == LibFunc_cospif) 2204 CosCalls.push_back(CI); 2205 else if (Func == LibFunc_sincospif_stret) 2206 SinCosCalls.push_back(CI); 2207 } else { 2208 if (Func == LibFunc_sinpi) 2209 SinCalls.push_back(CI); 2210 else if (Func == LibFunc_cospi) 2211 CosCalls.push_back(CI); 2212 else if (Func == LibFunc_sincospi_stret) 2213 SinCosCalls.push_back(CI); 2214 } 2215 } 2216 2217 //===----------------------------------------------------------------------===// 2218 // Integer Library Call Optimizations 2219 //===----------------------------------------------------------------------===// 2220 2221 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) { 2222 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 2223 Value *Op = CI->getArgOperand(0); 2224 Type *ArgType = Op->getType(); 2225 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 2226 Intrinsic::cttz, ArgType); 2227 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz"); 2228 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 2229 V = B.CreateIntCast(V, B.getInt32Ty(), false); 2230 2231 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 2232 return B.CreateSelect(Cond, V, B.getInt32(0)); 2233 } 2234 2235 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) { 2236 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false)) 2237 Value *Op = CI->getArgOperand(0); 2238 Type *ArgType = Op->getType(); 2239 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 2240 Intrinsic::ctlz, ArgType); 2241 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz"); 2242 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 2243 V); 2244 return B.CreateIntCast(V, CI->getType(), false); 2245 } 2246 2247 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) { 2248 // abs(x) -> x <s 0 ? -x : x 2249 // The negation has 'nsw' because abs of INT_MIN is undefined. 2250 Value *X = CI->getArgOperand(0); 2251 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType())); 2252 Value *NegX = B.CreateNSWNeg(X, "neg"); 2253 return B.CreateSelect(IsNeg, NegX, X); 2254 } 2255 2256 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) { 2257 // isdigit(c) -> (c-'0') <u 10 2258 Value *Op = CI->getArgOperand(0); 2259 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 2260 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 2261 return B.CreateZExt(Op, CI->getType()); 2262 } 2263 2264 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) { 2265 // isascii(c) -> c <u 128 2266 Value *Op = CI->getArgOperand(0); 2267 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 2268 return B.CreateZExt(Op, CI->getType()); 2269 } 2270 2271 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) { 2272 // toascii(c) -> c & 0x7f 2273 return B.CreateAnd(CI->getArgOperand(0), 2274 ConstantInt::get(CI->getType(), 0x7F)); 2275 } 2276 2277 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) { 2278 StringRef Str; 2279 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2280 return nullptr; 2281 2282 return convertStrToNumber(CI, Str, 10); 2283 } 2284 2285 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilderBase &B) { 2286 StringRef Str; 2287 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2288 return nullptr; 2289 2290 if (!isa<ConstantPointerNull>(CI->getArgOperand(1))) 2291 return nullptr; 2292 2293 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 2294 return convertStrToNumber(CI, Str, CInt->getSExtValue()); 2295 } 2296 2297 return nullptr; 2298 } 2299 2300 //===----------------------------------------------------------------------===// 2301 // Formatting and IO Library Call Optimizations 2302 //===----------------------------------------------------------------------===// 2303 2304 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 2305 2306 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B, 2307 int StreamArg) { 2308 Function *Callee = CI->getCalledFunction(); 2309 // Error reporting calls should be cold, mark them as such. 2310 // This applies even to non-builtin calls: it is only a hint and applies to 2311 // functions that the frontend might not understand as builtins. 2312 2313 // This heuristic was suggested in: 2314 // Improving Static Branch Prediction in a Compiler 2315 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 2316 // Proceedings of PACT'98, Oct. 1998, IEEE 2317 if (!CI->hasFnAttr(Attribute::Cold) && 2318 isReportingError(Callee, CI, StreamArg)) { 2319 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold); 2320 } 2321 2322 return nullptr; 2323 } 2324 2325 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 2326 if (!Callee || !Callee->isDeclaration()) 2327 return false; 2328 2329 if (StreamArg < 0) 2330 return true; 2331 2332 // These functions might be considered cold, but only if their stream 2333 // argument is stderr. 2334 2335 if (StreamArg >= (int)CI->getNumArgOperands()) 2336 return false; 2337 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 2338 if (!LI) 2339 return false; 2340 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 2341 if (!GV || !GV->isDeclaration()) 2342 return false; 2343 return GV->getName() == "stderr"; 2344 } 2345 2346 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) { 2347 // Check for a fixed format string. 2348 StringRef FormatStr; 2349 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 2350 return nullptr; 2351 2352 // Empty format string -> noop. 2353 if (FormatStr.empty()) // Tolerate printf's declared void. 2354 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 2355 2356 // Do not do any of the following transformations if the printf return value 2357 // is used, in general the printf return value is not compatible with either 2358 // putchar() or puts(). 2359 if (!CI->use_empty()) 2360 return nullptr; 2361 2362 // printf("x") -> putchar('x'), even for "%" and "%%". 2363 if (FormatStr.size() == 1 || FormatStr == "%%") 2364 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI); 2365 2366 // printf("%s", "a") --> putchar('a') 2367 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) { 2368 StringRef ChrStr; 2369 if (!getConstantStringInfo(CI->getOperand(1), ChrStr)) 2370 return nullptr; 2371 if (ChrStr.size() != 1) 2372 return nullptr; 2373 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI); 2374 } 2375 2376 // printf("foo\n") --> puts("foo") 2377 if (FormatStr[FormatStr.size() - 1] == '\n' && 2378 FormatStr.find('%') == StringRef::npos) { // No format characters. 2379 // Create a string literal with no \n on it. We expect the constant merge 2380 // pass to be run after this pass, to merge duplicate strings. 2381 FormatStr = FormatStr.drop_back(); 2382 Value *GV = B.CreateGlobalString(FormatStr, "str"); 2383 return emitPutS(GV, B, TLI); 2384 } 2385 2386 // Optimize specific format strings. 2387 // printf("%c", chr) --> putchar(chr) 2388 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 && 2389 CI->getArgOperand(1)->getType()->isIntegerTy()) 2390 return emitPutChar(CI->getArgOperand(1), B, TLI); 2391 2392 // printf("%s\n", str) --> puts(str) 2393 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 && 2394 CI->getArgOperand(1)->getType()->isPointerTy()) 2395 return emitPutS(CI->getArgOperand(1), B, TLI); 2396 return nullptr; 2397 } 2398 2399 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) { 2400 2401 Function *Callee = CI->getCalledFunction(); 2402 FunctionType *FT = Callee->getFunctionType(); 2403 if (Value *V = optimizePrintFString(CI, B)) { 2404 return V; 2405 } 2406 2407 // printf(format, ...) -> iprintf(format, ...) if no floating point 2408 // arguments. 2409 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) { 2410 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2411 FunctionCallee IPrintFFn = 2412 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes()); 2413 CallInst *New = cast<CallInst>(CI->clone()); 2414 New->setCalledFunction(IPrintFFn); 2415 B.Insert(New); 2416 return New; 2417 } 2418 2419 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point 2420 // arguments. 2421 if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) { 2422 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2423 auto SmallPrintFFn = 2424 M->getOrInsertFunction(TLI->getName(LibFunc_small_printf), 2425 FT, Callee->getAttributes()); 2426 CallInst *New = cast<CallInst>(CI->clone()); 2427 New->setCalledFunction(SmallPrintFFn); 2428 B.Insert(New); 2429 return New; 2430 } 2431 2432 annotateNonNullBasedOnAccess(CI, 0); 2433 return nullptr; 2434 } 2435 2436 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, 2437 IRBuilderBase &B) { 2438 // Check for a fixed format string. 2439 StringRef FormatStr; 2440 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2441 return nullptr; 2442 2443 // If we just have a format string (nothing else crazy) transform it. 2444 if (CI->getNumArgOperands() == 2) { 2445 // Make sure there's no % in the constant array. We could try to handle 2446 // %% -> % in the future if we cared. 2447 if (FormatStr.find('%') != StringRef::npos) 2448 return nullptr; // we found a format specifier, bail out. 2449 2450 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 2451 B.CreateMemCpy( 2452 CI->getArgOperand(0), Align(1), CI->getArgOperand(1), Align(1), 2453 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2454 FormatStr.size() + 1)); // Copy the null byte. 2455 return ConstantInt::get(CI->getType(), FormatStr.size()); 2456 } 2457 2458 // The remaining optimizations require the format string to be "%s" or "%c" 2459 // and have an extra operand. 2460 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 2461 CI->getNumArgOperands() < 3) 2462 return nullptr; 2463 2464 // Decode the second character of the format string. 2465 if (FormatStr[1] == 'c') { 2466 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2467 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2468 return nullptr; 2469 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 2470 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 2471 B.CreateStore(V, Ptr); 2472 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2473 B.CreateStore(B.getInt8(0), Ptr); 2474 2475 return ConstantInt::get(CI->getType(), 1); 2476 } 2477 2478 if (FormatStr[1] == 's') { 2479 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str, 2480 // strlen(str)+1) 2481 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2482 return nullptr; 2483 2484 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 2485 if (!Len) 2486 return nullptr; 2487 Value *IncLen = 2488 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 2489 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(2), 2490 Align(1), IncLen); 2491 2492 // The sprintf result is the unincremented number of bytes in the string. 2493 return B.CreateIntCast(Len, CI->getType(), false); 2494 } 2495 return nullptr; 2496 } 2497 2498 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) { 2499 Function *Callee = CI->getCalledFunction(); 2500 FunctionType *FT = Callee->getFunctionType(); 2501 if (Value *V = optimizeSPrintFString(CI, B)) { 2502 return V; 2503 } 2504 2505 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 2506 // point arguments. 2507 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) { 2508 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2509 FunctionCallee SIPrintFFn = 2510 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes()); 2511 CallInst *New = cast<CallInst>(CI->clone()); 2512 New->setCalledFunction(SIPrintFFn); 2513 B.Insert(New); 2514 return New; 2515 } 2516 2517 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit 2518 // floating point arguments. 2519 if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) { 2520 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2521 auto SmallSPrintFFn = 2522 M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf), 2523 FT, Callee->getAttributes()); 2524 CallInst *New = cast<CallInst>(CI->clone()); 2525 New->setCalledFunction(SmallSPrintFFn); 2526 B.Insert(New); 2527 return New; 2528 } 2529 2530 annotateNonNullBasedOnAccess(CI, {0, 1}); 2531 return nullptr; 2532 } 2533 2534 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, 2535 IRBuilderBase &B) { 2536 // Check for size 2537 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2538 if (!Size) 2539 return nullptr; 2540 2541 uint64_t N = Size->getZExtValue(); 2542 // Check for a fixed format string. 2543 StringRef FormatStr; 2544 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr)) 2545 return nullptr; 2546 2547 // If we just have a format string (nothing else crazy) transform it. 2548 if (CI->getNumArgOperands() == 3) { 2549 // Make sure there's no % in the constant array. We could try to handle 2550 // %% -> % in the future if we cared. 2551 if (FormatStr.find('%') != StringRef::npos) 2552 return nullptr; // we found a format specifier, bail out. 2553 2554 if (N == 0) 2555 return ConstantInt::get(CI->getType(), FormatStr.size()); 2556 else if (N < FormatStr.size() + 1) 2557 return nullptr; 2558 2559 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt, 2560 // strlen(fmt)+1) 2561 B.CreateMemCpy( 2562 CI->getArgOperand(0), Align(1), CI->getArgOperand(2), Align(1), 2563 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2564 FormatStr.size() + 1)); // Copy the null byte. 2565 return ConstantInt::get(CI->getType(), FormatStr.size()); 2566 } 2567 2568 // The remaining optimizations require the format string to be "%s" or "%c" 2569 // and have an extra operand. 2570 if (FormatStr.size() == 2 && FormatStr[0] == '%' && 2571 CI->getNumArgOperands() == 4) { 2572 2573 // Decode the second character of the format string. 2574 if (FormatStr[1] == 'c') { 2575 if (N == 0) 2576 return ConstantInt::get(CI->getType(), 1); 2577 else if (N == 1) 2578 return nullptr; 2579 2580 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2581 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 2582 return nullptr; 2583 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 2584 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 2585 B.CreateStore(V, Ptr); 2586 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2587 B.CreateStore(B.getInt8(0), Ptr); 2588 2589 return ConstantInt::get(CI->getType(), 1); 2590 } 2591 2592 if (FormatStr[1] == 's') { 2593 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 2594 StringRef Str; 2595 if (!getConstantStringInfo(CI->getArgOperand(3), Str)) 2596 return nullptr; 2597 2598 if (N == 0) 2599 return ConstantInt::get(CI->getType(), Str.size()); 2600 else if (N < Str.size() + 1) 2601 return nullptr; 2602 2603 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(3), 2604 Align(1), ConstantInt::get(CI->getType(), Str.size() + 1)); 2605 2606 // The snprintf result is the unincremented number of bytes in the string. 2607 return ConstantInt::get(CI->getType(), Str.size()); 2608 } 2609 } 2610 return nullptr; 2611 } 2612 2613 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) { 2614 if (Value *V = optimizeSnPrintFString(CI, B)) { 2615 return V; 2616 } 2617 2618 if (isKnownNonZero(CI->getOperand(1), DL)) 2619 annotateNonNullBasedOnAccess(CI, 0); 2620 return nullptr; 2621 } 2622 2623 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, 2624 IRBuilderBase &B) { 2625 optimizeErrorReporting(CI, B, 0); 2626 2627 // All the optimizations depend on the format string. 2628 StringRef FormatStr; 2629 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2630 return nullptr; 2631 2632 // Do not do any of the following transformations if the fprintf return 2633 // value is used, in general the fprintf return value is not compatible 2634 // with fwrite(), fputc() or fputs(). 2635 if (!CI->use_empty()) 2636 return nullptr; 2637 2638 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 2639 if (CI->getNumArgOperands() == 2) { 2640 // Could handle %% -> % if we cared. 2641 if (FormatStr.find('%') != StringRef::npos) 2642 return nullptr; // We found a format specifier. 2643 2644 return emitFWrite( 2645 CI->getArgOperand(1), 2646 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()), 2647 CI->getArgOperand(0), B, DL, TLI); 2648 } 2649 2650 // The remaining optimizations require the format string to be "%s" or "%c" 2651 // and have an extra operand. 2652 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 2653 CI->getNumArgOperands() < 3) 2654 return nullptr; 2655 2656 // Decode the second character of the format string. 2657 if (FormatStr[1] == 'c') { 2658 // fprintf(F, "%c", chr) --> fputc(chr, F) 2659 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2660 return nullptr; 2661 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 2662 } 2663 2664 if (FormatStr[1] == 's') { 2665 // fprintf(F, "%s", str) --> fputs(str, F) 2666 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2667 return nullptr; 2668 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 2669 } 2670 return nullptr; 2671 } 2672 2673 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) { 2674 Function *Callee = CI->getCalledFunction(); 2675 FunctionType *FT = Callee->getFunctionType(); 2676 if (Value *V = optimizeFPrintFString(CI, B)) { 2677 return V; 2678 } 2679 2680 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 2681 // floating point arguments. 2682 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) { 2683 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2684 FunctionCallee FIPrintFFn = 2685 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes()); 2686 CallInst *New = cast<CallInst>(CI->clone()); 2687 New->setCalledFunction(FIPrintFFn); 2688 B.Insert(New); 2689 return New; 2690 } 2691 2692 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no 2693 // 128-bit floating point arguments. 2694 if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) { 2695 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2696 auto SmallFPrintFFn = 2697 M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf), 2698 FT, Callee->getAttributes()); 2699 CallInst *New = cast<CallInst>(CI->clone()); 2700 New->setCalledFunction(SmallFPrintFFn); 2701 B.Insert(New); 2702 return New; 2703 } 2704 2705 return nullptr; 2706 } 2707 2708 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) { 2709 optimizeErrorReporting(CI, B, 3); 2710 2711 // Get the element size and count. 2712 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2713 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 2714 if (SizeC && CountC) { 2715 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 2716 2717 // If this is writing zero records, remove the call (it's a noop). 2718 if (Bytes == 0) 2719 return ConstantInt::get(CI->getType(), 0); 2720 2721 // If this is writing one byte, turn it into fputc. 2722 // This optimisation is only valid, if the return value is unused. 2723 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 2724 Value *Char = B.CreateLoad(B.getInt8Ty(), 2725 castToCStr(CI->getArgOperand(0), B), "char"); 2726 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI); 2727 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 2728 } 2729 } 2730 2731 return nullptr; 2732 } 2733 2734 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) { 2735 optimizeErrorReporting(CI, B, 1); 2736 2737 // Don't rewrite fputs to fwrite when optimising for size because fwrite 2738 // requires more arguments and thus extra MOVs are required. 2739 bool OptForSize = CI->getFunction()->hasOptSize() || 2740 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI, 2741 PGSOQueryType::IRPass); 2742 if (OptForSize) 2743 return nullptr; 2744 2745 // We can't optimize if return value is used. 2746 if (!CI->use_empty()) 2747 return nullptr; 2748 2749 // fputs(s,F) --> fwrite(s,strlen(s),1,F) 2750 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 2751 if (!Len) 2752 return nullptr; 2753 2754 // Known to have no uses (see above). 2755 return emitFWrite( 2756 CI->getArgOperand(0), 2757 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1), 2758 CI->getArgOperand(1), B, DL, TLI); 2759 } 2760 2761 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) { 2762 annotateNonNullBasedOnAccess(CI, 0); 2763 if (!CI->use_empty()) 2764 return nullptr; 2765 2766 // Check for a constant string. 2767 // puts("") -> putchar('\n') 2768 StringRef Str; 2769 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) 2770 return emitPutChar(B.getInt32('\n'), B, TLI); 2771 2772 return nullptr; 2773 } 2774 2775 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) { 2776 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) 2777 return B.CreateMemMove(CI->getArgOperand(1), Align(1), CI->getArgOperand(0), 2778 Align(1), CI->getArgOperand(2)); 2779 } 2780 2781 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) { 2782 LibFunc Func; 2783 SmallString<20> FloatFuncName = FuncName; 2784 FloatFuncName += 'f'; 2785 if (TLI->getLibFunc(FloatFuncName, Func)) 2786 return TLI->has(Func); 2787 return false; 2788 } 2789 2790 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 2791 IRBuilderBase &Builder) { 2792 LibFunc Func; 2793 Function *Callee = CI->getCalledFunction(); 2794 // Check for string/memory library functions. 2795 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 2796 // Make sure we never change the calling convention. 2797 assert((ignoreCallingConv(Func) || 2798 isCallingConvCCompatible(CI)) && 2799 "Optimizing string/memory libcall would change the calling convention"); 2800 switch (Func) { 2801 case LibFunc_strcat: 2802 return optimizeStrCat(CI, Builder); 2803 case LibFunc_strncat: 2804 return optimizeStrNCat(CI, Builder); 2805 case LibFunc_strchr: 2806 return optimizeStrChr(CI, Builder); 2807 case LibFunc_strrchr: 2808 return optimizeStrRChr(CI, Builder); 2809 case LibFunc_strcmp: 2810 return optimizeStrCmp(CI, Builder); 2811 case LibFunc_strncmp: 2812 return optimizeStrNCmp(CI, Builder); 2813 case LibFunc_strcpy: 2814 return optimizeStrCpy(CI, Builder); 2815 case LibFunc_stpcpy: 2816 return optimizeStpCpy(CI, Builder); 2817 case LibFunc_strncpy: 2818 return optimizeStrNCpy(CI, Builder); 2819 case LibFunc_strlen: 2820 return optimizeStrLen(CI, Builder); 2821 case LibFunc_strpbrk: 2822 return optimizeStrPBrk(CI, Builder); 2823 case LibFunc_strndup: 2824 return optimizeStrNDup(CI, Builder); 2825 case LibFunc_strtol: 2826 case LibFunc_strtod: 2827 case LibFunc_strtof: 2828 case LibFunc_strtoul: 2829 case LibFunc_strtoll: 2830 case LibFunc_strtold: 2831 case LibFunc_strtoull: 2832 return optimizeStrTo(CI, Builder); 2833 case LibFunc_strspn: 2834 return optimizeStrSpn(CI, Builder); 2835 case LibFunc_strcspn: 2836 return optimizeStrCSpn(CI, Builder); 2837 case LibFunc_strstr: 2838 return optimizeStrStr(CI, Builder); 2839 case LibFunc_memchr: 2840 return optimizeMemChr(CI, Builder); 2841 case LibFunc_memrchr: 2842 return optimizeMemRChr(CI, Builder); 2843 case LibFunc_bcmp: 2844 return optimizeBCmp(CI, Builder); 2845 case LibFunc_memcmp: 2846 return optimizeMemCmp(CI, Builder); 2847 case LibFunc_memcpy: 2848 return optimizeMemCpy(CI, Builder); 2849 case LibFunc_memccpy: 2850 return optimizeMemCCpy(CI, Builder); 2851 case LibFunc_mempcpy: 2852 return optimizeMemPCpy(CI, Builder); 2853 case LibFunc_memmove: 2854 return optimizeMemMove(CI, Builder); 2855 case LibFunc_memset: 2856 return optimizeMemSet(CI, Builder); 2857 case LibFunc_realloc: 2858 return optimizeRealloc(CI, Builder); 2859 case LibFunc_wcslen: 2860 return optimizeWcslen(CI, Builder); 2861 case LibFunc_bcopy: 2862 return optimizeBCopy(CI, Builder); 2863 default: 2864 break; 2865 } 2866 } 2867 return nullptr; 2868 } 2869 2870 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 2871 LibFunc Func, 2872 IRBuilderBase &Builder) { 2873 // Don't optimize calls that require strict floating point semantics. 2874 if (CI->isStrictFP()) 2875 return nullptr; 2876 2877 if (Value *V = optimizeTrigReflections(CI, Func, Builder)) 2878 return V; 2879 2880 switch (Func) { 2881 case LibFunc_sinpif: 2882 case LibFunc_sinpi: 2883 case LibFunc_cospif: 2884 case LibFunc_cospi: 2885 return optimizeSinCosPi(CI, Builder); 2886 case LibFunc_powf: 2887 case LibFunc_pow: 2888 case LibFunc_powl: 2889 return optimizePow(CI, Builder); 2890 case LibFunc_exp2l: 2891 case LibFunc_exp2: 2892 case LibFunc_exp2f: 2893 return optimizeExp2(CI, Builder); 2894 case LibFunc_fabsf: 2895 case LibFunc_fabs: 2896 case LibFunc_fabsl: 2897 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 2898 case LibFunc_sqrtf: 2899 case LibFunc_sqrt: 2900 case LibFunc_sqrtl: 2901 return optimizeSqrt(CI, Builder); 2902 case LibFunc_logf: 2903 case LibFunc_log: 2904 case LibFunc_logl: 2905 case LibFunc_log10f: 2906 case LibFunc_log10: 2907 case LibFunc_log10l: 2908 case LibFunc_log1pf: 2909 case LibFunc_log1p: 2910 case LibFunc_log1pl: 2911 case LibFunc_log2f: 2912 case LibFunc_log2: 2913 case LibFunc_log2l: 2914 case LibFunc_logbf: 2915 case LibFunc_logb: 2916 case LibFunc_logbl: 2917 return optimizeLog(CI, Builder); 2918 case LibFunc_tan: 2919 case LibFunc_tanf: 2920 case LibFunc_tanl: 2921 return optimizeTan(CI, Builder); 2922 case LibFunc_ceil: 2923 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 2924 case LibFunc_floor: 2925 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 2926 case LibFunc_round: 2927 return replaceUnaryCall(CI, Builder, Intrinsic::round); 2928 case LibFunc_nearbyint: 2929 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 2930 case LibFunc_rint: 2931 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 2932 case LibFunc_trunc: 2933 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 2934 case LibFunc_acos: 2935 case LibFunc_acosh: 2936 case LibFunc_asin: 2937 case LibFunc_asinh: 2938 case LibFunc_atan: 2939 case LibFunc_atanh: 2940 case LibFunc_cbrt: 2941 case LibFunc_cosh: 2942 case LibFunc_exp: 2943 case LibFunc_exp10: 2944 case LibFunc_expm1: 2945 case LibFunc_cos: 2946 case LibFunc_sin: 2947 case LibFunc_sinh: 2948 case LibFunc_tanh: 2949 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName())) 2950 return optimizeUnaryDoubleFP(CI, Builder, true); 2951 return nullptr; 2952 case LibFunc_copysign: 2953 if (hasFloatVersion(CI->getCalledFunction()->getName())) 2954 return optimizeBinaryDoubleFP(CI, Builder); 2955 return nullptr; 2956 case LibFunc_fminf: 2957 case LibFunc_fmin: 2958 case LibFunc_fminl: 2959 case LibFunc_fmaxf: 2960 case LibFunc_fmax: 2961 case LibFunc_fmaxl: 2962 return optimizeFMinFMax(CI, Builder); 2963 case LibFunc_cabs: 2964 case LibFunc_cabsf: 2965 case LibFunc_cabsl: 2966 return optimizeCAbs(CI, Builder); 2967 default: 2968 return nullptr; 2969 } 2970 } 2971 2972 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) { 2973 // TODO: Split out the code below that operates on FP calls so that 2974 // we can all non-FP calls with the StrictFP attribute to be 2975 // optimized. 2976 if (CI->isNoBuiltin()) 2977 return nullptr; 2978 2979 LibFunc Func; 2980 Function *Callee = CI->getCalledFunction(); 2981 bool isCallingConvC = isCallingConvCCompatible(CI); 2982 2983 SmallVector<OperandBundleDef, 2> OpBundles; 2984 CI->getOperandBundlesAsDefs(OpBundles); 2985 2986 IRBuilderBase::OperandBundlesGuard Guard(Builder); 2987 Builder.setDefaultOperandBundles(OpBundles); 2988 2989 // Command-line parameter overrides instruction attribute. 2990 // This can't be moved to optimizeFloatingPointLibCall() because it may be 2991 // used by the intrinsic optimizations. 2992 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 2993 UnsafeFPShrink = EnableUnsafeFPShrink; 2994 else if (isa<FPMathOperator>(CI) && CI->isFast()) 2995 UnsafeFPShrink = true; 2996 2997 // First, check for intrinsics. 2998 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 2999 if (!isCallingConvC) 3000 return nullptr; 3001 // The FP intrinsics have corresponding constrained versions so we don't 3002 // need to check for the StrictFP attribute here. 3003 switch (II->getIntrinsicID()) { 3004 case Intrinsic::pow: 3005 return optimizePow(CI, Builder); 3006 case Intrinsic::exp2: 3007 return optimizeExp2(CI, Builder); 3008 case Intrinsic::log: 3009 case Intrinsic::log2: 3010 case Intrinsic::log10: 3011 return optimizeLog(CI, Builder); 3012 case Intrinsic::sqrt: 3013 return optimizeSqrt(CI, Builder); 3014 // TODO: Use foldMallocMemset() with memset intrinsic. 3015 case Intrinsic::memset: 3016 return optimizeMemSet(CI, Builder); 3017 case Intrinsic::memcpy: 3018 return optimizeMemCpy(CI, Builder); 3019 case Intrinsic::memmove: 3020 return optimizeMemMove(CI, Builder); 3021 default: 3022 return nullptr; 3023 } 3024 } 3025 3026 // Also try to simplify calls to fortified library functions. 3027 if (Value *SimplifiedFortifiedCI = 3028 FortifiedSimplifier.optimizeCall(CI, Builder)) { 3029 // Try to further simplify the result. 3030 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 3031 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 3032 // Ensure that SimplifiedCI's uses are complete, since some calls have 3033 // their uses analyzed. 3034 replaceAllUsesWith(CI, SimplifiedCI); 3035 3036 // Set insertion point to SimplifiedCI to guarantee we reach all uses 3037 // we might replace later on. 3038 IRBuilderBase::InsertPointGuard Guard(Builder); 3039 Builder.SetInsertPoint(SimplifiedCI); 3040 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) { 3041 // If we were able to further simplify, remove the now redundant call. 3042 substituteInParent(SimplifiedCI, V); 3043 return V; 3044 } 3045 } 3046 return SimplifiedFortifiedCI; 3047 } 3048 3049 // Then check for known library functions. 3050 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 3051 // We never change the calling convention. 3052 if (!ignoreCallingConv(Func) && !isCallingConvC) 3053 return nullptr; 3054 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 3055 return V; 3056 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 3057 return V; 3058 switch (Func) { 3059 case LibFunc_ffs: 3060 case LibFunc_ffsl: 3061 case LibFunc_ffsll: 3062 return optimizeFFS(CI, Builder); 3063 case LibFunc_fls: 3064 case LibFunc_flsl: 3065 case LibFunc_flsll: 3066 return optimizeFls(CI, Builder); 3067 case LibFunc_abs: 3068 case LibFunc_labs: 3069 case LibFunc_llabs: 3070 return optimizeAbs(CI, Builder); 3071 case LibFunc_isdigit: 3072 return optimizeIsDigit(CI, Builder); 3073 case LibFunc_isascii: 3074 return optimizeIsAscii(CI, Builder); 3075 case LibFunc_toascii: 3076 return optimizeToAscii(CI, Builder); 3077 case LibFunc_atoi: 3078 case LibFunc_atol: 3079 case LibFunc_atoll: 3080 return optimizeAtoi(CI, Builder); 3081 case LibFunc_strtol: 3082 case LibFunc_strtoll: 3083 return optimizeStrtol(CI, Builder); 3084 case LibFunc_printf: 3085 return optimizePrintF(CI, Builder); 3086 case LibFunc_sprintf: 3087 return optimizeSPrintF(CI, Builder); 3088 case LibFunc_snprintf: 3089 return optimizeSnPrintF(CI, Builder); 3090 case LibFunc_fprintf: 3091 return optimizeFPrintF(CI, Builder); 3092 case LibFunc_fwrite: 3093 return optimizeFWrite(CI, Builder); 3094 case LibFunc_fputs: 3095 return optimizeFPuts(CI, Builder); 3096 case LibFunc_puts: 3097 return optimizePuts(CI, Builder); 3098 case LibFunc_perror: 3099 return optimizeErrorReporting(CI, Builder); 3100 case LibFunc_vfprintf: 3101 case LibFunc_fiprintf: 3102 return optimizeErrorReporting(CI, Builder, 0); 3103 default: 3104 return nullptr; 3105 } 3106 } 3107 return nullptr; 3108 } 3109 3110 LibCallSimplifier::LibCallSimplifier( 3111 const DataLayout &DL, const TargetLibraryInfo *TLI, 3112 OptimizationRemarkEmitter &ORE, 3113 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 3114 function_ref<void(Instruction *, Value *)> Replacer, 3115 function_ref<void(Instruction *)> Eraser) 3116 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI), 3117 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {} 3118 3119 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 3120 // Indirect through the replacer used in this instance. 3121 Replacer(I, With); 3122 } 3123 3124 void LibCallSimplifier::eraseFromParent(Instruction *I) { 3125 Eraser(I); 3126 } 3127 3128 // TODO: 3129 // Additional cases that we need to add to this file: 3130 // 3131 // cbrt: 3132 // * cbrt(expN(X)) -> expN(x/3) 3133 // * cbrt(sqrt(x)) -> pow(x,1/6) 3134 // * cbrt(cbrt(x)) -> pow(x,1/9) 3135 // 3136 // exp, expf, expl: 3137 // * exp(log(x)) -> x 3138 // 3139 // log, logf, logl: 3140 // * log(exp(x)) -> x 3141 // * log(exp(y)) -> y*log(e) 3142 // * log(exp10(y)) -> y*log(10) 3143 // * log(sqrt(x)) -> 0.5*log(x) 3144 // 3145 // pow, powf, powl: 3146 // * pow(sqrt(x),y) -> pow(x,y*0.5) 3147 // * pow(pow(x,y),z)-> pow(x,y*z) 3148 // 3149 // signbit: 3150 // * signbit(cnst) -> cnst' 3151 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 3152 // 3153 // sqrt, sqrtf, sqrtl: 3154 // * sqrt(expN(x)) -> expN(x*0.5) 3155 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 3156 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 3157 // 3158 3159 //===----------------------------------------------------------------------===// 3160 // Fortified Library Call Optimizations 3161 //===----------------------------------------------------------------------===// 3162 3163 bool 3164 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 3165 unsigned ObjSizeOp, 3166 Optional<unsigned> SizeOp, 3167 Optional<unsigned> StrOp, 3168 Optional<unsigned> FlagOp) { 3169 // If this function takes a flag argument, the implementation may use it to 3170 // perform extra checks. Don't fold into the non-checking variant. 3171 if (FlagOp) { 3172 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp)); 3173 if (!Flag || !Flag->isZero()) 3174 return false; 3175 } 3176 3177 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp)) 3178 return true; 3179 3180 if (ConstantInt *ObjSizeCI = 3181 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 3182 if (ObjSizeCI->isMinusOne()) 3183 return true; 3184 // If the object size wasn't -1 (unknown), bail out if we were asked to. 3185 if (OnlyLowerUnknownSize) 3186 return false; 3187 if (StrOp) { 3188 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp)); 3189 // If the length is 0 we don't know how long it is and so we can't 3190 // remove the check. 3191 if (Len) 3192 annotateDereferenceableBytes(CI, *StrOp, Len); 3193 else 3194 return false; 3195 return ObjSizeCI->getZExtValue() >= Len; 3196 } 3197 3198 if (SizeOp) { 3199 if (ConstantInt *SizeCI = 3200 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp))) 3201 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 3202 } 3203 } 3204 return false; 3205 } 3206 3207 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 3208 IRBuilderBase &B) { 3209 if (isFortifiedCallFoldable(CI, 3, 2)) { 3210 CallInst *NewCI = 3211 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 3212 Align(1), CI->getArgOperand(2)); 3213 NewCI->setAttributes(CI->getAttributes()); 3214 return CI->getArgOperand(0); 3215 } 3216 return nullptr; 3217 } 3218 3219 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 3220 IRBuilderBase &B) { 3221 if (isFortifiedCallFoldable(CI, 3, 2)) { 3222 CallInst *NewCI = 3223 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1), 3224 Align(1), CI->getArgOperand(2)); 3225 NewCI->setAttributes(CI->getAttributes()); 3226 return CI->getArgOperand(0); 3227 } 3228 return nullptr; 3229 } 3230 3231 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 3232 IRBuilderBase &B) { 3233 // TODO: Try foldMallocMemset() here. 3234 3235 if (isFortifiedCallFoldable(CI, 3, 2)) { 3236 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 3237 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, 3238 CI->getArgOperand(2), Align(1)); 3239 NewCI->setAttributes(CI->getAttributes()); 3240 return CI->getArgOperand(0); 3241 } 3242 return nullptr; 3243 } 3244 3245 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 3246 IRBuilderBase &B, 3247 LibFunc Func) { 3248 const DataLayout &DL = CI->getModule()->getDataLayout(); 3249 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 3250 *ObjSize = CI->getArgOperand(2); 3251 3252 // __stpcpy_chk(x,x,...) -> x+strlen(x) 3253 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 3254 Value *StrLen = emitStrLen(Src, B, DL, TLI); 3255 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 3256 } 3257 3258 // If a) we don't have any length information, or b) we know this will 3259 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 3260 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 3261 // TODO: It might be nice to get a maximum length out of the possible 3262 // string lengths for varying. 3263 if (isFortifiedCallFoldable(CI, 2, None, 1)) { 3264 if (Func == LibFunc_strcpy_chk) 3265 return emitStrCpy(Dst, Src, B, TLI); 3266 else 3267 return emitStpCpy(Dst, Src, B, TLI); 3268 } 3269 3270 if (OnlyLowerUnknownSize) 3271 return nullptr; 3272 3273 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 3274 uint64_t Len = GetStringLength(Src); 3275 if (Len) 3276 annotateDereferenceableBytes(CI, 1, Len); 3277 else 3278 return nullptr; 3279 3280 Type *SizeTTy = DL.getIntPtrType(CI->getContext()); 3281 Value *LenV = ConstantInt::get(SizeTTy, Len); 3282 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 3283 // If the function was an __stpcpy_chk, and we were able to fold it into 3284 // a __memcpy_chk, we still need to return the correct end pointer. 3285 if (Ret && Func == LibFunc_stpcpy_chk) 3286 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 3287 return Ret; 3288 } 3289 3290 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI, 3291 IRBuilderBase &B) { 3292 if (isFortifiedCallFoldable(CI, 1, None, 0)) 3293 return emitStrLen(CI->getArgOperand(0), B, CI->getModule()->getDataLayout(), 3294 TLI); 3295 return nullptr; 3296 } 3297 3298 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 3299 IRBuilderBase &B, 3300 LibFunc Func) { 3301 if (isFortifiedCallFoldable(CI, 3, 2)) { 3302 if (Func == LibFunc_strncpy_chk) 3303 return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3304 CI->getArgOperand(2), B, TLI); 3305 else 3306 return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3307 CI->getArgOperand(2), B, TLI); 3308 } 3309 3310 return nullptr; 3311 } 3312 3313 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI, 3314 IRBuilderBase &B) { 3315 if (isFortifiedCallFoldable(CI, 4, 3)) 3316 return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3317 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI); 3318 3319 return nullptr; 3320 } 3321 3322 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI, 3323 IRBuilderBase &B) { 3324 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) { 3325 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end()); 3326 return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3327 CI->getArgOperand(4), VariadicArgs, B, TLI); 3328 } 3329 3330 return nullptr; 3331 } 3332 3333 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI, 3334 IRBuilderBase &B) { 3335 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) { 3336 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end()); 3337 return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs, 3338 B, TLI); 3339 } 3340 3341 return nullptr; 3342 } 3343 3344 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI, 3345 IRBuilderBase &B) { 3346 if (isFortifiedCallFoldable(CI, 2)) 3347 return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI); 3348 3349 return nullptr; 3350 } 3351 3352 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI, 3353 IRBuilderBase &B) { 3354 if (isFortifiedCallFoldable(CI, 3)) 3355 return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1), 3356 CI->getArgOperand(2), B, TLI); 3357 3358 return nullptr; 3359 } 3360 3361 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI, 3362 IRBuilderBase &B) { 3363 if (isFortifiedCallFoldable(CI, 3)) 3364 return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1), 3365 CI->getArgOperand(2), B, TLI); 3366 3367 return nullptr; 3368 } 3369 3370 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI, 3371 IRBuilderBase &B) { 3372 if (isFortifiedCallFoldable(CI, 3)) 3373 return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1), 3374 CI->getArgOperand(2), B, TLI); 3375 3376 return nullptr; 3377 } 3378 3379 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI, 3380 IRBuilderBase &B) { 3381 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) 3382 return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1), 3383 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI); 3384 3385 return nullptr; 3386 } 3387 3388 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI, 3389 IRBuilderBase &B) { 3390 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) 3391 return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), 3392 CI->getArgOperand(4), B, TLI); 3393 3394 return nullptr; 3395 } 3396 3397 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI, 3398 IRBuilderBase &Builder) { 3399 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 3400 // Some clang users checked for _chk libcall availability using: 3401 // __has_builtin(__builtin___memcpy_chk) 3402 // When compiling with -fno-builtin, this is always true. 3403 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 3404 // end up with fortified libcalls, which isn't acceptable in a freestanding 3405 // environment which only provides their non-fortified counterparts. 3406 // 3407 // Until we change clang and/or teach external users to check for availability 3408 // differently, disregard the "nobuiltin" attribute and TLI::has. 3409 // 3410 // PR23093. 3411 3412 LibFunc Func; 3413 Function *Callee = CI->getCalledFunction(); 3414 bool isCallingConvC = isCallingConvCCompatible(CI); 3415 3416 SmallVector<OperandBundleDef, 2> OpBundles; 3417 CI->getOperandBundlesAsDefs(OpBundles); 3418 3419 IRBuilderBase::OperandBundlesGuard Guard(Builder); 3420 Builder.setDefaultOperandBundles(OpBundles); 3421 3422 // First, check that this is a known library functions and that the prototype 3423 // is correct. 3424 if (!TLI->getLibFunc(*Callee, Func)) 3425 return nullptr; 3426 3427 // We never change the calling convention. 3428 if (!ignoreCallingConv(Func) && !isCallingConvC) 3429 return nullptr; 3430 3431 switch (Func) { 3432 case LibFunc_memcpy_chk: 3433 return optimizeMemCpyChk(CI, Builder); 3434 case LibFunc_memmove_chk: 3435 return optimizeMemMoveChk(CI, Builder); 3436 case LibFunc_memset_chk: 3437 return optimizeMemSetChk(CI, Builder); 3438 case LibFunc_stpcpy_chk: 3439 case LibFunc_strcpy_chk: 3440 return optimizeStrpCpyChk(CI, Builder, Func); 3441 case LibFunc_strlen_chk: 3442 return optimizeStrLenChk(CI, Builder); 3443 case LibFunc_stpncpy_chk: 3444 case LibFunc_strncpy_chk: 3445 return optimizeStrpNCpyChk(CI, Builder, Func); 3446 case LibFunc_memccpy_chk: 3447 return optimizeMemCCpyChk(CI, Builder); 3448 case LibFunc_snprintf_chk: 3449 return optimizeSNPrintfChk(CI, Builder); 3450 case LibFunc_sprintf_chk: 3451 return optimizeSPrintfChk(CI, Builder); 3452 case LibFunc_strcat_chk: 3453 return optimizeStrCatChk(CI, Builder); 3454 case LibFunc_strlcat_chk: 3455 return optimizeStrLCat(CI, Builder); 3456 case LibFunc_strncat_chk: 3457 return optimizeStrNCatChk(CI, Builder); 3458 case LibFunc_strlcpy_chk: 3459 return optimizeStrLCpyChk(CI, Builder); 3460 case LibFunc_vsnprintf_chk: 3461 return optimizeVSNPrintfChk(CI, Builder); 3462 case LibFunc_vsprintf_chk: 3463 return optimizeVSPrintfChk(CI, Builder); 3464 default: 3465 break; 3466 } 3467 return nullptr; 3468 } 3469 3470 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 3471 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 3472 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 3473