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