1 //===- AMDGPULibCalls.cpp -------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file does AMD library function optimizations.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "amdgpu-simplifylib"
17 #include "AMDGPULibFunc.h"
18 #include "AMDGPUSubtarget.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/Loads.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
41 static cl::opt
<bool> EnablePreLink("amdgpu-prelink",
42 cl::desc("Enable pre-link mode optimizations"),
46 static cl::list
<std::string
> UseNative("amdgpu-use-native",
47 cl::desc("Comma separated list of functions to replace with native, or all"),
48 cl::CommaSeparated
, cl::ValueOptional
,
51 #define MATH_PI 3.14159265358979323846264338327950288419716939937511
52 #define MATH_E 2.71828182845904523536028747135266249775724709369996
53 #define MATH_SQRT2 1.41421356237309504880168872420969807856967187537695
55 #define MATH_LOG2E 1.4426950408889634073599246810018921374266459541529859
56 #define MATH_LOG10E 0.4342944819032518276511289189166050822943970058036665
58 #define MATH_LOG2_10 3.3219280948873623478703194294893901758648313930245806
59 // Value of 1 / log2(10)
60 #define MATH_RLOG2_10 0.3010299956639811952137388947244930267681898814621085
61 // Value of 1 / M_LOG2E_F = 1 / log2(e)
62 #define MATH_RLOG2_E 0.6931471805599453094172321214581765680755001343602552
66 class AMDGPULibCalls
{
69 typedef llvm::AMDGPULibFunc FuncInfo
;
71 const TargetMachine
*TM
;
74 bool AllNative
= false;
76 bool useNativeFunc(const StringRef F
) const;
78 // Return a pointer (pointer expr) to the function if function defintion with
79 // "FuncName" exists. It may create a new function prototype in pre-link mode.
80 FunctionCallee
getFunction(Module
*M
, const FuncInfo
&fInfo
);
82 // Replace a normal function with its native version.
83 bool replaceWithNative(CallInst
*CI
, const FuncInfo
&FInfo
);
85 bool parseFunctionName(const StringRef
& FMangledName
,
86 FuncInfo
*FInfo
=nullptr /*out*/);
88 bool TDOFold(CallInst
*CI
, const FuncInfo
&FInfo
);
90 /* Specialized optimizations */
92 // recip (half or native)
93 bool fold_recip(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
95 // divide (half or native)
96 bool fold_divide(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
99 bool fold_pow(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
102 bool fold_rootn(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
105 bool fold_fma_mad(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
107 // -fuse-native for sincos
108 bool sincosUseNative(CallInst
*aCI
, const FuncInfo
&FInfo
);
110 // evaluate calls if calls' arguments are constants.
111 bool evaluateScalarMathFunc(FuncInfo
&FInfo
, double& Res0
,
112 double& Res1
, Constant
*copr0
, Constant
*copr1
, Constant
*copr2
);
113 bool evaluateCall(CallInst
*aCI
, FuncInfo
&FInfo
);
116 bool fold_exp(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
119 bool fold_exp2(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
122 bool fold_exp10(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
125 bool fold_log(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
128 bool fold_log2(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
131 bool fold_log10(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
134 bool fold_sqrt(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
137 bool fold_sincos(CallInst
* CI
, IRBuilder
<> &B
, AliasAnalysis
* AA
);
139 // __read_pipe/__write_pipe
140 bool fold_read_write_pipe(CallInst
*CI
, IRBuilder
<> &B
, FuncInfo
&FInfo
);
142 // llvm.amdgcn.wavefrontsize
143 bool fold_wavefrontsize(CallInst
*CI
, IRBuilder
<> &B
);
145 // Get insertion point at entry.
146 BasicBlock::iterator
getEntryIns(CallInst
* UI
);
147 // Insert an Alloc instruction.
148 AllocaInst
* insertAlloca(CallInst
* UI
, IRBuilder
<> &B
, const char *prefix
);
149 // Get a scalar native builtin signle argument FP function
150 FunctionCallee
getNativeFunction(Module
*M
, const FuncInfo
&FInfo
);
155 bool isUnsafeMath(const CallInst
*CI
) const;
157 void replaceCall(Value
*With
) {
158 CI
->replaceAllUsesWith(With
);
159 CI
->eraseFromParent();
163 AMDGPULibCalls(const TargetMachine
*TM_
= nullptr) : TM(TM_
) {}
165 bool fold(CallInst
*CI
, AliasAnalysis
*AA
= nullptr);
167 void initNativeFuncs();
169 // Replace a normal math function call with that native version
170 bool useNative(CallInst
*CI
);
173 } // end llvm namespace
177 class AMDGPUSimplifyLibCalls
: public FunctionPass
{
179 const TargetOptions Options
;
181 AMDGPULibCalls Simplifier
;
184 static char ID
; // Pass identification
186 AMDGPUSimplifyLibCalls(const TargetOptions
&Opt
= TargetOptions(),
187 const TargetMachine
*TM
= nullptr)
188 : FunctionPass(ID
), Options(Opt
), Simplifier(TM
) {
189 initializeAMDGPUSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
192 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
193 AU
.addRequired
<AAResultsWrapperPass
>();
196 bool runOnFunction(Function
&M
) override
;
199 class AMDGPUUseNativeCalls
: public FunctionPass
{
201 AMDGPULibCalls Simplifier
;
204 static char ID
; // Pass identification
206 AMDGPUUseNativeCalls() : FunctionPass(ID
) {
207 initializeAMDGPUUseNativeCallsPass(*PassRegistry::getPassRegistry());
208 Simplifier
.initNativeFuncs();
211 bool runOnFunction(Function
&F
) override
;
214 } // end anonymous namespace.
216 char AMDGPUSimplifyLibCalls::ID
= 0;
217 char AMDGPUUseNativeCalls::ID
= 0;
219 INITIALIZE_PASS_BEGIN(AMDGPUSimplifyLibCalls
, "amdgpu-simplifylib",
220 "Simplify well-known AMD library calls", false, false)
221 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
222 INITIALIZE_PASS_END(AMDGPUSimplifyLibCalls
, "amdgpu-simplifylib",
223 "Simplify well-known AMD library calls", false, false)
225 INITIALIZE_PASS(AMDGPUUseNativeCalls
, "amdgpu-usenative",
226 "Replace builtin math calls with that native versions.",
229 template <typename IRB
>
230 static CallInst
*CreateCallEx(IRB
&B
, FunctionCallee Callee
, Value
*Arg
,
231 const Twine
&Name
= "") {
232 CallInst
*R
= B
.CreateCall(Callee
, Arg
, Name
);
233 if (Function
*F
= dyn_cast
<Function
>(Callee
.getCallee()))
234 R
->setCallingConv(F
->getCallingConv());
238 template <typename IRB
>
239 static CallInst
*CreateCallEx2(IRB
&B
, FunctionCallee Callee
, Value
*Arg1
,
240 Value
*Arg2
, const Twine
&Name
= "") {
241 CallInst
*R
= B
.CreateCall(Callee
, {Arg1
, Arg2
}, Name
);
242 if (Function
*F
= dyn_cast
<Function
>(Callee
.getCallee()))
243 R
->setCallingConv(F
->getCallingConv());
247 // Data structures for table-driven optimizations.
248 // FuncTbl works for both f32 and f64 functions with 1 input argument
255 /* a list of {result, input} */
256 static const TableEntry tbl_acos
[] = {
262 static const TableEntry tbl_acosh
[] = {
265 static const TableEntry tbl_acospi
[] = {
271 static const TableEntry tbl_asin
[] = {
277 static const TableEntry tbl_asinh
[] = {
281 static const TableEntry tbl_asinpi
[] = {
287 static const TableEntry tbl_atan
[] = {
293 static const TableEntry tbl_atanh
[] = {
297 static const TableEntry tbl_atanpi
[] = {
303 static const TableEntry tbl_cbrt
[] = {
309 static const TableEntry tbl_cos
[] = {
313 static const TableEntry tbl_cosh
[] = {
317 static const TableEntry tbl_cospi
[] = {
321 static const TableEntry tbl_erfc
[] = {
325 static const TableEntry tbl_erf
[] = {
329 static const TableEntry tbl_exp
[] = {
334 static const TableEntry tbl_exp2
[] = {
339 static const TableEntry tbl_exp10
[] = {
344 static const TableEntry tbl_expm1
[] = {
348 static const TableEntry tbl_log
[] = {
352 static const TableEntry tbl_log2
[] = {
356 static const TableEntry tbl_log10
[] = {
360 static const TableEntry tbl_rsqrt
[] = {
362 {1.0/MATH_SQRT2
, 2.0}
364 static const TableEntry tbl_sin
[] = {
368 static const TableEntry tbl_sinh
[] = {
372 static const TableEntry tbl_sinpi
[] = {
376 static const TableEntry tbl_sqrt
[] = {
381 static const TableEntry tbl_tan
[] = {
385 static const TableEntry tbl_tanh
[] = {
389 static const TableEntry tbl_tanpi
[] = {
393 static const TableEntry tbl_tgamma
[] = {
400 static bool HasNative(AMDGPULibFunc::EFuncId id
) {
402 case AMDGPULibFunc::EI_DIVIDE
:
403 case AMDGPULibFunc::EI_COS
:
404 case AMDGPULibFunc::EI_EXP
:
405 case AMDGPULibFunc::EI_EXP2
:
406 case AMDGPULibFunc::EI_EXP10
:
407 case AMDGPULibFunc::EI_LOG
:
408 case AMDGPULibFunc::EI_LOG2
:
409 case AMDGPULibFunc::EI_LOG10
:
410 case AMDGPULibFunc::EI_POWR
:
411 case AMDGPULibFunc::EI_RECIP
:
412 case AMDGPULibFunc::EI_RSQRT
:
413 case AMDGPULibFunc::EI_SIN
:
414 case AMDGPULibFunc::EI_SINCOS
:
415 case AMDGPULibFunc::EI_SQRT
:
416 case AMDGPULibFunc::EI_TAN
:
425 const TableEntry
*table
; // variable size: from 0 to (size - 1)
427 TableRef() : size(0), table(nullptr) {}
430 TableRef(const TableEntry (&tbl
)[N
]) : size(N
), table(&tbl
[0]) {}
433 static TableRef
getOptTable(AMDGPULibFunc::EFuncId id
) {
435 case AMDGPULibFunc::EI_ACOS
: return TableRef(tbl_acos
);
436 case AMDGPULibFunc::EI_ACOSH
: return TableRef(tbl_acosh
);
437 case AMDGPULibFunc::EI_ACOSPI
: return TableRef(tbl_acospi
);
438 case AMDGPULibFunc::EI_ASIN
: return TableRef(tbl_asin
);
439 case AMDGPULibFunc::EI_ASINH
: return TableRef(tbl_asinh
);
440 case AMDGPULibFunc::EI_ASINPI
: return TableRef(tbl_asinpi
);
441 case AMDGPULibFunc::EI_ATAN
: return TableRef(tbl_atan
);
442 case AMDGPULibFunc::EI_ATANH
: return TableRef(tbl_atanh
);
443 case AMDGPULibFunc::EI_ATANPI
: return TableRef(tbl_atanpi
);
444 case AMDGPULibFunc::EI_CBRT
: return TableRef(tbl_cbrt
);
445 case AMDGPULibFunc::EI_NCOS
:
446 case AMDGPULibFunc::EI_COS
: return TableRef(tbl_cos
);
447 case AMDGPULibFunc::EI_COSH
: return TableRef(tbl_cosh
);
448 case AMDGPULibFunc::EI_COSPI
: return TableRef(tbl_cospi
);
449 case AMDGPULibFunc::EI_ERFC
: return TableRef(tbl_erfc
);
450 case AMDGPULibFunc::EI_ERF
: return TableRef(tbl_erf
);
451 case AMDGPULibFunc::EI_EXP
: return TableRef(tbl_exp
);
452 case AMDGPULibFunc::EI_NEXP2
:
453 case AMDGPULibFunc::EI_EXP2
: return TableRef(tbl_exp2
);
454 case AMDGPULibFunc::EI_EXP10
: return TableRef(tbl_exp10
);
455 case AMDGPULibFunc::EI_EXPM1
: return TableRef(tbl_expm1
);
456 case AMDGPULibFunc::EI_LOG
: return TableRef(tbl_log
);
457 case AMDGPULibFunc::EI_NLOG2
:
458 case AMDGPULibFunc::EI_LOG2
: return TableRef(tbl_log2
);
459 case AMDGPULibFunc::EI_LOG10
: return TableRef(tbl_log10
);
460 case AMDGPULibFunc::EI_NRSQRT
:
461 case AMDGPULibFunc::EI_RSQRT
: return TableRef(tbl_rsqrt
);
462 case AMDGPULibFunc::EI_NSIN
:
463 case AMDGPULibFunc::EI_SIN
: return TableRef(tbl_sin
);
464 case AMDGPULibFunc::EI_SINH
: return TableRef(tbl_sinh
);
465 case AMDGPULibFunc::EI_SINPI
: return TableRef(tbl_sinpi
);
466 case AMDGPULibFunc::EI_NSQRT
:
467 case AMDGPULibFunc::EI_SQRT
: return TableRef(tbl_sqrt
);
468 case AMDGPULibFunc::EI_TAN
: return TableRef(tbl_tan
);
469 case AMDGPULibFunc::EI_TANH
: return TableRef(tbl_tanh
);
470 case AMDGPULibFunc::EI_TANPI
: return TableRef(tbl_tanpi
);
471 case AMDGPULibFunc::EI_TGAMMA
: return TableRef(tbl_tgamma
);
477 static inline int getVecSize(const AMDGPULibFunc
& FInfo
) {
478 return FInfo
.getLeads()[0].VectorSize
;
481 static inline AMDGPULibFunc::EType
getArgType(const AMDGPULibFunc
& FInfo
) {
482 return (AMDGPULibFunc::EType
)FInfo
.getLeads()[0].ArgType
;
485 FunctionCallee
AMDGPULibCalls::getFunction(Module
*M
, const FuncInfo
&fInfo
) {
486 // If we are doing PreLinkOpt, the function is external. So it is safe to
487 // use getOrInsertFunction() at this stage.
489 return EnablePreLink
? AMDGPULibFunc::getOrInsertFunction(M
, fInfo
)
490 : AMDGPULibFunc::getFunction(M
, fInfo
);
493 bool AMDGPULibCalls::parseFunctionName(const StringRef
& FMangledName
,
495 return AMDGPULibFunc::parse(FMangledName
, *FInfo
);
498 bool AMDGPULibCalls::isUnsafeMath(const CallInst
*CI
) const {
499 if (auto Op
= dyn_cast
<FPMathOperator
>(CI
))
502 const Function
*F
= CI
->getParent()->getParent();
503 Attribute Attr
= F
->getFnAttribute("unsafe-fp-math");
504 return Attr
.getValueAsString() == "true";
507 bool AMDGPULibCalls::useNativeFunc(const StringRef F
) const {
509 std::find(UseNative
.begin(), UseNative
.end(), F
) != UseNative
.end();
512 void AMDGPULibCalls::initNativeFuncs() {
513 AllNative
= useNativeFunc("all") ||
514 (UseNative
.getNumOccurrences() && UseNative
.size() == 1 &&
515 UseNative
.begin()->empty());
518 bool AMDGPULibCalls::sincosUseNative(CallInst
*aCI
, const FuncInfo
&FInfo
) {
519 bool native_sin
= useNativeFunc("sin");
520 bool native_cos
= useNativeFunc("cos");
522 if (native_sin
&& native_cos
) {
523 Module
*M
= aCI
->getModule();
524 Value
*opr0
= aCI
->getArgOperand(0);
527 nf
.getLeads()[0].ArgType
= FInfo
.getLeads()[0].ArgType
;
528 nf
.getLeads()[0].VectorSize
= FInfo
.getLeads()[0].VectorSize
;
530 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
531 nf
.setId(AMDGPULibFunc::EI_SIN
);
532 FunctionCallee sinExpr
= getFunction(M
, nf
);
534 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
535 nf
.setId(AMDGPULibFunc::EI_COS
);
536 FunctionCallee cosExpr
= getFunction(M
, nf
);
537 if (sinExpr
&& cosExpr
) {
538 Value
*sinval
= CallInst::Create(sinExpr
, opr0
, "splitsin", aCI
);
539 Value
*cosval
= CallInst::Create(cosExpr
, opr0
, "splitcos", aCI
);
540 new StoreInst(cosval
, aCI
->getArgOperand(1), aCI
);
542 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
543 << " with native version of sin/cos");
552 bool AMDGPULibCalls::useNative(CallInst
*aCI
) {
554 Function
*Callee
= aCI
->getCalledFunction();
557 if (!parseFunctionName(Callee
->getName(), &FInfo
) || !FInfo
.isMangled() ||
558 FInfo
.getPrefix() != AMDGPULibFunc::NOPFX
||
559 getArgType(FInfo
) == AMDGPULibFunc::F64
|| !HasNative(FInfo
.getId()) ||
560 !(AllNative
|| useNativeFunc(FInfo
.getName()))) {
564 if (FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
)
565 return sincosUseNative(aCI
, FInfo
);
567 FInfo
.setPrefix(AMDGPULibFunc::NATIVE
);
568 FunctionCallee F
= getFunction(aCI
->getModule(), FInfo
);
572 aCI
->setCalledFunction(F
);
573 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
574 << " with native version");
578 // Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
579 // builtin, with appended type size and alignment arguments, where 2 or 4
580 // indicates the original number of arguments. The library has optimized version
581 // of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
582 // power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
583 // for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
584 // 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
585 bool AMDGPULibCalls::fold_read_write_pipe(CallInst
*CI
, IRBuilder
<> &B
,
587 auto *Callee
= CI
->getCalledFunction();
588 if (!Callee
->isDeclaration())
591 assert(Callee
->hasName() && "Invalid read_pipe/write_pipe function");
592 auto *M
= Callee
->getParent();
593 auto &Ctx
= M
->getContext();
594 std::string Name
= Callee
->getName();
595 auto NumArg
= CI
->getNumArgOperands();
596 if (NumArg
!= 4 && NumArg
!= 6)
598 auto *PacketSize
= CI
->getArgOperand(NumArg
- 2);
599 auto *PacketAlign
= CI
->getArgOperand(NumArg
- 1);
600 if (!isa
<ConstantInt
>(PacketSize
) || !isa
<ConstantInt
>(PacketAlign
))
602 unsigned Size
= cast
<ConstantInt
>(PacketSize
)->getZExtValue();
603 unsigned Align
= cast
<ConstantInt
>(PacketAlign
)->getZExtValue();
604 if (Size
!= Align
|| !isPowerOf2_32(Size
))
609 PtrElemTy
= Type::getIntNTy(Ctx
, Size
* 8);
611 PtrElemTy
= VectorType::get(Type::getInt64Ty(Ctx
), Size
/ 8);
612 unsigned PtrArgLoc
= CI
->getNumArgOperands() - 3;
613 auto PtrArg
= CI
->getArgOperand(PtrArgLoc
);
614 unsigned PtrArgAS
= PtrArg
->getType()->getPointerAddressSpace();
615 auto *PtrTy
= llvm::PointerType::get(PtrElemTy
, PtrArgAS
);
617 SmallVector
<llvm::Type
*, 6> ArgTys
;
618 for (unsigned I
= 0; I
!= PtrArgLoc
; ++I
)
619 ArgTys
.push_back(CI
->getArgOperand(I
)->getType());
620 ArgTys
.push_back(PtrTy
);
622 Name
= Name
+ "_" + std::to_string(Size
);
623 auto *FTy
= FunctionType::get(Callee
->getReturnType(),
624 ArrayRef
<Type
*>(ArgTys
), false);
625 AMDGPULibFunc
NewLibFunc(Name
, FTy
);
626 FunctionCallee F
= AMDGPULibFunc::getOrInsertFunction(M
, NewLibFunc
);
630 auto *BCast
= B
.CreatePointerCast(PtrArg
, PtrTy
);
631 SmallVector
<Value
*, 6> Args
;
632 for (unsigned I
= 0; I
!= PtrArgLoc
; ++I
)
633 Args
.push_back(CI
->getArgOperand(I
));
634 Args
.push_back(BCast
);
636 auto *NCI
= B
.CreateCall(F
, Args
);
637 NCI
->setAttributes(CI
->getAttributes());
638 CI
->replaceAllUsesWith(NCI
);
639 CI
->dropAllReferences();
640 CI
->eraseFromParent();
645 // This function returns false if no change; return true otherwise.
646 bool AMDGPULibCalls::fold(CallInst
*CI
, AliasAnalysis
*AA
) {
648 Function
*Callee
= CI
->getCalledFunction();
650 // Ignore indirect calls.
651 if (Callee
== 0) return false;
653 BasicBlock
*BB
= CI
->getParent();
654 LLVMContext
&Context
= CI
->getParent()->getContext();
655 IRBuilder
<> B(Context
);
657 // Set the builder to the instruction after the call.
658 B
.SetInsertPoint(BB
, CI
->getIterator());
660 // Copy fast flags from the original call.
661 if (const FPMathOperator
*FPOp
= dyn_cast
<const FPMathOperator
>(CI
))
662 B
.setFastMathFlags(FPOp
->getFastMathFlags());
664 switch (Callee
->getIntrinsicID()) {
667 case Intrinsic::amdgcn_wavefrontsize
:
668 return !EnablePreLink
&& fold_wavefrontsize(CI
, B
);
672 if (!parseFunctionName(Callee
->getName(), &FInfo
))
675 // Further check the number of arguments to see if they match.
676 if (CI
->getNumArgOperands() != FInfo
.getNumArgs())
679 if (TDOFold(CI
, FInfo
))
682 // Under unsafe-math, evaluate calls if possible.
683 // According to Brian Sumner, we can do this for all f32 function calls
684 // using host's double function calls.
685 if (isUnsafeMath(CI
) && evaluateCall(CI
, FInfo
))
688 // Specilized optimizations for each function call
689 switch (FInfo
.getId()) {
690 case AMDGPULibFunc::EI_RECIP
:
691 // skip vector function
692 assert ((FInfo
.getPrefix() == AMDGPULibFunc::NATIVE
||
693 FInfo
.getPrefix() == AMDGPULibFunc::HALF
) &&
694 "recip must be an either native or half function");
695 return (getVecSize(FInfo
) != 1) ? false : fold_recip(CI
, B
, FInfo
);
697 case AMDGPULibFunc::EI_DIVIDE
:
698 // skip vector function
699 assert ((FInfo
.getPrefix() == AMDGPULibFunc::NATIVE
||
700 FInfo
.getPrefix() == AMDGPULibFunc::HALF
) &&
701 "divide must be an either native or half function");
702 return (getVecSize(FInfo
) != 1) ? false : fold_divide(CI
, B
, FInfo
);
704 case AMDGPULibFunc::EI_POW
:
705 case AMDGPULibFunc::EI_POWR
:
706 case AMDGPULibFunc::EI_POWN
:
707 return fold_pow(CI
, B
, FInfo
);
709 case AMDGPULibFunc::EI_ROOTN
:
710 // skip vector function
711 return (getVecSize(FInfo
) != 1) ? false : fold_rootn(CI
, B
, FInfo
);
713 case AMDGPULibFunc::EI_FMA
:
714 case AMDGPULibFunc::EI_MAD
:
715 case AMDGPULibFunc::EI_NFMA
:
716 // skip vector function
717 return (getVecSize(FInfo
) != 1) ? false : fold_fma_mad(CI
, B
, FInfo
);
719 case AMDGPULibFunc::EI_SQRT
:
720 return isUnsafeMath(CI
) && fold_sqrt(CI
, B
, FInfo
);
721 case AMDGPULibFunc::EI_COS
:
722 case AMDGPULibFunc::EI_SIN
:
723 if ((getArgType(FInfo
) == AMDGPULibFunc::F32
||
724 getArgType(FInfo
) == AMDGPULibFunc::F64
)
725 && (FInfo
.getPrefix() == AMDGPULibFunc::NOPFX
))
726 return fold_sincos(CI
, B
, AA
);
729 case AMDGPULibFunc::EI_READ_PIPE_2
:
730 case AMDGPULibFunc::EI_READ_PIPE_4
:
731 case AMDGPULibFunc::EI_WRITE_PIPE_2
:
732 case AMDGPULibFunc::EI_WRITE_PIPE_4
:
733 return fold_read_write_pipe(CI
, B
, FInfo
);
742 bool AMDGPULibCalls::TDOFold(CallInst
*CI
, const FuncInfo
&FInfo
) {
743 // Table-Driven optimization
744 const TableRef tr
= getOptTable(FInfo
.getId());
748 int const sz
= (int)tr
.size
;
749 const TableEntry
* const ftbl
= tr
.table
;
750 Value
*opr0
= CI
->getArgOperand(0);
752 if (getVecSize(FInfo
) > 1) {
753 if (ConstantDataVector
*CV
= dyn_cast
<ConstantDataVector
>(opr0
)) {
754 SmallVector
<double, 0> DVal
;
755 for (int eltNo
= 0; eltNo
< getVecSize(FInfo
); ++eltNo
) {
756 ConstantFP
*eltval
= dyn_cast
<ConstantFP
>(
757 CV
->getElementAsConstant((unsigned)eltNo
));
758 assert(eltval
&& "Non-FP arguments in math function!");
760 for (int i
=0; i
< sz
; ++i
) {
761 if (eltval
->isExactlyValue(ftbl
[i
].input
)) {
762 DVal
.push_back(ftbl
[i
].result
);
768 // This vector constants not handled yet.
772 LLVMContext
&context
= CI
->getParent()->getParent()->getContext();
774 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
775 SmallVector
<float, 0> FVal
;
776 for (unsigned i
= 0; i
< DVal
.size(); ++i
) {
777 FVal
.push_back((float)DVal
[i
]);
779 ArrayRef
<float> tmp(FVal
);
780 nval
= ConstantDataVector::get(context
, tmp
);
782 ArrayRef
<double> tmp(DVal
);
783 nval
= ConstantDataVector::get(context
, tmp
);
785 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
791 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr0
)) {
792 for (int i
= 0; i
< sz
; ++i
) {
793 if (CF
->isExactlyValue(ftbl
[i
].input
)) {
794 Value
*nval
= ConstantFP::get(CF
->getType(), ftbl
[i
].result
);
795 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
806 bool AMDGPULibCalls::replaceWithNative(CallInst
*CI
, const FuncInfo
&FInfo
) {
807 Module
*M
= CI
->getModule();
808 if (getArgType(FInfo
) != AMDGPULibFunc::F32
||
809 FInfo
.getPrefix() != AMDGPULibFunc::NOPFX
||
810 !HasNative(FInfo
.getId()))
813 AMDGPULibFunc nf
= FInfo
;
814 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
815 if (FunctionCallee FPExpr
= getFunction(M
, nf
)) {
816 LLVM_DEBUG(dbgs() << "AMDIC: " << *CI
<< " ---> ");
818 CI
->setCalledFunction(FPExpr
);
820 LLVM_DEBUG(dbgs() << *CI
<< '\n');
827 // [native_]half_recip(c) ==> 1.0/c
828 bool AMDGPULibCalls::fold_recip(CallInst
*CI
, IRBuilder
<> &B
,
829 const FuncInfo
&FInfo
) {
830 Value
*opr0
= CI
->getArgOperand(0);
831 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr0
)) {
832 // Just create a normal div. Later, InstCombine will be able
833 // to compute the divide into a constant (avoid check float infinity
834 // or subnormal at this point).
835 Value
*nval
= B
.CreateFDiv(ConstantFP::get(CF
->getType(), 1.0),
838 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
845 // [native_]half_divide(x, c) ==> x/c
846 bool AMDGPULibCalls::fold_divide(CallInst
*CI
, IRBuilder
<> &B
,
847 const FuncInfo
&FInfo
) {
848 Value
*opr0
= CI
->getArgOperand(0);
849 Value
*opr1
= CI
->getArgOperand(1);
850 ConstantFP
*CF0
= dyn_cast
<ConstantFP
>(opr0
);
851 ConstantFP
*CF1
= dyn_cast
<ConstantFP
>(opr1
);
853 if ((CF0
&& CF1
) || // both are constants
854 (CF1
&& (getArgType(FInfo
) == AMDGPULibFunc::F32
)))
855 // CF1 is constant && f32 divide
857 Value
*nval1
= B
.CreateFDiv(ConstantFP::get(opr1
->getType(), 1.0),
858 opr1
, "__div2recip");
859 Value
*nval
= B
.CreateFMul(opr0
, nval1
, "__div2mul");
867 static double log2(double V
) {
868 #if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
871 return log(V
) / 0.693147180559945309417;
876 bool AMDGPULibCalls::fold_pow(CallInst
*CI
, IRBuilder
<> &B
,
877 const FuncInfo
&FInfo
) {
878 assert((FInfo
.getId() == AMDGPULibFunc::EI_POW
||
879 FInfo
.getId() == AMDGPULibFunc::EI_POWR
||
880 FInfo
.getId() == AMDGPULibFunc::EI_POWN
) &&
881 "fold_pow: encounter a wrong function call");
886 ConstantAggregateZero
*CZero
;
889 opr0
= CI
->getArgOperand(0);
890 opr1
= CI
->getArgOperand(1);
891 CZero
= dyn_cast
<ConstantAggregateZero
>(opr1
);
892 if (getVecSize(FInfo
) == 1) {
893 eltType
= opr0
->getType();
894 CF
= dyn_cast
<ConstantFP
>(opr1
);
895 CINT
= dyn_cast
<ConstantInt
>(opr1
);
897 VectorType
*VTy
= dyn_cast
<VectorType
>(opr0
->getType());
898 assert(VTy
&& "Oprand of vector function should be of vectortype");
899 eltType
= VTy
->getElementType();
900 ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr1
);
902 // Now, only Handle vector const whose elements have the same value.
903 CF
= CDV
? dyn_cast_or_null
<ConstantFP
>(CDV
->getSplatValue()) : nullptr;
904 CINT
= CDV
? dyn_cast_or_null
<ConstantInt
>(CDV
->getSplatValue()) : nullptr;
907 // No unsafe math , no constant argument, do nothing
908 if (!isUnsafeMath(CI
) && !CF
&& !CINT
&& !CZero
)
911 // 0x1111111 means that we don't do anything for this call.
912 int ci_opr1
= (CINT
? (int)CINT
->getSExtValue() : 0x1111111);
914 if ((CF
&& CF
->isZero()) || (CINT
&& ci_opr1
== 0) || CZero
) {
915 // pow/powr/pown(x, 0) == 1
916 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1\n");
917 Constant
*cnval
= ConstantFP::get(eltType
, 1.0);
918 if (getVecSize(FInfo
) > 1) {
919 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
924 if ((CF
&& CF
->isExactlyValue(1.0)) || (CINT
&& ci_opr1
== 1)) {
925 // pow/powr/pown(x, 1.0) = x
926 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< "\n");
930 if ((CF
&& CF
->isExactlyValue(2.0)) || (CINT
&& ci_opr1
== 2)) {
931 // pow/powr/pown(x, 2.0) = x*x
932 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " * " << *opr0
934 Value
*nval
= B
.CreateFMul(opr0
, opr0
, "__pow2");
938 if ((CF
&& CF
->isExactlyValue(-1.0)) || (CINT
&& ci_opr1
== -1)) {
939 // pow/powr/pown(x, -1.0) = 1.0/x
940 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1 / " << *opr0
<< "\n");
941 Constant
*cnval
= ConstantFP::get(eltType
, 1.0);
942 if (getVecSize(FInfo
) > 1) {
943 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
945 Value
*nval
= B
.CreateFDiv(cnval
, opr0
, "__powrecip");
950 Module
*M
= CI
->getModule();
951 if (CF
&& (CF
->isExactlyValue(0.5) || CF
->isExactlyValue(-0.5))) {
952 // pow[r](x, [-]0.5) = sqrt(x)
953 bool issqrt
= CF
->isExactlyValue(0.5);
954 if (FunctionCallee FPExpr
=
955 getFunction(M
, AMDGPULibFunc(issqrt
? AMDGPULibFunc::EI_SQRT
956 : AMDGPULibFunc::EI_RSQRT
,
958 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
959 << FInfo
.getName().c_str() << "(" << *opr0
<< ")\n");
960 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, issqrt
? "__pow2sqrt"
967 if (!isUnsafeMath(CI
))
970 // Unsafe Math optimization
972 // Remember that ci_opr1 is set if opr1 is integral
974 double dval
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
975 ? (double)CF
->getValueAPF().convertToFloat()
976 : CF
->getValueAPF().convertToDouble();
977 int ival
= (int)dval
;
978 if ((double)ival
== dval
) {
981 ci_opr1
= 0x11111111;
984 // pow/powr/pown(x, c) = [1/](x*x*..x); where
985 // trunc(c) == c && the number of x == c && |c| <= 12
986 unsigned abs_opr1
= (ci_opr1
< 0) ? -ci_opr1
: ci_opr1
;
987 if (abs_opr1
<= 12) {
991 cnval
= ConstantFP::get(eltType
, 1.0);
992 if (getVecSize(FInfo
) > 1) {
993 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
997 Value
*valx2
= nullptr;
999 while (abs_opr1
> 0) {
1000 valx2
= valx2
? B
.CreateFMul(valx2
, valx2
, "__powx2") : opr0
;
1002 nval
= nval
? B
.CreateFMul(nval
, valx2
, "__powprod") : valx2
;
1009 cnval
= ConstantFP::get(eltType
, 1.0);
1010 if (getVecSize(FInfo
) > 1) {
1011 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
1013 nval
= B
.CreateFDiv(cnval
, nval
, "__1powprod");
1015 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1016 << ((ci_opr1
< 0) ? "1/prod(" : "prod(") << *opr0
1022 // powr ---> exp2(y * log2(x))
1023 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
1024 FunctionCallee ExpExpr
=
1025 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2
, FInfo
));
1029 bool needlog
= false;
1030 bool needabs
= false;
1031 bool needcopysign
= false;
1032 Constant
*cnval
= nullptr;
1033 if (getVecSize(FInfo
) == 1) {
1034 CF
= dyn_cast
<ConstantFP
>(opr0
);
1037 double V
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1038 ? (double)CF
->getValueAPF().convertToFloat()
1039 : CF
->getValueAPF().convertToDouble();
1041 V
= log2(std::abs(V
));
1042 cnval
= ConstantFP::get(eltType
, V
);
1043 needcopysign
= (FInfo
.getId() != AMDGPULibFunc::EI_POWR
) &&
1047 needcopysign
= needabs
= FInfo
.getId() != AMDGPULibFunc::EI_POWR
&&
1048 (!CF
|| CF
->isNegative());
1051 ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr0
);
1055 needcopysign
= needabs
= FInfo
.getId() != AMDGPULibFunc::EI_POWR
;
1057 assert ((int)CDV
->getNumElements() == getVecSize(FInfo
) &&
1058 "Wrong vector size detected");
1060 SmallVector
<double, 0> DVal
;
1061 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1062 double V
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1063 ? (double)CDV
->getElementAsFloat(i
)
1064 : CDV
->getElementAsDouble(i
);
1065 if (V
< 0.0) needcopysign
= true;
1066 V
= log2(std::abs(V
));
1069 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
1070 SmallVector
<float, 0> FVal
;
1071 for (unsigned i
=0; i
< DVal
.size(); ++i
) {
1072 FVal
.push_back((float)DVal
[i
]);
1074 ArrayRef
<float> tmp(FVal
);
1075 cnval
= ConstantDataVector::get(M
->getContext(), tmp
);
1077 ArrayRef
<double> tmp(DVal
);
1078 cnval
= ConstantDataVector::get(M
->getContext(), tmp
);
1083 if (needcopysign
&& (FInfo
.getId() == AMDGPULibFunc::EI_POW
)) {
1084 // We cannot handle corner cases for a general pow() function, give up
1085 // unless y is a constant integral value. Then proceed as if it were pown.
1086 if (getVecSize(FInfo
) == 1) {
1087 if (const ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr1
)) {
1088 double y
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1089 ? (double)CF
->getValueAPF().convertToFloat()
1090 : CF
->getValueAPF().convertToDouble();
1091 if (y
!= (double)(int64_t)y
)
1096 if (const ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr1
)) {
1097 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1098 double y
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1099 ? (double)CDV
->getElementAsFloat(i
)
1100 : CDV
->getElementAsDouble(i
);
1101 if (y
!= (double)(int64_t)y
)
1111 FunctionCallee AbsExpr
=
1112 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_FABS
, FInfo
));
1115 nval
= CreateCallEx(B
, AbsExpr
, opr0
, "__fabs");
1117 nval
= cnval
? cnval
: opr0
;
1120 FunctionCallee LogExpr
=
1121 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2
, FInfo
));
1124 nval
= CreateCallEx(B
,LogExpr
, nval
, "__log2");
1127 if (FInfo
.getId() == AMDGPULibFunc::EI_POWN
) {
1128 // convert int(32) to fp(f32 or f64)
1129 opr1
= B
.CreateSIToFP(opr1
, nval
->getType(), "pownI2F");
1131 nval
= B
.CreateFMul(opr1
, nval
, "__ylogx");
1132 nval
= CreateCallEx(B
,ExpExpr
, nval
, "__exp2");
1136 Type
* rTy
= opr0
->getType();
1137 Type
* nTyS
= eltType
->isDoubleTy() ? B
.getInt64Ty() : B
.getInt32Ty();
1139 if (const VectorType
*vTy
= dyn_cast
<VectorType
>(rTy
))
1140 nTy
= VectorType::get(nTyS
, vTy
->getNumElements());
1141 unsigned size
= nTy
->getScalarSizeInBits();
1142 opr_n
= CI
->getArgOperand(1);
1143 if (opr_n
->getType()->isIntegerTy())
1144 opr_n
= B
.CreateZExtOrBitCast(opr_n
, nTy
, "__ytou");
1146 opr_n
= B
.CreateFPToSI(opr1
, nTy
, "__ytou");
1148 Value
*sign
= B
.CreateShl(opr_n
, size
-1, "__yeven");
1149 sign
= B
.CreateAnd(B
.CreateBitCast(opr0
, nTy
), sign
, "__pow_sign");
1150 nval
= B
.CreateOr(B
.CreateBitCast(nval
, nTy
), sign
);
1151 nval
= B
.CreateBitCast(nval
, opr0
->getType());
1154 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1155 << "exp2(" << *opr1
<< " * log2(" << *opr0
<< "))\n");
1161 bool AMDGPULibCalls::fold_rootn(CallInst
*CI
, IRBuilder
<> &B
,
1162 const FuncInfo
&FInfo
) {
1163 Value
*opr0
= CI
->getArgOperand(0);
1164 Value
*opr1
= CI
->getArgOperand(1);
1166 ConstantInt
*CINT
= dyn_cast
<ConstantInt
>(opr1
);
1170 int ci_opr1
= (int)CINT
->getSExtValue();
1171 if (ci_opr1
== 1) { // rootn(x, 1) = x
1172 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< "\n");
1176 if (ci_opr1
== 2) { // rootn(x, 2) = sqrt(x)
1177 std::vector
<const Type
*> ParamsTys
;
1178 ParamsTys
.push_back(opr0
->getType());
1179 Module
*M
= CI
->getModule();
1180 if (FunctionCallee FPExpr
=
1181 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT
, FInfo
))) {
1182 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> sqrt(" << *opr0
<< ")\n");
1183 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2sqrt");
1187 } else if (ci_opr1
== 3) { // rootn(x, 3) = cbrt(x)
1188 Module
*M
= CI
->getModule();
1189 if (FunctionCallee FPExpr
=
1190 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT
, FInfo
))) {
1191 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> cbrt(" << *opr0
<< ")\n");
1192 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2cbrt");
1196 } else if (ci_opr1
== -1) { // rootn(x, -1) = 1.0/x
1197 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1.0 / " << *opr0
<< "\n");
1198 Value
*nval
= B
.CreateFDiv(ConstantFP::get(opr0
->getType(), 1.0),
1203 } else if (ci_opr1
== -2) { // rootn(x, -2) = rsqrt(x)
1204 std::vector
<const Type
*> ParamsTys
;
1205 ParamsTys
.push_back(opr0
->getType());
1206 Module
*M
= CI
->getModule();
1207 if (FunctionCallee FPExpr
=
1208 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT
, FInfo
))) {
1209 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> rsqrt(" << *opr0
1211 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2rsqrt");
1219 bool AMDGPULibCalls::fold_fma_mad(CallInst
*CI
, IRBuilder
<> &B
,
1220 const FuncInfo
&FInfo
) {
1221 Value
*opr0
= CI
->getArgOperand(0);
1222 Value
*opr1
= CI
->getArgOperand(1);
1223 Value
*opr2
= CI
->getArgOperand(2);
1225 ConstantFP
*CF0
= dyn_cast
<ConstantFP
>(opr0
);
1226 ConstantFP
*CF1
= dyn_cast
<ConstantFP
>(opr1
);
1227 if ((CF0
&& CF0
->isZero()) || (CF1
&& CF1
->isZero())) {
1228 // fma/mad(a, b, c) = c if a=0 || b=0
1229 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr2
<< "\n");
1233 if (CF0
&& CF0
->isExactlyValue(1.0f
)) {
1234 // fma/mad(a, b, c) = b+c if a=1
1235 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr1
<< " + " << *opr2
1237 Value
*nval
= B
.CreateFAdd(opr1
, opr2
, "fmaadd");
1241 if (CF1
&& CF1
->isExactlyValue(1.0f
)) {
1242 // fma/mad(a, b, c) = a+c if b=1
1243 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " + " << *opr2
1245 Value
*nval
= B
.CreateFAdd(opr0
, opr2
, "fmaadd");
1249 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr2
)) {
1251 // fma/mad(a, b, c) = a*b if c=0
1252 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " * "
1254 Value
*nval
= B
.CreateFMul(opr0
, opr1
, "fmamul");
1263 // Get a scalar native builtin signle argument FP function
1264 FunctionCallee
AMDGPULibCalls::getNativeFunction(Module
*M
,
1265 const FuncInfo
&FInfo
) {
1266 if (getArgType(FInfo
) == AMDGPULibFunc::F64
|| !HasNative(FInfo
.getId()))
1268 FuncInfo nf
= FInfo
;
1269 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
1270 return getFunction(M
, nf
);
1273 // fold sqrt -> native_sqrt (x)
1274 bool AMDGPULibCalls::fold_sqrt(CallInst
*CI
, IRBuilder
<> &B
,
1275 const FuncInfo
&FInfo
) {
1276 if (getArgType(FInfo
) == AMDGPULibFunc::F32
&& (getVecSize(FInfo
) == 1) &&
1277 (FInfo
.getPrefix() != AMDGPULibFunc::NATIVE
)) {
1278 if (FunctionCallee FPExpr
= getNativeFunction(
1279 CI
->getModule(), AMDGPULibFunc(AMDGPULibFunc::EI_SQRT
, FInfo
))) {
1280 Value
*opr0
= CI
->getArgOperand(0);
1281 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1282 << "sqrt(" << *opr0
<< ")\n");
1283 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__sqrt");
1291 // fold sin, cos -> sincos.
1292 bool AMDGPULibCalls::fold_sincos(CallInst
*CI
, IRBuilder
<> &B
,
1293 AliasAnalysis
*AA
) {
1294 AMDGPULibFunc fInfo
;
1295 if (!AMDGPULibFunc::parse(CI
->getCalledFunction()->getName(), fInfo
))
1298 assert(fInfo
.getId() == AMDGPULibFunc::EI_SIN
||
1299 fInfo
.getId() == AMDGPULibFunc::EI_COS
);
1300 bool const isSin
= fInfo
.getId() == AMDGPULibFunc::EI_SIN
;
1302 Value
*CArgVal
= CI
->getArgOperand(0);
1303 BasicBlock
* const CBB
= CI
->getParent();
1305 int const MaxScan
= 30;
1307 { // fold in load value.
1308 LoadInst
*LI
= dyn_cast
<LoadInst
>(CArgVal
);
1309 if (LI
&& LI
->getParent() == CBB
) {
1310 BasicBlock::iterator BBI
= LI
->getIterator();
1311 Value
*AvailableVal
= FindAvailableLoadedValue(LI
, CBB
, BBI
, MaxScan
, AA
);
1313 CArgVal
->replaceAllUsesWith(AvailableVal
);
1314 if (CArgVal
->getNumUses() == 0)
1315 LI
->eraseFromParent();
1316 CArgVal
= CI
->getArgOperand(0);
1321 Module
*M
= CI
->getModule();
1322 fInfo
.setId(isSin
? AMDGPULibFunc::EI_COS
: AMDGPULibFunc::EI_SIN
);
1323 std::string
const PairName
= fInfo
.mangle();
1325 CallInst
*UI
= nullptr;
1326 for (User
* U
: CArgVal
->users()) {
1327 CallInst
*XI
= dyn_cast_or_null
<CallInst
>(U
);
1328 if (!XI
|| XI
== CI
|| XI
->getParent() != CBB
)
1331 Function
*UCallee
= XI
->getCalledFunction();
1332 if (!UCallee
|| !UCallee
->getName().equals(PairName
))
1335 BasicBlock::iterator BBI
= CI
->getIterator();
1336 if (BBI
== CI
->getParent()->begin())
1339 for (int I
= MaxScan
; I
> 0 && BBI
!= CBB
->begin(); --BBI
, --I
) {
1340 if (cast
<Instruction
>(BBI
) == XI
) {
1348 if (!UI
) return false;
1350 // Merge the sin and cos.
1352 // for OpenCL 2.0 we have only generic implementation of sincos
1354 AMDGPULibFunc
nf(AMDGPULibFunc::EI_SINCOS
, fInfo
);
1355 nf
.getLeads()[0].PtrKind
= AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::FLAT_ADDRESS
);
1356 FunctionCallee Fsincos
= getFunction(M
, nf
);
1357 if (!Fsincos
) return false;
1359 BasicBlock::iterator ItOld
= B
.GetInsertPoint();
1360 AllocaInst
*Alloc
= insertAlloca(UI
, B
, "__sincos_");
1361 B
.SetInsertPoint(UI
);
1364 Type
*PTy
= Fsincos
.getFunctionType()->getParamType(1);
1365 // The allocaInst allocates the memory in private address space. This need
1366 // to be bitcasted to point to the address space of cos pointer type.
1367 // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1368 if (PTy
->getPointerAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS
)
1369 P
= B
.CreateAddrSpaceCast(Alloc
, PTy
);
1370 CallInst
*Call
= CreateCallEx2(B
, Fsincos
, UI
->getArgOperand(0), P
);
1372 LLVM_DEBUG(errs() << "AMDIC: fold_sincos (" << *CI
<< ", " << *UI
<< ") with "
1375 if (!isSin
) { // CI->cos, UI->sin
1376 B
.SetInsertPoint(&*ItOld
);
1377 UI
->replaceAllUsesWith(&*Call
);
1378 Instruction
*Reload
= B
.CreateLoad(Alloc
->getAllocatedType(), Alloc
);
1379 CI
->replaceAllUsesWith(Reload
);
1380 UI
->eraseFromParent();
1381 CI
->eraseFromParent();
1382 } else { // CI->sin, UI->cos
1383 Instruction
*Reload
= B
.CreateLoad(Alloc
->getAllocatedType(), Alloc
);
1384 UI
->replaceAllUsesWith(Reload
);
1385 CI
->replaceAllUsesWith(Call
);
1386 UI
->eraseFromParent();
1387 CI
->eraseFromParent();
1392 bool AMDGPULibCalls::fold_wavefrontsize(CallInst
*CI
, IRBuilder
<> &B
) {
1396 StringRef CPU
= TM
->getTargetCPU();
1397 StringRef Features
= TM
->getTargetFeatureString();
1398 if ((CPU
.empty() || CPU
.equals_lower("generic")) &&
1399 (Features
.empty() ||
1400 Features
.find_lower("wavefrontsize") == StringRef::npos
))
1403 Function
*F
= CI
->getParent()->getParent();
1404 const GCNSubtarget
&ST
= TM
->getSubtarget
<GCNSubtarget
>(*F
);
1405 unsigned N
= ST
.getWavefrontSize();
1407 LLVM_DEBUG(errs() << "AMDIC: fold_wavefrontsize (" << *CI
<< ") with "
1410 CI
->replaceAllUsesWith(ConstantInt::get(B
.getInt32Ty(), N
));
1411 CI
->eraseFromParent();
1415 // Get insertion point at entry.
1416 BasicBlock::iterator
AMDGPULibCalls::getEntryIns(CallInst
* UI
) {
1417 Function
* Func
= UI
->getParent()->getParent();
1418 BasicBlock
* BB
= &Func
->getEntryBlock();
1419 assert(BB
&& "Entry block not found!");
1420 BasicBlock::iterator ItNew
= BB
->begin();
1424 // Insert a AllocsInst at the beginning of function entry block.
1425 AllocaInst
* AMDGPULibCalls::insertAlloca(CallInst
*UI
, IRBuilder
<> &B
,
1426 const char *prefix
) {
1427 BasicBlock::iterator ItNew
= getEntryIns(UI
);
1428 Function
*UCallee
= UI
->getCalledFunction();
1429 Type
*RetType
= UCallee
->getReturnType();
1430 B
.SetInsertPoint(&*ItNew
);
1431 AllocaInst
*Alloc
= B
.CreateAlloca(RetType
, 0,
1432 std::string(prefix
) + UI
->getName());
1433 Alloc
->setAlignment(MaybeAlign(
1434 UCallee
->getParent()->getDataLayout().getTypeAllocSize(RetType
)));
1438 bool AMDGPULibCalls::evaluateScalarMathFunc(FuncInfo
&FInfo
,
1439 double& Res0
, double& Res1
,
1440 Constant
*copr0
, Constant
*copr1
,
1442 // By default, opr0/opr1/opr3 holds values of float/double type.
1443 // If they are not float/double, each function has to its
1444 // operand separately.
1445 double opr0
=0.0, opr1
=0.0, opr2
=0.0;
1446 ConstantFP
*fpopr0
= dyn_cast_or_null
<ConstantFP
>(copr0
);
1447 ConstantFP
*fpopr1
= dyn_cast_or_null
<ConstantFP
>(copr1
);
1448 ConstantFP
*fpopr2
= dyn_cast_or_null
<ConstantFP
>(copr2
);
1450 opr0
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1451 ? fpopr0
->getValueAPF().convertToDouble()
1452 : (double)fpopr0
->getValueAPF().convertToFloat();
1456 opr1
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1457 ? fpopr1
->getValueAPF().convertToDouble()
1458 : (double)fpopr1
->getValueAPF().convertToFloat();
1462 opr2
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1463 ? fpopr2
->getValueAPF().convertToDouble()
1464 : (double)fpopr2
->getValueAPF().convertToFloat();
1467 switch (FInfo
.getId()) {
1468 default : return false;
1470 case AMDGPULibFunc::EI_ACOS
:
1474 case AMDGPULibFunc::EI_ACOSH
:
1475 // acosh(x) == log(x + sqrt(x*x - 1))
1476 Res0
= log(opr0
+ sqrt(opr0
*opr0
- 1.0));
1479 case AMDGPULibFunc::EI_ACOSPI
:
1480 Res0
= acos(opr0
) / MATH_PI
;
1483 case AMDGPULibFunc::EI_ASIN
:
1487 case AMDGPULibFunc::EI_ASINH
:
1488 // asinh(x) == log(x + sqrt(x*x + 1))
1489 Res0
= log(opr0
+ sqrt(opr0
*opr0
+ 1.0));
1492 case AMDGPULibFunc::EI_ASINPI
:
1493 Res0
= asin(opr0
) / MATH_PI
;
1496 case AMDGPULibFunc::EI_ATAN
:
1500 case AMDGPULibFunc::EI_ATANH
:
1501 // atanh(x) == (log(x+1) - log(x-1))/2;
1502 Res0
= (log(opr0
+ 1.0) - log(opr0
- 1.0))/2.0;
1505 case AMDGPULibFunc::EI_ATANPI
:
1506 Res0
= atan(opr0
) / MATH_PI
;
1509 case AMDGPULibFunc::EI_CBRT
:
1510 Res0
= (opr0
< 0.0) ? -pow(-opr0
, 1.0/3.0) : pow(opr0
, 1.0/3.0);
1513 case AMDGPULibFunc::EI_COS
:
1517 case AMDGPULibFunc::EI_COSH
:
1521 case AMDGPULibFunc::EI_COSPI
:
1522 Res0
= cos(MATH_PI
* opr0
);
1525 case AMDGPULibFunc::EI_EXP
:
1529 case AMDGPULibFunc::EI_EXP2
:
1530 Res0
= pow(2.0, opr0
);
1533 case AMDGPULibFunc::EI_EXP10
:
1534 Res0
= pow(10.0, opr0
);
1537 case AMDGPULibFunc::EI_EXPM1
:
1538 Res0
= exp(opr0
) - 1.0;
1541 case AMDGPULibFunc::EI_LOG
:
1545 case AMDGPULibFunc::EI_LOG2
:
1546 Res0
= log(opr0
) / log(2.0);
1549 case AMDGPULibFunc::EI_LOG10
:
1550 Res0
= log(opr0
) / log(10.0);
1553 case AMDGPULibFunc::EI_RSQRT
:
1554 Res0
= 1.0 / sqrt(opr0
);
1557 case AMDGPULibFunc::EI_SIN
:
1561 case AMDGPULibFunc::EI_SINH
:
1565 case AMDGPULibFunc::EI_SINPI
:
1566 Res0
= sin(MATH_PI
* opr0
);
1569 case AMDGPULibFunc::EI_SQRT
:
1573 case AMDGPULibFunc::EI_TAN
:
1577 case AMDGPULibFunc::EI_TANH
:
1581 case AMDGPULibFunc::EI_TANPI
:
1582 Res0
= tan(MATH_PI
* opr0
);
1585 case AMDGPULibFunc::EI_RECIP
:
1589 // two-arg functions
1590 case AMDGPULibFunc::EI_DIVIDE
:
1594 case AMDGPULibFunc::EI_POW
:
1595 case AMDGPULibFunc::EI_POWR
:
1596 Res0
= pow(opr0
, opr1
);
1599 case AMDGPULibFunc::EI_POWN
: {
1600 if (ConstantInt
*iopr1
= dyn_cast_or_null
<ConstantInt
>(copr1
)) {
1601 double val
= (double)iopr1
->getSExtValue();
1602 Res0
= pow(opr0
, val
);
1608 case AMDGPULibFunc::EI_ROOTN
: {
1609 if (ConstantInt
*iopr1
= dyn_cast_or_null
<ConstantInt
>(copr1
)) {
1610 double val
= (double)iopr1
->getSExtValue();
1611 Res0
= pow(opr0
, 1.0 / val
);
1618 case AMDGPULibFunc::EI_SINCOS
:
1623 // three-arg functions
1624 case AMDGPULibFunc::EI_FMA
:
1625 case AMDGPULibFunc::EI_MAD
:
1626 Res0
= opr0
* opr1
+ opr2
;
1633 bool AMDGPULibCalls::evaluateCall(CallInst
*aCI
, FuncInfo
&FInfo
) {
1634 int numArgs
= (int)aCI
->getNumArgOperands();
1638 Constant
*copr0
= nullptr;
1639 Constant
*copr1
= nullptr;
1640 Constant
*copr2
= nullptr;
1642 if ((copr0
= dyn_cast
<Constant
>(aCI
->getArgOperand(0))) == nullptr)
1647 if ((copr1
= dyn_cast
<Constant
>(aCI
->getArgOperand(1))) == nullptr) {
1648 if (FInfo
.getId() != AMDGPULibFunc::EI_SINCOS
)
1654 if ((copr2
= dyn_cast
<Constant
>(aCI
->getArgOperand(2))) == nullptr)
1658 // At this point, all arguments to aCI are constants.
1660 // max vector size is 16, and sincos will generate two results.
1661 double DVal0
[16], DVal1
[16];
1662 bool hasTwoResults
= (FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
);
1663 if (getVecSize(FInfo
) == 1) {
1664 if (!evaluateScalarMathFunc(FInfo
, DVal0
[0],
1665 DVal1
[0], copr0
, copr1
, copr2
)) {
1669 ConstantDataVector
*CDV0
= dyn_cast_or_null
<ConstantDataVector
>(copr0
);
1670 ConstantDataVector
*CDV1
= dyn_cast_or_null
<ConstantDataVector
>(copr1
);
1671 ConstantDataVector
*CDV2
= dyn_cast_or_null
<ConstantDataVector
>(copr2
);
1672 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1673 Constant
*celt0
= CDV0
? CDV0
->getElementAsConstant(i
) : nullptr;
1674 Constant
*celt1
= CDV1
? CDV1
->getElementAsConstant(i
) : nullptr;
1675 Constant
*celt2
= CDV2
? CDV2
->getElementAsConstant(i
) : nullptr;
1676 if (!evaluateScalarMathFunc(FInfo
, DVal0
[i
],
1677 DVal1
[i
], celt0
, celt1
, celt2
)) {
1683 LLVMContext
&context
= CI
->getParent()->getParent()->getContext();
1684 Constant
*nval0
, *nval1
;
1685 if (getVecSize(FInfo
) == 1) {
1686 nval0
= ConstantFP::get(CI
->getType(), DVal0
[0]);
1688 nval1
= ConstantFP::get(CI
->getType(), DVal1
[0]);
1690 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
1691 SmallVector
<float, 0> FVal0
, FVal1
;
1692 for (int i
=0; i
< getVecSize(FInfo
); ++i
)
1693 FVal0
.push_back((float)DVal0
[i
]);
1694 ArrayRef
<float> tmp0(FVal0
);
1695 nval0
= ConstantDataVector::get(context
, tmp0
);
1696 if (hasTwoResults
) {
1697 for (int i
=0; i
< getVecSize(FInfo
); ++i
)
1698 FVal1
.push_back((float)DVal1
[i
]);
1699 ArrayRef
<float> tmp1(FVal1
);
1700 nval1
= ConstantDataVector::get(context
, tmp1
);
1703 ArrayRef
<double> tmp0(DVal0
);
1704 nval0
= ConstantDataVector::get(context
, tmp0
);
1705 if (hasTwoResults
) {
1706 ArrayRef
<double> tmp1(DVal1
);
1707 nval1
= ConstantDataVector::get(context
, tmp1
);
1712 if (hasTwoResults
) {
1714 assert(FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
&&
1715 "math function with ptr arg not supported yet");
1716 new StoreInst(nval1
, aCI
->getArgOperand(1), aCI
);
1723 // Public interface to the Simplify LibCalls pass.
1724 FunctionPass
*llvm::createAMDGPUSimplifyLibCallsPass(const TargetOptions
&Opt
,
1725 const TargetMachine
*TM
) {
1726 return new AMDGPUSimplifyLibCalls(Opt
, TM
);
1729 FunctionPass
*llvm::createAMDGPUUseNativeCallsPass() {
1730 return new AMDGPUUseNativeCalls();
1733 static bool setFastFlags(Function
&F
, const TargetOptions
&Options
) {
1736 if (Options
.UnsafeFPMath
|| Options
.NoInfsFPMath
)
1737 B
.addAttribute("no-infs-fp-math", "true");
1738 if (Options
.UnsafeFPMath
|| Options
.NoNaNsFPMath
)
1739 B
.addAttribute("no-nans-fp-math", "true");
1740 if (Options
.UnsafeFPMath
) {
1741 B
.addAttribute("less-precise-fpmad", "true");
1742 B
.addAttribute("unsafe-fp-math", "true");
1745 if (!B
.hasAttributes())
1748 F
.addAttributes(AttributeList::FunctionIndex
, B
);
1753 bool AMDGPUSimplifyLibCalls::runOnFunction(Function
&F
) {
1754 if (skipFunction(F
))
1757 bool Changed
= false;
1758 auto AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
1760 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1761 F
.printAsOperand(dbgs(), false, F
.getParent()); dbgs() << '\n';);
1764 Changed
|= setFastFlags(F
, Options
);
1766 for (auto &BB
: F
) {
1767 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ) {
1768 // Ignore non-calls.
1769 CallInst
*CI
= dyn_cast
<CallInst
>(I
);
1773 // Ignore indirect calls.
1774 Function
*Callee
= CI
->getCalledFunction();
1775 if (Callee
== 0) continue;
1777 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI
<< "\n";
1779 if(Simplifier
.fold(CI
, AA
))
1786 bool AMDGPUUseNativeCalls::runOnFunction(Function
&F
) {
1787 if (skipFunction(F
) || UseNative
.empty())
1790 bool Changed
= false;
1791 for (auto &BB
: F
) {
1792 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ) {
1793 // Ignore non-calls.
1794 CallInst
*CI
= dyn_cast
<CallInst
>(I
);
1798 // Ignore indirect calls.
1799 Function
*Callee
= CI
->getCalledFunction();
1800 if (Callee
== 0) continue;
1802 if(Simplifier
.useNative(CI
))