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