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