1 //===- AMDGPULibCalls.cpp -------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// This file does AMD library function optimizations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AMDGPU.h" 15 #include "AMDGPULibFunc.h" 16 #include "GCNSubtarget.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/Loads.h" 19 #include "llvm/IR/IRBuilder.h" 20 #include "llvm/IR/IntrinsicInst.h" 21 #include "llvm/IR/IntrinsicsAMDGPU.h" 22 #include "llvm/InitializePasses.h" 23 #include <cmath> 24 25 #define DEBUG_TYPE "amdgpu-simplifylib" 26 27 using namespace llvm; 28 29 static cl::opt<bool> EnablePreLink("amdgpu-prelink", 30 cl::desc("Enable pre-link mode optimizations"), 31 cl::init(false), 32 cl::Hidden); 33 34 static cl::list<std::string> UseNative("amdgpu-use-native", 35 cl::desc("Comma separated list of functions to replace with native, or all"), 36 cl::CommaSeparated, cl::ValueOptional, 37 cl::Hidden); 38 39 #define MATH_PI numbers::pi 40 #define MATH_E numbers::e 41 #define MATH_SQRT2 numbers::sqrt2 42 #define MATH_SQRT1_2 numbers::inv_sqrt2 43 44 namespace llvm { 45 46 class AMDGPULibCalls { 47 private: 48 49 typedef llvm::AMDGPULibFunc FuncInfo; 50 51 bool UnsafeFPMath = false; 52 53 // -fuse-native. 54 bool AllNative = false; 55 56 bool useNativeFunc(const StringRef F) const; 57 58 // Return a pointer (pointer expr) to the function if function definition with 59 // "FuncName" exists. It may create a new function prototype in pre-link mode. 60 FunctionCallee getFunction(Module *M, const FuncInfo &fInfo); 61 62 bool parseFunctionName(const StringRef &FMangledName, FuncInfo &FInfo); 63 64 bool TDOFold(CallInst *CI, const FuncInfo &FInfo); 65 66 /* Specialized optimizations */ 67 68 // pow/powr/pown 69 bool fold_pow(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo); 70 71 // rootn 72 bool fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo); 73 74 // -fuse-native for sincos 75 bool sincosUseNative(CallInst *aCI, const FuncInfo &FInfo); 76 77 // evaluate calls if calls' arguments are constants. 78 bool evaluateScalarMathFunc(const FuncInfo &FInfo, double& Res0, 79 double& Res1, Constant *copr0, Constant *copr1, Constant *copr2); 80 bool evaluateCall(CallInst *aCI, const FuncInfo &FInfo); 81 82 // sqrt 83 bool fold_sqrt(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo); 84 85 /// Insert a value to sincos function \p Fsincos. Returns (value of sin, value 86 /// of cos, sincos call). 87 std::tuple<Value *, Value *, Value *> insertSinCos(Value *Arg, 88 FastMathFlags FMF, 89 IRBuilder<> &B, 90 FunctionCallee Fsincos); 91 92 // sin/cos 93 bool fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo); 94 95 // __read_pipe/__write_pipe 96 bool fold_read_write_pipe(CallInst *CI, IRBuilder<> &B, 97 const FuncInfo &FInfo); 98 99 // Get a scalar native builtin single argument FP function 100 FunctionCallee getNativeFunction(Module *M, const FuncInfo &FInfo); 101 102 /// Substitute a call to a known libcall with an intrinsic call. If \p 103 /// AllowMinSize is true, allow the replacement in a minsize function. 104 bool shouldReplaceLibcallWithIntrinsic(const CallInst *CI, 105 bool AllowMinSizeF32 = false, 106 bool AllowF64 = false); 107 void replaceLibCallWithSimpleIntrinsic(CallInst *CI, Intrinsic::ID IntrID); 108 109 bool tryReplaceLibcallWithSimpleIntrinsic(CallInst *CI, Intrinsic::ID IntrID, 110 bool AllowMinSizeF32 = false, 111 bool AllowF64 = false); 112 113 protected: 114 bool isUnsafeMath(const FPMathOperator *FPOp) const; 115 116 bool canIncreasePrecisionOfConstantFold(const FPMathOperator *FPOp) const; 117 118 static void replaceCall(Instruction *I, Value *With) { 119 I->replaceAllUsesWith(With); 120 I->eraseFromParent(); 121 } 122 123 static void replaceCall(FPMathOperator *I, Value *With) { 124 replaceCall(cast<Instruction>(I), With); 125 } 126 127 public: 128 AMDGPULibCalls() {} 129 130 bool fold(CallInst *CI); 131 132 void initFunction(const Function &F); 133 void initNativeFuncs(); 134 135 // Replace a normal math function call with that native version 136 bool useNative(CallInst *CI); 137 }; 138 139 } // end llvm namespace 140 141 template <typename IRB> 142 static CallInst *CreateCallEx(IRB &B, FunctionCallee Callee, Value *Arg, 143 const Twine &Name = "") { 144 CallInst *R = B.CreateCall(Callee, Arg, Name); 145 if (Function *F = dyn_cast<Function>(Callee.getCallee())) 146 R->setCallingConv(F->getCallingConv()); 147 return R; 148 } 149 150 template <typename IRB> 151 static CallInst *CreateCallEx2(IRB &B, FunctionCallee Callee, Value *Arg1, 152 Value *Arg2, const Twine &Name = "") { 153 CallInst *R = B.CreateCall(Callee, {Arg1, Arg2}, Name); 154 if (Function *F = dyn_cast<Function>(Callee.getCallee())) 155 R->setCallingConv(F->getCallingConv()); 156 return R; 157 } 158 159 // Data structures for table-driven optimizations. 160 // FuncTbl works for both f32 and f64 functions with 1 input argument 161 162 struct TableEntry { 163 double result; 164 double input; 165 }; 166 167 /* a list of {result, input} */ 168 static const TableEntry tbl_acos[] = { 169 {MATH_PI / 2.0, 0.0}, 170 {MATH_PI / 2.0, -0.0}, 171 {0.0, 1.0}, 172 {MATH_PI, -1.0} 173 }; 174 static const TableEntry tbl_acosh[] = { 175 {0.0, 1.0} 176 }; 177 static const TableEntry tbl_acospi[] = { 178 {0.5, 0.0}, 179 {0.5, -0.0}, 180 {0.0, 1.0}, 181 {1.0, -1.0} 182 }; 183 static const TableEntry tbl_asin[] = { 184 {0.0, 0.0}, 185 {-0.0, -0.0}, 186 {MATH_PI / 2.0, 1.0}, 187 {-MATH_PI / 2.0, -1.0} 188 }; 189 static const TableEntry tbl_asinh[] = { 190 {0.0, 0.0}, 191 {-0.0, -0.0} 192 }; 193 static const TableEntry tbl_asinpi[] = { 194 {0.0, 0.0}, 195 {-0.0, -0.0}, 196 {0.5, 1.0}, 197 {-0.5, -1.0} 198 }; 199 static const TableEntry tbl_atan[] = { 200 {0.0, 0.0}, 201 {-0.0, -0.0}, 202 {MATH_PI / 4.0, 1.0}, 203 {-MATH_PI / 4.0, -1.0} 204 }; 205 static const TableEntry tbl_atanh[] = { 206 {0.0, 0.0}, 207 {-0.0, -0.0} 208 }; 209 static const TableEntry tbl_atanpi[] = { 210 {0.0, 0.0}, 211 {-0.0, -0.0}, 212 {0.25, 1.0}, 213 {-0.25, -1.0} 214 }; 215 static const TableEntry tbl_cbrt[] = { 216 {0.0, 0.0}, 217 {-0.0, -0.0}, 218 {1.0, 1.0}, 219 {-1.0, -1.0}, 220 }; 221 static const TableEntry tbl_cos[] = { 222 {1.0, 0.0}, 223 {1.0, -0.0} 224 }; 225 static const TableEntry tbl_cosh[] = { 226 {1.0, 0.0}, 227 {1.0, -0.0} 228 }; 229 static const TableEntry tbl_cospi[] = { 230 {1.0, 0.0}, 231 {1.0, -0.0} 232 }; 233 static const TableEntry tbl_erfc[] = { 234 {1.0, 0.0}, 235 {1.0, -0.0} 236 }; 237 static const TableEntry tbl_erf[] = { 238 {0.0, 0.0}, 239 {-0.0, -0.0} 240 }; 241 static const TableEntry tbl_exp[] = { 242 {1.0, 0.0}, 243 {1.0, -0.0}, 244 {MATH_E, 1.0} 245 }; 246 static const TableEntry tbl_exp2[] = { 247 {1.0, 0.0}, 248 {1.0, -0.0}, 249 {2.0, 1.0} 250 }; 251 static const TableEntry tbl_exp10[] = { 252 {1.0, 0.0}, 253 {1.0, -0.0}, 254 {10.0, 1.0} 255 }; 256 static const TableEntry tbl_expm1[] = { 257 {0.0, 0.0}, 258 {-0.0, -0.0} 259 }; 260 static const TableEntry tbl_log[] = { 261 {0.0, 1.0}, 262 {1.0, MATH_E} 263 }; 264 static const TableEntry tbl_log2[] = { 265 {0.0, 1.0}, 266 {1.0, 2.0} 267 }; 268 static const TableEntry tbl_log10[] = { 269 {0.0, 1.0}, 270 {1.0, 10.0} 271 }; 272 static const TableEntry tbl_rsqrt[] = { 273 {1.0, 1.0}, 274 {MATH_SQRT1_2, 2.0} 275 }; 276 static const TableEntry tbl_sin[] = { 277 {0.0, 0.0}, 278 {-0.0, -0.0} 279 }; 280 static const TableEntry tbl_sinh[] = { 281 {0.0, 0.0}, 282 {-0.0, -0.0} 283 }; 284 static const TableEntry tbl_sinpi[] = { 285 {0.0, 0.0}, 286 {-0.0, -0.0} 287 }; 288 static const TableEntry tbl_sqrt[] = { 289 {0.0, 0.0}, 290 {1.0, 1.0}, 291 {MATH_SQRT2, 2.0} 292 }; 293 static const TableEntry tbl_tan[] = { 294 {0.0, 0.0}, 295 {-0.0, -0.0} 296 }; 297 static const TableEntry tbl_tanh[] = { 298 {0.0, 0.0}, 299 {-0.0, -0.0} 300 }; 301 static const TableEntry tbl_tanpi[] = { 302 {0.0, 0.0}, 303 {-0.0, -0.0} 304 }; 305 static const TableEntry tbl_tgamma[] = { 306 {1.0, 1.0}, 307 {1.0, 2.0}, 308 {2.0, 3.0}, 309 {6.0, 4.0} 310 }; 311 312 static bool HasNative(AMDGPULibFunc::EFuncId id) { 313 switch(id) { 314 case AMDGPULibFunc::EI_DIVIDE: 315 case AMDGPULibFunc::EI_COS: 316 case AMDGPULibFunc::EI_EXP: 317 case AMDGPULibFunc::EI_EXP2: 318 case AMDGPULibFunc::EI_EXP10: 319 case AMDGPULibFunc::EI_LOG: 320 case AMDGPULibFunc::EI_LOG2: 321 case AMDGPULibFunc::EI_LOG10: 322 case AMDGPULibFunc::EI_POWR: 323 case AMDGPULibFunc::EI_RECIP: 324 case AMDGPULibFunc::EI_RSQRT: 325 case AMDGPULibFunc::EI_SIN: 326 case AMDGPULibFunc::EI_SINCOS: 327 case AMDGPULibFunc::EI_SQRT: 328 case AMDGPULibFunc::EI_TAN: 329 return true; 330 default:; 331 } 332 return false; 333 } 334 335 using TableRef = ArrayRef<TableEntry>; 336 337 static TableRef getOptTable(AMDGPULibFunc::EFuncId id) { 338 switch(id) { 339 case AMDGPULibFunc::EI_ACOS: return TableRef(tbl_acos); 340 case AMDGPULibFunc::EI_ACOSH: return TableRef(tbl_acosh); 341 case AMDGPULibFunc::EI_ACOSPI: return TableRef(tbl_acospi); 342 case AMDGPULibFunc::EI_ASIN: return TableRef(tbl_asin); 343 case AMDGPULibFunc::EI_ASINH: return TableRef(tbl_asinh); 344 case AMDGPULibFunc::EI_ASINPI: return TableRef(tbl_asinpi); 345 case AMDGPULibFunc::EI_ATAN: return TableRef(tbl_atan); 346 case AMDGPULibFunc::EI_ATANH: return TableRef(tbl_atanh); 347 case AMDGPULibFunc::EI_ATANPI: return TableRef(tbl_atanpi); 348 case AMDGPULibFunc::EI_CBRT: return TableRef(tbl_cbrt); 349 case AMDGPULibFunc::EI_NCOS: 350 case AMDGPULibFunc::EI_COS: return TableRef(tbl_cos); 351 case AMDGPULibFunc::EI_COSH: return TableRef(tbl_cosh); 352 case AMDGPULibFunc::EI_COSPI: return TableRef(tbl_cospi); 353 case AMDGPULibFunc::EI_ERFC: return TableRef(tbl_erfc); 354 case AMDGPULibFunc::EI_ERF: return TableRef(tbl_erf); 355 case AMDGPULibFunc::EI_EXP: return TableRef(tbl_exp); 356 case AMDGPULibFunc::EI_NEXP2: 357 case AMDGPULibFunc::EI_EXP2: return TableRef(tbl_exp2); 358 case AMDGPULibFunc::EI_EXP10: return TableRef(tbl_exp10); 359 case AMDGPULibFunc::EI_EXPM1: return TableRef(tbl_expm1); 360 case AMDGPULibFunc::EI_LOG: return TableRef(tbl_log); 361 case AMDGPULibFunc::EI_NLOG2: 362 case AMDGPULibFunc::EI_LOG2: return TableRef(tbl_log2); 363 case AMDGPULibFunc::EI_LOG10: return TableRef(tbl_log10); 364 case AMDGPULibFunc::EI_NRSQRT: 365 case AMDGPULibFunc::EI_RSQRT: return TableRef(tbl_rsqrt); 366 case AMDGPULibFunc::EI_NSIN: 367 case AMDGPULibFunc::EI_SIN: return TableRef(tbl_sin); 368 case AMDGPULibFunc::EI_SINH: return TableRef(tbl_sinh); 369 case AMDGPULibFunc::EI_SINPI: return TableRef(tbl_sinpi); 370 case AMDGPULibFunc::EI_NSQRT: 371 case AMDGPULibFunc::EI_SQRT: return TableRef(tbl_sqrt); 372 case AMDGPULibFunc::EI_TAN: return TableRef(tbl_tan); 373 case AMDGPULibFunc::EI_TANH: return TableRef(tbl_tanh); 374 case AMDGPULibFunc::EI_TANPI: return TableRef(tbl_tanpi); 375 case AMDGPULibFunc::EI_TGAMMA: return TableRef(tbl_tgamma); 376 default:; 377 } 378 return TableRef(); 379 } 380 381 static inline int getVecSize(const AMDGPULibFunc& FInfo) { 382 return FInfo.getLeads()[0].VectorSize; 383 } 384 385 static inline AMDGPULibFunc::EType getArgType(const AMDGPULibFunc& FInfo) { 386 return (AMDGPULibFunc::EType)FInfo.getLeads()[0].ArgType; 387 } 388 389 FunctionCallee AMDGPULibCalls::getFunction(Module *M, const FuncInfo &fInfo) { 390 // If we are doing PreLinkOpt, the function is external. So it is safe to 391 // use getOrInsertFunction() at this stage. 392 393 return EnablePreLink ? AMDGPULibFunc::getOrInsertFunction(M, fInfo) 394 : AMDGPULibFunc::getFunction(M, fInfo); 395 } 396 397 bool AMDGPULibCalls::parseFunctionName(const StringRef &FMangledName, 398 FuncInfo &FInfo) { 399 return AMDGPULibFunc::parse(FMangledName, FInfo); 400 } 401 402 bool AMDGPULibCalls::isUnsafeMath(const FPMathOperator *FPOp) const { 403 return UnsafeFPMath || FPOp->isFast(); 404 } 405 406 bool AMDGPULibCalls::canIncreasePrecisionOfConstantFold( 407 const FPMathOperator *FPOp) const { 408 // TODO: Refine to approxFunc or contract 409 return isUnsafeMath(FPOp); 410 } 411 412 void AMDGPULibCalls::initFunction(const Function &F) { 413 UnsafeFPMath = F.getFnAttribute("unsafe-fp-math").getValueAsBool(); 414 } 415 416 bool AMDGPULibCalls::useNativeFunc(const StringRef F) const { 417 return AllNative || llvm::is_contained(UseNative, F); 418 } 419 420 void AMDGPULibCalls::initNativeFuncs() { 421 AllNative = useNativeFunc("all") || 422 (UseNative.getNumOccurrences() && UseNative.size() == 1 && 423 UseNative.begin()->empty()); 424 } 425 426 bool AMDGPULibCalls::sincosUseNative(CallInst *aCI, const FuncInfo &FInfo) { 427 bool native_sin = useNativeFunc("sin"); 428 bool native_cos = useNativeFunc("cos"); 429 430 if (native_sin && native_cos) { 431 Module *M = aCI->getModule(); 432 Value *opr0 = aCI->getArgOperand(0); 433 434 AMDGPULibFunc nf; 435 nf.getLeads()[0].ArgType = FInfo.getLeads()[0].ArgType; 436 nf.getLeads()[0].VectorSize = FInfo.getLeads()[0].VectorSize; 437 438 nf.setPrefix(AMDGPULibFunc::NATIVE); 439 nf.setId(AMDGPULibFunc::EI_SIN); 440 FunctionCallee sinExpr = getFunction(M, nf); 441 442 nf.setPrefix(AMDGPULibFunc::NATIVE); 443 nf.setId(AMDGPULibFunc::EI_COS); 444 FunctionCallee cosExpr = getFunction(M, nf); 445 if (sinExpr && cosExpr) { 446 Value *sinval = CallInst::Create(sinExpr, opr0, "splitsin", aCI); 447 Value *cosval = CallInst::Create(cosExpr, opr0, "splitcos", aCI); 448 new StoreInst(cosval, aCI->getArgOperand(1), aCI); 449 450 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI 451 << " with native version of sin/cos"); 452 453 replaceCall(aCI, sinval); 454 return true; 455 } 456 } 457 return false; 458 } 459 460 bool AMDGPULibCalls::useNative(CallInst *aCI) { 461 Function *Callee = aCI->getCalledFunction(); 462 if (!Callee || aCI->isNoBuiltin()) 463 return false; 464 465 FuncInfo FInfo; 466 if (!parseFunctionName(Callee->getName(), FInfo) || !FInfo.isMangled() || 467 FInfo.getPrefix() != AMDGPULibFunc::NOPFX || 468 getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()) || 469 !(AllNative || useNativeFunc(FInfo.getName()))) { 470 return false; 471 } 472 473 if (FInfo.getId() == AMDGPULibFunc::EI_SINCOS) 474 return sincosUseNative(aCI, FInfo); 475 476 FInfo.setPrefix(AMDGPULibFunc::NATIVE); 477 FunctionCallee F = getFunction(aCI->getModule(), FInfo); 478 if (!F) 479 return false; 480 481 aCI->setCalledFunction(F); 482 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI 483 << " with native version"); 484 return true; 485 } 486 487 // Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe 488 // builtin, with appended type size and alignment arguments, where 2 or 4 489 // indicates the original number of arguments. The library has optimized version 490 // of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same 491 // power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N 492 // for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ..., 493 // 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4. 494 bool AMDGPULibCalls::fold_read_write_pipe(CallInst *CI, IRBuilder<> &B, 495 const FuncInfo &FInfo) { 496 auto *Callee = CI->getCalledFunction(); 497 if (!Callee->isDeclaration()) 498 return false; 499 500 assert(Callee->hasName() && "Invalid read_pipe/write_pipe function"); 501 auto *M = Callee->getParent(); 502 std::string Name = std::string(Callee->getName()); 503 auto NumArg = CI->arg_size(); 504 if (NumArg != 4 && NumArg != 6) 505 return false; 506 ConstantInt *PacketSize = 507 dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 2)); 508 ConstantInt *PacketAlign = 509 dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 1)); 510 if (!PacketSize || !PacketAlign) 511 return false; 512 513 unsigned Size = PacketSize->getZExtValue(); 514 Align Alignment = PacketAlign->getAlignValue(); 515 if (Alignment != Size) 516 return false; 517 518 unsigned PtrArgLoc = CI->arg_size() - 3; 519 Value *PtrArg = CI->getArgOperand(PtrArgLoc); 520 Type *PtrTy = PtrArg->getType(); 521 522 SmallVector<llvm::Type *, 6> ArgTys; 523 for (unsigned I = 0; I != PtrArgLoc; ++I) 524 ArgTys.push_back(CI->getArgOperand(I)->getType()); 525 ArgTys.push_back(PtrTy); 526 527 Name = Name + "_" + std::to_string(Size); 528 auto *FTy = FunctionType::get(Callee->getReturnType(), 529 ArrayRef<Type *>(ArgTys), false); 530 AMDGPULibFunc NewLibFunc(Name, FTy); 531 FunctionCallee F = AMDGPULibFunc::getOrInsertFunction(M, NewLibFunc); 532 if (!F) 533 return false; 534 535 auto *BCast = B.CreatePointerCast(PtrArg, PtrTy); 536 SmallVector<Value *, 6> Args; 537 for (unsigned I = 0; I != PtrArgLoc; ++I) 538 Args.push_back(CI->getArgOperand(I)); 539 Args.push_back(BCast); 540 541 auto *NCI = B.CreateCall(F, Args); 542 NCI->setAttributes(CI->getAttributes()); 543 CI->replaceAllUsesWith(NCI); 544 CI->dropAllReferences(); 545 CI->eraseFromParent(); 546 547 return true; 548 } 549 550 // This function returns false if no change; return true otherwise. 551 bool AMDGPULibCalls::fold(CallInst *CI) { 552 Function *Callee = CI->getCalledFunction(); 553 // Ignore indirect calls. 554 if (!Callee || Callee->isIntrinsic() || CI->isNoBuiltin()) 555 return false; 556 557 FuncInfo FInfo; 558 if (!parseFunctionName(Callee->getName(), FInfo)) 559 return false; 560 561 // Further check the number of arguments to see if they match. 562 // TODO: Check calling convention matches too 563 if (!FInfo.isCompatibleSignature(CI->getFunctionType())) 564 return false; 565 566 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI << '\n'); 567 568 if (TDOFold(CI, FInfo)) 569 return true; 570 571 IRBuilder<> B(CI); 572 573 if (FPMathOperator *FPOp = dyn_cast<FPMathOperator>(CI)) { 574 // Under unsafe-math, evaluate calls if possible. 575 // According to Brian Sumner, we can do this for all f32 function calls 576 // using host's double function calls. 577 if (canIncreasePrecisionOfConstantFold(FPOp) && evaluateCall(CI, FInfo)) 578 return true; 579 580 // Copy fast flags from the original call. 581 FastMathFlags FMF = FPOp->getFastMathFlags(); 582 B.setFastMathFlags(FMF); 583 584 // Specialized optimizations for each function call. 585 // 586 // TODO: Handle other simple intrinsic wrappers. Sqrt, copysign, fabs, 587 // ldexp, log, rounding intrinsics. 588 // 589 // TODO: Handle native functions 590 switch (FInfo.getId()) { 591 case AMDGPULibFunc::EI_EXP: 592 if (FMF.none()) 593 return false; 594 return tryReplaceLibcallWithSimpleIntrinsic(CI, Intrinsic::exp, 595 FMF.approxFunc()); 596 case AMDGPULibFunc::EI_EXP2: 597 if (FMF.none()) 598 return false; 599 return tryReplaceLibcallWithSimpleIntrinsic(CI, Intrinsic::exp2, 600 FMF.approxFunc()); 601 case AMDGPULibFunc::EI_FMIN: 602 return tryReplaceLibcallWithSimpleIntrinsic(CI, Intrinsic::minnum, true, 603 true); 604 case AMDGPULibFunc::EI_FMAX: 605 return tryReplaceLibcallWithSimpleIntrinsic(CI, Intrinsic::maxnum, true, 606 true); 607 case AMDGPULibFunc::EI_FMA: 608 return tryReplaceLibcallWithSimpleIntrinsic(CI, Intrinsic::fma, true, 609 true); 610 case AMDGPULibFunc::EI_MAD: 611 return tryReplaceLibcallWithSimpleIntrinsic(CI, Intrinsic::fmuladd, true, 612 true); 613 case AMDGPULibFunc::EI_POW: 614 case AMDGPULibFunc::EI_POWR: 615 case AMDGPULibFunc::EI_POWN: 616 return fold_pow(FPOp, B, FInfo); 617 case AMDGPULibFunc::EI_ROOTN: 618 return fold_rootn(FPOp, B, FInfo); 619 case AMDGPULibFunc::EI_SQRT: 620 return fold_sqrt(FPOp, B, FInfo); 621 case AMDGPULibFunc::EI_COS: 622 case AMDGPULibFunc::EI_SIN: 623 return fold_sincos(FPOp, B, FInfo); 624 default: 625 break; 626 } 627 } else { 628 // Specialized optimizations for each function call 629 switch (FInfo.getId()) { 630 case AMDGPULibFunc::EI_READ_PIPE_2: 631 case AMDGPULibFunc::EI_READ_PIPE_4: 632 case AMDGPULibFunc::EI_WRITE_PIPE_2: 633 case AMDGPULibFunc::EI_WRITE_PIPE_4: 634 return fold_read_write_pipe(CI, B, FInfo); 635 default: 636 break; 637 } 638 } 639 640 return false; 641 } 642 643 bool AMDGPULibCalls::TDOFold(CallInst *CI, const FuncInfo &FInfo) { 644 // Table-Driven optimization 645 const TableRef tr = getOptTable(FInfo.getId()); 646 if (tr.empty()) 647 return false; 648 649 int const sz = (int)tr.size(); 650 Value *opr0 = CI->getArgOperand(0); 651 652 if (getVecSize(FInfo) > 1) { 653 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(opr0)) { 654 SmallVector<double, 0> DVal; 655 for (int eltNo = 0; eltNo < getVecSize(FInfo); ++eltNo) { 656 ConstantFP *eltval = dyn_cast<ConstantFP>( 657 CV->getElementAsConstant((unsigned)eltNo)); 658 assert(eltval && "Non-FP arguments in math function!"); 659 bool found = false; 660 for (int i=0; i < sz; ++i) { 661 if (eltval->isExactlyValue(tr[i].input)) { 662 DVal.push_back(tr[i].result); 663 found = true; 664 break; 665 } 666 } 667 if (!found) { 668 // This vector constants not handled yet. 669 return false; 670 } 671 } 672 LLVMContext &context = CI->getParent()->getParent()->getContext(); 673 Constant *nval; 674 if (getArgType(FInfo) == AMDGPULibFunc::F32) { 675 SmallVector<float, 0> FVal; 676 for (unsigned i = 0; i < DVal.size(); ++i) { 677 FVal.push_back((float)DVal[i]); 678 } 679 ArrayRef<float> tmp(FVal); 680 nval = ConstantDataVector::get(context, tmp); 681 } else { // F64 682 ArrayRef<double> tmp(DVal); 683 nval = ConstantDataVector::get(context, tmp); 684 } 685 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n"); 686 replaceCall(CI, nval); 687 return true; 688 } 689 } else { 690 // Scalar version 691 if (ConstantFP *CF = dyn_cast<ConstantFP>(opr0)) { 692 for (int i = 0; i < sz; ++i) { 693 if (CF->isExactlyValue(tr[i].input)) { 694 Value *nval = ConstantFP::get(CF->getType(), tr[i].result); 695 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n"); 696 replaceCall(CI, nval); 697 return true; 698 } 699 } 700 } 701 } 702 703 return false; 704 } 705 706 namespace llvm { 707 static double log2(double V) { 708 #if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L 709 return ::log2(V); 710 #else 711 return log(V) / numbers::ln2; 712 #endif 713 } 714 } 715 716 bool AMDGPULibCalls::fold_pow(FPMathOperator *FPOp, IRBuilder<> &B, 717 const FuncInfo &FInfo) { 718 assert((FInfo.getId() == AMDGPULibFunc::EI_POW || 719 FInfo.getId() == AMDGPULibFunc::EI_POWR || 720 FInfo.getId() == AMDGPULibFunc::EI_POWN) && 721 "fold_pow: encounter a wrong function call"); 722 723 Module *M = B.GetInsertBlock()->getModule(); 724 ConstantFP *CF; 725 ConstantInt *CINT; 726 Type *eltType; 727 Value *opr0 = FPOp->getOperand(0); 728 Value *opr1 = FPOp->getOperand(1); 729 ConstantAggregateZero *CZero = dyn_cast<ConstantAggregateZero>(opr1); 730 731 if (getVecSize(FInfo) == 1) { 732 eltType = opr0->getType(); 733 CF = dyn_cast<ConstantFP>(opr1); 734 CINT = dyn_cast<ConstantInt>(opr1); 735 } else { 736 VectorType *VTy = dyn_cast<VectorType>(opr0->getType()); 737 assert(VTy && "Oprand of vector function should be of vectortype"); 738 eltType = VTy->getElementType(); 739 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr1); 740 741 // Now, only Handle vector const whose elements have the same value. 742 CF = CDV ? dyn_cast_or_null<ConstantFP>(CDV->getSplatValue()) : nullptr; 743 CINT = CDV ? dyn_cast_or_null<ConstantInt>(CDV->getSplatValue()) : nullptr; 744 } 745 746 // No unsafe math , no constant argument, do nothing 747 if (!isUnsafeMath(FPOp) && !CF && !CINT && !CZero) 748 return false; 749 750 // 0x1111111 means that we don't do anything for this call. 751 int ci_opr1 = (CINT ? (int)CINT->getSExtValue() : 0x1111111); 752 753 if ((CF && CF->isZero()) || (CINT && ci_opr1 == 0) || CZero) { 754 // pow/powr/pown(x, 0) == 1 755 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1\n"); 756 Constant *cnval = ConstantFP::get(eltType, 1.0); 757 if (getVecSize(FInfo) > 1) { 758 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval); 759 } 760 replaceCall(FPOp, cnval); 761 return true; 762 } 763 if ((CF && CF->isExactlyValue(1.0)) || (CINT && ci_opr1 == 1)) { 764 // pow/powr/pown(x, 1.0) = x 765 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n"); 766 replaceCall(FPOp, opr0); 767 return true; 768 } 769 if ((CF && CF->isExactlyValue(2.0)) || (CINT && ci_opr1 == 2)) { 770 // pow/powr/pown(x, 2.0) = x*x 771 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << " * " 772 << *opr0 << "\n"); 773 Value *nval = B.CreateFMul(opr0, opr0, "__pow2"); 774 replaceCall(FPOp, nval); 775 return true; 776 } 777 if ((CF && CF->isExactlyValue(-1.0)) || (CINT && ci_opr1 == -1)) { 778 // pow/powr/pown(x, -1.0) = 1.0/x 779 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1 / " << *opr0 << "\n"); 780 Constant *cnval = ConstantFP::get(eltType, 1.0); 781 if (getVecSize(FInfo) > 1) { 782 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval); 783 } 784 Value *nval = B.CreateFDiv(cnval, opr0, "__powrecip"); 785 replaceCall(FPOp, nval); 786 return true; 787 } 788 789 if (CF && (CF->isExactlyValue(0.5) || CF->isExactlyValue(-0.5))) { 790 // pow[r](x, [-]0.5) = sqrt(x) 791 bool issqrt = CF->isExactlyValue(0.5); 792 if (FunctionCallee FPExpr = 793 getFunction(M, AMDGPULibFunc(issqrt ? AMDGPULibFunc::EI_SQRT 794 : AMDGPULibFunc::EI_RSQRT, 795 FInfo))) { 796 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << FInfo.getName() 797 << '(' << *opr0 << ")\n"); 798 Value *nval = CreateCallEx(B,FPExpr, opr0, issqrt ? "__pow2sqrt" 799 : "__pow2rsqrt"); 800 replaceCall(FPOp, nval); 801 return true; 802 } 803 } 804 805 if (!isUnsafeMath(FPOp)) 806 return false; 807 808 // Unsafe Math optimization 809 810 // Remember that ci_opr1 is set if opr1 is integral 811 if (CF) { 812 double dval = (getArgType(FInfo) == AMDGPULibFunc::F32) 813 ? (double)CF->getValueAPF().convertToFloat() 814 : CF->getValueAPF().convertToDouble(); 815 int ival = (int)dval; 816 if ((double)ival == dval) { 817 ci_opr1 = ival; 818 } else 819 ci_opr1 = 0x11111111; 820 } 821 822 // pow/powr/pown(x, c) = [1/](x*x*..x); where 823 // trunc(c) == c && the number of x == c && |c| <= 12 824 unsigned abs_opr1 = (ci_opr1 < 0) ? -ci_opr1 : ci_opr1; 825 if (abs_opr1 <= 12) { 826 Constant *cnval; 827 Value *nval; 828 if (abs_opr1 == 0) { 829 cnval = ConstantFP::get(eltType, 1.0); 830 if (getVecSize(FInfo) > 1) { 831 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval); 832 } 833 nval = cnval; 834 } else { 835 Value *valx2 = nullptr; 836 nval = nullptr; 837 while (abs_opr1 > 0) { 838 valx2 = valx2 ? B.CreateFMul(valx2, valx2, "__powx2") : opr0; 839 if (abs_opr1 & 1) { 840 nval = nval ? B.CreateFMul(nval, valx2, "__powprod") : valx2; 841 } 842 abs_opr1 >>= 1; 843 } 844 } 845 846 if (ci_opr1 < 0) { 847 cnval = ConstantFP::get(eltType, 1.0); 848 if (getVecSize(FInfo) > 1) { 849 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval); 850 } 851 nval = B.CreateFDiv(cnval, nval, "__1powprod"); 852 } 853 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " 854 << ((ci_opr1 < 0) ? "1/prod(" : "prod(") << *opr0 855 << ")\n"); 856 replaceCall(FPOp, nval); 857 return true; 858 } 859 860 // powr ---> exp2(y * log2(x)) 861 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31)) 862 FunctionCallee ExpExpr = 863 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2, FInfo)); 864 if (!ExpExpr) 865 return false; 866 867 bool needlog = false; 868 bool needabs = false; 869 bool needcopysign = false; 870 Constant *cnval = nullptr; 871 if (getVecSize(FInfo) == 1) { 872 CF = dyn_cast<ConstantFP>(opr0); 873 874 if (CF) { 875 double V = (getArgType(FInfo) == AMDGPULibFunc::F32) 876 ? (double)CF->getValueAPF().convertToFloat() 877 : CF->getValueAPF().convertToDouble(); 878 879 V = log2(std::abs(V)); 880 cnval = ConstantFP::get(eltType, V); 881 needcopysign = (FInfo.getId() != AMDGPULibFunc::EI_POWR) && 882 CF->isNegative(); 883 } else { 884 needlog = true; 885 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR && 886 (!CF || CF->isNegative()); 887 } 888 } else { 889 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr0); 890 891 if (!CDV) { 892 needlog = true; 893 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR; 894 } else { 895 assert ((int)CDV->getNumElements() == getVecSize(FInfo) && 896 "Wrong vector size detected"); 897 898 SmallVector<double, 0> DVal; 899 for (int i=0; i < getVecSize(FInfo); ++i) { 900 double V = (getArgType(FInfo) == AMDGPULibFunc::F32) 901 ? (double)CDV->getElementAsFloat(i) 902 : CDV->getElementAsDouble(i); 903 if (V < 0.0) needcopysign = true; 904 V = log2(std::abs(V)); 905 DVal.push_back(V); 906 } 907 if (getArgType(FInfo) == AMDGPULibFunc::F32) { 908 SmallVector<float, 0> FVal; 909 for (unsigned i=0; i < DVal.size(); ++i) { 910 FVal.push_back((float)DVal[i]); 911 } 912 ArrayRef<float> tmp(FVal); 913 cnval = ConstantDataVector::get(M->getContext(), tmp); 914 } else { 915 ArrayRef<double> tmp(DVal); 916 cnval = ConstantDataVector::get(M->getContext(), tmp); 917 } 918 } 919 } 920 921 if (needcopysign && (FInfo.getId() == AMDGPULibFunc::EI_POW)) { 922 // We cannot handle corner cases for a general pow() function, give up 923 // unless y is a constant integral value. Then proceed as if it were pown. 924 if (getVecSize(FInfo) == 1) { 925 if (const ConstantFP *CF = dyn_cast<ConstantFP>(opr1)) { 926 double y = (getArgType(FInfo) == AMDGPULibFunc::F32) 927 ? (double)CF->getValueAPF().convertToFloat() 928 : CF->getValueAPF().convertToDouble(); 929 if (y != (double)(int64_t)y) 930 return false; 931 } else 932 return false; 933 } else { 934 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr1)) { 935 for (int i=0; i < getVecSize(FInfo); ++i) { 936 double y = (getArgType(FInfo) == AMDGPULibFunc::F32) 937 ? (double)CDV->getElementAsFloat(i) 938 : CDV->getElementAsDouble(i); 939 if (y != (double)(int64_t)y) 940 return false; 941 } 942 } else 943 return false; 944 } 945 } 946 947 Value *nval; 948 if (needabs) { 949 nval = B.CreateUnaryIntrinsic(Intrinsic::fabs, opr0, nullptr, "__fabs"); 950 } else { 951 nval = cnval ? cnval : opr0; 952 } 953 if (needlog) { 954 FunctionCallee LogExpr = 955 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2, FInfo)); 956 if (!LogExpr) 957 return false; 958 nval = CreateCallEx(B,LogExpr, nval, "__log2"); 959 } 960 961 if (FInfo.getId() == AMDGPULibFunc::EI_POWN) { 962 // convert int(32) to fp(f32 or f64) 963 opr1 = B.CreateSIToFP(opr1, nval->getType(), "pownI2F"); 964 } 965 nval = B.CreateFMul(opr1, nval, "__ylogx"); 966 nval = CreateCallEx(B,ExpExpr, nval, "__exp2"); 967 968 if (needcopysign) { 969 Value *opr_n; 970 Type* rTy = opr0->getType(); 971 Type* nTyS = eltType->isDoubleTy() ? B.getInt64Ty() : B.getInt32Ty(); 972 Type *nTy = nTyS; 973 if (const auto *vTy = dyn_cast<FixedVectorType>(rTy)) 974 nTy = FixedVectorType::get(nTyS, vTy); 975 unsigned size = nTy->getScalarSizeInBits(); 976 opr_n = FPOp->getOperand(1); 977 if (opr_n->getType()->isIntegerTy()) 978 opr_n = B.CreateZExtOrBitCast(opr_n, nTy, "__ytou"); 979 else 980 opr_n = B.CreateFPToSI(opr1, nTy, "__ytou"); 981 982 Value *sign = B.CreateShl(opr_n, size-1, "__yeven"); 983 sign = B.CreateAnd(B.CreateBitCast(opr0, nTy), sign, "__pow_sign"); 984 nval = B.CreateOr(B.CreateBitCast(nval, nTy), sign); 985 nval = B.CreateBitCast(nval, opr0->getType()); 986 } 987 988 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " 989 << "exp2(" << *opr1 << " * log2(" << *opr0 << "))\n"); 990 replaceCall(FPOp, nval); 991 992 return true; 993 } 994 995 bool AMDGPULibCalls::fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B, 996 const FuncInfo &FInfo) { 997 // skip vector function 998 if (getVecSize(FInfo) != 1) 999 return false; 1000 1001 Value *opr0 = FPOp->getOperand(0); 1002 Value *opr1 = FPOp->getOperand(1); 1003 1004 ConstantInt *CINT = dyn_cast<ConstantInt>(opr1); 1005 if (!CINT) { 1006 return false; 1007 } 1008 int ci_opr1 = (int)CINT->getSExtValue(); 1009 if (ci_opr1 == 1) { // rootn(x, 1) = x 1010 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n"); 1011 replaceCall(FPOp, opr0); 1012 return true; 1013 } 1014 1015 Module *M = B.GetInsertBlock()->getModule(); 1016 if (ci_opr1 == 2) { // rootn(x, 2) = sqrt(x) 1017 if (FunctionCallee FPExpr = 1018 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) { 1019 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> sqrt(" << *opr0 1020 << ")\n"); 1021 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2sqrt"); 1022 replaceCall(FPOp, nval); 1023 return true; 1024 } 1025 } else if (ci_opr1 == 3) { // rootn(x, 3) = cbrt(x) 1026 if (FunctionCallee FPExpr = 1027 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT, FInfo))) { 1028 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> cbrt(" << *opr0 1029 << ")\n"); 1030 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2cbrt"); 1031 replaceCall(FPOp, nval); 1032 return true; 1033 } 1034 } else if (ci_opr1 == -1) { // rootn(x, -1) = 1.0/x 1035 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1.0 / " << *opr0 << "\n"); 1036 Value *nval = B.CreateFDiv(ConstantFP::get(opr0->getType(), 1.0), 1037 opr0, 1038 "__rootn2div"); 1039 replaceCall(FPOp, nval); 1040 return true; 1041 } else if (ci_opr1 == -2) { // rootn(x, -2) = rsqrt(x) 1042 if (FunctionCallee FPExpr = 1043 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT, FInfo))) { 1044 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> rsqrt(" << *opr0 1045 << ")\n"); 1046 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2rsqrt"); 1047 replaceCall(FPOp, nval); 1048 return true; 1049 } 1050 } 1051 return false; 1052 } 1053 1054 // Get a scalar native builtin single argument FP function 1055 FunctionCallee AMDGPULibCalls::getNativeFunction(Module *M, 1056 const FuncInfo &FInfo) { 1057 if (getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId())) 1058 return nullptr; 1059 FuncInfo nf = FInfo; 1060 nf.setPrefix(AMDGPULibFunc::NATIVE); 1061 return getFunction(M, nf); 1062 } 1063 1064 // Some library calls are just wrappers around llvm intrinsics, but compiled 1065 // conservatively. Preserve the flags from the original call site by 1066 // substituting them with direct calls with all the flags. 1067 bool AMDGPULibCalls::shouldReplaceLibcallWithIntrinsic(const CallInst *CI, 1068 bool AllowMinSizeF32, 1069 bool AllowF64) { 1070 Type *FltTy = CI->getType()->getScalarType(); 1071 const bool IsF32 = FltTy->isFloatTy(); 1072 1073 // f64 intrinsics aren't implemented for most operations. 1074 if (!IsF32 && !FltTy->isHalfTy() && (!AllowF64 || !FltTy->isDoubleTy())) 1075 return false; 1076 1077 // We're implicitly inlining by replacing the libcall with the intrinsic, so 1078 // don't do it for noinline call sites. 1079 if (CI->isNoInline()) 1080 return false; 1081 1082 const Function *ParentF = CI->getFunction(); 1083 // TODO: Handle strictfp 1084 if (ParentF->hasFnAttribute(Attribute::StrictFP)) 1085 return false; 1086 1087 if (IsF32 && !AllowMinSizeF32 && ParentF->hasMinSize()) 1088 return false; 1089 return true; 1090 } 1091 1092 void AMDGPULibCalls::replaceLibCallWithSimpleIntrinsic(CallInst *CI, 1093 Intrinsic::ID IntrID) { 1094 CI->setCalledFunction( 1095 Intrinsic::getDeclaration(CI->getModule(), IntrID, {CI->getType()})); 1096 } 1097 1098 bool AMDGPULibCalls::tryReplaceLibcallWithSimpleIntrinsic(CallInst *CI, 1099 Intrinsic::ID IntrID, 1100 bool AllowMinSizeF32, 1101 bool AllowF64) { 1102 if (!shouldReplaceLibcallWithIntrinsic(CI, AllowMinSizeF32, AllowF64)) 1103 return false; 1104 replaceLibCallWithSimpleIntrinsic(CI, IntrID); 1105 return true; 1106 } 1107 1108 // fold sqrt -> native_sqrt (x) 1109 bool AMDGPULibCalls::fold_sqrt(FPMathOperator *FPOp, IRBuilder<> &B, 1110 const FuncInfo &FInfo) { 1111 if (!isUnsafeMath(FPOp)) 1112 return false; 1113 1114 if (getArgType(FInfo) == AMDGPULibFunc::F32 && (getVecSize(FInfo) == 1) && 1115 (FInfo.getPrefix() != AMDGPULibFunc::NATIVE)) { 1116 Module *M = B.GetInsertBlock()->getModule(); 1117 1118 if (FunctionCallee FPExpr = getNativeFunction( 1119 M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) { 1120 Value *opr0 = FPOp->getOperand(0); 1121 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " 1122 << "sqrt(" << *opr0 << ")\n"); 1123 Value *nval = CreateCallEx(B,FPExpr, opr0, "__sqrt"); 1124 replaceCall(FPOp, nval); 1125 return true; 1126 } 1127 } 1128 return false; 1129 } 1130 1131 std::tuple<Value *, Value *, Value *> 1132 AMDGPULibCalls::insertSinCos(Value *Arg, FastMathFlags FMF, IRBuilder<> &B, 1133 FunctionCallee Fsincos) { 1134 DebugLoc DL = B.getCurrentDebugLocation(); 1135 Function *F = B.GetInsertBlock()->getParent(); 1136 B.SetInsertPointPastAllocas(F); 1137 1138 AllocaInst *Alloc = B.CreateAlloca(Arg->getType(), nullptr, "__sincos_"); 1139 1140 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) { 1141 // If the argument is an instruction, it must dominate all uses so put our 1142 // sincos call there. Otherwise, right after the allocas works well enough 1143 // if it's an argument or constant. 1144 1145 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator()); 1146 1147 // SetInsertPoint unwelcomely always tries to set the debug loc. 1148 B.SetCurrentDebugLocation(DL); 1149 } 1150 1151 Type *CosPtrTy = Fsincos.getFunctionType()->getParamType(1); 1152 1153 // The allocaInst allocates the memory in private address space. This need 1154 // to be addrspacecasted to point to the address space of cos pointer type. 1155 // In OpenCL 2.0 this is generic, while in 1.2 that is private. 1156 Value *CastAlloc = B.CreateAddrSpaceCast(Alloc, CosPtrTy); 1157 1158 CallInst *SinCos = CreateCallEx2(B, Fsincos, Arg, CastAlloc); 1159 1160 // TODO: Is it worth trying to preserve the location for the cos calls for the 1161 // load? 1162 1163 LoadInst *LoadCos = B.CreateLoad(Alloc->getAllocatedType(), Alloc); 1164 return {SinCos, LoadCos, SinCos}; 1165 } 1166 1167 // fold sin, cos -> sincos. 1168 bool AMDGPULibCalls::fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B, 1169 const FuncInfo &fInfo) { 1170 assert(fInfo.getId() == AMDGPULibFunc::EI_SIN || 1171 fInfo.getId() == AMDGPULibFunc::EI_COS); 1172 1173 if ((getArgType(fInfo) != AMDGPULibFunc::F32 && 1174 getArgType(fInfo) != AMDGPULibFunc::F64) || 1175 fInfo.getPrefix() != AMDGPULibFunc::NOPFX) 1176 return false; 1177 1178 bool const isSin = fInfo.getId() == AMDGPULibFunc::EI_SIN; 1179 1180 Value *CArgVal = FPOp->getOperand(0); 1181 CallInst *CI = cast<CallInst>(FPOp); 1182 1183 Function *F = B.GetInsertBlock()->getParent(); 1184 Module *M = F->getParent(); 1185 1186 // Merge the sin and cos. For OpenCL 2.0, there may only be a generic pointer 1187 // implementation. Prefer the private form if available. 1188 AMDGPULibFunc SinCosLibFuncPrivate(AMDGPULibFunc::EI_SINCOS, fInfo); 1189 SinCosLibFuncPrivate.getLeads()[0].PtrKind = 1190 AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::PRIVATE_ADDRESS); 1191 1192 AMDGPULibFunc SinCosLibFuncGeneric(AMDGPULibFunc::EI_SINCOS, fInfo); 1193 SinCosLibFuncGeneric.getLeads()[0].PtrKind = 1194 AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::FLAT_ADDRESS); 1195 1196 FunctionCallee FSinCosPrivate = getFunction(M, SinCosLibFuncPrivate); 1197 FunctionCallee FSinCosGeneric = getFunction(M, SinCosLibFuncGeneric); 1198 FunctionCallee FSinCos = FSinCosPrivate ? FSinCosPrivate : FSinCosGeneric; 1199 if (!FSinCos) 1200 return false; 1201 1202 SmallVector<CallInst *> SinCalls; 1203 SmallVector<CallInst *> CosCalls; 1204 SmallVector<CallInst *> SinCosCalls; 1205 FuncInfo PartnerInfo(isSin ? AMDGPULibFunc::EI_COS : AMDGPULibFunc::EI_SIN, 1206 fInfo); 1207 const std::string PairName = PartnerInfo.mangle(); 1208 1209 StringRef SinName = isSin ? CI->getCalledFunction()->getName() : PairName; 1210 StringRef CosName = isSin ? PairName : CI->getCalledFunction()->getName(); 1211 const std::string SinCosPrivateName = SinCosLibFuncPrivate.mangle(); 1212 const std::string SinCosGenericName = SinCosLibFuncGeneric.mangle(); 1213 1214 // Intersect the two sets of flags. 1215 FastMathFlags FMF = FPOp->getFastMathFlags(); 1216 MDNode *FPMath = CI->getMetadata(LLVMContext::MD_fpmath); 1217 1218 SmallVector<DILocation *> MergeDbgLocs = {CI->getDebugLoc()}; 1219 1220 for (User* U : CArgVal->users()) { 1221 CallInst *XI = dyn_cast<CallInst>(U); 1222 if (!XI || XI->getFunction() != F || XI->isNoBuiltin()) 1223 continue; 1224 1225 Function *UCallee = XI->getCalledFunction(); 1226 if (!UCallee) 1227 continue; 1228 1229 bool Handled = true; 1230 1231 if (UCallee->getName() == SinName) 1232 SinCalls.push_back(XI); 1233 else if (UCallee->getName() == CosName) 1234 CosCalls.push_back(XI); 1235 else if (UCallee->getName() == SinCosPrivateName || 1236 UCallee->getName() == SinCosGenericName) 1237 SinCosCalls.push_back(XI); 1238 else 1239 Handled = false; 1240 1241 if (Handled) { 1242 MergeDbgLocs.push_back(XI->getDebugLoc()); 1243 auto *OtherOp = cast<FPMathOperator>(XI); 1244 FMF &= OtherOp->getFastMathFlags(); 1245 FPMath = MDNode::getMostGenericFPMath( 1246 FPMath, XI->getMetadata(LLVMContext::MD_fpmath)); 1247 } 1248 } 1249 1250 if (SinCalls.empty() || CosCalls.empty()) 1251 return false; 1252 1253 B.setFastMathFlags(FMF); 1254 B.setDefaultFPMathTag(FPMath); 1255 DILocation *DbgLoc = DILocation::getMergedLocations(MergeDbgLocs); 1256 B.SetCurrentDebugLocation(DbgLoc); 1257 1258 auto [Sin, Cos, SinCos] = insertSinCos(CArgVal, FMF, B, FSinCos); 1259 1260 auto replaceTrigInsts = [](ArrayRef<CallInst *> Calls, Value *Res) { 1261 for (CallInst *C : Calls) 1262 C->replaceAllUsesWith(Res); 1263 1264 // Leave the other dead instructions to avoid clobbering iterators. 1265 }; 1266 1267 replaceTrigInsts(SinCalls, Sin); 1268 replaceTrigInsts(CosCalls, Cos); 1269 replaceTrigInsts(SinCosCalls, SinCos); 1270 1271 // It's safe to delete the original now. 1272 CI->eraseFromParent(); 1273 return true; 1274 } 1275 1276 bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, 1277 double& Res0, double& Res1, 1278 Constant *copr0, Constant *copr1, 1279 Constant *copr2) { 1280 // By default, opr0/opr1/opr3 holds values of float/double type. 1281 // If they are not float/double, each function has to its 1282 // operand separately. 1283 double opr0=0.0, opr1=0.0, opr2=0.0; 1284 ConstantFP *fpopr0 = dyn_cast_or_null<ConstantFP>(copr0); 1285 ConstantFP *fpopr1 = dyn_cast_or_null<ConstantFP>(copr1); 1286 ConstantFP *fpopr2 = dyn_cast_or_null<ConstantFP>(copr2); 1287 if (fpopr0) { 1288 opr0 = (getArgType(FInfo) == AMDGPULibFunc::F64) 1289 ? fpopr0->getValueAPF().convertToDouble() 1290 : (double)fpopr0->getValueAPF().convertToFloat(); 1291 } 1292 1293 if (fpopr1) { 1294 opr1 = (getArgType(FInfo) == AMDGPULibFunc::F64) 1295 ? fpopr1->getValueAPF().convertToDouble() 1296 : (double)fpopr1->getValueAPF().convertToFloat(); 1297 } 1298 1299 if (fpopr2) { 1300 opr2 = (getArgType(FInfo) == AMDGPULibFunc::F64) 1301 ? fpopr2->getValueAPF().convertToDouble() 1302 : (double)fpopr2->getValueAPF().convertToFloat(); 1303 } 1304 1305 switch (FInfo.getId()) { 1306 default : return false; 1307 1308 case AMDGPULibFunc::EI_ACOS: 1309 Res0 = acos(opr0); 1310 return true; 1311 1312 case AMDGPULibFunc::EI_ACOSH: 1313 // acosh(x) == log(x + sqrt(x*x - 1)) 1314 Res0 = log(opr0 + sqrt(opr0*opr0 - 1.0)); 1315 return true; 1316 1317 case AMDGPULibFunc::EI_ACOSPI: 1318 Res0 = acos(opr0) / MATH_PI; 1319 return true; 1320 1321 case AMDGPULibFunc::EI_ASIN: 1322 Res0 = asin(opr0); 1323 return true; 1324 1325 case AMDGPULibFunc::EI_ASINH: 1326 // asinh(x) == log(x + sqrt(x*x + 1)) 1327 Res0 = log(opr0 + sqrt(opr0*opr0 + 1.0)); 1328 return true; 1329 1330 case AMDGPULibFunc::EI_ASINPI: 1331 Res0 = asin(opr0) / MATH_PI; 1332 return true; 1333 1334 case AMDGPULibFunc::EI_ATAN: 1335 Res0 = atan(opr0); 1336 return true; 1337 1338 case AMDGPULibFunc::EI_ATANH: 1339 // atanh(x) == (log(x+1) - log(x-1))/2; 1340 Res0 = (log(opr0 + 1.0) - log(opr0 - 1.0))/2.0; 1341 return true; 1342 1343 case AMDGPULibFunc::EI_ATANPI: 1344 Res0 = atan(opr0) / MATH_PI; 1345 return true; 1346 1347 case AMDGPULibFunc::EI_CBRT: 1348 Res0 = (opr0 < 0.0) ? -pow(-opr0, 1.0/3.0) : pow(opr0, 1.0/3.0); 1349 return true; 1350 1351 case AMDGPULibFunc::EI_COS: 1352 Res0 = cos(opr0); 1353 return true; 1354 1355 case AMDGPULibFunc::EI_COSH: 1356 Res0 = cosh(opr0); 1357 return true; 1358 1359 case AMDGPULibFunc::EI_COSPI: 1360 Res0 = cos(MATH_PI * opr0); 1361 return true; 1362 1363 case AMDGPULibFunc::EI_EXP: 1364 Res0 = exp(opr0); 1365 return true; 1366 1367 case AMDGPULibFunc::EI_EXP2: 1368 Res0 = pow(2.0, opr0); 1369 return true; 1370 1371 case AMDGPULibFunc::EI_EXP10: 1372 Res0 = pow(10.0, opr0); 1373 return true; 1374 1375 case AMDGPULibFunc::EI_LOG: 1376 Res0 = log(opr0); 1377 return true; 1378 1379 case AMDGPULibFunc::EI_LOG2: 1380 Res0 = log(opr0) / log(2.0); 1381 return true; 1382 1383 case AMDGPULibFunc::EI_LOG10: 1384 Res0 = log(opr0) / log(10.0); 1385 return true; 1386 1387 case AMDGPULibFunc::EI_RSQRT: 1388 Res0 = 1.0 / sqrt(opr0); 1389 return true; 1390 1391 case AMDGPULibFunc::EI_SIN: 1392 Res0 = sin(opr0); 1393 return true; 1394 1395 case AMDGPULibFunc::EI_SINH: 1396 Res0 = sinh(opr0); 1397 return true; 1398 1399 case AMDGPULibFunc::EI_SINPI: 1400 Res0 = sin(MATH_PI * opr0); 1401 return true; 1402 1403 case AMDGPULibFunc::EI_SQRT: 1404 Res0 = sqrt(opr0); 1405 return true; 1406 1407 case AMDGPULibFunc::EI_TAN: 1408 Res0 = tan(opr0); 1409 return true; 1410 1411 case AMDGPULibFunc::EI_TANH: 1412 Res0 = tanh(opr0); 1413 return true; 1414 1415 case AMDGPULibFunc::EI_TANPI: 1416 Res0 = tan(MATH_PI * opr0); 1417 return true; 1418 1419 case AMDGPULibFunc::EI_RECIP: 1420 Res0 = 1.0 / opr0; 1421 return true; 1422 1423 // two-arg functions 1424 case AMDGPULibFunc::EI_DIVIDE: 1425 Res0 = opr0 / opr1; 1426 return true; 1427 1428 case AMDGPULibFunc::EI_POW: 1429 case AMDGPULibFunc::EI_POWR: 1430 Res0 = pow(opr0, opr1); 1431 return true; 1432 1433 case AMDGPULibFunc::EI_POWN: { 1434 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) { 1435 double val = (double)iopr1->getSExtValue(); 1436 Res0 = pow(opr0, val); 1437 return true; 1438 } 1439 return false; 1440 } 1441 1442 case AMDGPULibFunc::EI_ROOTN: { 1443 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) { 1444 double val = (double)iopr1->getSExtValue(); 1445 Res0 = pow(opr0, 1.0 / val); 1446 return true; 1447 } 1448 return false; 1449 } 1450 1451 // with ptr arg 1452 case AMDGPULibFunc::EI_SINCOS: 1453 Res0 = sin(opr0); 1454 Res1 = cos(opr0); 1455 return true; 1456 1457 // three-arg functions 1458 case AMDGPULibFunc::EI_FMA: 1459 case AMDGPULibFunc::EI_MAD: 1460 Res0 = opr0 * opr1 + opr2; 1461 return true; 1462 } 1463 1464 return false; 1465 } 1466 1467 bool AMDGPULibCalls::evaluateCall(CallInst *aCI, const FuncInfo &FInfo) { 1468 int numArgs = (int)aCI->arg_size(); 1469 if (numArgs > 3) 1470 return false; 1471 1472 Constant *copr0 = nullptr; 1473 Constant *copr1 = nullptr; 1474 Constant *copr2 = nullptr; 1475 if (numArgs > 0) { 1476 if ((copr0 = dyn_cast<Constant>(aCI->getArgOperand(0))) == nullptr) 1477 return false; 1478 } 1479 1480 if (numArgs > 1) { 1481 if ((copr1 = dyn_cast<Constant>(aCI->getArgOperand(1))) == nullptr) { 1482 if (FInfo.getId() != AMDGPULibFunc::EI_SINCOS) 1483 return false; 1484 } 1485 } 1486 1487 if (numArgs > 2) { 1488 if ((copr2 = dyn_cast<Constant>(aCI->getArgOperand(2))) == nullptr) 1489 return false; 1490 } 1491 1492 // At this point, all arguments to aCI are constants. 1493 1494 // max vector size is 16, and sincos will generate two results. 1495 double DVal0[16], DVal1[16]; 1496 int FuncVecSize = getVecSize(FInfo); 1497 bool hasTwoResults = (FInfo.getId() == AMDGPULibFunc::EI_SINCOS); 1498 if (FuncVecSize == 1) { 1499 if (!evaluateScalarMathFunc(FInfo, DVal0[0], 1500 DVal1[0], copr0, copr1, copr2)) { 1501 return false; 1502 } 1503 } else { 1504 ConstantDataVector *CDV0 = dyn_cast_or_null<ConstantDataVector>(copr0); 1505 ConstantDataVector *CDV1 = dyn_cast_or_null<ConstantDataVector>(copr1); 1506 ConstantDataVector *CDV2 = dyn_cast_or_null<ConstantDataVector>(copr2); 1507 for (int i = 0; i < FuncVecSize; ++i) { 1508 Constant *celt0 = CDV0 ? CDV0->getElementAsConstant(i) : nullptr; 1509 Constant *celt1 = CDV1 ? CDV1->getElementAsConstant(i) : nullptr; 1510 Constant *celt2 = CDV2 ? CDV2->getElementAsConstant(i) : nullptr; 1511 if (!evaluateScalarMathFunc(FInfo, DVal0[i], 1512 DVal1[i], celt0, celt1, celt2)) { 1513 return false; 1514 } 1515 } 1516 } 1517 1518 LLVMContext &context = aCI->getContext(); 1519 Constant *nval0, *nval1; 1520 if (FuncVecSize == 1) { 1521 nval0 = ConstantFP::get(aCI->getType(), DVal0[0]); 1522 if (hasTwoResults) 1523 nval1 = ConstantFP::get(aCI->getType(), DVal1[0]); 1524 } else { 1525 if (getArgType(FInfo) == AMDGPULibFunc::F32) { 1526 SmallVector <float, 0> FVal0, FVal1; 1527 for (int i = 0; i < FuncVecSize; ++i) 1528 FVal0.push_back((float)DVal0[i]); 1529 ArrayRef<float> tmp0(FVal0); 1530 nval0 = ConstantDataVector::get(context, tmp0); 1531 if (hasTwoResults) { 1532 for (int i = 0; i < FuncVecSize; ++i) 1533 FVal1.push_back((float)DVal1[i]); 1534 ArrayRef<float> tmp1(FVal1); 1535 nval1 = ConstantDataVector::get(context, tmp1); 1536 } 1537 } else { 1538 ArrayRef<double> tmp0(DVal0); 1539 nval0 = ConstantDataVector::get(context, tmp0); 1540 if (hasTwoResults) { 1541 ArrayRef<double> tmp1(DVal1); 1542 nval1 = ConstantDataVector::get(context, tmp1); 1543 } 1544 } 1545 } 1546 1547 if (hasTwoResults) { 1548 // sincos 1549 assert(FInfo.getId() == AMDGPULibFunc::EI_SINCOS && 1550 "math function with ptr arg not supported yet"); 1551 new StoreInst(nval1, aCI->getArgOperand(1), aCI); 1552 } 1553 1554 replaceCall(aCI, nval0); 1555 return true; 1556 } 1557 1558 PreservedAnalyses AMDGPUSimplifyLibCallsPass::run(Function &F, 1559 FunctionAnalysisManager &AM) { 1560 AMDGPULibCalls Simplifier; 1561 Simplifier.initNativeFuncs(); 1562 Simplifier.initFunction(F); 1563 1564 bool Changed = false; 1565 1566 LLVM_DEBUG(dbgs() << "AMDIC: process function "; 1567 F.printAsOperand(dbgs(), false, F.getParent()); dbgs() << '\n';); 1568 1569 for (auto &BB : F) { 1570 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) { 1571 // Ignore non-calls. 1572 CallInst *CI = dyn_cast<CallInst>(I); 1573 ++I; 1574 1575 if (CI) { 1576 if (Simplifier.fold(CI)) 1577 Changed = true; 1578 } 1579 } 1580 } 1581 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all(); 1582 } 1583 1584 PreservedAnalyses AMDGPUUseNativeCallsPass::run(Function &F, 1585 FunctionAnalysisManager &AM) { 1586 if (UseNative.empty()) 1587 return PreservedAnalyses::all(); 1588 1589 AMDGPULibCalls Simplifier; 1590 Simplifier.initNativeFuncs(); 1591 Simplifier.initFunction(F); 1592 1593 bool Changed = false; 1594 for (auto &BB : F) { 1595 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) { 1596 // Ignore non-calls. 1597 CallInst *CI = dyn_cast<CallInst>(I); 1598 ++I; 1599 if (CI && Simplifier.useNative(CI)) 1600 Changed = true; 1601 } 1602 } 1603 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all(); 1604 } 1605