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