LLVM 19.0.0git
AMDGPULibCalls.cpp
Go to the documentation of this file.
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"
21#include "llvm/IR/Dominators.h"
22#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/IntrinsicsAMDGPU.h"
27#include <cmath>
28
29#define DEBUG_TYPE "amdgpu-simplifylib"
30
31using namespace llvm;
32using namespace llvm::PatternMatch;
33
34static cl::opt<bool> EnablePreLink("amdgpu-prelink",
35 cl::desc("Enable pre-link mode optimizations"),
36 cl::init(false),
38
39static cl::list<std::string> UseNative("amdgpu-use-native",
40 cl::desc("Comma separated list of functions to replace with native, or all"),
43
44#define MATH_PI numbers::pi
45#define MATH_E numbers::e
46#define MATH_SQRT2 numbers::sqrt2
47#define MATH_SQRT1_2 numbers::inv_sqrt2
48
49namespace llvm {
50
52private:
53 const TargetLibraryInfo *TLInfo = nullptr;
54 AssumptionCache *AC = nullptr;
55 DominatorTree *DT = nullptr;
56
58
59 bool UnsafeFPMath = false;
60
61 // -fuse-native.
62 bool AllNative = false;
63
64 bool useNativeFunc(const StringRef F) const;
65
66 // Return a pointer (pointer expr) to the function if function definition with
67 // "FuncName" exists. It may create a new function prototype in pre-link mode.
68 FunctionCallee getFunction(Module *M, const FuncInfo &fInfo);
69
70 bool parseFunctionName(const StringRef &FMangledName, FuncInfo &FInfo);
71
72 bool TDOFold(CallInst *CI, const FuncInfo &FInfo);
73
74 /* Specialized optimizations */
75
76 // pow/powr/pown
77 bool fold_pow(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
78
79 // rootn
80 bool fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
81
82 // -fuse-native for sincos
83 bool sincosUseNative(CallInst *aCI, const FuncInfo &FInfo);
84
85 // evaluate calls if calls' arguments are constants.
86 bool evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0, double &Res1,
87 Constant *copr0, Constant *copr1);
88 bool evaluateCall(CallInst *aCI, const FuncInfo &FInfo);
89
90 /// Insert a value to sincos function \p Fsincos. Returns (value of sin, value
91 /// of cos, sincos call).
92 std::tuple<Value *, Value *, Value *> insertSinCos(Value *Arg,
93 FastMathFlags FMF,
95 FunctionCallee Fsincos);
96
97 // sin/cos
98 bool fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
99
100 // __read_pipe/__write_pipe
101 bool fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
102 const FuncInfo &FInfo);
103
104 // Get a scalar native builtin single argument FP function
105 FunctionCallee getNativeFunction(Module *M, const FuncInfo &FInfo);
106
107 /// Substitute a call to a known libcall with an intrinsic call. If \p
108 /// AllowMinSize is true, allow the replacement in a minsize function.
109 bool shouldReplaceLibcallWithIntrinsic(const CallInst *CI,
110 bool AllowMinSizeF32 = false,
111 bool AllowF64 = false,
112 bool AllowStrictFP = false);
113 void replaceLibCallWithSimpleIntrinsic(IRBuilder<> &B, CallInst *CI,
114 Intrinsic::ID IntrID);
115
116 bool tryReplaceLibcallWithSimpleIntrinsic(IRBuilder<> &B, CallInst *CI,
117 Intrinsic::ID IntrID,
118 bool AllowMinSizeF32 = false,
119 bool AllowF64 = false,
120 bool AllowStrictFP = false);
121
122protected:
123 bool isUnsafeMath(const FPMathOperator *FPOp) const;
124 bool isUnsafeFiniteOnlyMath(const FPMathOperator *FPOp) const;
125
127
128 static void replaceCall(Instruction *I, Value *With) {
129 I->replaceAllUsesWith(With);
130 I->eraseFromParent();
131 }
132
133 static void replaceCall(FPMathOperator *I, Value *With) {
134 replaceCall(cast<Instruction>(I), With);
135 }
136
137public:
139
140 bool fold(CallInst *CI);
141
143 void initNativeFuncs();
144
145 // Replace a normal math function call with that native version
146 bool useNative(CallInst *CI);
147};
148
149} // end llvm namespace
150
151template <typename IRB>
152static CallInst *CreateCallEx(IRB &B, FunctionCallee Callee, Value *Arg,
153 const Twine &Name = "") {
154 CallInst *R = B.CreateCall(Callee, Arg, Name);
155 if (Function *F = dyn_cast<Function>(Callee.getCallee()))
156 R->setCallingConv(F->getCallingConv());
157 return R;
158}
159
160template <typename IRB>
161static CallInst *CreateCallEx2(IRB &B, FunctionCallee Callee, Value *Arg1,
162 Value *Arg2, const Twine &Name = "") {
163 CallInst *R = B.CreateCall(Callee, {Arg1, Arg2}, Name);
164 if (Function *F = dyn_cast<Function>(Callee.getCallee()))
165 R->setCallingConv(F->getCallingConv());
166 return R;
167}
168
170 Type *PowNExpTy = Type::getInt32Ty(FT->getContext());
171 if (VectorType *VecTy = dyn_cast<VectorType>(FT->getReturnType()))
172 PowNExpTy = VectorType::get(PowNExpTy, VecTy->getElementCount());
173
174 return FunctionType::get(FT->getReturnType(),
175 {FT->getParamType(0), PowNExpTy}, false);
176}
177
178// Data structures for table-driven optimizations.
179// FuncTbl works for both f32 and f64 functions with 1 input argument
180
182 double result;
183 double input;
184};
185
186/* a list of {result, input} */
187static const TableEntry tbl_acos[] = {
188 {MATH_PI / 2.0, 0.0},
189 {MATH_PI / 2.0, -0.0},
190 {0.0, 1.0},
191 {MATH_PI, -1.0}
192};
193static const TableEntry tbl_acosh[] = {
194 {0.0, 1.0}
195};
196static const TableEntry tbl_acospi[] = {
197 {0.5, 0.0},
198 {0.5, -0.0},
199 {0.0, 1.0},
200 {1.0, -1.0}
201};
202static const TableEntry tbl_asin[] = {
203 {0.0, 0.0},
204 {-0.0, -0.0},
205 {MATH_PI / 2.0, 1.0},
206 {-MATH_PI / 2.0, -1.0}
207};
208static const TableEntry tbl_asinh[] = {
209 {0.0, 0.0},
210 {-0.0, -0.0}
211};
212static const TableEntry tbl_asinpi[] = {
213 {0.0, 0.0},
214 {-0.0, -0.0},
215 {0.5, 1.0},
216 {-0.5, -1.0}
217};
218static const TableEntry tbl_atan[] = {
219 {0.0, 0.0},
220 {-0.0, -0.0},
221 {MATH_PI / 4.0, 1.0},
222 {-MATH_PI / 4.0, -1.0}
223};
224static const TableEntry tbl_atanh[] = {
225 {0.0, 0.0},
226 {-0.0, -0.0}
227};
228static const TableEntry tbl_atanpi[] = {
229 {0.0, 0.0},
230 {-0.0, -0.0},
231 {0.25, 1.0},
232 {-0.25, -1.0}
233};
234static const TableEntry tbl_cbrt[] = {
235 {0.0, 0.0},
236 {-0.0, -0.0},
237 {1.0, 1.0},
238 {-1.0, -1.0},
239};
240static const TableEntry tbl_cos[] = {
241 {1.0, 0.0},
242 {1.0, -0.0}
243};
244static const TableEntry tbl_cosh[] = {
245 {1.0, 0.0},
246 {1.0, -0.0}
247};
248static const TableEntry tbl_cospi[] = {
249 {1.0, 0.0},
250 {1.0, -0.0}
251};
252static const TableEntry tbl_erfc[] = {
253 {1.0, 0.0},
254 {1.0, -0.0}
255};
256static const TableEntry tbl_erf[] = {
257 {0.0, 0.0},
258 {-0.0, -0.0}
259};
260static const TableEntry tbl_exp[] = {
261 {1.0, 0.0},
262 {1.0, -0.0},
263 {MATH_E, 1.0}
264};
265static const TableEntry tbl_exp2[] = {
266 {1.0, 0.0},
267 {1.0, -0.0},
268 {2.0, 1.0}
269};
270static const TableEntry tbl_exp10[] = {
271 {1.0, 0.0},
272 {1.0, -0.0},
273 {10.0, 1.0}
274};
275static const TableEntry tbl_expm1[] = {
276 {0.0, 0.0},
277 {-0.0, -0.0}
278};
279static const TableEntry tbl_log[] = {
280 {0.0, 1.0},
281 {1.0, MATH_E}
282};
283static const TableEntry tbl_log2[] = {
284 {0.0, 1.0},
285 {1.0, 2.0}
286};
287static const TableEntry tbl_log10[] = {
288 {0.0, 1.0},
289 {1.0, 10.0}
290};
291static const TableEntry tbl_rsqrt[] = {
292 {1.0, 1.0},
293 {MATH_SQRT1_2, 2.0}
294};
295static const TableEntry tbl_sin[] = {
296 {0.0, 0.0},
297 {-0.0, -0.0}
298};
299static const TableEntry tbl_sinh[] = {
300 {0.0, 0.0},
301 {-0.0, -0.0}
302};
303static const TableEntry tbl_sinpi[] = {
304 {0.0, 0.0},
305 {-0.0, -0.0}
306};
307static const TableEntry tbl_sqrt[] = {
308 {0.0, 0.0},
309 {1.0, 1.0},
310 {MATH_SQRT2, 2.0}
311};
312static const TableEntry tbl_tan[] = {
313 {0.0, 0.0},
314 {-0.0, -0.0}
315};
316static const TableEntry tbl_tanh[] = {
317 {0.0, 0.0},
318 {-0.0, -0.0}
319};
320static const TableEntry tbl_tanpi[] = {
321 {0.0, 0.0},
322 {-0.0, -0.0}
323};
324static const TableEntry tbl_tgamma[] = {
325 {1.0, 1.0},
326 {1.0, 2.0},
327 {2.0, 3.0},
328 {6.0, 4.0}
329};
330
332 switch(id) {
333 case AMDGPULibFunc::EI_DIVIDE:
334 case AMDGPULibFunc::EI_COS:
335 case AMDGPULibFunc::EI_EXP:
336 case AMDGPULibFunc::EI_EXP2:
337 case AMDGPULibFunc::EI_EXP10:
338 case AMDGPULibFunc::EI_LOG:
339 case AMDGPULibFunc::EI_LOG2:
340 case AMDGPULibFunc::EI_LOG10:
341 case AMDGPULibFunc::EI_POWR:
342 case AMDGPULibFunc::EI_RECIP:
343 case AMDGPULibFunc::EI_RSQRT:
344 case AMDGPULibFunc::EI_SIN:
345 case AMDGPULibFunc::EI_SINCOS:
346 case AMDGPULibFunc::EI_SQRT:
347 case AMDGPULibFunc::EI_TAN:
348 return true;
349 default:;
350 }
351 return false;
352}
353
355
357 switch(id) {
358 case AMDGPULibFunc::EI_ACOS: return TableRef(tbl_acos);
359 case AMDGPULibFunc::EI_ACOSH: return TableRef(tbl_acosh);
360 case AMDGPULibFunc::EI_ACOSPI: return TableRef(tbl_acospi);
361 case AMDGPULibFunc::EI_ASIN: return TableRef(tbl_asin);
362 case AMDGPULibFunc::EI_ASINH: return TableRef(tbl_asinh);
363 case AMDGPULibFunc::EI_ASINPI: return TableRef(tbl_asinpi);
364 case AMDGPULibFunc::EI_ATAN: return TableRef(tbl_atan);
365 case AMDGPULibFunc::EI_ATANH: return TableRef(tbl_atanh);
366 case AMDGPULibFunc::EI_ATANPI: return TableRef(tbl_atanpi);
367 case AMDGPULibFunc::EI_CBRT: return TableRef(tbl_cbrt);
368 case AMDGPULibFunc::EI_NCOS:
369 case AMDGPULibFunc::EI_COS: return TableRef(tbl_cos);
370 case AMDGPULibFunc::EI_COSH: return TableRef(tbl_cosh);
371 case AMDGPULibFunc::EI_COSPI: return TableRef(tbl_cospi);
372 case AMDGPULibFunc::EI_ERFC: return TableRef(tbl_erfc);
373 case AMDGPULibFunc::EI_ERF: return TableRef(tbl_erf);
374 case AMDGPULibFunc::EI_EXP: return TableRef(tbl_exp);
375 case AMDGPULibFunc::EI_NEXP2:
376 case AMDGPULibFunc::EI_EXP2: return TableRef(tbl_exp2);
377 case AMDGPULibFunc::EI_EXP10: return TableRef(tbl_exp10);
378 case AMDGPULibFunc::EI_EXPM1: return TableRef(tbl_expm1);
379 case AMDGPULibFunc::EI_LOG: return TableRef(tbl_log);
380 case AMDGPULibFunc::EI_NLOG2:
381 case AMDGPULibFunc::EI_LOG2: return TableRef(tbl_log2);
382 case AMDGPULibFunc::EI_LOG10: return TableRef(tbl_log10);
383 case AMDGPULibFunc::EI_NRSQRT:
384 case AMDGPULibFunc::EI_RSQRT: return TableRef(tbl_rsqrt);
385 case AMDGPULibFunc::EI_NSIN:
386 case AMDGPULibFunc::EI_SIN: return TableRef(tbl_sin);
387 case AMDGPULibFunc::EI_SINH: return TableRef(tbl_sinh);
388 case AMDGPULibFunc::EI_SINPI: return TableRef(tbl_sinpi);
389 case AMDGPULibFunc::EI_NSQRT:
390 case AMDGPULibFunc::EI_SQRT: return TableRef(tbl_sqrt);
391 case AMDGPULibFunc::EI_TAN: return TableRef(tbl_tan);
392 case AMDGPULibFunc::EI_TANH: return TableRef(tbl_tanh);
393 case AMDGPULibFunc::EI_TANPI: return TableRef(tbl_tanpi);
394 case AMDGPULibFunc::EI_TGAMMA: return TableRef(tbl_tgamma);
395 default:;
396 }
397 return TableRef();
398}
399
400static inline int getVecSize(const AMDGPULibFunc& FInfo) {
401 return FInfo.getLeads()[0].VectorSize;
402}
403
404static inline AMDGPULibFunc::EType getArgType(const AMDGPULibFunc& FInfo) {
405 return (AMDGPULibFunc::EType)FInfo.getLeads()[0].ArgType;
406}
407
408FunctionCallee AMDGPULibCalls::getFunction(Module *M, const FuncInfo &fInfo) {
409 // If we are doing PreLinkOpt, the function is external. So it is safe to
410 // use getOrInsertFunction() at this stage.
411
413 : AMDGPULibFunc::getFunction(M, fInfo);
414}
415
416bool AMDGPULibCalls::parseFunctionName(const StringRef &FMangledName,
417 FuncInfo &FInfo) {
418 return AMDGPULibFunc::parse(FMangledName, FInfo);
419}
420
422 return UnsafeFPMath || FPOp->isFast();
423}
424
426 return UnsafeFPMath ||
427 (FPOp->hasApproxFunc() && FPOp->hasNoNaNs() && FPOp->hasNoInfs());
428}
429
431 const FPMathOperator *FPOp) const {
432 // TODO: Refine to approxFunc or contract
433 return isUnsafeMath(FPOp);
434}
435
437 UnsafeFPMath = F.getFnAttribute("unsafe-fp-math").getValueAsBool();
441}
442
443bool AMDGPULibCalls::useNativeFunc(const StringRef F) const {
444 return AllNative || llvm::is_contained(UseNative, F);
445}
446
448 AllNative = useNativeFunc("all") ||
449 (UseNative.getNumOccurrences() && UseNative.size() == 1 &&
450 UseNative.begin()->empty());
451}
452
453bool AMDGPULibCalls::sincosUseNative(CallInst *aCI, const FuncInfo &FInfo) {
454 bool native_sin = useNativeFunc("sin");
455 bool native_cos = useNativeFunc("cos");
456
457 if (native_sin && native_cos) {
458 Module *M = aCI->getModule();
459 Value *opr0 = aCI->getArgOperand(0);
460
461 AMDGPULibFunc nf;
462 nf.getLeads()[0].ArgType = FInfo.getLeads()[0].ArgType;
463 nf.getLeads()[0].VectorSize = FInfo.getLeads()[0].VectorSize;
464
467 FunctionCallee sinExpr = getFunction(M, nf);
468
471 FunctionCallee cosExpr = getFunction(M, nf);
472 if (sinExpr && cosExpr) {
473 Value *sinval =
474 CallInst::Create(sinExpr, opr0, "splitsin", aCI->getIterator());
475 Value *cosval =
476 CallInst::Create(cosExpr, opr0, "splitcos", aCI->getIterator());
477 new StoreInst(cosval, aCI->getArgOperand(1), aCI->getIterator());
478
479 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
480 << " with native version of sin/cos");
481
482 replaceCall(aCI, sinval);
483 return true;
484 }
485 }
486 return false;
487}
488
490 Function *Callee = aCI->getCalledFunction();
491 if (!Callee || aCI->isNoBuiltin())
492 return false;
493
494 FuncInfo FInfo;
495 if (!parseFunctionName(Callee->getName(), FInfo) || !FInfo.isMangled() ||
496 FInfo.getPrefix() != AMDGPULibFunc::NOPFX ||
497 getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()) ||
498 !(AllNative || useNativeFunc(FInfo.getName()))) {
499 return false;
500 }
501
502 if (FInfo.getId() == AMDGPULibFunc::EI_SINCOS)
503 return sincosUseNative(aCI, FInfo);
504
506 FunctionCallee F = getFunction(aCI->getModule(), FInfo);
507 if (!F)
508 return false;
509
510 aCI->setCalledFunction(F);
511 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
512 << " with native version");
513 return true;
514}
515
516// Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
517// builtin, with appended type size and alignment arguments, where 2 or 4
518// indicates the original number of arguments. The library has optimized version
519// of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
520// power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
521// for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
522// 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
523bool AMDGPULibCalls::fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
524 const FuncInfo &FInfo) {
525 auto *Callee = CI->getCalledFunction();
526 if (!Callee->isDeclaration())
527 return false;
528
529 assert(Callee->hasName() && "Invalid read_pipe/write_pipe function");
530 auto *M = Callee->getParent();
531 std::string Name = std::string(Callee->getName());
532 auto NumArg = CI->arg_size();
533 if (NumArg != 4 && NumArg != 6)
534 return false;
535 ConstantInt *PacketSize =
536 dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 2));
537 ConstantInt *PacketAlign =
538 dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 1));
539 if (!PacketSize || !PacketAlign)
540 return false;
541
542 unsigned Size = PacketSize->getZExtValue();
543 Align Alignment = PacketAlign->getAlignValue();
544 if (Alignment != Size)
545 return false;
546
547 unsigned PtrArgLoc = CI->arg_size() - 3;
548 Value *PtrArg = CI->getArgOperand(PtrArgLoc);
549 Type *PtrTy = PtrArg->getType();
550
552 for (unsigned I = 0; I != PtrArgLoc; ++I)
553 ArgTys.push_back(CI->getArgOperand(I)->getType());
554 ArgTys.push_back(PtrTy);
555
556 Name = Name + "_" + std::to_string(Size);
557 auto *FTy = FunctionType::get(Callee->getReturnType(),
558 ArrayRef<Type *>(ArgTys), false);
559 AMDGPULibFunc NewLibFunc(Name, FTy);
561 if (!F)
562 return false;
563
565 for (unsigned I = 0; I != PtrArgLoc; ++I)
566 Args.push_back(CI->getArgOperand(I));
567 Args.push_back(PtrArg);
568
569 auto *NCI = B.CreateCall(F, Args);
570 NCI->setAttributes(CI->getAttributes());
571 CI->replaceAllUsesWith(NCI);
572 CI->dropAllReferences();
573 CI->eraseFromParent();
574
575 return true;
576}
577
578static bool isKnownIntegral(const Value *V, const DataLayout &DL,
579 FastMathFlags FMF) {
580 if (isa<UndefValue>(V))
581 return true;
582
583 if (const ConstantFP *CF = dyn_cast<ConstantFP>(V))
584 return CF->getValueAPF().isInteger();
585
586 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
587 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
588 Constant *ConstElt = CDV->getElementAsConstant(i);
589 if (isa<UndefValue>(ConstElt))
590 continue;
591 const ConstantFP *CFP = dyn_cast<ConstantFP>(ConstElt);
592 if (!CFP || !CFP->getValue().isInteger())
593 return false;
594 }
595
596 return true;
597 }
598
599 const Instruction *I = dyn_cast<Instruction>(V);
600 if (!I)
601 return false;
602
603 switch (I->getOpcode()) {
604 case Instruction::SIToFP:
605 case Instruction::UIToFP:
606 // TODO: Could check nofpclass(inf) on incoming argument
607 if (FMF.noInfs())
608 return true;
609
610 // Need to check int size cannot produce infinity, which computeKnownFPClass
611 // knows how to do already.
612 return isKnownNeverInfinity(I, /*Depth=*/0, SimplifyQuery(DL));
613 case Instruction::Call: {
614 const CallInst *CI = cast<CallInst>(I);
615 switch (CI->getIntrinsicID()) {
616 case Intrinsic::trunc:
617 case Intrinsic::floor:
618 case Intrinsic::ceil:
619 case Intrinsic::rint:
620 case Intrinsic::nearbyint:
621 case Intrinsic::round:
622 case Intrinsic::roundeven:
623 return (FMF.noInfs() && FMF.noNaNs()) ||
624 isKnownNeverInfOrNaN(I, /*Depth=*/0, SimplifyQuery(DL));
625 default:
626 break;
627 }
628
629 break;
630 }
631 default:
632 break;
633 }
634
635 return false;
636}
637
638// This function returns false if no change; return true otherwise.
640 Function *Callee = CI->getCalledFunction();
641 // Ignore indirect calls.
642 if (!Callee || Callee->isIntrinsic() || CI->isNoBuiltin())
643 return false;
644
645 FuncInfo FInfo;
646 if (!parseFunctionName(Callee->getName(), FInfo))
647 return false;
648
649 // Further check the number of arguments to see if they match.
650 // TODO: Check calling convention matches too
651 if (!FInfo.isCompatibleSignature(CI->getFunctionType()))
652 return false;
653
654 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI << '\n');
655
656 if (TDOFold(CI, FInfo))
657 return true;
658
659 IRBuilder<> B(CI);
660 if (CI->isStrictFP())
661 B.setIsFPConstrained(true);
662
663 if (FPMathOperator *FPOp = dyn_cast<FPMathOperator>(CI)) {
664 // Under unsafe-math, evaluate calls if possible.
665 // According to Brian Sumner, we can do this for all f32 function calls
666 // using host's double function calls.
667 if (canIncreasePrecisionOfConstantFold(FPOp) && evaluateCall(CI, FInfo))
668 return true;
669
670 // Copy fast flags from the original call.
671 FastMathFlags FMF = FPOp->getFastMathFlags();
672 B.setFastMathFlags(FMF);
673
674 // Specialized optimizations for each function call.
675 //
676 // TODO: Handle native functions
677 switch (FInfo.getId()) {
679 if (FMF.none())
680 return false;
681 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::exp,
682 FMF.approxFunc());
684 if (FMF.none())
685 return false;
686 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::exp2,
687 FMF.approxFunc());
689 if (FMF.none())
690 return false;
691 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log,
692 FMF.approxFunc());
694 if (FMF.none())
695 return false;
696 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log2,
697 FMF.approxFunc());
699 if (FMF.none())
700 return false;
701 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log10,
702 FMF.approxFunc());
704 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::minnum,
705 true, true);
707 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::maxnum,
708 true, true);
710 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fma, true,
711 true);
713 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fmuladd,
714 true, true);
716 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fabs, true,
717 true, true);
719 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::copysign,
720 true, true, true);
722 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::floor, true,
723 true);
725 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::ceil, true,
726 true);
728 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::trunc, true,
729 true);
731 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::rint, true,
732 true);
734 return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::round, true,
735 true);
737 if (!shouldReplaceLibcallWithIntrinsic(CI, true, true))
738 return false;
739
740 Value *Arg1 = CI->getArgOperand(1);
741 if (VectorType *VecTy = dyn_cast<VectorType>(CI->getType());
742 VecTy && !isa<VectorType>(Arg1->getType())) {
743 Value *SplatArg1 = B.CreateVectorSplat(VecTy->getElementCount(), Arg1);
744 CI->setArgOperand(1, SplatArg1);
745 }
746
748 CI->getModule(), Intrinsic::ldexp,
749 {CI->getType(), CI->getArgOperand(1)->getType()}));
750 return true;
751 }
753 Module *M = Callee->getParent();
754 AMDGPULibFunc PowrInfo(AMDGPULibFunc::EI_POWR, FInfo);
755 FunctionCallee PowrFunc = getFunction(M, PowrInfo);
756 CallInst *Call = cast<CallInst>(FPOp);
757
758 // pow(x, y) -> powr(x, y) for x >= -0.0
759 // TODO: Account for flags on current call
760 if (PowrFunc &&
762 FPOp->getOperand(0), /*Depth=*/0,
763 SimplifyQuery(M->getDataLayout(), TLInfo, DT, AC, Call))) {
764 Call->setCalledFunction(PowrFunc);
765 return fold_pow(FPOp, B, PowrInfo) || true;
766 }
767
768 // pow(x, y) -> pown(x, y) for known integral y
769 if (isKnownIntegral(FPOp->getOperand(1), M->getDataLayout(),
770 FPOp->getFastMathFlags())) {
771 FunctionType *PownType = getPownType(CI->getFunctionType());
772 AMDGPULibFunc PownInfo(AMDGPULibFunc::EI_POWN, PownType, true);
773 FunctionCallee PownFunc = getFunction(M, PownInfo);
774 if (PownFunc) {
775 // TODO: If the incoming integral value is an sitofp/uitofp, it won't
776 // fold out without a known range. We can probably take the source
777 // value directly.
778 Value *CastedArg =
779 B.CreateFPToSI(FPOp->getOperand(1), PownType->getParamType(1));
780 // Have to drop any nofpclass attributes on the original call site.
781 Call->removeParamAttrs(
783 Call->setCalledFunction(PownFunc);
784 Call->setArgOperand(1, CastedArg);
785 return fold_pow(FPOp, B, PownInfo) || true;
786 }
787 }
788
789 return fold_pow(FPOp, B, FInfo);
790 }
793 return fold_pow(FPOp, B, FInfo);
795 return fold_rootn(FPOp, B, FInfo);
797 // TODO: Allow with strictfp + constrained intrinsic
798 return tryReplaceLibcallWithSimpleIntrinsic(
799 B, CI, Intrinsic::sqrt, true, true, /*AllowStrictFP=*/false);
802 return fold_sincos(FPOp, B, FInfo);
803 default:
804 break;
805 }
806 } else {
807 // Specialized optimizations for each function call
808 switch (FInfo.getId()) {
813 return fold_read_write_pipe(CI, B, FInfo);
814 default:
815 break;
816 }
817 }
818
819 return false;
820}
821
822bool AMDGPULibCalls::TDOFold(CallInst *CI, const FuncInfo &FInfo) {
823 // Table-Driven optimization
824 const TableRef tr = getOptTable(FInfo.getId());
825 if (tr.empty())
826 return false;
827
828 int const sz = (int)tr.size();
829 Value *opr0 = CI->getArgOperand(0);
830
831 if (getVecSize(FInfo) > 1) {
832 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(opr0)) {
834 for (int eltNo = 0; eltNo < getVecSize(FInfo); ++eltNo) {
835 ConstantFP *eltval = dyn_cast<ConstantFP>(
836 CV->getElementAsConstant((unsigned)eltNo));
837 assert(eltval && "Non-FP arguments in math function!");
838 bool found = false;
839 for (int i=0; i < sz; ++i) {
840 if (eltval->isExactlyValue(tr[i].input)) {
841 DVal.push_back(tr[i].result);
842 found = true;
843 break;
844 }
845 }
846 if (!found) {
847 // This vector constants not handled yet.
848 return false;
849 }
850 }
851 LLVMContext &context = CI->getParent()->getParent()->getContext();
852 Constant *nval;
853 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
855 for (unsigned i = 0; i < DVal.size(); ++i) {
856 FVal.push_back((float)DVal[i]);
857 }
858 ArrayRef<float> tmp(FVal);
859 nval = ConstantDataVector::get(context, tmp);
860 } else { // F64
861 ArrayRef<double> tmp(DVal);
862 nval = ConstantDataVector::get(context, tmp);
863 }
864 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
865 replaceCall(CI, nval);
866 return true;
867 }
868 } else {
869 // Scalar version
870 if (ConstantFP *CF = dyn_cast<ConstantFP>(opr0)) {
871 for (int i = 0; i < sz; ++i) {
872 if (CF->isExactlyValue(tr[i].input)) {
873 Value *nval = ConstantFP::get(CF->getType(), tr[i].result);
874 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
875 replaceCall(CI, nval);
876 return true;
877 }
878 }
879 }
880 }
881
882 return false;
883}
884
885namespace llvm {
886static double log2(double V) {
887#if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
888 return ::log2(V);
889#else
890 return log(V) / numbers::ln2;
891#endif
892}
893}
894
895bool AMDGPULibCalls::fold_pow(FPMathOperator *FPOp, IRBuilder<> &B,
896 const FuncInfo &FInfo) {
897 assert((FInfo.getId() == AMDGPULibFunc::EI_POW ||
898 FInfo.getId() == AMDGPULibFunc::EI_POWR ||
899 FInfo.getId() == AMDGPULibFunc::EI_POWN) &&
900 "fold_pow: encounter a wrong function call");
901
902 Module *M = B.GetInsertBlock()->getModule();
903 Type *eltType = FPOp->getType()->getScalarType();
904 Value *opr0 = FPOp->getOperand(0);
905 Value *opr1 = FPOp->getOperand(1);
906
907 const APFloat *CF = nullptr;
908 const APInt *CINT = nullptr;
909 if (!match(opr1, m_APFloatAllowPoison(CF)))
910 match(opr1, m_APIntAllowPoison(CINT));
911
912 // 0x1111111 means that we don't do anything for this call.
913 int ci_opr1 = (CINT ? (int)CINT->getSExtValue() : 0x1111111);
914
915 if ((CF && CF->isZero()) || (CINT && ci_opr1 == 0)) {
916 // pow/powr/pown(x, 0) == 1
917 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1\n");
918 Constant *cnval = ConstantFP::get(eltType, 1.0);
919 if (getVecSize(FInfo) > 1) {
920 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
921 }
922 replaceCall(FPOp, cnval);
923 return true;
924 }
925 if ((CF && CF->isExactlyValue(1.0)) || (CINT && ci_opr1 == 1)) {
926 // pow/powr/pown(x, 1.0) = x
927 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n");
928 replaceCall(FPOp, opr0);
929 return true;
930 }
931 if ((CF && CF->isExactlyValue(2.0)) || (CINT && ci_opr1 == 2)) {
932 // pow/powr/pown(x, 2.0) = x*x
933 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << " * "
934 << *opr0 << "\n");
935 Value *nval = B.CreateFMul(opr0, opr0, "__pow2");
936 replaceCall(FPOp, nval);
937 return true;
938 }
939 if ((CF && CF->isExactlyValue(-1.0)) || (CINT && ci_opr1 == -1)) {
940 // pow/powr/pown(x, -1.0) = 1.0/x
941 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1 / " << *opr0 << "\n");
942 Constant *cnval = ConstantFP::get(eltType, 1.0);
943 if (getVecSize(FInfo) > 1) {
944 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
945 }
946 Value *nval = B.CreateFDiv(cnval, opr0, "__powrecip");
947 replaceCall(FPOp, nval);
948 return true;
949 }
950
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
957 FInfo))) {
958 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << FInfo.getName()
959 << '(' << *opr0 << ")\n");
960 Value *nval = CreateCallEx(B,FPExpr, opr0, issqrt ? "__pow2sqrt"
961 : "__pow2rsqrt");
962 replaceCall(FPOp, nval);
963 return true;
964 }
965 }
966
967 if (!isUnsafeFiniteOnlyMath(FPOp))
968 return false;
969
970 // Unsafe Math optimization
971
972 // Remember that ci_opr1 is set if opr1 is integral
973 if (CF) {
974 double dval = (getArgType(FInfo) == AMDGPULibFunc::F32)
975 ? (double)CF->convertToFloat()
976 : CF->convertToDouble();
977 int ival = (int)dval;
978 if ((double)ival == dval) {
979 ci_opr1 = ival;
980 } else
981 ci_opr1 = 0x11111111;
982 }
983
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) {
988 Constant *cnval;
989 Value *nval;
990 if (abs_opr1 == 0) {
991 cnval = ConstantFP::get(eltType, 1.0);
992 if (getVecSize(FInfo) > 1) {
993 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
994 }
995 nval = cnval;
996 } else {
997 Value *valx2 = nullptr;
998 nval = nullptr;
999 while (abs_opr1 > 0) {
1000 valx2 = valx2 ? B.CreateFMul(valx2, valx2, "__powx2") : opr0;
1001 if (abs_opr1 & 1) {
1002 nval = nval ? B.CreateFMul(nval, valx2, "__powprod") : valx2;
1003 }
1004 abs_opr1 >>= 1;
1005 }
1006 }
1007
1008 if (ci_opr1 < 0) {
1009 cnval = ConstantFP::get(eltType, 1.0);
1010 if (getVecSize(FInfo) > 1) {
1011 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
1012 }
1013 nval = B.CreateFDiv(cnval, nval, "__1powprod");
1014 }
1015 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
1016 << ((ci_opr1 < 0) ? "1/prod(" : "prod(") << *opr0
1017 << ")\n");
1018 replaceCall(FPOp, nval);
1019 return true;
1020 }
1021
1022 // If we should use the generic intrinsic instead of emitting a libcall
1023 const bool ShouldUseIntrinsic = eltType->isFloatTy() || eltType->isHalfTy();
1024
1025 // powr ---> exp2(y * log2(x))
1026 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
1027 FunctionCallee ExpExpr;
1028 if (ShouldUseIntrinsic)
1029 ExpExpr = Intrinsic::getDeclaration(M, Intrinsic::exp2, {FPOp->getType()});
1030 else {
1031 ExpExpr = getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2, FInfo));
1032 if (!ExpExpr)
1033 return false;
1034 }
1035
1036 bool needlog = false;
1037 bool needabs = false;
1038 bool needcopysign = false;
1039 Constant *cnval = nullptr;
1040 if (getVecSize(FInfo) == 1) {
1041 CF = nullptr;
1042 match(opr0, m_APFloatAllowPoison(CF));
1043
1044 if (CF) {
1045 double V = (getArgType(FInfo) == AMDGPULibFunc::F32)
1046 ? (double)CF->convertToFloat()
1047 : CF->convertToDouble();
1048
1049 V = log2(std::abs(V));
1050 cnval = ConstantFP::get(eltType, V);
1051 needcopysign = (FInfo.getId() != AMDGPULibFunc::EI_POWR) &&
1052 CF->isNegative();
1053 } else {
1054 needlog = true;
1055 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR;
1056 }
1057 } else {
1058 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr0);
1059
1060 if (!CDV) {
1061 needlog = true;
1062 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR;
1063 } else {
1064 assert ((int)CDV->getNumElements() == getVecSize(FInfo) &&
1065 "Wrong vector size detected");
1066
1068 for (int i=0; i < getVecSize(FInfo); ++i) {
1069 double V = CDV->getElementAsAPFloat(i).convertToDouble();
1070 if (V < 0.0) needcopysign = true;
1071 V = log2(std::abs(V));
1072 DVal.push_back(V);
1073 }
1074 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1076 for (unsigned i=0; i < DVal.size(); ++i) {
1077 FVal.push_back((float)DVal[i]);
1078 }
1079 ArrayRef<float> tmp(FVal);
1080 cnval = ConstantDataVector::get(M->getContext(), tmp);
1081 } else {
1082 ArrayRef<double> tmp(DVal);
1083 cnval = ConstantDataVector::get(M->getContext(), tmp);
1084 }
1085 }
1086 }
1087
1088 if (needcopysign && (FInfo.getId() == AMDGPULibFunc::EI_POW)) {
1089 // We cannot handle corner cases for a general pow() function, give up
1090 // unless y is a constant integral value. Then proceed as if it were pown.
1091 if (!isKnownIntegral(opr1, M->getDataLayout(), FPOp->getFastMathFlags()))
1092 return false;
1093 }
1094
1095 Value *nval;
1096 if (needabs) {
1097 nval = B.CreateUnaryIntrinsic(Intrinsic::fabs, opr0, nullptr, "__fabs");
1098 } else {
1099 nval = cnval ? cnval : opr0;
1100 }
1101 if (needlog) {
1102 FunctionCallee LogExpr;
1103 if (ShouldUseIntrinsic) {
1104 LogExpr =
1105 Intrinsic::getDeclaration(M, Intrinsic::log2, {FPOp->getType()});
1106 } else {
1107 LogExpr = getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2, FInfo));
1108 if (!LogExpr)
1109 return false;
1110 }
1111
1112 nval = CreateCallEx(B,LogExpr, nval, "__log2");
1113 }
1114
1115 if (FInfo.getId() == AMDGPULibFunc::EI_POWN) {
1116 // convert int(32) to fp(f32 or f64)
1117 opr1 = B.CreateSIToFP(opr1, nval->getType(), "pownI2F");
1118 }
1119 nval = B.CreateFMul(opr1, nval, "__ylogx");
1120 nval = CreateCallEx(B,ExpExpr, nval, "__exp2");
1121
1122 if (needcopysign) {
1123 Value *opr_n;
1124 Type* rTy = opr0->getType();
1125 Type* nTyS = B.getIntNTy(eltType->getPrimitiveSizeInBits());
1126 Type *nTy = nTyS;
1127 if (const auto *vTy = dyn_cast<FixedVectorType>(rTy))
1128 nTy = FixedVectorType::get(nTyS, vTy);
1129 unsigned size = nTy->getScalarSizeInBits();
1130 opr_n = FPOp->getOperand(1);
1131 if (opr_n->getType()->isIntegerTy())
1132 opr_n = B.CreateZExtOrTrunc(opr_n, nTy, "__ytou");
1133 else
1134 opr_n = B.CreateFPToSI(opr1, nTy, "__ytou");
1135
1136 Value *sign = B.CreateShl(opr_n, size-1, "__yeven");
1137 sign = B.CreateAnd(B.CreateBitCast(opr0, nTy), sign, "__pow_sign");
1138 nval = B.CreateOr(B.CreateBitCast(nval, nTy), sign);
1139 nval = B.CreateBitCast(nval, opr0->getType());
1140 }
1141
1142 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
1143 << "exp2(" << *opr1 << " * log2(" << *opr0 << "))\n");
1144 replaceCall(FPOp, nval);
1145
1146 return true;
1147}
1148
1149bool AMDGPULibCalls::fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B,
1150 const FuncInfo &FInfo) {
1151 // skip vector function
1152 if (getVecSize(FInfo) != 1)
1153 return false;
1154
1155 Value *opr0 = FPOp->getOperand(0);
1156 Value *opr1 = FPOp->getOperand(1);
1157
1158 ConstantInt *CINT = dyn_cast<ConstantInt>(opr1);
1159 if (!CINT) {
1160 return false;
1161 }
1162 int ci_opr1 = (int)CINT->getSExtValue();
1163 if (ci_opr1 == 1) { // rootn(x, 1) = x
1164 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n");
1165 replaceCall(FPOp, opr0);
1166 return true;
1167 }
1168
1169 Module *M = B.GetInsertBlock()->getModule();
1170 if (ci_opr1 == 2) { // rootn(x, 2) = sqrt(x)
1171 if (FunctionCallee FPExpr =
1172 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) {
1173 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> sqrt(" << *opr0
1174 << ")\n");
1175 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2sqrt");
1176 replaceCall(FPOp, nval);
1177 return true;
1178 }
1179 } else if (ci_opr1 == 3) { // rootn(x, 3) = cbrt(x)
1180 if (FunctionCallee FPExpr =
1181 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT, FInfo))) {
1182 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> cbrt(" << *opr0
1183 << ")\n");
1184 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2cbrt");
1185 replaceCall(FPOp, nval);
1186 return true;
1187 }
1188 } else if (ci_opr1 == -1) { // rootn(x, -1) = 1.0/x
1189 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1.0 / " << *opr0 << "\n");
1190 Value *nval = B.CreateFDiv(ConstantFP::get(opr0->getType(), 1.0),
1191 opr0,
1192 "__rootn2div");
1193 replaceCall(FPOp, nval);
1194 return true;
1195 } else if (ci_opr1 == -2) { // rootn(x, -2) = rsqrt(x)
1196 if (FunctionCallee FPExpr =
1197 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT, FInfo))) {
1198 LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> rsqrt(" << *opr0
1199 << ")\n");
1200 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2rsqrt");
1201 replaceCall(FPOp, nval);
1202 return true;
1203 }
1204 }
1205 return false;
1206}
1207
1208// Get a scalar native builtin single argument FP function
1209FunctionCallee AMDGPULibCalls::getNativeFunction(Module *M,
1210 const FuncInfo &FInfo) {
1211 if (getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()))
1212 return nullptr;
1213 FuncInfo nf = FInfo;
1215 return getFunction(M, nf);
1216}
1217
1218// Some library calls are just wrappers around llvm intrinsics, but compiled
1219// conservatively. Preserve the flags from the original call site by
1220// substituting them with direct calls with all the flags.
1221bool AMDGPULibCalls::shouldReplaceLibcallWithIntrinsic(const CallInst *CI,
1222 bool AllowMinSizeF32,
1223 bool AllowF64,
1224 bool AllowStrictFP) {
1225 Type *FltTy = CI->getType()->getScalarType();
1226 const bool IsF32 = FltTy->isFloatTy();
1227
1228 // f64 intrinsics aren't implemented for most operations.
1229 if (!IsF32 && !FltTy->isHalfTy() && (!AllowF64 || !FltTy->isDoubleTy()))
1230 return false;
1231
1232 // We're implicitly inlining by replacing the libcall with the intrinsic, so
1233 // don't do it for noinline call sites.
1234 if (CI->isNoInline())
1235 return false;
1236
1237 const Function *ParentF = CI->getFunction();
1238 // TODO: Handle strictfp
1239 if (!AllowStrictFP && ParentF->hasFnAttribute(Attribute::StrictFP))
1240 return false;
1241
1242 if (IsF32 && !AllowMinSizeF32 && ParentF->hasMinSize())
1243 return false;
1244 return true;
1245}
1246
1247void AMDGPULibCalls::replaceLibCallWithSimpleIntrinsic(IRBuilder<> &B,
1248 CallInst *CI,
1249 Intrinsic::ID IntrID) {
1250 if (CI->arg_size() == 2) {
1251 Value *Arg0 = CI->getArgOperand(0);
1252 Value *Arg1 = CI->getArgOperand(1);
1253 VectorType *Arg0VecTy = dyn_cast<VectorType>(Arg0->getType());
1254 VectorType *Arg1VecTy = dyn_cast<VectorType>(Arg1->getType());
1255 if (Arg0VecTy && !Arg1VecTy) {
1256 Value *SplatRHS = B.CreateVectorSplat(Arg0VecTy->getElementCount(), Arg1);
1257 CI->setArgOperand(1, SplatRHS);
1258 } else if (!Arg0VecTy && Arg1VecTy) {
1259 Value *SplatLHS = B.CreateVectorSplat(Arg1VecTy->getElementCount(), Arg0);
1260 CI->setArgOperand(0, SplatLHS);
1261 }
1262 }
1263
1265 Intrinsic::getDeclaration(CI->getModule(), IntrID, {CI->getType()}));
1266}
1267
1268bool AMDGPULibCalls::tryReplaceLibcallWithSimpleIntrinsic(
1269 IRBuilder<> &B, CallInst *CI, Intrinsic::ID IntrID, bool AllowMinSizeF32,
1270 bool AllowF64, bool AllowStrictFP) {
1271 if (!shouldReplaceLibcallWithIntrinsic(CI, AllowMinSizeF32, AllowF64,
1272 AllowStrictFP))
1273 return false;
1274 replaceLibCallWithSimpleIntrinsic(B, CI, IntrID);
1275 return true;
1276}
1277
1278std::tuple<Value *, Value *, Value *>
1279AMDGPULibCalls::insertSinCos(Value *Arg, FastMathFlags FMF, IRBuilder<> &B,
1280 FunctionCallee Fsincos) {
1281 DebugLoc DL = B.getCurrentDebugLocation();
1282 Function *F = B.GetInsertBlock()->getParent();
1283 B.SetInsertPointPastAllocas(F);
1284
1285 AllocaInst *Alloc = B.CreateAlloca(Arg->getType(), nullptr, "__sincos_");
1286
1287 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1288 // If the argument is an instruction, it must dominate all uses so put our
1289 // sincos call there. Otherwise, right after the allocas works well enough
1290 // if it's an argument or constant.
1291
1292 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1293
1294 // SetInsertPoint unwelcomely always tries to set the debug loc.
1295 B.SetCurrentDebugLocation(DL);
1296 }
1297
1298 Type *CosPtrTy = Fsincos.getFunctionType()->getParamType(1);
1299
1300 // The allocaInst allocates the memory in private address space. This need
1301 // to be addrspacecasted to point to the address space of cos pointer type.
1302 // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1303 Value *CastAlloc = B.CreateAddrSpaceCast(Alloc, CosPtrTy);
1304
1305 CallInst *SinCos = CreateCallEx2(B, Fsincos, Arg, CastAlloc);
1306
1307 // TODO: Is it worth trying to preserve the location for the cos calls for the
1308 // load?
1309
1310 LoadInst *LoadCos = B.CreateLoad(Alloc->getAllocatedType(), Alloc);
1311 return {SinCos, LoadCos, SinCos};
1312}
1313
1314// fold sin, cos -> sincos.
1315bool AMDGPULibCalls::fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B,
1316 const FuncInfo &fInfo) {
1317 assert(fInfo.getId() == AMDGPULibFunc::EI_SIN ||
1318 fInfo.getId() == AMDGPULibFunc::EI_COS);
1319
1320 if ((getArgType(fInfo) != AMDGPULibFunc::F32 &&
1321 getArgType(fInfo) != AMDGPULibFunc::F64) ||
1322 fInfo.getPrefix() != AMDGPULibFunc::NOPFX)
1323 return false;
1324
1325 bool const isSin = fInfo.getId() == AMDGPULibFunc::EI_SIN;
1326
1327 Value *CArgVal = FPOp->getOperand(0);
1328 CallInst *CI = cast<CallInst>(FPOp);
1329
1330 Function *F = B.GetInsertBlock()->getParent();
1331 Module *M = F->getParent();
1332
1333 // Merge the sin and cos. For OpenCL 2.0, there may only be a generic pointer
1334 // implementation. Prefer the private form if available.
1335 AMDGPULibFunc SinCosLibFuncPrivate(AMDGPULibFunc::EI_SINCOS, fInfo);
1336 SinCosLibFuncPrivate.getLeads()[0].PtrKind =
1338
1339 AMDGPULibFunc SinCosLibFuncGeneric(AMDGPULibFunc::EI_SINCOS, fInfo);
1340 SinCosLibFuncGeneric.getLeads()[0].PtrKind =
1342
1343 FunctionCallee FSinCosPrivate = getFunction(M, SinCosLibFuncPrivate);
1344 FunctionCallee FSinCosGeneric = getFunction(M, SinCosLibFuncGeneric);
1345 FunctionCallee FSinCos = FSinCosPrivate ? FSinCosPrivate : FSinCosGeneric;
1346 if (!FSinCos)
1347 return false;
1348
1349 SmallVector<CallInst *> SinCalls;
1350 SmallVector<CallInst *> CosCalls;
1351 SmallVector<CallInst *> SinCosCalls;
1352 FuncInfo PartnerInfo(isSin ? AMDGPULibFunc::EI_COS : AMDGPULibFunc::EI_SIN,
1353 fInfo);
1354 const std::string PairName = PartnerInfo.mangle();
1355
1356 StringRef SinName = isSin ? CI->getCalledFunction()->getName() : PairName;
1357 StringRef CosName = isSin ? PairName : CI->getCalledFunction()->getName();
1358 const std::string SinCosPrivateName = SinCosLibFuncPrivate.mangle();
1359 const std::string SinCosGenericName = SinCosLibFuncGeneric.mangle();
1360
1361 // Intersect the two sets of flags.
1362 FastMathFlags FMF = FPOp->getFastMathFlags();
1363 MDNode *FPMath = CI->getMetadata(LLVMContext::MD_fpmath);
1364
1365 SmallVector<DILocation *> MergeDbgLocs = {CI->getDebugLoc()};
1366
1367 for (User* U : CArgVal->users()) {
1368 CallInst *XI = dyn_cast<CallInst>(U);
1369 if (!XI || XI->getFunction() != F || XI->isNoBuiltin())
1370 continue;
1371
1372 Function *UCallee = XI->getCalledFunction();
1373 if (!UCallee)
1374 continue;
1375
1376 bool Handled = true;
1377
1378 if (UCallee->getName() == SinName)
1379 SinCalls.push_back(XI);
1380 else if (UCallee->getName() == CosName)
1381 CosCalls.push_back(XI);
1382 else if (UCallee->getName() == SinCosPrivateName ||
1383 UCallee->getName() == SinCosGenericName)
1384 SinCosCalls.push_back(XI);
1385 else
1386 Handled = false;
1387
1388 if (Handled) {
1389 MergeDbgLocs.push_back(XI->getDebugLoc());
1390 auto *OtherOp = cast<FPMathOperator>(XI);
1391 FMF &= OtherOp->getFastMathFlags();
1393 FPMath, XI->getMetadata(LLVMContext::MD_fpmath));
1394 }
1395 }
1396
1397 if (SinCalls.empty() || CosCalls.empty())
1398 return false;
1399
1400 B.setFastMathFlags(FMF);
1401 B.setDefaultFPMathTag(FPMath);
1402 DILocation *DbgLoc = DILocation::getMergedLocations(MergeDbgLocs);
1403 B.SetCurrentDebugLocation(DbgLoc);
1404
1405 auto [Sin, Cos, SinCos] = insertSinCos(CArgVal, FMF, B, FSinCos);
1406
1407 auto replaceTrigInsts = [](ArrayRef<CallInst *> Calls, Value *Res) {
1408 for (CallInst *C : Calls)
1409 C->replaceAllUsesWith(Res);
1410
1411 // Leave the other dead instructions to avoid clobbering iterators.
1412 };
1413
1414 replaceTrigInsts(SinCalls, Sin);
1415 replaceTrigInsts(CosCalls, Cos);
1416 replaceTrigInsts(SinCosCalls, SinCos);
1417
1418 // It's safe to delete the original now.
1419 CI->eraseFromParent();
1420 return true;
1421}
1422
1423bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0,
1424 double &Res1, Constant *copr0,
1425 Constant *copr1) {
1426 // By default, opr0/opr1/opr3 holds values of float/double type.
1427 // If they are not float/double, each function has to its
1428 // operand separately.
1429 double opr0 = 0.0, opr1 = 0.0;
1430 ConstantFP *fpopr0 = dyn_cast_or_null<ConstantFP>(copr0);
1431 ConstantFP *fpopr1 = dyn_cast_or_null<ConstantFP>(copr1);
1432 if (fpopr0) {
1433 opr0 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1434 ? fpopr0->getValueAPF().convertToDouble()
1435 : (double)fpopr0->getValueAPF().convertToFloat();
1436 }
1437
1438 if (fpopr1) {
1439 opr1 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1440 ? fpopr1->getValueAPF().convertToDouble()
1441 : (double)fpopr1->getValueAPF().convertToFloat();
1442 }
1443
1444 switch (FInfo.getId()) {
1445 default : return false;
1446
1448 Res0 = acos(opr0);
1449 return true;
1450
1452 // acosh(x) == log(x + sqrt(x*x - 1))
1453 Res0 = log(opr0 + sqrt(opr0*opr0 - 1.0));
1454 return true;
1455
1457 Res0 = acos(opr0) / MATH_PI;
1458 return true;
1459
1461 Res0 = asin(opr0);
1462 return true;
1463
1465 // asinh(x) == log(x + sqrt(x*x + 1))
1466 Res0 = log(opr0 + sqrt(opr0*opr0 + 1.0));
1467 return true;
1468
1470 Res0 = asin(opr0) / MATH_PI;
1471 return true;
1472
1474 Res0 = atan(opr0);
1475 return true;
1476
1478 // atanh(x) == (log(x+1) - log(x-1))/2;
1479 Res0 = (log(opr0 + 1.0) - log(opr0 - 1.0))/2.0;
1480 return true;
1481
1483 Res0 = atan(opr0) / MATH_PI;
1484 return true;
1485
1487 Res0 = (opr0 < 0.0) ? -pow(-opr0, 1.0/3.0) : pow(opr0, 1.0/3.0);
1488 return true;
1489
1491 Res0 = cos(opr0);
1492 return true;
1493
1495 Res0 = cosh(opr0);
1496 return true;
1497
1499 Res0 = cos(MATH_PI * opr0);
1500 return true;
1501
1503 Res0 = exp(opr0);
1504 return true;
1505
1507 Res0 = pow(2.0, opr0);
1508 return true;
1509
1511 Res0 = pow(10.0, opr0);
1512 return true;
1513
1515 Res0 = log(opr0);
1516 return true;
1517
1519 Res0 = log(opr0) / log(2.0);
1520 return true;
1521
1523 Res0 = log(opr0) / log(10.0);
1524 return true;
1525
1527 Res0 = 1.0 / sqrt(opr0);
1528 return true;
1529
1531 Res0 = sin(opr0);
1532 return true;
1533
1535 Res0 = sinh(opr0);
1536 return true;
1537
1539 Res0 = sin(MATH_PI * opr0);
1540 return true;
1541
1543 Res0 = tan(opr0);
1544 return true;
1545
1547 Res0 = tanh(opr0);
1548 return true;
1549
1551 Res0 = tan(MATH_PI * opr0);
1552 return true;
1553
1554 // two-arg functions
1557 Res0 = pow(opr0, opr1);
1558 return true;
1559
1561 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1562 double val = (double)iopr1->getSExtValue();
1563 Res0 = pow(opr0, val);
1564 return true;
1565 }
1566 return false;
1567 }
1568
1570 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1571 double val = (double)iopr1->getSExtValue();
1572 Res0 = pow(opr0, 1.0 / val);
1573 return true;
1574 }
1575 return false;
1576 }
1577
1578 // with ptr arg
1580 Res0 = sin(opr0);
1581 Res1 = cos(opr0);
1582 return true;
1583 }
1584
1585 return false;
1586}
1587
1588bool AMDGPULibCalls::evaluateCall(CallInst *aCI, const FuncInfo &FInfo) {
1589 int numArgs = (int)aCI->arg_size();
1590 if (numArgs > 3)
1591 return false;
1592
1593 Constant *copr0 = nullptr;
1594 Constant *copr1 = nullptr;
1595 if (numArgs > 0) {
1596 if ((copr0 = dyn_cast<Constant>(aCI->getArgOperand(0))) == nullptr)
1597 return false;
1598 }
1599
1600 if (numArgs > 1) {
1601 if ((copr1 = dyn_cast<Constant>(aCI->getArgOperand(1))) == nullptr) {
1602 if (FInfo.getId() != AMDGPULibFunc::EI_SINCOS)
1603 return false;
1604 }
1605 }
1606
1607 // At this point, all arguments to aCI are constants.
1608
1609 // max vector size is 16, and sincos will generate two results.
1610 double DVal0[16], DVal1[16];
1611 int FuncVecSize = getVecSize(FInfo);
1612 bool hasTwoResults = (FInfo.getId() == AMDGPULibFunc::EI_SINCOS);
1613 if (FuncVecSize == 1) {
1614 if (!evaluateScalarMathFunc(FInfo, DVal0[0], DVal1[0], copr0, copr1)) {
1615 return false;
1616 }
1617 } else {
1618 ConstantDataVector *CDV0 = dyn_cast_or_null<ConstantDataVector>(copr0);
1619 ConstantDataVector *CDV1 = dyn_cast_or_null<ConstantDataVector>(copr1);
1620 for (int i = 0; i < FuncVecSize; ++i) {
1621 Constant *celt0 = CDV0 ? CDV0->getElementAsConstant(i) : nullptr;
1622 Constant *celt1 = CDV1 ? CDV1->getElementAsConstant(i) : nullptr;
1623 if (!evaluateScalarMathFunc(FInfo, DVal0[i], DVal1[i], celt0, celt1)) {
1624 return false;
1625 }
1626 }
1627 }
1628
1629 LLVMContext &context = aCI->getContext();
1630 Constant *nval0, *nval1;
1631 if (FuncVecSize == 1) {
1632 nval0 = ConstantFP::get(aCI->getType(), DVal0[0]);
1633 if (hasTwoResults)
1634 nval1 = ConstantFP::get(aCI->getType(), DVal1[0]);
1635 } else {
1636 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1637 SmallVector <float, 0> FVal0, FVal1;
1638 for (int i = 0; i < FuncVecSize; ++i)
1639 FVal0.push_back((float)DVal0[i]);
1640 ArrayRef<float> tmp0(FVal0);
1641 nval0 = ConstantDataVector::get(context, tmp0);
1642 if (hasTwoResults) {
1643 for (int i = 0; i < FuncVecSize; ++i)
1644 FVal1.push_back((float)DVal1[i]);
1645 ArrayRef<float> tmp1(FVal1);
1646 nval1 = ConstantDataVector::get(context, tmp1);
1647 }
1648 } else {
1649 ArrayRef<double> tmp0(DVal0);
1650 nval0 = ConstantDataVector::get(context, tmp0);
1651 if (hasTwoResults) {
1652 ArrayRef<double> tmp1(DVal1);
1653 nval1 = ConstantDataVector::get(context, tmp1);
1654 }
1655 }
1656 }
1657
1658 if (hasTwoResults) {
1659 // sincos
1660 assert(FInfo.getId() == AMDGPULibFunc::EI_SINCOS &&
1661 "math function with ptr arg not supported yet");
1662 new StoreInst(nval1, aCI->getArgOperand(1), aCI->getIterator());
1663 }
1664
1665 replaceCall(aCI, nval0);
1666 return true;
1667}
1668
1671 AMDGPULibCalls Simplifier;
1672 Simplifier.initNativeFuncs();
1673 Simplifier.initFunction(F, AM);
1674
1675 bool Changed = false;
1676
1677 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1678 F.printAsOperand(dbgs(), false, F.getParent()); dbgs() << '\n';);
1679
1680 for (auto &BB : F) {
1681 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1682 // Ignore non-calls.
1683 CallInst *CI = dyn_cast<CallInst>(I);
1684 ++I;
1685
1686 if (CI) {
1687 if (Simplifier.fold(CI))
1688 Changed = true;
1689 }
1690 }
1691 }
1692 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1693}
1694
1697 if (UseNative.empty())
1698 return PreservedAnalyses::all();
1699
1700 AMDGPULibCalls Simplifier;
1701 Simplifier.initNativeFuncs();
1702 Simplifier.initFunction(F, AM);
1703
1704 bool Changed = false;
1705 for (auto &BB : F) {
1706 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1707 // Ignore non-calls.
1708 CallInst *CI = dyn_cast<CallInst>(I);
1709 ++I;
1710 if (CI && Simplifier.useNative(CI))
1711 Changed = true;
1712 }
1713 }
1714 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1715}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isKnownIntegral(const Value *V, const DataLayout &DL, FastMathFlags FMF)
static const TableEntry tbl_log[]
static const TableEntry tbl_tgamma[]
static AMDGPULibFunc::EType getArgType(const AMDGPULibFunc &FInfo)
static const TableEntry tbl_expm1[]
static const TableEntry tbl_asinpi[]
static const TableEntry tbl_cos[]
#define MATH_SQRT2
static const TableEntry tbl_exp10[]
static CallInst * CreateCallEx(IRB &B, FunctionCallee Callee, Value *Arg, const Twine &Name="")
static CallInst * CreateCallEx2(IRB &B, FunctionCallee Callee, Value *Arg1, Value *Arg2, const Twine &Name="")
static const TableEntry tbl_rsqrt[]
static const TableEntry tbl_atanh[]
static const TableEntry tbl_cosh[]
static const TableEntry tbl_asin[]
static const TableEntry tbl_sinh[]
static const TableEntry tbl_acos[]
static const TableEntry tbl_tan[]
static const TableEntry tbl_cospi[]
static const TableEntry tbl_tanpi[]
static cl::opt< bool > EnablePreLink("amdgpu-prelink", cl::desc("Enable pre-link mode optimizations"), cl::init(false), cl::Hidden)
static bool HasNative(AMDGPULibFunc::EFuncId id)
ArrayRef< TableEntry > TableRef
static int getVecSize(const AMDGPULibFunc &FInfo)
static const TableEntry tbl_sin[]
static const TableEntry tbl_atan[]
static const TableEntry tbl_log2[]
static const TableEntry tbl_acospi[]
static const TableEntry tbl_sqrt[]
static const TableEntry tbl_asinh[]
#define MATH_E
static TableRef getOptTable(AMDGPULibFunc::EFuncId id)
static const TableEntry tbl_acosh[]
static const TableEntry tbl_exp[]
static const TableEntry tbl_cbrt[]
static const TableEntry tbl_sinpi[]
static const TableEntry tbl_atanpi[]
#define MATH_PI
static FunctionType * getPownType(FunctionType *FT)
static const TableEntry tbl_erf[]
static const TableEntry tbl_log10[]
#define MATH_SQRT1_2
static const TableEntry tbl_erfc[]
static cl::list< std::string > UseNative("amdgpu-use-native", cl::desc("Comma separated list of functions to replace with native, or all"), cl::CommaSeparated, cl::ValueOptional, cl::Hidden)
static const TableEntry tbl_tanh[]
static const TableEntry tbl_exp2[]
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
std::string Name
uint64_t Size
AMD GCN specific subclass of TargetSubtarget.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void replaceCall(FPMathOperator *I, Value *With)
bool isUnsafeFiniteOnlyMath(const FPMathOperator *FPOp) const
bool canIncreasePrecisionOfConstantFold(const FPMathOperator *FPOp) const
bool fold(CallInst *CI)
static void replaceCall(Instruction *I, Value *With)
bool useNative(CallInst *CI)
void initFunction(Function &F, FunctionAnalysisManager &FAM)
bool isUnsafeMath(const FPMathOperator *FPOp) const
static unsigned getEPtrKindFromAddrSpace(unsigned AS)
Wrapper class for AMDGPULIbFuncImpl.
static bool parse(StringRef MangledName, AMDGPULibFunc &Ptr)
std::string getName() const
Get unmangled name for mangled library function and name for unmangled library function.
static FunctionCallee getOrInsertFunction(llvm::Module *M, const AMDGPULibFunc &fInfo)
void setPrefix(ENamePrefix PFX)
EFuncId getId() const
bool isCompatibleSignature(const FunctionType *FuncTy) const
bool isMangled() const
Param * getLeads()
Get leading parameters for mangled lib functions.
void setId(EFuncId Id)
ENamePrefix getPrefix() const
bool isNegative() const
Definition: APFloat.h:1295
double convertToDouble() const
Converts this APFloat to host double value.
Definition: APFloat.cpp:5255
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition: APFloat.h:1278
float convertToFloat() const
Converts this APFloat to host float value.
Definition: APFloat.cpp:5268
bool isZero() const
Definition: APFloat.h:1291
bool isInteger() const
Definition: APFloat.h:1312
Class for arbitrary precision integers.
Definition: APInt.h:76
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1513
an instruction to allocate memory on the stack
Definition: Instructions.h:59
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:492
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: InstrTypes.h:2227
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1742
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
Definition: InstrTypes.h:2233
bool isNoInline() const
Return true if the call should not be inlined.
Definition: InstrTypes.h:2236
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1687
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1692
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1600
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
Definition: InstrTypes.h:1685
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1819
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1781
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2748
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index's element.
Definition: Constants.cpp:3090
APFloat getElementAsAPFloat(unsigned i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
Definition: Constants.cpp:3053
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:766
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:2958
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
Definition: Constants.cpp:2897
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:268
const APFloat & getValue() const
Definition: Constants.h:312
const APFloat & getValueAPF() const
Definition: Constants.h:311
bool isExactlyValue(const APFloat &V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition: Constants.cpp:1099
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:160
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:154
Align getAlignValue() const
Return the constant as an llvm::Align, interpreting 0 as Align(1).
Definition: Constants.h:172
This is an important base class in LLVM.
Definition: Constant.h:41
Debug location.
static DILocation * getMergedLocations(ArrayRef< DILocation * > Locs)
Try to combine the vector of locations passed as input in a single one.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
A debug info location.
Definition: DebugLoc.h:33
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition: Operator.h:201
bool isFast() const
Test if this operation allows all non-strict floating-point transforms.
Definition: Operator.h:272
bool hasNoNaNs() const
Test if this operation's arguments and results are assumed not-NaN.
Definition: Operator.h:288
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition: Operator.h:319
bool hasNoInfs() const
Test if this operation's arguments and results are assumed not-infinite.
Definition: Operator.h:293
bool hasApproxFunc() const
Test if this operation allows approximations of math library functions or intrinsics.
Definition: Operator.h:314
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
bool noInfs() const
Definition: FMF.h:67
bool none() const
Definition: FMF.h:58
bool approxFunc() const
Definition: FMF.h:71
bool noNaNs() const
Definition: FMF.h:66
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:692
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
FunctionType * getFunctionType()
Definition: DerivedTypes.h:185
Class to represent function types.
Definition: DerivedTypes.h:103
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition: Function.h:678
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:356
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:675
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:454
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:83
const BasicBlock * getParent() const
Definition: Instruction.h:152
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:87
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:359
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
Metadata node.
Definition: Metadata.h:1067
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1167
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:154
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:143
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:157
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
void dropAllReferences()
Drop all references to operands.
Definition: User.h:299
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
self_iterator getIterator()
Definition: ilist_node.h:109
@ FLAT_ADDRESS
Address space for flat memory.
@ PRIVATE_ADDRESS
Address space for private memory.
AttributeMask typeIncompatible(Type *Ty, AttributeSafetyKind ASK=ASK_ALL)
Which attributes cannot be applied to a type.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1465
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
apint_match m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
Definition: PatternMatch.h:305
apfloat_match m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
Definition: PatternMatch.h:322
@ ValueOptional
Definition: CommandLine.h:131
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
@ CommaSeparated
Definition: CommandLine.h:164
constexpr double ln2
Definition: MathExtras.h:33
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
static double log2(double V)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1680
bool isKnownNeverInfinity(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
bool isKnownNeverInfOrNaN(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point value can never contain a NaN or infinity.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
bool cannotBeOrderedLessThanZero(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39