1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the library calls simplifier. It does not implement 11 // any pass, but can't be used by other passes to do simplifications. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Analysis/ConstantFolding.h" 20 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Transforms/Utils/Local.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/Analysis/CaptureTracking.h" 25 #include "llvm/Analysis/Loads.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/Intrinsics.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/PatternMatch.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/KnownBits.h" 36 #include "llvm/Transforms/Utils/BuildLibCalls.h" 37 38 using namespace llvm; 39 using namespace PatternMatch; 40 41 static cl::opt<bool> 42 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, 43 cl::init(false), 44 cl::desc("Enable unsafe double to float " 45 "shrinking for math lib calls")); 46 47 48 //===----------------------------------------------------------------------===// 49 // Helper Functions 50 //===----------------------------------------------------------------------===// 51 52 static bool ignoreCallingConv(LibFunc Func) { 53 return Func == LibFunc_abs || Func == LibFunc_labs || 54 Func == LibFunc_llabs || Func == LibFunc_strlen; 55 } 56 57 static bool isCallingConvCCompatible(CallInst *CI) { 58 switch(CI->getCallingConv()) { 59 default: 60 return false; 61 case llvm::CallingConv::C: 62 return true; 63 case llvm::CallingConv::ARM_APCS: 64 case llvm::CallingConv::ARM_AAPCS: 65 case llvm::CallingConv::ARM_AAPCS_VFP: { 66 67 // The iOS ABI diverges from the standard in some cases, so for now don't 68 // try to simplify those calls. 69 if (Triple(CI->getModule()->getTargetTriple()).isiOS()) 70 return false; 71 72 auto *FuncTy = CI->getFunctionType(); 73 74 if (!FuncTy->getReturnType()->isPointerTy() && 75 !FuncTy->getReturnType()->isIntegerTy() && 76 !FuncTy->getReturnType()->isVoidTy()) 77 return false; 78 79 for (auto Param : FuncTy->params()) { 80 if (!Param->isPointerTy() && !Param->isIntegerTy()) 81 return false; 82 } 83 return true; 84 } 85 } 86 return false; 87 } 88 89 /// Return true if it is only used in equality comparisons with With. 90 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) { 91 for (User *U : V->users()) { 92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 93 if (IC->isEquality() && IC->getOperand(1) == With) 94 continue; 95 // Unknown instruction. 96 return false; 97 } 98 return true; 99 } 100 101 static bool callHasFloatingPointArgument(const CallInst *CI) { 102 return any_of(CI->operands(), [](const Use &OI) { 103 return OI->getType()->isFloatingPointTy(); 104 }); 105 } 106 107 static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) { 108 if (Base < 2 || Base > 36) 109 // handle special zero base 110 if (Base != 0) 111 return nullptr; 112 113 char *End; 114 std::string nptr = Str.str(); 115 errno = 0; 116 long long int Result = strtoll(nptr.c_str(), &End, Base); 117 if (errno) 118 return nullptr; 119 120 // if we assume all possible target locales are ASCII supersets, 121 // then if strtoll successfully parses a number on the host, 122 // it will also successfully parse the same way on the target 123 if (*End != '\0') 124 return nullptr; 125 126 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result)) 127 return nullptr; 128 129 return ConstantInt::get(CI->getType(), Result); 130 } 131 132 static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B, 133 const TargetLibraryInfo *TLI) { 134 CallInst *FOpen = dyn_cast<CallInst>(File); 135 if (!FOpen) 136 return false; 137 138 Function *InnerCallee = FOpen->getCalledFunction(); 139 if (!InnerCallee) 140 return false; 141 142 LibFunc Func; 143 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) || 144 Func != LibFunc_fopen) 145 return false; 146 147 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI); 148 if (PointerMayBeCaptured(File, true, true)) 149 return false; 150 151 return true; 152 } 153 154 static bool isOnlyUsedInComparisonWithZero(Value *V) { 155 for (User *U : V->users()) { 156 if (ICmpInst *IC = dyn_cast<ICmpInst>(U)) 157 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 158 if (C->isNullValue()) 159 continue; 160 // Unknown instruction. 161 return false; 162 } 163 return true; 164 } 165 166 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, 167 const DataLayout &DL) { 168 if (!isOnlyUsedInComparisonWithZero(CI)) 169 return false; 170 171 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL)) 172 return false; 173 174 return true; 175 } 176 177 //===----------------------------------------------------------------------===// 178 // String and Memory Library Call Optimizations 179 //===----------------------------------------------------------------------===// 180 181 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) { 182 // Extract some information from the instruction 183 Value *Dst = CI->getArgOperand(0); 184 Value *Src = CI->getArgOperand(1); 185 186 // See if we can get the length of the input string. 187 uint64_t Len = GetStringLength(Src); 188 if (Len == 0) 189 return nullptr; 190 --Len; // Unbias length. 191 192 // Handle the simple, do-nothing case: strcat(x, "") -> x 193 if (Len == 0) 194 return Dst; 195 196 return emitStrLenMemCpy(Src, Dst, Len, B); 197 } 198 199 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, 200 IRBuilder<> &B) { 201 // We need to find the end of the destination string. That's where the 202 // memory is to be moved to. We just generate a call to strlen. 203 Value *DstLen = emitStrLen(Dst, B, DL, TLI); 204 if (!DstLen) 205 return nullptr; 206 207 // Now that we have the destination's length, we must index into the 208 // destination's pointer to get the actual memcpy destination (end of 209 // the string .. we're concatenating). 210 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr"); 211 212 // We have enough information to now generate the memcpy call to do the 213 // concatenation for us. Make a memcpy to copy the nul byte with align = 1. 214 B.CreateMemCpy(CpyDst, 1, Src, 1, 215 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1)); 216 return Dst; 217 } 218 219 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) { 220 // Extract some information from the instruction. 221 Value *Dst = CI->getArgOperand(0); 222 Value *Src = CI->getArgOperand(1); 223 uint64_t Len; 224 225 // We don't do anything if length is not constant. 226 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2))) 227 Len = LengthArg->getZExtValue(); 228 else 229 return nullptr; 230 231 // See if we can get the length of the input string. 232 uint64_t SrcLen = GetStringLength(Src); 233 if (SrcLen == 0) 234 return nullptr; 235 --SrcLen; // Unbias length. 236 237 // Handle the simple, do-nothing cases: 238 // strncat(x, "", c) -> x 239 // strncat(x, c, 0) -> x 240 if (SrcLen == 0 || Len == 0) 241 return Dst; 242 243 // We don't optimize this case. 244 if (Len < SrcLen) 245 return nullptr; 246 247 // strncat(x, s, c) -> strcat(x, s) 248 // s is constant so the strcat can be optimized further. 249 return emitStrLenMemCpy(Src, Dst, SrcLen, B); 250 } 251 252 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) { 253 Function *Callee = CI->getCalledFunction(); 254 FunctionType *FT = Callee->getFunctionType(); 255 Value *SrcStr = CI->getArgOperand(0); 256 257 // If the second operand is non-constant, see if we can compute the length 258 // of the input string and turn this into memchr. 259 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 260 if (!CharC) { 261 uint64_t Len = GetStringLength(SrcStr); 262 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32. 263 return nullptr; 264 265 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul. 266 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 267 B, DL, TLI); 268 } 269 270 // Otherwise, the character is a constant, see if the first argument is 271 // a string literal. If so, we can constant fold. 272 StringRef Str; 273 if (!getConstantStringInfo(SrcStr, Str)) { 274 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) 275 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI), 276 "strchr"); 277 return nullptr; 278 } 279 280 // Compute the offset, make sure to handle the case when we're searching for 281 // zero (a weird way to spell strlen). 282 size_t I = (0xFF & CharC->getSExtValue()) == 0 283 ? Str.size() 284 : Str.find(CharC->getSExtValue()); 285 if (I == StringRef::npos) // Didn't find the char. strchr returns null. 286 return Constant::getNullValue(CI->getType()); 287 288 // strchr(s+n,c) -> gep(s+n+i,c) 289 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr"); 290 } 291 292 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) { 293 Value *SrcStr = CI->getArgOperand(0); 294 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 295 296 // Cannot fold anything if we're not looking for a constant. 297 if (!CharC) 298 return nullptr; 299 300 StringRef Str; 301 if (!getConstantStringInfo(SrcStr, Str)) { 302 // strrchr(s, 0) -> strchr(s, 0) 303 if (CharC->isZero()) 304 return emitStrChr(SrcStr, '\0', B, TLI); 305 return nullptr; 306 } 307 308 // Compute the offset. 309 size_t I = (0xFF & CharC->getSExtValue()) == 0 310 ? Str.size() 311 : Str.rfind(CharC->getSExtValue()); 312 if (I == StringRef::npos) // Didn't find the char. Return null. 313 return Constant::getNullValue(CI->getType()); 314 315 // strrchr(s+n,c) -> gep(s+n+i,c) 316 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr"); 317 } 318 319 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) { 320 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 321 if (Str1P == Str2P) // strcmp(x,x) -> 0 322 return ConstantInt::get(CI->getType(), 0); 323 324 StringRef Str1, Str2; 325 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 326 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 327 328 // strcmp(x, y) -> cnst (if both x and y are constant strings) 329 if (HasStr1 && HasStr2) 330 return ConstantInt::get(CI->getType(), Str1.compare(Str2)); 331 332 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x 333 return B.CreateNeg( 334 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType())); 335 336 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x 337 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 338 339 // strcmp(P, "x") -> memcmp(P, "x", 2) 340 uint64_t Len1 = GetStringLength(Str1P); 341 uint64_t Len2 = GetStringLength(Str2P); 342 if (Len1 && Len2) { 343 return emitMemCmp(Str1P, Str2P, 344 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 345 std::min(Len1, Len2)), 346 B, DL, TLI); 347 } 348 349 // strcmp to memcmp 350 if (!HasStr1 && HasStr2) { 351 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 352 return emitMemCmp( 353 Str1P, Str2P, 354 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL, 355 TLI); 356 } else if (HasStr1 && !HasStr2) { 357 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 358 return emitMemCmp( 359 Str1P, Str2P, 360 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL, 361 TLI); 362 } 363 364 return nullptr; 365 } 366 367 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) { 368 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1); 369 if (Str1P == Str2P) // strncmp(x,x,n) -> 0 370 return ConstantInt::get(CI->getType(), 0); 371 372 // Get the length argument if it is constant. 373 uint64_t Length; 374 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2))) 375 Length = LengthArg->getZExtValue(); 376 else 377 return nullptr; 378 379 if (Length == 0) // strncmp(x,y,0) -> 0 380 return ConstantInt::get(CI->getType(), 0); 381 382 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1) 383 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI); 384 385 StringRef Str1, Str2; 386 bool HasStr1 = getConstantStringInfo(Str1P, Str1); 387 bool HasStr2 = getConstantStringInfo(Str2P, Str2); 388 389 // strncmp(x, y) -> cnst (if both x and y are constant strings) 390 if (HasStr1 && HasStr2) { 391 StringRef SubStr1 = Str1.substr(0, Length); 392 StringRef SubStr2 = Str2.substr(0, Length); 393 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2)); 394 } 395 396 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x 397 return B.CreateNeg( 398 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType())); 399 400 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x 401 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType()); 402 403 uint64_t Len1 = GetStringLength(Str1P); 404 uint64_t Len2 = GetStringLength(Str2P); 405 406 // strncmp to memcmp 407 if (!HasStr1 && HasStr2) { 408 Len2 = std::min(Len2, Length); 409 if (canTransformToMemCmp(CI, Str1P, Len2, DL)) 410 return emitMemCmp( 411 Str1P, Str2P, 412 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL, 413 TLI); 414 } else if (HasStr1 && !HasStr2) { 415 Len1 = std::min(Len1, Length); 416 if (canTransformToMemCmp(CI, Str2P, Len1, DL)) 417 return emitMemCmp( 418 Str1P, Str2P, 419 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL, 420 TLI); 421 } 422 423 return nullptr; 424 } 425 426 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) { 427 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 428 if (Dst == Src) // strcpy(x,x) -> x 429 return Src; 430 431 // See if we can get the length of the input string. 432 uint64_t Len = GetStringLength(Src); 433 if (Len == 0) 434 return nullptr; 435 436 // We have enough information to now generate the memcpy call to do the 437 // copy for us. Make a memcpy to copy the nul byte with align = 1. 438 B.CreateMemCpy(Dst, 1, Src, 1, 439 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len)); 440 return Dst; 441 } 442 443 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) { 444 Function *Callee = CI->getCalledFunction(); 445 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1); 446 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x) 447 Value *StrLen = emitStrLen(Src, B, DL, TLI); 448 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 449 } 450 451 // See if we can get the length of the input string. 452 uint64_t Len = GetStringLength(Src); 453 if (Len == 0) 454 return nullptr; 455 456 Type *PT = Callee->getFunctionType()->getParamType(0); 457 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len); 458 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst, 459 ConstantInt::get(DL.getIntPtrType(PT), Len - 1)); 460 461 // We have enough information to now generate the memcpy call to do the 462 // copy for us. Make a memcpy to copy the nul byte with align = 1. 463 B.CreateMemCpy(Dst, 1, Src, 1, LenV); 464 return DstEnd; 465 } 466 467 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) { 468 Function *Callee = CI->getCalledFunction(); 469 Value *Dst = CI->getArgOperand(0); 470 Value *Src = CI->getArgOperand(1); 471 Value *LenOp = CI->getArgOperand(2); 472 473 // See if we can get the length of the input string. 474 uint64_t SrcLen = GetStringLength(Src); 475 if (SrcLen == 0) 476 return nullptr; 477 --SrcLen; 478 479 if (SrcLen == 0) { 480 // strncpy(x, "", y) -> memset(align 1 x, '\0', y) 481 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1); 482 return Dst; 483 } 484 485 uint64_t Len; 486 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp)) 487 Len = LengthArg->getZExtValue(); 488 else 489 return nullptr; 490 491 if (Len == 0) 492 return Dst; // strncpy(x, y, 0) -> x 493 494 // Let strncpy handle the zero padding 495 if (Len > SrcLen + 1) 496 return nullptr; 497 498 Type *PT = Callee->getFunctionType()->getParamType(0); 499 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant] 500 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len)); 501 502 return Dst; 503 } 504 505 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B, 506 unsigned CharSize) { 507 Value *Src = CI->getArgOperand(0); 508 509 // Constant folding: strlen("xyz") -> 3 510 if (uint64_t Len = GetStringLength(Src, CharSize)) 511 return ConstantInt::get(CI->getType(), Len - 1); 512 513 // If s is a constant pointer pointing to a string literal, we can fold 514 // strlen(s + x) to strlen(s) - x, when x is known to be in the range 515 // [0, strlen(s)] or the string has a single null terminator '\0' at the end. 516 // We only try to simplify strlen when the pointer s points to an array 517 // of i8. Otherwise, we would need to scale the offset x before doing the 518 // subtraction. This will make the optimization more complex, and it's not 519 // very useful because calling strlen for a pointer of other types is 520 // very uncommon. 521 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) { 522 if (!isGEPBasedOnPointerToString(GEP, CharSize)) 523 return nullptr; 524 525 ConstantDataArraySlice Slice; 526 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) { 527 uint64_t NullTermIdx; 528 if (Slice.Array == nullptr) { 529 NullTermIdx = 0; 530 } else { 531 NullTermIdx = ~((uint64_t)0); 532 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) { 533 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) { 534 NullTermIdx = I; 535 break; 536 } 537 } 538 // If the string does not have '\0', leave it to strlen to compute 539 // its length. 540 if (NullTermIdx == ~((uint64_t)0)) 541 return nullptr; 542 } 543 544 Value *Offset = GEP->getOperand(2); 545 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr); 546 Known.Zero.flipAllBits(); 547 uint64_t ArrSize = 548 cast<ArrayType>(GEP->getSourceElementType())->getNumElements(); 549 550 // KnownZero's bits are flipped, so zeros in KnownZero now represent 551 // bits known to be zeros in Offset, and ones in KnowZero represent 552 // bits unknown in Offset. Therefore, Offset is known to be in range 553 // [0, NullTermIdx] when the flipped KnownZero is non-negative and 554 // unsigned-less-than NullTermIdx. 555 // 556 // If Offset is not provably in the range [0, NullTermIdx], we can still 557 // optimize if we can prove that the program has undefined behavior when 558 // Offset is outside that range. That is the case when GEP->getOperand(0) 559 // is a pointer to an object whose memory extent is NullTermIdx+1. 560 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) || 561 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) && 562 NullTermIdx == ArrSize - 1)) { 563 Offset = B.CreateSExtOrTrunc(Offset, CI->getType()); 564 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx), 565 Offset); 566 } 567 } 568 569 return nullptr; 570 } 571 572 // strlen(x?"foo":"bars") --> x ? 3 : 4 573 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) { 574 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize); 575 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize); 576 if (LenTrue && LenFalse) { 577 ORE.emit([&]() { 578 return OptimizationRemark("instcombine", "simplify-libcalls", CI) 579 << "folded strlen(select) to select of constants"; 580 }); 581 return B.CreateSelect(SI->getCondition(), 582 ConstantInt::get(CI->getType(), LenTrue - 1), 583 ConstantInt::get(CI->getType(), LenFalse - 1)); 584 } 585 } 586 587 // strlen(x) != 0 --> *x != 0 588 // strlen(x) == 0 --> *x == 0 589 if (isOnlyUsedInZeroEqualityComparison(CI)) 590 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType()); 591 592 return nullptr; 593 } 594 595 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) { 596 return optimizeStringLength(CI, B, 8); 597 } 598 599 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) { 600 Module &M = *CI->getModule(); 601 unsigned WCharSize = TLI->getWCharSize(M) * 8; 602 // We cannot perform this optimization without wchar_size metadata. 603 if (WCharSize == 0) 604 return nullptr; 605 606 return optimizeStringLength(CI, B, WCharSize); 607 } 608 609 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) { 610 StringRef S1, S2; 611 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 612 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 613 614 // strpbrk(s, "") -> nullptr 615 // strpbrk("", s) -> nullptr 616 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 617 return Constant::getNullValue(CI->getType()); 618 619 // Constant folding. 620 if (HasS1 && HasS2) { 621 size_t I = S1.find_first_of(S2); 622 if (I == StringRef::npos) // No match. 623 return Constant::getNullValue(CI->getType()); 624 625 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), 626 "strpbrk"); 627 } 628 629 // strpbrk(s, "a") -> strchr(s, 'a') 630 if (HasS2 && S2.size() == 1) 631 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI); 632 633 return nullptr; 634 } 635 636 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) { 637 Value *EndPtr = CI->getArgOperand(1); 638 if (isa<ConstantPointerNull>(EndPtr)) { 639 // With a null EndPtr, this function won't capture the main argument. 640 // It would be readonly too, except that it still may write to errno. 641 CI->addParamAttr(0, Attribute::NoCapture); 642 } 643 644 return nullptr; 645 } 646 647 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) { 648 StringRef S1, S2; 649 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 650 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 651 652 // strspn(s, "") -> 0 653 // strspn("", s) -> 0 654 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty())) 655 return Constant::getNullValue(CI->getType()); 656 657 // Constant folding. 658 if (HasS1 && HasS2) { 659 size_t Pos = S1.find_first_not_of(S2); 660 if (Pos == StringRef::npos) 661 Pos = S1.size(); 662 return ConstantInt::get(CI->getType(), Pos); 663 } 664 665 return nullptr; 666 } 667 668 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) { 669 StringRef S1, S2; 670 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1); 671 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2); 672 673 // strcspn("", s) -> 0 674 if (HasS1 && S1.empty()) 675 return Constant::getNullValue(CI->getType()); 676 677 // Constant folding. 678 if (HasS1 && HasS2) { 679 size_t Pos = S1.find_first_of(S2); 680 if (Pos == StringRef::npos) 681 Pos = S1.size(); 682 return ConstantInt::get(CI->getType(), Pos); 683 } 684 685 // strcspn(s, "") -> strlen(s) 686 if (HasS2 && S2.empty()) 687 return emitStrLen(CI->getArgOperand(0), B, DL, TLI); 688 689 return nullptr; 690 } 691 692 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) { 693 // fold strstr(x, x) -> x. 694 if (CI->getArgOperand(0) == CI->getArgOperand(1)) 695 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 696 697 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0 698 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) { 699 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI); 700 if (!StrLen) 701 return nullptr; 702 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1), 703 StrLen, B, DL, TLI); 704 if (!StrNCmp) 705 return nullptr; 706 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) { 707 ICmpInst *Old = cast<ICmpInst>(*UI++); 708 Value *Cmp = 709 B.CreateICmp(Old->getPredicate(), StrNCmp, 710 ConstantInt::getNullValue(StrNCmp->getType()), "cmp"); 711 replaceAllUsesWith(Old, Cmp); 712 } 713 return CI; 714 } 715 716 // See if either input string is a constant string. 717 StringRef SearchStr, ToFindStr; 718 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr); 719 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr); 720 721 // fold strstr(x, "") -> x. 722 if (HasStr2 && ToFindStr.empty()) 723 return B.CreateBitCast(CI->getArgOperand(0), CI->getType()); 724 725 // If both strings are known, constant fold it. 726 if (HasStr1 && HasStr2) { 727 size_t Offset = SearchStr.find(ToFindStr); 728 729 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null 730 return Constant::getNullValue(CI->getType()); 731 732 // strstr("abcd", "bc") -> gep((char*)"abcd", 1) 733 Value *Result = castToCStr(CI->getArgOperand(0), B); 734 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr"); 735 return B.CreateBitCast(Result, CI->getType()); 736 } 737 738 // fold strstr(x, "y") -> strchr(x, 'y'). 739 if (HasStr2 && ToFindStr.size() == 1) { 740 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI); 741 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr; 742 } 743 return nullptr; 744 } 745 746 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) { 747 Value *SrcStr = CI->getArgOperand(0); 748 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 749 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 750 751 // memchr(x, y, 0) -> null 752 if (LenC && LenC->isZero()) 753 return Constant::getNullValue(CI->getType()); 754 755 // From now on we need at least constant length and string. 756 StringRef Str; 757 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false)) 758 return nullptr; 759 760 // Truncate the string to LenC. If Str is smaller than LenC we will still only 761 // scan the string, as reading past the end of it is undefined and we can just 762 // return null if we don't find the char. 763 Str = Str.substr(0, LenC->getZExtValue()); 764 765 // If the char is variable but the input str and length are not we can turn 766 // this memchr call into a simple bit field test. Of course this only works 767 // when the return value is only checked against null. 768 // 769 // It would be really nice to reuse switch lowering here but we can't change 770 // the CFG at this point. 771 // 772 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0 773 // after bounds check. 774 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) { 775 unsigned char Max = 776 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()), 777 reinterpret_cast<const unsigned char *>(Str.end())); 778 779 // Make sure the bit field we're about to create fits in a register on the 780 // target. 781 // FIXME: On a 64 bit architecture this prevents us from using the 782 // interesting range of alpha ascii chars. We could do better by emitting 783 // two bitfields or shifting the range by 64 if no lower chars are used. 784 if (!DL.fitsInLegalInteger(Max + 1)) 785 return nullptr; 786 787 // For the bit field use a power-of-2 type with at least 8 bits to avoid 788 // creating unnecessary illegal types. 789 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max)); 790 791 // Now build the bit field. 792 APInt Bitfield(Width, 0); 793 for (char C : Str) 794 Bitfield.setBit((unsigned char)C); 795 Value *BitfieldC = B.getInt(Bitfield); 796 797 // First check that the bit field access is within bounds. 798 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType()); 799 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width), 800 "memchr.bounds"); 801 802 // Create code that checks if the given bit is set in the field. 803 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C); 804 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits"); 805 806 // Finally merge both checks and cast to pointer type. The inttoptr 807 // implicitly zexts the i1 to intptr type. 808 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType()); 809 } 810 811 // Check if all arguments are constants. If so, we can constant fold. 812 if (!CharC) 813 return nullptr; 814 815 // Compute the offset. 816 size_t I = Str.find(CharC->getSExtValue() & 0xFF); 817 if (I == StringRef::npos) // Didn't find the char. memchr returns null. 818 return Constant::getNullValue(CI->getType()); 819 820 // memchr(s+n,c,l) -> gep(s+n+i,c) 821 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr"); 822 } 823 824 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) { 825 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1); 826 827 if (LHS == RHS) // memcmp(s,s,x) -> 0 828 return Constant::getNullValue(CI->getType()); 829 830 // Make sure we have a constant length. 831 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 832 if (!LenC) 833 return nullptr; 834 835 uint64_t Len = LenC->getZExtValue(); 836 if (Len == 0) // memcmp(s1,s2,0) -> 0 837 return Constant::getNullValue(CI->getType()); 838 839 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS 840 if (Len == 1) { 841 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"), 842 CI->getType(), "lhsv"); 843 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"), 844 CI->getType(), "rhsv"); 845 return B.CreateSub(LHSV, RHSV, "chardiff"); 846 } 847 848 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0 849 // TODO: The case where both inputs are constants does not need to be limited 850 // to legal integers or equality comparison. See block below this. 851 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) { 852 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8); 853 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType); 854 855 // First, see if we can fold either argument to a constant. 856 Value *LHSV = nullptr; 857 if (auto *LHSC = dyn_cast<Constant>(LHS)) { 858 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo()); 859 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL); 860 } 861 Value *RHSV = nullptr; 862 if (auto *RHSC = dyn_cast<Constant>(RHS)) { 863 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo()); 864 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL); 865 } 866 867 // Don't generate unaligned loads. If either source is constant data, 868 // alignment doesn't matter for that source because there is no load. 869 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) && 870 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) { 871 if (!LHSV) { 872 Type *LHSPtrTy = 873 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace()); 874 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv"); 875 } 876 if (!RHSV) { 877 Type *RHSPtrTy = 878 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace()); 879 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv"); 880 } 881 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp"); 882 } 883 } 884 885 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const). 886 // TODO: This is limited to i8 arrays. 887 StringRef LHSStr, RHSStr; 888 if (getConstantStringInfo(LHS, LHSStr) && 889 getConstantStringInfo(RHS, RHSStr)) { 890 // Make sure we're not reading out-of-bounds memory. 891 if (Len > LHSStr.size() || Len > RHSStr.size()) 892 return nullptr; 893 // Fold the memcmp and normalize the result. This way we get consistent 894 // results across multiple platforms. 895 uint64_t Ret = 0; 896 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len); 897 if (Cmp < 0) 898 Ret = -1; 899 else if (Cmp > 0) 900 Ret = 1; 901 return ConstantInt::get(CI->getType(), Ret); 902 } 903 904 return nullptr; 905 } 906 907 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) { 908 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n) 909 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, 910 CI->getArgOperand(2)); 911 return CI->getArgOperand(0); 912 } 913 914 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) { 915 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n) 916 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, 917 CI->getArgOperand(2)); 918 return CI->getArgOperand(0); 919 } 920 921 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n). 922 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B, 923 const TargetLibraryInfo &TLI) { 924 // This has to be a memset of zeros (bzero). 925 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1)); 926 if (!FillValue || FillValue->getZExtValue() != 0) 927 return nullptr; 928 929 // TODO: We should handle the case where the malloc has more than one use. 930 // This is necessary to optimize common patterns such as when the result of 931 // the malloc is checked against null or when a memset intrinsic is used in 932 // place of a memset library call. 933 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0)); 934 if (!Malloc || !Malloc->hasOneUse()) 935 return nullptr; 936 937 // Is the inner call really malloc()? 938 Function *InnerCallee = Malloc->getCalledFunction(); 939 if (!InnerCallee) 940 return nullptr; 941 942 LibFunc Func; 943 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) || 944 Func != LibFunc_malloc) 945 return nullptr; 946 947 // The memset must cover the same number of bytes that are malloc'd. 948 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0)) 949 return nullptr; 950 951 // Replace the malloc with a calloc. We need the data layout to know what the 952 // actual size of a 'size_t' parameter is. 953 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator()); 954 const DataLayout &DL = Malloc->getModule()->getDataLayout(); 955 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext()); 956 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1), 957 Malloc->getArgOperand(0), Malloc->getAttributes(), 958 B, TLI); 959 if (!Calloc) 960 return nullptr; 961 962 Malloc->replaceAllUsesWith(Calloc); 963 Malloc->eraseFromParent(); 964 965 return Calloc; 966 } 967 968 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) { 969 if (auto *Calloc = foldMallocMemset(CI, B, *TLI)) 970 return Calloc; 971 972 // memset(p, v, n) -> llvm.memset(align 1 p, v, n) 973 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 974 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 975 return CI->getArgOperand(0); 976 } 977 978 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) { 979 if (isa<ConstantPointerNull>(CI->getArgOperand(0))) 980 return emitMalloc(CI->getArgOperand(1), B, DL, TLI); 981 982 return nullptr; 983 } 984 985 //===----------------------------------------------------------------------===// 986 // Math Library Optimizations 987 //===----------------------------------------------------------------------===// 988 989 // Replace a libcall \p CI with a call to intrinsic \p IID 990 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) { 991 // Propagate fast-math flags from the existing call to the new call. 992 IRBuilder<>::FastMathFlagGuard Guard(B); 993 B.setFastMathFlags(CI->getFastMathFlags()); 994 995 Module *M = CI->getModule(); 996 Value *V = CI->getArgOperand(0); 997 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType()); 998 CallInst *NewCall = B.CreateCall(F, V); 999 NewCall->takeName(CI); 1000 return NewCall; 1001 } 1002 1003 /// Return a variant of Val with float type. 1004 /// Currently this works in two cases: If Val is an FPExtension of a float 1005 /// value to something bigger, simply return the operand. 1006 /// If Val is a ConstantFP but can be converted to a float ConstantFP without 1007 /// loss of precision do so. 1008 static Value *valueHasFloatPrecision(Value *Val) { 1009 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) { 1010 Value *Op = Cast->getOperand(0); 1011 if (Op->getType()->isFloatTy()) 1012 return Op; 1013 } 1014 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) { 1015 APFloat F = Const->getValueAPF(); 1016 bool losesInfo; 1017 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 1018 &losesInfo); 1019 if (!losesInfo) 1020 return ConstantFP::get(Const->getContext(), F); 1021 } 1022 return nullptr; 1023 } 1024 1025 /// Shrink double -> float functions. 1026 static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B, 1027 bool isBinary, bool isPrecise = false) { 1028 if (!CI->getType()->isDoubleTy()) 1029 return nullptr; 1030 1031 // If not all the uses of the function are converted to float, then bail out. 1032 // This matters if the precision of the result is more important than the 1033 // precision of the arguments. 1034 if (isPrecise) 1035 for (User *U : CI->users()) { 1036 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U); 1037 if (!Cast || !Cast->getType()->isFloatTy()) 1038 return nullptr; 1039 } 1040 1041 // If this is something like 'g((double) float)', convert to 'gf(float)'. 1042 Value *V[2]; 1043 V[0] = valueHasFloatPrecision(CI->getArgOperand(0)); 1044 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr; 1045 if (!V[0] || (isBinary && !V[1])) 1046 return nullptr; 1047 1048 // If call isn't an intrinsic, check that it isn't within a function with the 1049 // same name as the float version of this call, otherwise the result is an 1050 // infinite loop. For example, from MinGW-w64: 1051 // 1052 // float expf(float val) { return (float) exp((double) val); } 1053 Function *CalleeFn = CI->getCalledFunction(); 1054 StringRef CalleeNm = CalleeFn->getName(); 1055 AttributeList CalleeAt = CalleeFn->getAttributes(); 1056 if (CalleeFn && !CalleeFn->isIntrinsic()) { 1057 const Function *Fn = CI->getFunction(); 1058 StringRef FnName = Fn->getName(); 1059 if (FnName.back() == 'f' && 1060 FnName.size() == (CalleeNm.size() + 1) && 1061 FnName.startswith(CalleeNm)) 1062 return nullptr; 1063 } 1064 1065 // Propagate the math semantics from the current function to the new function. 1066 IRBuilder<>::FastMathFlagGuard Guard(B); 1067 B.setFastMathFlags(CI->getFastMathFlags()); 1068 1069 // g((double) float) -> (double) gf(float) 1070 Value *R; 1071 if (CalleeFn->isIntrinsic()) { 1072 Module *M = CI->getModule(); 1073 Intrinsic::ID IID = CalleeFn->getIntrinsicID(); 1074 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy()); 1075 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]); 1076 } 1077 else 1078 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt) 1079 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt); 1080 1081 return B.CreateFPExt(R, B.getDoubleTy()); 1082 } 1083 1084 /// Shrink double -> float for unary functions. 1085 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B, 1086 bool isPrecise = false) { 1087 return optimizeDoubleFP(CI, B, false, isPrecise); 1088 } 1089 1090 /// Shrink double -> float for binary functions. 1091 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B, 1092 bool isPrecise = false) { 1093 return optimizeDoubleFP(CI, B, true, isPrecise); 1094 } 1095 1096 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z))) 1097 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) { 1098 if (!CI->isFast()) 1099 return nullptr; 1100 1101 // Propagate fast-math flags from the existing call to new instructions. 1102 IRBuilder<>::FastMathFlagGuard Guard(B); 1103 B.setFastMathFlags(CI->getFastMathFlags()); 1104 1105 Value *Real, *Imag; 1106 if (CI->getNumArgOperands() == 1) { 1107 Value *Op = CI->getArgOperand(0); 1108 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!"); 1109 Real = B.CreateExtractValue(Op, 0, "real"); 1110 Imag = B.CreateExtractValue(Op, 1, "imag"); 1111 } else { 1112 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!"); 1113 Real = CI->getArgOperand(0); 1114 Imag = CI->getArgOperand(1); 1115 } 1116 1117 Value *RealReal = B.CreateFMul(Real, Real); 1118 Value *ImagImag = B.CreateFMul(Imag, Imag); 1119 1120 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt, 1121 CI->getType()); 1122 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"); 1123 } 1124 1125 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func, 1126 IRBuilder<> &B) { 1127 if (!isa<FPMathOperator>(Call)) 1128 return nullptr; 1129 1130 IRBuilder<>::FastMathFlagGuard Guard(B); 1131 B.setFastMathFlags(Call->getFastMathFlags()); 1132 1133 // TODO: Can this be shared to also handle LLVM intrinsics? 1134 Value *X; 1135 switch (Func) { 1136 case LibFunc_sin: 1137 case LibFunc_sinf: 1138 case LibFunc_sinl: 1139 case LibFunc_tan: 1140 case LibFunc_tanf: 1141 case LibFunc_tanl: 1142 // sin(-X) --> -sin(X) 1143 // tan(-X) --> -tan(X) 1144 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) 1145 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X)); 1146 break; 1147 case LibFunc_cos: 1148 case LibFunc_cosf: 1149 case LibFunc_cosl: 1150 // cos(-X) --> cos(X) 1151 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X)))) 1152 return B.CreateCall(Call->getCalledFunction(), X, "cos"); 1153 break; 1154 default: 1155 break; 1156 } 1157 return nullptr; 1158 } 1159 1160 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) { 1161 // Multiplications calculated using Addition Chains. 1162 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html 1163 1164 assert(Exp != 0 && "Incorrect exponent 0 not handled"); 1165 1166 if (InnerChain[Exp]) 1167 return InnerChain[Exp]; 1168 1169 static const unsigned AddChain[33][2] = { 1170 {0, 0}, // Unused. 1171 {0, 0}, // Unused (base case = pow1). 1172 {1, 1}, // Unused (pre-computed). 1173 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4}, 1174 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7}, 1175 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10}, 1176 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13}, 1177 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16}, 1178 }; 1179 1180 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B), 1181 getPow(InnerChain, AddChain[Exp][1], B)); 1182 return InnerChain[Exp]; 1183 } 1184 1185 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y); 1186 /// exp2(x) for pow(2.0, x); exp10(x) for pow(10.0, x). 1187 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) { 1188 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1189 AttributeList Attrs = Pow->getCalledFunction()->getAttributes(); 1190 Module *Mod = Pow->getModule(); 1191 Type *Ty = Pow->getType(); 1192 1193 // Evaluate special cases related to a nested function as the base. 1194 1195 // pow(exp(x), y) -> exp(x * y) 1196 // pow(exp2(x), y) -> exp2(x * y) 1197 // If exp{,2}() is used only once, it is better to fold two transcendental 1198 // math functions into one. If used again, exp{,2}() would still have to be 1199 // called with the original argument, then keep both original transcendental 1200 // functions. However, this transformation is only safe with fully relaxed 1201 // math semantics, since, besides rounding differences, it changes overflow 1202 // and underflow behavior quite dramatically. For example: 1203 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf 1204 // Whereas: 1205 // exp(1000 * 0.001) = exp(1) 1206 // TODO: Loosen the requirement for fully relaxed math semantics. 1207 // TODO: Handle exp10() when more targets have it available. 1208 CallInst *BaseFn = dyn_cast<CallInst>(Base); 1209 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) { 1210 LibFunc LibFn; 1211 1212 Function *CalleeFn = BaseFn->getCalledFunction(); 1213 if (CalleeFn && 1214 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) { 1215 StringRef ExpName; 1216 Intrinsic::ID ID; 1217 Value *ExpFn; 1218 1219 switch (LibFn) { 1220 default: 1221 return nullptr; 1222 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl: 1223 ExpName = TLI->getName(LibFunc_exp); 1224 ID = Intrinsic::exp; 1225 break; 1226 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l: 1227 ExpName = TLI->getName(LibFunc_exp2); 1228 ID = Intrinsic::exp2; 1229 break; 1230 } 1231 1232 // Create new exp{,2}() with the product as its argument. 1233 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul"); 1234 ExpFn = BaseFn->doesNotAccessMemory() 1235 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty), 1236 FMul, ExpName) 1237 : emitUnaryFloatFnCall(FMul, ExpName, B, BaseFn->getAttributes()); 1238 1239 // Since the new exp{,2}() is different from the original one, dead code 1240 // elimination cannot be trusted to remove it, since it may have side 1241 // effects (e.g., errno). When the only consumer for the original 1242 // exp{,2}() is pow(), then it has to be explicitly erased. 1243 BaseFn->replaceAllUsesWith(ExpFn); 1244 BaseFn->eraseFromParent(); 1245 1246 return ExpFn; 1247 } 1248 } 1249 1250 // Evaluate special cases related to a constant base. 1251 1252 // pow(2.0, x) -> exp2(x) 1253 if (match(Base, m_SpecificFP(2.0))) { 1254 Value *Exp2 = Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty); 1255 return B.CreateCall(Exp2, Expo, "exp2"); 1256 } 1257 1258 // pow(10.0, x) -> exp10(x) 1259 // TODO: There is no exp10() intrinsic yet, but some day there shall be one. 1260 if (match(Base, m_SpecificFP(10.0)) && 1261 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) 1262 return emitUnaryFloatFnCall(Expo, TLI->getName(LibFunc_exp10), B, Attrs); 1263 1264 return nullptr; 1265 } 1266 1267 /// Use square root in place of pow(x, +/-0.5). 1268 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) { 1269 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1270 AttributeList Attrs = Pow->getCalledFunction()->getAttributes(); 1271 Module *Mod = Pow->getModule(); 1272 Type *Ty = Pow->getType(); 1273 1274 const APFloat *ExpoF; 1275 if (!match(Expo, m_APFloat(ExpoF)) || 1276 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5))) 1277 return nullptr; 1278 1279 // If errno is never set, then use the intrinsic for sqrt(). 1280 if (Pow->doesNotAccessMemory()) { 1281 Function *SqrtFn = Intrinsic::getDeclaration(Pow->getModule(), 1282 Intrinsic::sqrt, Ty); 1283 Sqrt = B.CreateCall(SqrtFn, Base, "sqrt"); 1284 } 1285 // Otherwise, use the libcall for sqrt(). 1286 else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) 1287 // TODO: We also should check that the target can in fact lower the sqrt() 1288 // libcall. We currently have no way to ask this question, so we ask if 1289 // the target has a sqrt() libcall, which is not exactly the same. 1290 Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt), B, Attrs); 1291 else 1292 return nullptr; 1293 1294 // Handle signed zero base by expanding to fabs(sqrt(x)). 1295 if (!Pow->hasNoSignedZeros()) { 1296 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty); 1297 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs"); 1298 } 1299 1300 // Handle non finite base by expanding to 1301 // (x == -infinity ? +infinity : sqrt(x)). 1302 if (!Pow->hasNoInfs()) { 1303 Value *PosInf = ConstantFP::getInfinity(Ty), 1304 *NegInf = ConstantFP::getInfinity(Ty, true); 1305 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf"); 1306 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt); 1307 } 1308 1309 // If the exponent is negative, then get the reciprocal. 1310 if (ExpoF->isNegative()) 1311 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal"); 1312 1313 return Sqrt; 1314 } 1315 1316 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) { 1317 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1); 1318 Function *Callee = Pow->getCalledFunction(); 1319 StringRef Name = Callee->getName(); 1320 Type *Ty = Pow->getType(); 1321 Value *Shrunk = nullptr; 1322 bool Ignored; 1323 1324 // Bail out if simplifying libcalls to pow() is disabled. 1325 if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl)) 1326 return nullptr; 1327 1328 // Propagate the math semantics from the call to any created instructions. 1329 IRBuilder<>::FastMathFlagGuard Guard(B); 1330 B.setFastMathFlags(Pow->getFastMathFlags()); 1331 1332 // Shrink pow() to powf() if the arguments are single precision, 1333 // unless the result is expected to be double precision. 1334 if (UnsafeFPShrink && 1335 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name)) 1336 Shrunk = optimizeBinaryDoubleFP(Pow, B, true); 1337 1338 // Evaluate special cases related to the base. 1339 1340 // pow(1.0, x) -> 1.0 1341 if (match(Base, m_FPOne())) 1342 return Base; 1343 1344 if (Value *Exp = replacePowWithExp(Pow, B)) 1345 return Exp; 1346 1347 // Evaluate special cases related to the exponent. 1348 1349 // pow(x, -1.0) -> 1.0 / x 1350 if (match(Expo, m_SpecificFP(-1.0))) 1351 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal"); 1352 1353 // pow(x, 0.0) -> 1.0 1354 if (match(Expo, m_SpecificFP(0.0))) 1355 return ConstantFP::get(Ty, 1.0); 1356 1357 // pow(x, 1.0) -> x 1358 if (match(Expo, m_FPOne())) 1359 return Base; 1360 1361 // pow(x, 2.0) -> x * x 1362 if (match(Expo, m_SpecificFP(2.0))) 1363 return B.CreateFMul(Base, Base, "square"); 1364 1365 if (Value *Sqrt = replacePowWithSqrt(Pow, B)) 1366 return Sqrt; 1367 1368 // pow(x, n) -> x * x * x * ... 1369 const APFloat *ExpoF; 1370 if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) { 1371 // We limit to a max of 7 multiplications, thus the maximum exponent is 32. 1372 APFloat LimF(ExpoF->getSemantics(), 33.0), 1373 ExpoA(abs(*ExpoF)); 1374 if (ExpoA.isInteger() && ExpoA.compare(LimF) == APFloat::cmpLessThan) { 1375 // We will memoize intermediate products of the Addition Chain. 1376 Value *InnerChain[33] = {nullptr}; 1377 InnerChain[1] = Base; 1378 InnerChain[2] = B.CreateFMul(Base, Base, "square"); 1379 1380 // We cannot readily convert a non-double type (like float) to a double. 1381 // So we first convert it to something which could be converted to double. 1382 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored); 1383 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B); 1384 1385 // If the exponent is negative, then get the reciprocal. 1386 if (ExpoF->isNegative()) 1387 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal"); 1388 1389 return FMul; 1390 } 1391 } 1392 1393 return Shrunk; 1394 } 1395 1396 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) { 1397 Function *Callee = CI->getCalledFunction(); 1398 Value *Ret = nullptr; 1399 StringRef Name = Callee->getName(); 1400 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name)) 1401 Ret = optimizeUnaryDoubleFP(CI, B, true); 1402 1403 Value *Op = CI->getArgOperand(0); 1404 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32 1405 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32 1406 LibFunc LdExp = LibFunc_ldexpl; 1407 if (Op->getType()->isFloatTy()) 1408 LdExp = LibFunc_ldexpf; 1409 else if (Op->getType()->isDoubleTy()) 1410 LdExp = LibFunc_ldexp; 1411 1412 if (TLI->has(LdExp)) { 1413 Value *LdExpArg = nullptr; 1414 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) { 1415 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32) 1416 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty()); 1417 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) { 1418 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32) 1419 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty()); 1420 } 1421 1422 if (LdExpArg) { 1423 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f)); 1424 if (!Op->getType()->isFloatTy()) 1425 One = ConstantExpr::getFPExtend(One, Op->getType()); 1426 1427 Module *M = CI->getModule(); 1428 Value *NewCallee = 1429 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(), 1430 Op->getType(), B.getInt32Ty()); 1431 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg}); 1432 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) 1433 CI->setCallingConv(F->getCallingConv()); 1434 1435 return CI; 1436 } 1437 } 1438 return Ret; 1439 } 1440 1441 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) { 1442 Function *Callee = CI->getCalledFunction(); 1443 // If we can shrink the call to a float function rather than a double 1444 // function, do that first. 1445 StringRef Name = Callee->getName(); 1446 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name)) 1447 if (Value *Ret = optimizeBinaryDoubleFP(CI, B)) 1448 return Ret; 1449 1450 IRBuilder<>::FastMathFlagGuard Guard(B); 1451 FastMathFlags FMF; 1452 if (CI->isFast()) { 1453 // If the call is 'fast', then anything we create here will also be 'fast'. 1454 FMF.setFast(); 1455 } else { 1456 // At a minimum, no-nans-fp-math must be true. 1457 if (!CI->hasNoNaNs()) 1458 return nullptr; 1459 // No-signed-zeros is implied by the definitions of fmax/fmin themselves: 1460 // "Ideally, fmax would be sensitive to the sign of zero, for example 1461 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software 1462 // might be impractical." 1463 FMF.setNoSignedZeros(); 1464 FMF.setNoNaNs(); 1465 } 1466 B.setFastMathFlags(FMF); 1467 1468 // We have a relaxed floating-point environment. We can ignore NaN-handling 1469 // and transform to a compare and select. We do not have to consider errno or 1470 // exceptions, because fmin/fmax do not have those. 1471 Value *Op0 = CI->getArgOperand(0); 1472 Value *Op1 = CI->getArgOperand(1); 1473 Value *Cmp = Callee->getName().startswith("fmin") ? 1474 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1); 1475 return B.CreateSelect(Cmp, Op0, Op1); 1476 } 1477 1478 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) { 1479 Function *Callee = CI->getCalledFunction(); 1480 Value *Ret = nullptr; 1481 StringRef Name = Callee->getName(); 1482 if (UnsafeFPShrink && hasFloatVersion(Name)) 1483 Ret = optimizeUnaryDoubleFP(CI, B, true); 1484 1485 if (!CI->isFast()) 1486 return Ret; 1487 Value *Op1 = CI->getArgOperand(0); 1488 auto *OpC = dyn_cast<CallInst>(Op1); 1489 1490 // The earlier call must also be 'fast' in order to do these transforms. 1491 if (!OpC || !OpC->isFast()) 1492 return Ret; 1493 1494 // log(pow(x,y)) -> y*log(x) 1495 // This is only applicable to log, log2, log10. 1496 if (Name != "log" && Name != "log2" && Name != "log10") 1497 return Ret; 1498 1499 IRBuilder<>::FastMathFlagGuard Guard(B); 1500 FastMathFlags FMF; 1501 FMF.setFast(); 1502 B.setFastMathFlags(FMF); 1503 1504 LibFunc Func; 1505 Function *F = OpC->getCalledFunction(); 1506 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 1507 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow)) 1508 return B.CreateFMul(OpC->getArgOperand(1), 1509 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B, 1510 Callee->getAttributes()), "mul"); 1511 1512 // log(exp2(y)) -> y*log(2) 1513 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) && 1514 TLI->has(Func) && Func == LibFunc_exp2) 1515 return B.CreateFMul( 1516 OpC->getArgOperand(0), 1517 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0), 1518 Callee->getName(), B, Callee->getAttributes()), 1519 "logmul"); 1520 return Ret; 1521 } 1522 1523 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) { 1524 Function *Callee = CI->getCalledFunction(); 1525 Value *Ret = nullptr; 1526 // TODO: Once we have a way (other than checking for the existince of the 1527 // libcall) to tell whether our target can lower @llvm.sqrt, relax the 1528 // condition below. 1529 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" || 1530 Callee->getIntrinsicID() == Intrinsic::sqrt)) 1531 Ret = optimizeUnaryDoubleFP(CI, B, true); 1532 1533 if (!CI->isFast()) 1534 return Ret; 1535 1536 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0)); 1537 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast()) 1538 return Ret; 1539 1540 // We're looking for a repeated factor in a multiplication tree, 1541 // so we can do this fold: sqrt(x * x) -> fabs(x); 1542 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y). 1543 Value *Op0 = I->getOperand(0); 1544 Value *Op1 = I->getOperand(1); 1545 Value *RepeatOp = nullptr; 1546 Value *OtherOp = nullptr; 1547 if (Op0 == Op1) { 1548 // Simple match: the operands of the multiply are identical. 1549 RepeatOp = Op0; 1550 } else { 1551 // Look for a more complicated pattern: one of the operands is itself 1552 // a multiply, so search for a common factor in that multiply. 1553 // Note: We don't bother looking any deeper than this first level or for 1554 // variations of this pattern because instcombine's visitFMUL and/or the 1555 // reassociation pass should give us this form. 1556 Value *OtherMul0, *OtherMul1; 1557 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) { 1558 // Pattern: sqrt((x * y) * z) 1559 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) { 1560 // Matched: sqrt((x * x) * z) 1561 RepeatOp = OtherMul0; 1562 OtherOp = Op1; 1563 } 1564 } 1565 } 1566 if (!RepeatOp) 1567 return Ret; 1568 1569 // Fast math flags for any created instructions should match the sqrt 1570 // and multiply. 1571 IRBuilder<>::FastMathFlagGuard Guard(B); 1572 B.setFastMathFlags(I->getFastMathFlags()); 1573 1574 // If we found a repeated factor, hoist it out of the square root and 1575 // replace it with the fabs of that factor. 1576 Module *M = Callee->getParent(); 1577 Type *ArgType = I->getType(); 1578 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType); 1579 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs"); 1580 if (OtherOp) { 1581 // If we found a non-repeated factor, we still need to get its square 1582 // root. We then multiply that by the value that was simplified out 1583 // of the square root calculation. 1584 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType); 1585 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt"); 1586 return B.CreateFMul(FabsCall, SqrtCall); 1587 } 1588 return FabsCall; 1589 } 1590 1591 // TODO: Generalize to handle any trig function and its inverse. 1592 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) { 1593 Function *Callee = CI->getCalledFunction(); 1594 Value *Ret = nullptr; 1595 StringRef Name = Callee->getName(); 1596 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name)) 1597 Ret = optimizeUnaryDoubleFP(CI, B, true); 1598 1599 Value *Op1 = CI->getArgOperand(0); 1600 auto *OpC = dyn_cast<CallInst>(Op1); 1601 if (!OpC) 1602 return Ret; 1603 1604 // Both calls must be 'fast' in order to remove them. 1605 if (!CI->isFast() || !OpC->isFast()) 1606 return Ret; 1607 1608 // tan(atan(x)) -> x 1609 // tanf(atanf(x)) -> x 1610 // tanl(atanl(x)) -> x 1611 LibFunc Func; 1612 Function *F = OpC->getCalledFunction(); 1613 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) && 1614 ((Func == LibFunc_atan && Callee->getName() == "tan") || 1615 (Func == LibFunc_atanf && Callee->getName() == "tanf") || 1616 (Func == LibFunc_atanl && Callee->getName() == "tanl"))) 1617 Ret = OpC->getArgOperand(0); 1618 return Ret; 1619 } 1620 1621 static bool isTrigLibCall(CallInst *CI) { 1622 // We can only hope to do anything useful if we can ignore things like errno 1623 // and floating-point exceptions. 1624 // We already checked the prototype. 1625 return CI->hasFnAttr(Attribute::NoUnwind) && 1626 CI->hasFnAttr(Attribute::ReadNone); 1627 } 1628 1629 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, 1630 bool UseFloat, Value *&Sin, Value *&Cos, 1631 Value *&SinCos) { 1632 Type *ArgTy = Arg->getType(); 1633 Type *ResTy; 1634 StringRef Name; 1635 1636 Triple T(OrigCallee->getParent()->getTargetTriple()); 1637 if (UseFloat) { 1638 Name = "__sincospif_stret"; 1639 1640 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now"); 1641 // x86_64 can't use {float, float} since that would be returned in both 1642 // xmm0 and xmm1, which isn't what a real struct would do. 1643 ResTy = T.getArch() == Triple::x86_64 1644 ? static_cast<Type *>(VectorType::get(ArgTy, 2)) 1645 : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); 1646 } else { 1647 Name = "__sincospi_stret"; 1648 ResTy = StructType::get(ArgTy, ArgTy); 1649 } 1650 1651 Module *M = OrigCallee->getParent(); 1652 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(), 1653 ResTy, ArgTy); 1654 1655 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 1656 // If the argument is an instruction, it must dominate all uses so put our 1657 // sincos call there. 1658 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 1659 } else { 1660 // Otherwise (e.g. for a constant) the beginning of the function is as 1661 // good a place as any. 1662 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock(); 1663 B.SetInsertPoint(&EntryBB, EntryBB.begin()); 1664 } 1665 1666 SinCos = B.CreateCall(Callee, Arg, "sincospi"); 1667 1668 if (SinCos->getType()->isStructTy()) { 1669 Sin = B.CreateExtractValue(SinCos, 0, "sinpi"); 1670 Cos = B.CreateExtractValue(SinCos, 1, "cospi"); 1671 } else { 1672 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0), 1673 "sinpi"); 1674 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1), 1675 "cospi"); 1676 } 1677 } 1678 1679 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) { 1680 // Make sure the prototype is as expected, otherwise the rest of the 1681 // function is probably invalid and likely to abort. 1682 if (!isTrigLibCall(CI)) 1683 return nullptr; 1684 1685 Value *Arg = CI->getArgOperand(0); 1686 SmallVector<CallInst *, 1> SinCalls; 1687 SmallVector<CallInst *, 1> CosCalls; 1688 SmallVector<CallInst *, 1> SinCosCalls; 1689 1690 bool IsFloat = Arg->getType()->isFloatTy(); 1691 1692 // Look for all compatible sinpi, cospi and sincospi calls with the same 1693 // argument. If there are enough (in some sense) we can make the 1694 // substitution. 1695 Function *F = CI->getFunction(); 1696 for (User *U : Arg->users()) 1697 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls); 1698 1699 // It's only worthwhile if both sinpi and cospi are actually used. 1700 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty())) 1701 return nullptr; 1702 1703 Value *Sin, *Cos, *SinCos; 1704 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos); 1705 1706 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls, 1707 Value *Res) { 1708 for (CallInst *C : Calls) 1709 replaceAllUsesWith(C, Res); 1710 }; 1711 1712 replaceTrigInsts(SinCalls, Sin); 1713 replaceTrigInsts(CosCalls, Cos); 1714 replaceTrigInsts(SinCosCalls, SinCos); 1715 1716 return nullptr; 1717 } 1718 1719 void LibCallSimplifier::classifyArgUse( 1720 Value *Val, Function *F, bool IsFloat, 1721 SmallVectorImpl<CallInst *> &SinCalls, 1722 SmallVectorImpl<CallInst *> &CosCalls, 1723 SmallVectorImpl<CallInst *> &SinCosCalls) { 1724 CallInst *CI = dyn_cast<CallInst>(Val); 1725 1726 if (!CI) 1727 return; 1728 1729 // Don't consider calls in other functions. 1730 if (CI->getFunction() != F) 1731 return; 1732 1733 Function *Callee = CI->getCalledFunction(); 1734 LibFunc Func; 1735 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) || 1736 !isTrigLibCall(CI)) 1737 return; 1738 1739 if (IsFloat) { 1740 if (Func == LibFunc_sinpif) 1741 SinCalls.push_back(CI); 1742 else if (Func == LibFunc_cospif) 1743 CosCalls.push_back(CI); 1744 else if (Func == LibFunc_sincospif_stret) 1745 SinCosCalls.push_back(CI); 1746 } else { 1747 if (Func == LibFunc_sinpi) 1748 SinCalls.push_back(CI); 1749 else if (Func == LibFunc_cospi) 1750 CosCalls.push_back(CI); 1751 else if (Func == LibFunc_sincospi_stret) 1752 SinCosCalls.push_back(CI); 1753 } 1754 } 1755 1756 //===----------------------------------------------------------------------===// 1757 // Integer Library Call Optimizations 1758 //===----------------------------------------------------------------------===// 1759 1760 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) { 1761 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0 1762 Value *Op = CI->getArgOperand(0); 1763 Type *ArgType = Op->getType(); 1764 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 1765 Intrinsic::cttz, ArgType); 1766 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz"); 1767 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1)); 1768 V = B.CreateIntCast(V, B.getInt32Ty(), false); 1769 1770 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType)); 1771 return B.CreateSelect(Cond, V, B.getInt32(0)); 1772 } 1773 1774 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) { 1775 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false)) 1776 Value *Op = CI->getArgOperand(0); 1777 Type *ArgType = Op->getType(); 1778 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(), 1779 Intrinsic::ctlz, ArgType); 1780 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz"); 1781 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()), 1782 V); 1783 return B.CreateIntCast(V, CI->getType(), false); 1784 } 1785 1786 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) { 1787 // abs(x) -> x <s 0 ? -x : x 1788 // The negation has 'nsw' because abs of INT_MIN is undefined. 1789 Value *X = CI->getArgOperand(0); 1790 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType())); 1791 Value *NegX = B.CreateNSWNeg(X, "neg"); 1792 return B.CreateSelect(IsNeg, NegX, X); 1793 } 1794 1795 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) { 1796 // isdigit(c) -> (c-'0') <u 10 1797 Value *Op = CI->getArgOperand(0); 1798 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp"); 1799 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit"); 1800 return B.CreateZExt(Op, CI->getType()); 1801 } 1802 1803 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) { 1804 // isascii(c) -> c <u 128 1805 Value *Op = CI->getArgOperand(0); 1806 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii"); 1807 return B.CreateZExt(Op, CI->getType()); 1808 } 1809 1810 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) { 1811 // toascii(c) -> c & 0x7f 1812 return B.CreateAnd(CI->getArgOperand(0), 1813 ConstantInt::get(CI->getType(), 0x7F)); 1814 } 1815 1816 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) { 1817 StringRef Str; 1818 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 1819 return nullptr; 1820 1821 return convertStrToNumber(CI, Str, 10); 1822 } 1823 1824 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) { 1825 StringRef Str; 1826 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 1827 return nullptr; 1828 1829 if (!isa<ConstantPointerNull>(CI->getArgOperand(1))) 1830 return nullptr; 1831 1832 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) { 1833 return convertStrToNumber(CI, Str, CInt->getSExtValue()); 1834 } 1835 1836 return nullptr; 1837 } 1838 1839 //===----------------------------------------------------------------------===// 1840 // Formatting and IO Library Call Optimizations 1841 //===----------------------------------------------------------------------===// 1842 1843 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg); 1844 1845 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B, 1846 int StreamArg) { 1847 Function *Callee = CI->getCalledFunction(); 1848 // Error reporting calls should be cold, mark them as such. 1849 // This applies even to non-builtin calls: it is only a hint and applies to 1850 // functions that the frontend might not understand as builtins. 1851 1852 // This heuristic was suggested in: 1853 // Improving Static Branch Prediction in a Compiler 1854 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu 1855 // Proceedings of PACT'98, Oct. 1998, IEEE 1856 if (!CI->hasFnAttr(Attribute::Cold) && 1857 isReportingError(Callee, CI, StreamArg)) { 1858 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold); 1859 } 1860 1861 return nullptr; 1862 } 1863 1864 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) { 1865 if (!Callee || !Callee->isDeclaration()) 1866 return false; 1867 1868 if (StreamArg < 0) 1869 return true; 1870 1871 // These functions might be considered cold, but only if their stream 1872 // argument is stderr. 1873 1874 if (StreamArg >= (int)CI->getNumArgOperands()) 1875 return false; 1876 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg)); 1877 if (!LI) 1878 return false; 1879 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()); 1880 if (!GV || !GV->isDeclaration()) 1881 return false; 1882 return GV->getName() == "stderr"; 1883 } 1884 1885 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) { 1886 // Check for a fixed format string. 1887 StringRef FormatStr; 1888 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr)) 1889 return nullptr; 1890 1891 // Empty format string -> noop. 1892 if (FormatStr.empty()) // Tolerate printf's declared void. 1893 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0); 1894 1895 // Do not do any of the following transformations if the printf return value 1896 // is used, in general the printf return value is not compatible with either 1897 // putchar() or puts(). 1898 if (!CI->use_empty()) 1899 return nullptr; 1900 1901 // printf("x") -> putchar('x'), even for "%" and "%%". 1902 if (FormatStr.size() == 1 || FormatStr == "%%") 1903 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI); 1904 1905 // printf("%s", "a") --> putchar('a') 1906 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) { 1907 StringRef ChrStr; 1908 if (!getConstantStringInfo(CI->getOperand(1), ChrStr)) 1909 return nullptr; 1910 if (ChrStr.size() != 1) 1911 return nullptr; 1912 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI); 1913 } 1914 1915 // printf("foo\n") --> puts("foo") 1916 if (FormatStr[FormatStr.size() - 1] == '\n' && 1917 FormatStr.find('%') == StringRef::npos) { // No format characters. 1918 // Create a string literal with no \n on it. We expect the constant merge 1919 // pass to be run after this pass, to merge duplicate strings. 1920 FormatStr = FormatStr.drop_back(); 1921 Value *GV = B.CreateGlobalString(FormatStr, "str"); 1922 return emitPutS(GV, B, TLI); 1923 } 1924 1925 // Optimize specific format strings. 1926 // printf("%c", chr) --> putchar(chr) 1927 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 && 1928 CI->getArgOperand(1)->getType()->isIntegerTy()) 1929 return emitPutChar(CI->getArgOperand(1), B, TLI); 1930 1931 // printf("%s\n", str) --> puts(str) 1932 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 && 1933 CI->getArgOperand(1)->getType()->isPointerTy()) 1934 return emitPutS(CI->getArgOperand(1), B, TLI); 1935 return nullptr; 1936 } 1937 1938 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) { 1939 1940 Function *Callee = CI->getCalledFunction(); 1941 FunctionType *FT = Callee->getFunctionType(); 1942 if (Value *V = optimizePrintFString(CI, B)) { 1943 return V; 1944 } 1945 1946 // printf(format, ...) -> iprintf(format, ...) if no floating point 1947 // arguments. 1948 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) { 1949 Module *M = B.GetInsertBlock()->getParent()->getParent(); 1950 Constant *IPrintFFn = 1951 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes()); 1952 CallInst *New = cast<CallInst>(CI->clone()); 1953 New->setCalledFunction(IPrintFFn); 1954 B.Insert(New); 1955 return New; 1956 } 1957 return nullptr; 1958 } 1959 1960 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) { 1961 // Check for a fixed format string. 1962 StringRef FormatStr; 1963 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 1964 return nullptr; 1965 1966 // If we just have a format string (nothing else crazy) transform it. 1967 if (CI->getNumArgOperands() == 2) { 1968 // Make sure there's no % in the constant array. We could try to handle 1969 // %% -> % in the future if we cared. 1970 if (FormatStr.find('%') != StringRef::npos) 1971 return nullptr; // we found a format specifier, bail out. 1972 1973 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1) 1974 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, 1975 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 1976 FormatStr.size() + 1)); // Copy the null byte. 1977 return ConstantInt::get(CI->getType(), FormatStr.size()); 1978 } 1979 1980 // The remaining optimizations require the format string to be "%s" or "%c" 1981 // and have an extra operand. 1982 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 1983 CI->getNumArgOperands() < 3) 1984 return nullptr; 1985 1986 // Decode the second character of the format string. 1987 if (FormatStr[1] == 'c') { 1988 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 1989 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 1990 return nullptr; 1991 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char"); 1992 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 1993 B.CreateStore(V, Ptr); 1994 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 1995 B.CreateStore(B.getInt8(0), Ptr); 1996 1997 return ConstantInt::get(CI->getType(), 1); 1998 } 1999 2000 if (FormatStr[1] == 's') { 2001 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1) 2002 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2003 return nullptr; 2004 2005 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI); 2006 if (!Len) 2007 return nullptr; 2008 Value *IncLen = 2009 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc"); 2010 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen); 2011 2012 // The sprintf result is the unincremented number of bytes in the string. 2013 return B.CreateIntCast(Len, CI->getType(), false); 2014 } 2015 return nullptr; 2016 } 2017 2018 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) { 2019 Function *Callee = CI->getCalledFunction(); 2020 FunctionType *FT = Callee->getFunctionType(); 2021 if (Value *V = optimizeSPrintFString(CI, B)) { 2022 return V; 2023 } 2024 2025 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating 2026 // point arguments. 2027 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) { 2028 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2029 Constant *SIPrintFFn = 2030 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes()); 2031 CallInst *New = cast<CallInst>(CI->clone()); 2032 New->setCalledFunction(SIPrintFFn); 2033 B.Insert(New); 2034 return New; 2035 } 2036 return nullptr; 2037 } 2038 2039 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) { 2040 // Check for a fixed format string. 2041 StringRef FormatStr; 2042 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr)) 2043 return nullptr; 2044 2045 // Check for size 2046 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2047 if (!Size) 2048 return nullptr; 2049 2050 uint64_t N = Size->getZExtValue(); 2051 2052 // If we just have a format string (nothing else crazy) transform it. 2053 if (CI->getNumArgOperands() == 3) { 2054 // Make sure there's no % in the constant array. We could try to handle 2055 // %% -> % in the future if we cared. 2056 if (FormatStr.find('%') != StringRef::npos) 2057 return nullptr; // we found a format specifier, bail out. 2058 2059 if (N == 0) 2060 return ConstantInt::get(CI->getType(), FormatStr.size()); 2061 else if (N < FormatStr.size() + 1) 2062 return nullptr; 2063 2064 // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, 2065 // strlen(fmt)+1) 2066 B.CreateMemCpy( 2067 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, 2068 ConstantInt::get(DL.getIntPtrType(CI->getContext()), 2069 FormatStr.size() + 1)); // Copy the null byte. 2070 return ConstantInt::get(CI->getType(), FormatStr.size()); 2071 } 2072 2073 // The remaining optimizations require the format string to be "%s" or "%c" 2074 // and have an extra operand. 2075 if (FormatStr.size() == 2 && FormatStr[0] == '%' && 2076 CI->getNumArgOperands() == 4) { 2077 2078 // Decode the second character of the format string. 2079 if (FormatStr[1] == 'c') { 2080 if (N == 0) 2081 return ConstantInt::get(CI->getType(), 1); 2082 else if (N == 1) 2083 return nullptr; 2084 2085 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0 2086 if (!CI->getArgOperand(3)->getType()->isIntegerTy()) 2087 return nullptr; 2088 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char"); 2089 Value *Ptr = castToCStr(CI->getArgOperand(0), B); 2090 B.CreateStore(V, Ptr); 2091 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul"); 2092 B.CreateStore(B.getInt8(0), Ptr); 2093 2094 return ConstantInt::get(CI->getType(), 1); 2095 } 2096 2097 if (FormatStr[1] == 's') { 2098 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1) 2099 StringRef Str; 2100 if (!getConstantStringInfo(CI->getArgOperand(3), Str)) 2101 return nullptr; 2102 2103 if (N == 0) 2104 return ConstantInt::get(CI->getType(), Str.size()); 2105 else if (N < Str.size() + 1) 2106 return nullptr; 2107 2108 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1, 2109 ConstantInt::get(CI->getType(), Str.size() + 1)); 2110 2111 // The snprintf result is the unincremented number of bytes in the string. 2112 return ConstantInt::get(CI->getType(), Str.size()); 2113 } 2114 } 2115 return nullptr; 2116 } 2117 2118 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) { 2119 if (Value *V = optimizeSnPrintFString(CI, B)) { 2120 return V; 2121 } 2122 2123 return nullptr; 2124 } 2125 2126 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) { 2127 optimizeErrorReporting(CI, B, 0); 2128 2129 // All the optimizations depend on the format string. 2130 StringRef FormatStr; 2131 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr)) 2132 return nullptr; 2133 2134 // Do not do any of the following transformations if the fprintf return 2135 // value is used, in general the fprintf return value is not compatible 2136 // with fwrite(), fputc() or fputs(). 2137 if (!CI->use_empty()) 2138 return nullptr; 2139 2140 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F) 2141 if (CI->getNumArgOperands() == 2) { 2142 // Could handle %% -> % if we cared. 2143 if (FormatStr.find('%') != StringRef::npos) 2144 return nullptr; // We found a format specifier. 2145 2146 return emitFWrite( 2147 CI->getArgOperand(1), 2148 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()), 2149 CI->getArgOperand(0), B, DL, TLI); 2150 } 2151 2152 // The remaining optimizations require the format string to be "%s" or "%c" 2153 // and have an extra operand. 2154 if (FormatStr.size() != 2 || FormatStr[0] != '%' || 2155 CI->getNumArgOperands() < 3) 2156 return nullptr; 2157 2158 // Decode the second character of the format string. 2159 if (FormatStr[1] == 'c') { 2160 // fprintf(F, "%c", chr) --> fputc(chr, F) 2161 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) 2162 return nullptr; 2163 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 2164 } 2165 2166 if (FormatStr[1] == 's') { 2167 // fprintf(F, "%s", str) --> fputs(str, F) 2168 if (!CI->getArgOperand(2)->getType()->isPointerTy()) 2169 return nullptr; 2170 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI); 2171 } 2172 return nullptr; 2173 } 2174 2175 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) { 2176 Function *Callee = CI->getCalledFunction(); 2177 FunctionType *FT = Callee->getFunctionType(); 2178 if (Value *V = optimizeFPrintFString(CI, B)) { 2179 return V; 2180 } 2181 2182 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no 2183 // floating point arguments. 2184 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) { 2185 Module *M = B.GetInsertBlock()->getParent()->getParent(); 2186 Constant *FIPrintFFn = 2187 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes()); 2188 CallInst *New = cast<CallInst>(CI->clone()); 2189 New->setCalledFunction(FIPrintFFn); 2190 B.Insert(New); 2191 return New; 2192 } 2193 return nullptr; 2194 } 2195 2196 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) { 2197 optimizeErrorReporting(CI, B, 3); 2198 2199 // Get the element size and count. 2200 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1)); 2201 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 2202 if (SizeC && CountC) { 2203 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue(); 2204 2205 // If this is writing zero records, remove the call (it's a noop). 2206 if (Bytes == 0) 2207 return ConstantInt::get(CI->getType(), 0); 2208 2209 // If this is writing one byte, turn it into fputc. 2210 // This optimisation is only valid, if the return value is unused. 2211 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F) 2212 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char"); 2213 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI); 2214 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr; 2215 } 2216 } 2217 2218 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI)) 2219 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), 2220 CI->getArgOperand(2), CI->getArgOperand(3), B, DL, 2221 TLI); 2222 2223 return nullptr; 2224 } 2225 2226 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) { 2227 optimizeErrorReporting(CI, B, 1); 2228 2229 // Don't rewrite fputs to fwrite when optimising for size because fwrite 2230 // requires more arguments and thus extra MOVs are required. 2231 if (CI->getFunction()->optForSize()) 2232 return nullptr; 2233 2234 // Check if has any use 2235 if (!CI->use_empty()) { 2236 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI)) 2237 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B, 2238 TLI); 2239 else 2240 // We can't optimize if return value is used. 2241 return nullptr; 2242 } 2243 2244 // fputs(s,F) --> fwrite(s,1,strlen(s),F) 2245 uint64_t Len = GetStringLength(CI->getArgOperand(0)); 2246 if (!Len) 2247 return nullptr; 2248 2249 // Known to have no uses (see above). 2250 return emitFWrite( 2251 CI->getArgOperand(0), 2252 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1), 2253 CI->getArgOperand(1), B, DL, TLI); 2254 } 2255 2256 Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) { 2257 optimizeErrorReporting(CI, B, 1); 2258 2259 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI)) 2260 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B, 2261 TLI); 2262 2263 return nullptr; 2264 } 2265 2266 Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) { 2267 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI)) 2268 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI); 2269 2270 return nullptr; 2271 } 2272 2273 Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) { 2274 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI)) 2275 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), 2276 CI->getArgOperand(2), B, TLI); 2277 2278 return nullptr; 2279 } 2280 2281 Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) { 2282 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI)) 2283 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), 2284 CI->getArgOperand(2), CI->getArgOperand(3), B, DL, 2285 TLI); 2286 2287 return nullptr; 2288 } 2289 2290 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) { 2291 // Check for a constant string. 2292 StringRef Str; 2293 if (!getConstantStringInfo(CI->getArgOperand(0), Str)) 2294 return nullptr; 2295 2296 if (Str.empty() && CI->use_empty()) { 2297 // puts("") -> putchar('\n') 2298 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI); 2299 if (CI->use_empty() || !Res) 2300 return Res; 2301 return B.CreateIntCast(Res, CI->getType(), true); 2302 } 2303 2304 return nullptr; 2305 } 2306 2307 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) { 2308 LibFunc Func; 2309 SmallString<20> FloatFuncName = FuncName; 2310 FloatFuncName += 'f'; 2311 if (TLI->getLibFunc(FloatFuncName, Func)) 2312 return TLI->has(Func); 2313 return false; 2314 } 2315 2316 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI, 2317 IRBuilder<> &Builder) { 2318 LibFunc Func; 2319 Function *Callee = CI->getCalledFunction(); 2320 // Check for string/memory library functions. 2321 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 2322 // Make sure we never change the calling convention. 2323 assert((ignoreCallingConv(Func) || 2324 isCallingConvCCompatible(CI)) && 2325 "Optimizing string/memory libcall would change the calling convention"); 2326 switch (Func) { 2327 case LibFunc_strcat: 2328 return optimizeStrCat(CI, Builder); 2329 case LibFunc_strncat: 2330 return optimizeStrNCat(CI, Builder); 2331 case LibFunc_strchr: 2332 return optimizeStrChr(CI, Builder); 2333 case LibFunc_strrchr: 2334 return optimizeStrRChr(CI, Builder); 2335 case LibFunc_strcmp: 2336 return optimizeStrCmp(CI, Builder); 2337 case LibFunc_strncmp: 2338 return optimizeStrNCmp(CI, Builder); 2339 case LibFunc_strcpy: 2340 return optimizeStrCpy(CI, Builder); 2341 case LibFunc_stpcpy: 2342 return optimizeStpCpy(CI, Builder); 2343 case LibFunc_strncpy: 2344 return optimizeStrNCpy(CI, Builder); 2345 case LibFunc_strlen: 2346 return optimizeStrLen(CI, Builder); 2347 case LibFunc_strpbrk: 2348 return optimizeStrPBrk(CI, Builder); 2349 case LibFunc_strtol: 2350 case LibFunc_strtod: 2351 case LibFunc_strtof: 2352 case LibFunc_strtoul: 2353 case LibFunc_strtoll: 2354 case LibFunc_strtold: 2355 case LibFunc_strtoull: 2356 return optimizeStrTo(CI, Builder); 2357 case LibFunc_strspn: 2358 return optimizeStrSpn(CI, Builder); 2359 case LibFunc_strcspn: 2360 return optimizeStrCSpn(CI, Builder); 2361 case LibFunc_strstr: 2362 return optimizeStrStr(CI, Builder); 2363 case LibFunc_memchr: 2364 return optimizeMemChr(CI, Builder); 2365 case LibFunc_memcmp: 2366 return optimizeMemCmp(CI, Builder); 2367 case LibFunc_memcpy: 2368 return optimizeMemCpy(CI, Builder); 2369 case LibFunc_memmove: 2370 return optimizeMemMove(CI, Builder); 2371 case LibFunc_memset: 2372 return optimizeMemSet(CI, Builder); 2373 case LibFunc_realloc: 2374 return optimizeRealloc(CI, Builder); 2375 case LibFunc_wcslen: 2376 return optimizeWcslen(CI, Builder); 2377 default: 2378 break; 2379 } 2380 } 2381 return nullptr; 2382 } 2383 2384 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI, 2385 LibFunc Func, 2386 IRBuilder<> &Builder) { 2387 // Don't optimize calls that require strict floating point semantics. 2388 if (CI->isStrictFP()) 2389 return nullptr; 2390 2391 if (Value *V = optimizeTrigReflections(CI, Func, Builder)) 2392 return V; 2393 2394 switch (Func) { 2395 case LibFunc_sinpif: 2396 case LibFunc_sinpi: 2397 case LibFunc_cospif: 2398 case LibFunc_cospi: 2399 return optimizeSinCosPi(CI, Builder); 2400 case LibFunc_powf: 2401 case LibFunc_pow: 2402 case LibFunc_powl: 2403 return optimizePow(CI, Builder); 2404 case LibFunc_exp2l: 2405 case LibFunc_exp2: 2406 case LibFunc_exp2f: 2407 return optimizeExp2(CI, Builder); 2408 case LibFunc_fabsf: 2409 case LibFunc_fabs: 2410 case LibFunc_fabsl: 2411 return replaceUnaryCall(CI, Builder, Intrinsic::fabs); 2412 case LibFunc_sqrtf: 2413 case LibFunc_sqrt: 2414 case LibFunc_sqrtl: 2415 return optimizeSqrt(CI, Builder); 2416 case LibFunc_log: 2417 case LibFunc_log10: 2418 case LibFunc_log1p: 2419 case LibFunc_log2: 2420 case LibFunc_logb: 2421 return optimizeLog(CI, Builder); 2422 case LibFunc_tan: 2423 case LibFunc_tanf: 2424 case LibFunc_tanl: 2425 return optimizeTan(CI, Builder); 2426 case LibFunc_ceil: 2427 return replaceUnaryCall(CI, Builder, Intrinsic::ceil); 2428 case LibFunc_floor: 2429 return replaceUnaryCall(CI, Builder, Intrinsic::floor); 2430 case LibFunc_round: 2431 return replaceUnaryCall(CI, Builder, Intrinsic::round); 2432 case LibFunc_nearbyint: 2433 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint); 2434 case LibFunc_rint: 2435 return replaceUnaryCall(CI, Builder, Intrinsic::rint); 2436 case LibFunc_trunc: 2437 return replaceUnaryCall(CI, Builder, Intrinsic::trunc); 2438 case LibFunc_acos: 2439 case LibFunc_acosh: 2440 case LibFunc_asin: 2441 case LibFunc_asinh: 2442 case LibFunc_atan: 2443 case LibFunc_atanh: 2444 case LibFunc_cbrt: 2445 case LibFunc_cosh: 2446 case LibFunc_exp: 2447 case LibFunc_exp10: 2448 case LibFunc_expm1: 2449 case LibFunc_cos: 2450 case LibFunc_sin: 2451 case LibFunc_sinh: 2452 case LibFunc_tanh: 2453 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName())) 2454 return optimizeUnaryDoubleFP(CI, Builder, true); 2455 return nullptr; 2456 case LibFunc_copysign: 2457 if (hasFloatVersion(CI->getCalledFunction()->getName())) 2458 return optimizeBinaryDoubleFP(CI, Builder); 2459 return nullptr; 2460 case LibFunc_fminf: 2461 case LibFunc_fmin: 2462 case LibFunc_fminl: 2463 case LibFunc_fmaxf: 2464 case LibFunc_fmax: 2465 case LibFunc_fmaxl: 2466 return optimizeFMinFMax(CI, Builder); 2467 case LibFunc_cabs: 2468 case LibFunc_cabsf: 2469 case LibFunc_cabsl: 2470 return optimizeCAbs(CI, Builder); 2471 default: 2472 return nullptr; 2473 } 2474 } 2475 2476 Value *LibCallSimplifier::optimizeCall(CallInst *CI) { 2477 // TODO: Split out the code below that operates on FP calls so that 2478 // we can all non-FP calls with the StrictFP attribute to be 2479 // optimized. 2480 if (CI->isNoBuiltin()) 2481 return nullptr; 2482 2483 LibFunc Func; 2484 Function *Callee = CI->getCalledFunction(); 2485 2486 SmallVector<OperandBundleDef, 2> OpBundles; 2487 CI->getOperandBundlesAsDefs(OpBundles); 2488 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 2489 bool isCallingConvC = isCallingConvCCompatible(CI); 2490 2491 // Command-line parameter overrides instruction attribute. 2492 // This can't be moved to optimizeFloatingPointLibCall() because it may be 2493 // used by the intrinsic optimizations. 2494 if (EnableUnsafeFPShrink.getNumOccurrences() > 0) 2495 UnsafeFPShrink = EnableUnsafeFPShrink; 2496 else if (isa<FPMathOperator>(CI) && CI->isFast()) 2497 UnsafeFPShrink = true; 2498 2499 // First, check for intrinsics. 2500 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 2501 if (!isCallingConvC) 2502 return nullptr; 2503 // The FP intrinsics have corresponding constrained versions so we don't 2504 // need to check for the StrictFP attribute here. 2505 switch (II->getIntrinsicID()) { 2506 case Intrinsic::pow: 2507 return optimizePow(CI, Builder); 2508 case Intrinsic::exp2: 2509 return optimizeExp2(CI, Builder); 2510 case Intrinsic::log: 2511 return optimizeLog(CI, Builder); 2512 case Intrinsic::sqrt: 2513 return optimizeSqrt(CI, Builder); 2514 // TODO: Use foldMallocMemset() with memset intrinsic. 2515 default: 2516 return nullptr; 2517 } 2518 } 2519 2520 // Also try to simplify calls to fortified library functions. 2521 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) { 2522 // Try to further simplify the result. 2523 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI); 2524 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) { 2525 // Use an IR Builder from SimplifiedCI if available instead of CI 2526 // to guarantee we reach all uses we might replace later on. 2527 IRBuilder<> TmpBuilder(SimplifiedCI); 2528 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) { 2529 // If we were able to further simplify, remove the now redundant call. 2530 SimplifiedCI->replaceAllUsesWith(V); 2531 SimplifiedCI->eraseFromParent(); 2532 return V; 2533 } 2534 } 2535 return SimplifiedFortifiedCI; 2536 } 2537 2538 // Then check for known library functions. 2539 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) { 2540 // We never change the calling convention. 2541 if (!ignoreCallingConv(Func) && !isCallingConvC) 2542 return nullptr; 2543 if (Value *V = optimizeStringMemoryLibCall(CI, Builder)) 2544 return V; 2545 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder)) 2546 return V; 2547 switch (Func) { 2548 case LibFunc_ffs: 2549 case LibFunc_ffsl: 2550 case LibFunc_ffsll: 2551 return optimizeFFS(CI, Builder); 2552 case LibFunc_fls: 2553 case LibFunc_flsl: 2554 case LibFunc_flsll: 2555 return optimizeFls(CI, Builder); 2556 case LibFunc_abs: 2557 case LibFunc_labs: 2558 case LibFunc_llabs: 2559 return optimizeAbs(CI, Builder); 2560 case LibFunc_isdigit: 2561 return optimizeIsDigit(CI, Builder); 2562 case LibFunc_isascii: 2563 return optimizeIsAscii(CI, Builder); 2564 case LibFunc_toascii: 2565 return optimizeToAscii(CI, Builder); 2566 case LibFunc_atoi: 2567 case LibFunc_atol: 2568 case LibFunc_atoll: 2569 return optimizeAtoi(CI, Builder); 2570 case LibFunc_strtol: 2571 case LibFunc_strtoll: 2572 return optimizeStrtol(CI, Builder); 2573 case LibFunc_printf: 2574 return optimizePrintF(CI, Builder); 2575 case LibFunc_sprintf: 2576 return optimizeSPrintF(CI, Builder); 2577 case LibFunc_snprintf: 2578 return optimizeSnPrintF(CI, Builder); 2579 case LibFunc_fprintf: 2580 return optimizeFPrintF(CI, Builder); 2581 case LibFunc_fwrite: 2582 return optimizeFWrite(CI, Builder); 2583 case LibFunc_fread: 2584 return optimizeFRead(CI, Builder); 2585 case LibFunc_fputs: 2586 return optimizeFPuts(CI, Builder); 2587 case LibFunc_fgets: 2588 return optimizeFGets(CI, Builder); 2589 case LibFunc_fputc: 2590 return optimizeFPutc(CI, Builder); 2591 case LibFunc_fgetc: 2592 return optimizeFGetc(CI, Builder); 2593 case LibFunc_puts: 2594 return optimizePuts(CI, Builder); 2595 case LibFunc_perror: 2596 return optimizeErrorReporting(CI, Builder); 2597 case LibFunc_vfprintf: 2598 case LibFunc_fiprintf: 2599 return optimizeErrorReporting(CI, Builder, 0); 2600 default: 2601 return nullptr; 2602 } 2603 } 2604 return nullptr; 2605 } 2606 2607 LibCallSimplifier::LibCallSimplifier( 2608 const DataLayout &DL, const TargetLibraryInfo *TLI, 2609 OptimizationRemarkEmitter &ORE, 2610 function_ref<void(Instruction *, Value *)> Replacer) 2611 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), 2612 UnsafeFPShrink(false), Replacer(Replacer) {} 2613 2614 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) { 2615 // Indirect through the replacer used in this instance. 2616 Replacer(I, With); 2617 } 2618 2619 // TODO: 2620 // Additional cases that we need to add to this file: 2621 // 2622 // cbrt: 2623 // * cbrt(expN(X)) -> expN(x/3) 2624 // * cbrt(sqrt(x)) -> pow(x,1/6) 2625 // * cbrt(cbrt(x)) -> pow(x,1/9) 2626 // 2627 // exp, expf, expl: 2628 // * exp(log(x)) -> x 2629 // 2630 // log, logf, logl: 2631 // * log(exp(x)) -> x 2632 // * log(exp(y)) -> y*log(e) 2633 // * log(exp10(y)) -> y*log(10) 2634 // * log(sqrt(x)) -> 0.5*log(x) 2635 // 2636 // pow, powf, powl: 2637 // * pow(sqrt(x),y) -> pow(x,y*0.5) 2638 // * pow(pow(x,y),z)-> pow(x,y*z) 2639 // 2640 // signbit: 2641 // * signbit(cnst) -> cnst' 2642 // * signbit(nncst) -> 0 (if pstv is a non-negative constant) 2643 // 2644 // sqrt, sqrtf, sqrtl: 2645 // * sqrt(expN(x)) -> expN(x*0.5) 2646 // * sqrt(Nroot(x)) -> pow(x,1/(2*N)) 2647 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5) 2648 // 2649 2650 //===----------------------------------------------------------------------===// 2651 // Fortified Library Call Optimizations 2652 //===----------------------------------------------------------------------===// 2653 2654 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI, 2655 unsigned ObjSizeOp, 2656 unsigned SizeOp, 2657 bool isString) { 2658 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp)) 2659 return true; 2660 if (ConstantInt *ObjSizeCI = 2661 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) { 2662 if (ObjSizeCI->isMinusOne()) 2663 return true; 2664 // If the object size wasn't -1 (unknown), bail out if we were asked to. 2665 if (OnlyLowerUnknownSize) 2666 return false; 2667 if (isString) { 2668 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp)); 2669 // If the length is 0 we don't know how long it is and so we can't 2670 // remove the check. 2671 if (Len == 0) 2672 return false; 2673 return ObjSizeCI->getZExtValue() >= Len; 2674 } 2675 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp))) 2676 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue(); 2677 } 2678 return false; 2679 } 2680 2681 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, 2682 IRBuilder<> &B) { 2683 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2684 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, 2685 CI->getArgOperand(2)); 2686 return CI->getArgOperand(0); 2687 } 2688 return nullptr; 2689 } 2690 2691 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, 2692 IRBuilder<> &B) { 2693 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2694 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, 2695 CI->getArgOperand(2)); 2696 return CI->getArgOperand(0); 2697 } 2698 return nullptr; 2699 } 2700 2701 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, 2702 IRBuilder<> &B) { 2703 // TODO: Try foldMallocMemset() here. 2704 2705 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2706 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false); 2707 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1); 2708 return CI->getArgOperand(0); 2709 } 2710 return nullptr; 2711 } 2712 2713 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI, 2714 IRBuilder<> &B, 2715 LibFunc Func) { 2716 Function *Callee = CI->getCalledFunction(); 2717 StringRef Name = Callee->getName(); 2718 const DataLayout &DL = CI->getModule()->getDataLayout(); 2719 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1), 2720 *ObjSize = CI->getArgOperand(2); 2721 2722 // __stpcpy_chk(x,x,...) -> x+strlen(x) 2723 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) { 2724 Value *StrLen = emitStrLen(Src, B, DL, TLI); 2725 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr; 2726 } 2727 2728 // If a) we don't have any length information, or b) we know this will 2729 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our 2730 // st[rp]cpy_chk call which may fail at runtime if the size is too long. 2731 // TODO: It might be nice to get a maximum length out of the possible 2732 // string lengths for varying. 2733 if (isFortifiedCallFoldable(CI, 2, 1, true)) 2734 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6)); 2735 2736 if (OnlyLowerUnknownSize) 2737 return nullptr; 2738 2739 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk. 2740 uint64_t Len = GetStringLength(Src); 2741 if (Len == 0) 2742 return nullptr; 2743 2744 Type *SizeTTy = DL.getIntPtrType(CI->getContext()); 2745 Value *LenV = ConstantInt::get(SizeTTy, Len); 2746 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI); 2747 // If the function was an __stpcpy_chk, and we were able to fold it into 2748 // a __memcpy_chk, we still need to return the correct end pointer. 2749 if (Ret && Func == LibFunc_stpcpy_chk) 2750 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1)); 2751 return Ret; 2752 } 2753 2754 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI, 2755 IRBuilder<> &B, 2756 LibFunc Func) { 2757 Function *Callee = CI->getCalledFunction(); 2758 StringRef Name = Callee->getName(); 2759 if (isFortifiedCallFoldable(CI, 3, 2, false)) { 2760 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1), 2761 CI->getArgOperand(2), B, TLI, Name.substr(2, 7)); 2762 return Ret; 2763 } 2764 return nullptr; 2765 } 2766 2767 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) { 2768 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here. 2769 // Some clang users checked for _chk libcall availability using: 2770 // __has_builtin(__builtin___memcpy_chk) 2771 // When compiling with -fno-builtin, this is always true. 2772 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we 2773 // end up with fortified libcalls, which isn't acceptable in a freestanding 2774 // environment which only provides their non-fortified counterparts. 2775 // 2776 // Until we change clang and/or teach external users to check for availability 2777 // differently, disregard the "nobuiltin" attribute and TLI::has. 2778 // 2779 // PR23093. 2780 2781 LibFunc Func; 2782 Function *Callee = CI->getCalledFunction(); 2783 2784 SmallVector<OperandBundleDef, 2> OpBundles; 2785 CI->getOperandBundlesAsDefs(OpBundles); 2786 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles); 2787 bool isCallingConvC = isCallingConvCCompatible(CI); 2788 2789 // First, check that this is a known library functions and that the prototype 2790 // is correct. 2791 if (!TLI->getLibFunc(*Callee, Func)) 2792 return nullptr; 2793 2794 // We never change the calling convention. 2795 if (!ignoreCallingConv(Func) && !isCallingConvC) 2796 return nullptr; 2797 2798 switch (Func) { 2799 case LibFunc_memcpy_chk: 2800 return optimizeMemCpyChk(CI, Builder); 2801 case LibFunc_memmove_chk: 2802 return optimizeMemMoveChk(CI, Builder); 2803 case LibFunc_memset_chk: 2804 return optimizeMemSetChk(CI, Builder); 2805 case LibFunc_stpcpy_chk: 2806 case LibFunc_strcpy_chk: 2807 return optimizeStrpCpyChk(CI, Builder, Func); 2808 case LibFunc_stpncpy_chk: 2809 case LibFunc_strncpy_chk: 2810 return optimizeStrpNCpyChk(CI, Builder, Func); 2811 default: 2812 break; 2813 } 2814 return nullptr; 2815 } 2816 2817 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier( 2818 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize) 2819 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {} 2820