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