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